axis.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759
  1. import CLASS from './class';
  2. import { Component } from './core';
  3. import { isValue, isFunction, isString, isEmpty } from './util';
  4. export var c3_axis_fn;
  5. export var c3_axis_internal_fn;
  6. function AxisInternal(component, params) {
  7. var internal = this;
  8. internal.component = component;
  9. internal.params = params || {};
  10. internal.d3 = component.d3;
  11. internal.scale = internal.d3.scaleLinear();
  12. internal.range;
  13. internal.orient = "bottom";
  14. internal.innerTickSize = 6;
  15. internal.outerTickSize = this.params.withOuterTick ? 6 : 0;
  16. internal.tickPadding = 3;
  17. internal.tickValues = null;
  18. internal.tickFormat;
  19. internal.tickArguments;
  20. internal.tickOffset = 0;
  21. internal.tickCulling = true;
  22. internal.tickCentered;
  23. internal.tickTextCharSize;
  24. internal.tickTextRotate = internal.params.tickTextRotate;
  25. internal.tickLength;
  26. internal.axis = internal.generateAxis();
  27. }
  28. c3_axis_internal_fn = AxisInternal.prototype;
  29. c3_axis_internal_fn.axisX = function (selection, x, tickOffset) {
  30. selection.attr("transform", function (d) {
  31. return "translate(" + Math.ceil(x(d) + tickOffset) + ", 0)";
  32. });
  33. };
  34. c3_axis_internal_fn.axisY = function (selection, y) {
  35. selection.attr("transform", function (d) {
  36. return "translate(0," + Math.ceil(y(d)) + ")";
  37. });
  38. };
  39. c3_axis_internal_fn.scaleExtent = function (domain) {
  40. var start = domain[0], stop = domain[domain.length - 1];
  41. return start < stop ? [ start, stop ] : [ stop, start ];
  42. };
  43. c3_axis_internal_fn.generateTicks = function (scale) {
  44. var internal = this;
  45. var i, domain, ticks = [];
  46. if (scale.ticks) {
  47. return scale.ticks.apply(scale, internal.tickArguments);
  48. }
  49. domain = scale.domain();
  50. for (i = Math.ceil(domain[0]); i < domain[1]; i++) {
  51. ticks.push(i);
  52. }
  53. if (ticks.length > 0 && ticks[0] > 0) {
  54. ticks.unshift(ticks[0] - (ticks[1] - ticks[0]));
  55. }
  56. return ticks;
  57. };
  58. c3_axis_internal_fn.copyScale = function () {
  59. var internal = this;
  60. var newScale = internal.scale.copy(), domain;
  61. if (internal.params.isCategory) {
  62. domain = internal.scale.domain();
  63. newScale.domain([domain[0], domain[1] - 1]);
  64. }
  65. return newScale;
  66. };
  67. c3_axis_internal_fn.textFormatted = function (v) {
  68. var internal = this,
  69. formatted = internal.tickFormat ? internal.tickFormat(v) : v;
  70. return typeof formatted !== 'undefined' ? formatted : '';
  71. };
  72. c3_axis_internal_fn.updateRange = function () {
  73. var internal = this;
  74. internal.range = internal.scale.rangeExtent ? internal.scale.rangeExtent() : internal.scaleExtent(internal.scale.range());
  75. return internal.range;
  76. };
  77. c3_axis_internal_fn.updateTickTextCharSize = function (tick) {
  78. var internal = this;
  79. if (internal.tickTextCharSize) {
  80. return internal.tickTextCharSize;
  81. }
  82. var size = {
  83. h: 11.5,
  84. w: 5.5
  85. };
  86. tick.select('text').text(function(d) { return internal.textFormatted(d); }).each(function (d) {
  87. var box = this.getBoundingClientRect(),
  88. text = internal.textFormatted(d),
  89. h = box.height,
  90. w = text ? (box.width / text.length) : undefined;
  91. if (h && w) {
  92. size.h = h;
  93. size.w = w;
  94. }
  95. }).text('');
  96. internal.tickTextCharSize = size;
  97. return size;
  98. };
  99. c3_axis_internal_fn.isVertical = function () {
  100. return this.orient === 'left' || this.orient === 'right';
  101. };
  102. c3_axis_internal_fn.tspanData = function (d, i, scale) {
  103. var internal = this;
  104. var splitted = internal.params.tickMultiline ? internal.splitTickText(d, scale) : [].concat(internal.textFormatted(d));
  105. return splitted.map(function (s) {
  106. return { index: i, splitted: s, length: splitted.length };
  107. });
  108. };
  109. c3_axis_internal_fn.splitTickText = function (d, scale) {
  110. var internal = this,
  111. tickText = internal.textFormatted(d),
  112. maxWidth = internal.params.tickWidth,
  113. subtext, spaceIndex, textWidth, splitted = [];
  114. if (Object.prototype.toString.call(tickText) === "[object Array]") {
  115. return tickText;
  116. }
  117. if (!maxWidth || maxWidth <= 0) {
  118. maxWidth = internal.isVertical() ? 95 : internal.params.isCategory ? (Math.ceil(scale(1) - scale(0)) - 12) : 110;
  119. }
  120. function split(splitted, text) {
  121. spaceIndex = undefined;
  122. for (var i = 1; i < text.length; i++) {
  123. if (text.charAt(i) === ' ') {
  124. spaceIndex = i;
  125. }
  126. subtext = text.substr(0, i + 1);
  127. textWidth = internal.tickTextCharSize.w * subtext.length;
  128. // if text width gets over tick width, split by space index or crrent index
  129. if (maxWidth < textWidth) {
  130. return split(
  131. splitted.concat(text.substr(0, spaceIndex ? spaceIndex : i)),
  132. text.slice(spaceIndex ? spaceIndex + 1 : i)
  133. );
  134. }
  135. }
  136. return splitted.concat(text);
  137. }
  138. return split(splitted, tickText + "");
  139. };
  140. c3_axis_internal_fn.updateTickLength = function () {
  141. var internal = this;
  142. internal.tickLength = Math.max(internal.innerTickSize, 0) + internal.tickPadding;
  143. };
  144. c3_axis_internal_fn.lineY2 = function (d) {
  145. var internal = this,
  146. tickPosition = internal.scale(d) + (internal.tickCentered ? 0 : internal.tickOffset);
  147. return internal.range[0] < tickPosition && tickPosition < internal.range[1] ? internal.innerTickSize : 0;
  148. };
  149. c3_axis_internal_fn.textY = function (){
  150. var internal = this, rotate = internal.tickTextRotate;
  151. return rotate ? 11.5 - 2.5 * (rotate / 15) * (rotate > 0 ? 1 : -1) : internal.tickLength;
  152. };
  153. c3_axis_internal_fn.textTransform = function () {
  154. var internal = this, rotate = internal.tickTextRotate;
  155. return rotate ? "rotate(" + rotate + ")" : "";
  156. };
  157. c3_axis_internal_fn.textTextAnchor = function () {
  158. var internal = this, rotate = internal.tickTextRotate;
  159. return rotate ? (rotate > 0 ? "start" : "end") : "middle";
  160. };
  161. c3_axis_internal_fn.tspanDx = function () {
  162. var internal = this, rotate = internal.tickTextRotate;
  163. return rotate ? 8 * Math.sin(Math.PI * (rotate / 180)) : 0;
  164. };
  165. c3_axis_internal_fn.tspanDy = function (d, i) {
  166. var internal = this,
  167. dy = internal.tickTextCharSize.h;
  168. if (i === 0) {
  169. if (internal.isVertical()) {
  170. dy = -((d.length - 1) * (internal.tickTextCharSize.h / 2) - 3);
  171. } else {
  172. dy = ".71em";
  173. }
  174. }
  175. return dy;
  176. };
  177. c3_axis_internal_fn.generateAxis = function () {
  178. var internal = this, d3 = internal.d3, params = internal.params;
  179. function axis(g, transition) {
  180. var self;
  181. g.each(function () {
  182. var g = axis.g = d3.select(this);
  183. var scale0 = this.__chart__ || internal.scale,
  184. scale1 = this.__chart__ = internal.copyScale();
  185. var ticksValues = internal.tickValues ? internal.tickValues : internal.generateTicks(scale1),
  186. ticks = g.selectAll(".tick").data(ticksValues, scale1),
  187. tickEnter = ticks.enter().insert("g", ".domain").attr("class", "tick").style("opacity", 1e-6),
  188. // MEMO: No exit transition. The reason is this transition affects max tick width calculation because old tick will be included in the ticks.
  189. tickExit = ticks.exit().remove(),
  190. tickUpdate = ticks.merge(tickEnter),
  191. tickTransform, tickX, tickY;
  192. if (params.isCategory) {
  193. internal.tickOffset = Math.ceil((scale1(1) - scale1(0)) / 2);
  194. tickX = internal.tickCentered ? 0 : internal.tickOffset;
  195. tickY = internal.tickCentered ? internal.tickOffset : 0;
  196. } else {
  197. internal.tickOffset = tickX = 0;
  198. }
  199. internal.updateRange();
  200. internal.updateTickLength();
  201. internal.updateTickTextCharSize(g.select('.tick'));
  202. var lineUpdate = tickUpdate.select("line").merge(tickEnter.append("line")),
  203. textUpdate = tickUpdate.select("text").merge(tickEnter.append("text"));
  204. var tspans = tickUpdate.selectAll('text').selectAll('tspan').data(function (d, i) {
  205. return internal.tspanData(d, i, scale1);
  206. }),
  207. tspanEnter = tspans.enter().append('tspan'),
  208. tspanUpdate = tspanEnter.merge(tspans).text(function (d) { return d.splitted; });
  209. tspans.exit().remove();
  210. var path = g.selectAll(".domain").data([ 0 ]),
  211. pathUpdate = path.enter().append("path").merge(path).attr("class", "domain");
  212. // TODO: each attr should be one function and change its behavior by internal.orient, probably
  213. switch (internal.orient) {
  214. case "bottom":
  215. {
  216. tickTransform = internal.axisX;
  217. lineUpdate.attr("x1", tickX)
  218. .attr("x2", tickX)
  219. .attr("y2", function (d, i) { return internal.lineY2(d, i); });
  220. textUpdate.attr("x", 0)
  221. .attr("y", function (d, i) { return internal.textY(d, i); })
  222. .attr("transform", function (d, i) { return internal.textTransform(d, i); })
  223. .style("text-anchor", function (d, i) { return internal.textTextAnchor(d, i); });
  224. tspanUpdate.attr('x', 0)
  225. .attr("dy", function (d, i) { return internal.tspanDy(d, i); })
  226. .attr('dx', function (d, i) { return internal.tspanDx(d, i); });
  227. pathUpdate.attr("d", "M" + internal.range[0] + "," + internal.outerTickSize + "V0H" + internal.range[1] + "V" + internal.outerTickSize);
  228. break;
  229. }
  230. case "top":
  231. {
  232. // TODO: rotated tick text
  233. tickTransform = internal.axisX;
  234. lineUpdate.attr("x1", tickX)
  235. .attr("x2", tickX)
  236. .attr("y2", function (d, i) { return -1 * internal.lineY2(d, i); });
  237. textUpdate.attr("x", 0)
  238. .attr("y", function (d, i) { return -1 * internal.textY(d, i) - (params.isCategory ? 2 : (internal.tickLength - 2)); })
  239. .attr("transform", function (d, i) { return internal.textTransform(d, i); })
  240. .style("text-anchor", function (d, i) { return internal.textTextAnchor(d, i); });
  241. tspanUpdate.attr('x', 0)
  242. .attr("dy", function (d, i) { return internal.tspanDy(d, i); })
  243. .attr('dx', function (d, i) { return internal.tspanDx(d, i); });
  244. pathUpdate.attr("d", "M" + internal.range[0] + "," + -internal.outerTickSize + "V0H" + internal.range[1] + "V" + -internal.outerTickSize);
  245. break;
  246. }
  247. case "left":
  248. {
  249. tickTransform = internal.axisY;
  250. lineUpdate.attr("x2", -internal.innerTickSize)
  251. .attr("y1", tickY)
  252. .attr("y2", tickY);
  253. textUpdate.attr("x", -internal.tickLength)
  254. .attr("y", internal.tickOffset)
  255. .style("text-anchor", "end");
  256. tspanUpdate.attr('x', -internal.tickLength)
  257. .attr("dy", function (d, i) { return internal.tspanDy(d, i); });
  258. pathUpdate.attr("d", "M" + -internal.outerTickSize + "," + internal.range[0] + "H0V" + internal.range[1] + "H" + -internal.outerTickSize);
  259. break;
  260. }
  261. case "right":
  262. {
  263. tickTransform = internal.axisY;
  264. lineUpdate.attr("x2", internal.innerTickSize)
  265. .attr("y1", tickY)
  266. .attr("y2", tickY);
  267. textUpdate.attr("x", internal.tickLength)
  268. .attr("y", internal.tickOffset)
  269. .style("text-anchor", "start");
  270. tspanUpdate.attr('x', internal.tickLength)
  271. .attr("dy", function (d, i) { return internal.tspanDy(d, i); });
  272. pathUpdate.attr("d", "M" + internal.outerTickSize + "," + internal.range[0] + "H0V" + internal.range[1] + "H" + internal.outerTickSize);
  273. break;
  274. }
  275. }
  276. if (scale1.rangeBand) {
  277. var x = scale1, dx = x.rangeBand() / 2;
  278. scale0 = scale1 = function (d) {
  279. return x(d) + dx;
  280. };
  281. } else if (scale0.rangeBand) {
  282. scale0 = scale1;
  283. } else {
  284. tickExit.call(tickTransform, scale1, internal.tickOffset);
  285. }
  286. tickEnter.call(tickTransform, scale0, internal.tickOffset);
  287. self = (transition ? tickUpdate.transition(transition) : tickUpdate)
  288. .style('opacity', 1)
  289. .call(tickTransform, scale1, internal.tickOffset);
  290. });
  291. return self;
  292. }
  293. axis.scale = function (x) {
  294. if (!arguments.length) { return internal.scale; }
  295. internal.scale = x;
  296. return axis;
  297. };
  298. axis.orient = function (x) {
  299. if (!arguments.length) { return internal.orient; }
  300. internal.orient = x in {top: 1, right: 1, bottom: 1, left: 1} ? x + "" : "bottom";
  301. return axis;
  302. };
  303. axis.tickFormat = function (format) {
  304. if (!arguments.length) { return internal.tickFormat; }
  305. internal.tickFormat = format;
  306. return axis;
  307. };
  308. axis.tickCentered = function (isCentered) {
  309. if (!arguments.length) { return internal.tickCentered; }
  310. internal.tickCentered = isCentered;
  311. return axis;
  312. };
  313. axis.tickOffset = function () {
  314. return internal.tickOffset;
  315. };
  316. axis.tickInterval = function () {
  317. var interval, length;
  318. if (params.isCategory) {
  319. interval = internal.tickOffset * 2;
  320. }
  321. else {
  322. length = axis.g.select('path.domain').node().getTotalLength() - internal.outerTickSize * 2;
  323. interval = length / axis.g.selectAll('line').size();
  324. }
  325. return interval === Infinity ? 0 : interval;
  326. };
  327. axis.ticks = function () {
  328. if (!arguments.length) { return internal.tickArguments; }
  329. internal.tickArguments = arguments;
  330. return axis;
  331. };
  332. axis.tickCulling = function (culling) {
  333. if (!arguments.length) { return internal.tickCulling; }
  334. internal.tickCulling = culling;
  335. return axis;
  336. };
  337. axis.tickValues = function (x) {
  338. if (typeof x === 'function') {
  339. internal.tickValues = function () {
  340. return x(internal.scale.domain());
  341. };
  342. }
  343. else {
  344. if (!arguments.length) { return internal.tickValues; }
  345. internal.tickValues = x;
  346. }
  347. return axis;
  348. };
  349. return axis;
  350. };
  351. export default class Axis extends Component {
  352. constructor (owner) {
  353. var fn = {
  354. fn: c3_axis_fn,
  355. internal: {
  356. fn: c3_axis_internal_fn
  357. }
  358. };
  359. super(owner, 'axis', fn);
  360. this.d3 = owner.d3;
  361. this.internal = AxisInternal;
  362. }
  363. }
  364. c3_axis_fn = Axis.prototype;
  365. c3_axis_fn.init = function init() {
  366. var $$ = this.owner, config = $$.config, main = $$.main;
  367. $$.axes.x = main.append("g")
  368. .attr("class", CLASS.axis + ' ' + CLASS.axisX)
  369. .attr("clip-path", config.axis_x_inner ? "" : $$.clipPathForXAxis)
  370. .attr("transform", $$.getTranslate('x'))
  371. .style("visibility", config.axis_x_show ? 'visible' : 'hidden');
  372. $$.axes.x.append("text")
  373. .attr("class", CLASS.axisXLabel)
  374. .attr("transform", config.axis_rotated ? "rotate(-90)" : "")
  375. .style("text-anchor", this.textAnchorForXAxisLabel.bind(this));
  376. $$.axes.y = main.append("g")
  377. .attr("class", CLASS.axis + ' ' + CLASS.axisY)
  378. .attr("clip-path", config.axis_y_inner ? "" : $$.clipPathForYAxis)
  379. .attr("transform", $$.getTranslate('y'))
  380. .style("visibility", config.axis_y_show ? 'visible' : 'hidden');
  381. $$.axes.y.append("text")
  382. .attr("class", CLASS.axisYLabel)
  383. .attr("transform", config.axis_rotated ? "" : "rotate(-90)")
  384. .style("text-anchor", this.textAnchorForYAxisLabel.bind(this));
  385. $$.axes.y2 = main.append("g")
  386. .attr("class", CLASS.axis + ' ' + CLASS.axisY2)
  387. // clip-path?
  388. .attr("transform", $$.getTranslate('y2'))
  389. .style("visibility", config.axis_y2_show ? 'visible' : 'hidden');
  390. $$.axes.y2.append("text")
  391. .attr("class", CLASS.axisY2Label)
  392. .attr("transform", config.axis_rotated ? "" : "rotate(-90)")
  393. .style("text-anchor", this.textAnchorForY2AxisLabel.bind(this));
  394. };
  395. c3_axis_fn.getXAxis = function getXAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
  396. var $$ = this.owner, config = $$.config,
  397. axisParams = {
  398. isCategory: $$.isCategorized(),
  399. withOuterTick: withOuterTick,
  400. tickMultiline: config.axis_x_tick_multiline,
  401. tickWidth: config.axis_x_tick_width,
  402. tickTextRotate: withoutRotateTickText ? 0 : config.axis_x_tick_rotate,
  403. withoutTransition: withoutTransition,
  404. },
  405. axis = new this.internal(this, axisParams).axis.scale(scale).orient(orient);
  406. if ($$.isTimeSeries() && tickValues && typeof tickValues !== "function") {
  407. tickValues = tickValues.map(function (v) { return $$.parseDate(v); });
  408. }
  409. // Set tick
  410. axis.tickFormat(tickFormat).tickValues(tickValues);
  411. if ($$.isCategorized()) {
  412. axis.tickCentered(config.axis_x_tick_centered);
  413. if (isEmpty(config.axis_x_tick_culling)) {
  414. config.axis_x_tick_culling = false;
  415. }
  416. }
  417. return axis;
  418. };
  419. c3_axis_fn.updateXAxisTickValues = function updateXAxisTickValues(targets, axis) {
  420. var $$ = this.owner, config = $$.config, tickValues;
  421. if (config.axis_x_tick_fit || config.axis_x_tick_count) {
  422. tickValues = this.generateTickValues($$.mapTargetsToUniqueXs(targets), config.axis_x_tick_count, $$.isTimeSeries());
  423. }
  424. if (axis) {
  425. axis.tickValues(tickValues);
  426. } else {
  427. $$.xAxis.tickValues(tickValues);
  428. $$.subXAxis.tickValues(tickValues);
  429. }
  430. return tickValues;
  431. };
  432. c3_axis_fn.getYAxis = function getYAxis(scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText) {
  433. var $$ = this.owner, config = $$.config,
  434. axisParams = {
  435. withOuterTick: withOuterTick,
  436. withoutTransition: withoutTransition,
  437. tickTextRotate: withoutRotateTickText ? 0 : config.axis_y_tick_rotate
  438. },
  439. axis = new this.internal(this, axisParams).axis.scale(scale).orient(orient).tickFormat(tickFormat);
  440. if ($$.isTimeSeriesY()) {
  441. axis.ticks(config.axis_y_tick_time_type, config.axis_y_tick_time_interval);
  442. } else {
  443. axis.tickValues(tickValues);
  444. }
  445. return axis;
  446. };
  447. c3_axis_fn.getId = function getId(id) {
  448. var config = this.owner.config;
  449. return id in config.data_axes ? config.data_axes[id] : 'y';
  450. };
  451. c3_axis_fn.getXAxisTickFormat = function getXAxisTickFormat() {
  452. var $$ = this.owner, config = $$.config,
  453. format = $$.isTimeSeries() ? $$.defaultAxisTimeFormat : $$.isCategorized() ? $$.categoryName : function (v) { return v < 0 ? v.toFixed(0) : v; };
  454. if (config.axis_x_tick_format) {
  455. if (isFunction(config.axis_x_tick_format)) {
  456. format = config.axis_x_tick_format;
  457. } else if ($$.isTimeSeries()) {
  458. format = function (date) {
  459. return date ? $$.axisTimeFormat(config.axis_x_tick_format)(date) : "";
  460. };
  461. }
  462. }
  463. return isFunction(format) ? function (v) { return format.call($$, v); } : format;
  464. };
  465. c3_axis_fn.getTickValues = function getTickValues(tickValues, axis) {
  466. return tickValues ? tickValues : axis ? axis.tickValues() : undefined;
  467. };
  468. c3_axis_fn.getXAxisTickValues = function getXAxisTickValues() {
  469. return this.getTickValues(this.owner.config.axis_x_tick_values, this.owner.xAxis);
  470. };
  471. c3_axis_fn.getYAxisTickValues = function getYAxisTickValues() {
  472. return this.getTickValues(this.owner.config.axis_y_tick_values, this.owner.yAxis);
  473. };
  474. c3_axis_fn.getY2AxisTickValues = function getY2AxisTickValues() {
  475. return this.getTickValues(this.owner.config.axis_y2_tick_values, this.owner.y2Axis);
  476. };
  477. c3_axis_fn.getLabelOptionByAxisId = function getLabelOptionByAxisId(axisId) {
  478. var $$ = this.owner, config = $$.config, option;
  479. if (axisId === 'y') {
  480. option = config.axis_y_label;
  481. } else if (axisId === 'y2') {
  482. option = config.axis_y2_label;
  483. } else if (axisId === 'x') {
  484. option = config.axis_x_label;
  485. }
  486. return option;
  487. };
  488. c3_axis_fn.getLabelText = function getLabelText(axisId) {
  489. var option = this.getLabelOptionByAxisId(axisId);
  490. return isString(option) ? option : option ? option.text : null;
  491. };
  492. c3_axis_fn.setLabelText = function setLabelText(axisId, text) {
  493. var $$ = this.owner, config = $$.config,
  494. option = this.getLabelOptionByAxisId(axisId);
  495. if (isString(option)) {
  496. if (axisId === 'y') {
  497. config.axis_y_label = text;
  498. } else if (axisId === 'y2') {
  499. config.axis_y2_label = text;
  500. } else if (axisId === 'x') {
  501. config.axis_x_label = text;
  502. }
  503. } else if (option) {
  504. option.text = text;
  505. }
  506. };
  507. c3_axis_fn.getLabelPosition = function getLabelPosition(axisId, defaultPosition) {
  508. var option = this.getLabelOptionByAxisId(axisId),
  509. position = (option && typeof option === 'object' && option.position) ? option.position : defaultPosition;
  510. return {
  511. isInner: position.indexOf('inner') >= 0,
  512. isOuter: position.indexOf('outer') >= 0,
  513. isLeft: position.indexOf('left') >= 0,
  514. isCenter: position.indexOf('center') >= 0,
  515. isRight: position.indexOf('right') >= 0,
  516. isTop: position.indexOf('top') >= 0,
  517. isMiddle: position.indexOf('middle') >= 0,
  518. isBottom: position.indexOf('bottom') >= 0
  519. };
  520. };
  521. c3_axis_fn.getXAxisLabelPosition = function getXAxisLabelPosition() {
  522. return this.getLabelPosition('x', this.owner.config.axis_rotated ? 'inner-top' : 'inner-right');
  523. };
  524. c3_axis_fn.getYAxisLabelPosition = function getYAxisLabelPosition() {
  525. return this.getLabelPosition('y', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top');
  526. };
  527. c3_axis_fn.getY2AxisLabelPosition = function getY2AxisLabelPosition() {
  528. return this.getLabelPosition('y2', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top');
  529. };
  530. c3_axis_fn.getLabelPositionById = function getLabelPositionById(id) {
  531. return id === 'y2' ? this.getY2AxisLabelPosition() : id === 'y' ? this.getYAxisLabelPosition() : this.getXAxisLabelPosition();
  532. };
  533. c3_axis_fn.textForXAxisLabel = function textForXAxisLabel() {
  534. return this.getLabelText('x');
  535. };
  536. c3_axis_fn.textForYAxisLabel = function textForYAxisLabel() {
  537. return this.getLabelText('y');
  538. };
  539. c3_axis_fn.textForY2AxisLabel = function textForY2AxisLabel() {
  540. return this.getLabelText('y2');
  541. };
  542. c3_axis_fn.xForAxisLabel = function xForAxisLabel(forHorizontal, position) {
  543. var $$ = this.owner;
  544. if (forHorizontal) {
  545. return position.isLeft ? 0 : position.isCenter ? $$.width / 2 : $$.width;
  546. } else {
  547. return position.isBottom ? -$$.height : position.isMiddle ? -$$.height / 2 : 0;
  548. }
  549. };
  550. c3_axis_fn.dxForAxisLabel = function dxForAxisLabel(forHorizontal, position) {
  551. if (forHorizontal) {
  552. return position.isLeft ? "0.5em" : position.isRight ? "-0.5em" : "0";
  553. } else {
  554. return position.isTop ? "-0.5em" : position.isBottom ? "0.5em" : "0";
  555. }
  556. };
  557. c3_axis_fn.textAnchorForAxisLabel = function textAnchorForAxisLabel(forHorizontal, position) {
  558. if (forHorizontal) {
  559. return position.isLeft ? 'start' : position.isCenter ? 'middle' : 'end';
  560. } else {
  561. return position.isBottom ? 'start' : position.isMiddle ? 'middle' : 'end';
  562. }
  563. };
  564. c3_axis_fn.xForXAxisLabel = function xForXAxisLabel() {
  565. return this.xForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition());
  566. };
  567. c3_axis_fn.xForYAxisLabel = function xForYAxisLabel() {
  568. return this.xForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition());
  569. };
  570. c3_axis_fn.xForY2AxisLabel = function xForY2AxisLabel() {
  571. return this.xForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition());
  572. };
  573. c3_axis_fn.dxForXAxisLabel = function dxForXAxisLabel() {
  574. return this.dxForAxisLabel(!this.owner.config.axis_rotated, this.getXAxisLabelPosition());
  575. };
  576. c3_axis_fn.dxForYAxisLabel = function dxForYAxisLabel() {
  577. return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getYAxisLabelPosition());
  578. };
  579. c3_axis_fn.dxForY2AxisLabel = function dxForY2AxisLabel() {
  580. return this.dxForAxisLabel(this.owner.config.axis_rotated, this.getY2AxisLabelPosition());
  581. };
  582. c3_axis_fn.dyForXAxisLabel = function dyForXAxisLabel() {
  583. var $$ = this.owner, config = $$.config,
  584. position = this.getXAxisLabelPosition();
  585. if (config.axis_rotated) {
  586. return position.isInner ? "1.2em" : -25 - ($$.config.axis_x_inner ? 0 : this.getMaxTickWidth('x'));
  587. } else {
  588. return position.isInner ? "-0.5em" : config.axis_x_height ? config.axis_x_height - 10 : "3em";
  589. }
  590. };
  591. c3_axis_fn.dyForYAxisLabel = function dyForYAxisLabel() {
  592. var $$ = this.owner,
  593. position = this.getYAxisLabelPosition();
  594. if ($$.config.axis_rotated) {
  595. return position.isInner ? "-0.5em" : "3em";
  596. } else {
  597. return position.isInner ? "1.2em" : -10 - ($$.config.axis_y_inner ? 0 : (this.getMaxTickWidth('y') + 10));
  598. }
  599. };
  600. c3_axis_fn.dyForY2AxisLabel = function dyForY2AxisLabel() {
  601. var $$ = this.owner,
  602. position = this.getY2AxisLabelPosition();
  603. if ($$.config.axis_rotated) {
  604. return position.isInner ? "1.2em" : "-2.2em";
  605. } else {
  606. return position.isInner ? "-0.5em" : 15 + ($$.config.axis_y2_inner ? 0 : (this.getMaxTickWidth('y2') + 15));
  607. }
  608. };
  609. c3_axis_fn.textAnchorForXAxisLabel = function textAnchorForXAxisLabel() {
  610. var $$ = this.owner;
  611. return this.textAnchorForAxisLabel(!$$.config.axis_rotated, this.getXAxisLabelPosition());
  612. };
  613. c3_axis_fn.textAnchorForYAxisLabel = function textAnchorForYAxisLabel() {
  614. var $$ = this.owner;
  615. return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getYAxisLabelPosition());
  616. };
  617. c3_axis_fn.textAnchorForY2AxisLabel = function textAnchorForY2AxisLabel() {
  618. var $$ = this.owner;
  619. return this.textAnchorForAxisLabel($$.config.axis_rotated, this.getY2AxisLabelPosition());
  620. };
  621. c3_axis_fn.getMaxTickWidth = function getMaxTickWidth(id, withoutRecompute) {
  622. var $$ = this.owner, config = $$.config,
  623. maxWidth = 0, targetsToShow, scale, axis, dummy, svg;
  624. if (withoutRecompute && $$.currentMaxTickWidths[id]) {
  625. return $$.currentMaxTickWidths[id];
  626. }
  627. if ($$.svg) {
  628. targetsToShow = $$.filterTargetsToShow($$.data.targets);
  629. if (id === 'y') {
  630. scale = $$.y.copy().domain($$.getYDomain(targetsToShow, 'y'));
  631. axis = this.getYAxis(scale, $$.yOrient, config.axis_y_tick_format, $$.yAxisTickValues, false, true, true);
  632. } else if (id === 'y2') {
  633. scale = $$.y2.copy().domain($$.getYDomain(targetsToShow, 'y2'));
  634. axis = this.getYAxis(scale, $$.y2Orient, config.axis_y2_tick_format, $$.y2AxisTickValues, false, true, true);
  635. } else {
  636. scale = $$.x.copy().domain($$.getXDomain(targetsToShow));
  637. axis = this.getXAxis(scale, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, false, true, true);
  638. this.updateXAxisTickValues(targetsToShow, axis);
  639. }
  640. dummy = $$.d3.select('body').append('div').classed('c3', true);
  641. svg = dummy.append("svg").style('visibility', 'hidden').style('position', 'fixed').style('top', 0).style('left', 0),
  642. svg.append('g').call(axis).each(function () {
  643. $$.d3.select(this).selectAll('text').each(function () {
  644. var box = this.getBoundingClientRect();
  645. if (maxWidth < box.width) { maxWidth = box.width; }
  646. });
  647. dummy.remove();
  648. });
  649. }
  650. $$.currentMaxTickWidths[id] = maxWidth <= 0 ? $$.currentMaxTickWidths[id] : maxWidth;
  651. return $$.currentMaxTickWidths[id];
  652. };
  653. c3_axis_fn.updateLabels = function updateLabels(withTransition) {
  654. var $$ = this.owner;
  655. var axisXLabel = $$.main.select('.' + CLASS.axisX + ' .' + CLASS.axisXLabel),
  656. axisYLabel = $$.main.select('.' + CLASS.axisY + ' .' + CLASS.axisYLabel),
  657. axisY2Label = $$.main.select('.' + CLASS.axisY2 + ' .' + CLASS.axisY2Label);
  658. (withTransition ? axisXLabel.transition() : axisXLabel)
  659. .attr("x", this.xForXAxisLabel.bind(this))
  660. .attr("dx", this.dxForXAxisLabel.bind(this))
  661. .attr("dy", this.dyForXAxisLabel.bind(this))
  662. .text(this.textForXAxisLabel.bind(this));
  663. (withTransition ? axisYLabel.transition() : axisYLabel)
  664. .attr("x", this.xForYAxisLabel.bind(this))
  665. .attr("dx", this.dxForYAxisLabel.bind(this))
  666. .attr("dy", this.dyForYAxisLabel.bind(this))
  667. .text(this.textForYAxisLabel.bind(this));
  668. (withTransition ? axisY2Label.transition() : axisY2Label)
  669. .attr("x", this.xForY2AxisLabel.bind(this))
  670. .attr("dx", this.dxForY2AxisLabel.bind(this))
  671. .attr("dy", this.dyForY2AxisLabel.bind(this))
  672. .text(this.textForY2AxisLabel.bind(this));
  673. };
  674. c3_axis_fn.getPadding = function getPadding(padding, key, defaultValue, domainLength) {
  675. var p = typeof padding === 'number' ? padding : padding[key];
  676. if (!isValue(p)) {
  677. return defaultValue;
  678. }
  679. if (padding.unit === 'ratio') {
  680. return padding[key] * domainLength;
  681. }
  682. // assume padding is pixels if unit is not specified
  683. return this.convertPixelsToAxisPadding(p, domainLength);
  684. };
  685. c3_axis_fn.convertPixelsToAxisPadding = function convertPixelsToAxisPadding(pixels, domainLength) {
  686. var $$ = this.owner,
  687. length = $$.config.axis_rotated ? $$.width : $$.height;
  688. return domainLength * (pixels / length);
  689. };
  690. c3_axis_fn.generateTickValues = function generateTickValues(values, tickCount, forTimeSeries) {
  691. var tickValues = values, targetCount, start, end, count, interval, i, tickValue;
  692. if (tickCount) {
  693. targetCount = isFunction(tickCount) ? tickCount() : tickCount;
  694. // compute ticks according to tickCount
  695. if (targetCount === 1) {
  696. tickValues = [values[0]];
  697. } else if (targetCount === 2) {
  698. tickValues = [values[0], values[values.length - 1]];
  699. } else if (targetCount > 2) {
  700. count = targetCount - 2;
  701. start = values[0];
  702. end = values[values.length - 1];
  703. interval = (end - start) / (count + 1);
  704. // re-construct unique values
  705. tickValues = [start];
  706. for (i = 0; i < count; i++) {
  707. tickValue = +start + interval * (i + 1);
  708. tickValues.push(forTimeSeries ? new Date(tickValue) : tickValue);
  709. }
  710. tickValues.push(end);
  711. }
  712. }
  713. if (!forTimeSeries) { tickValues = tickValues.sort(function (a, b) { return a - b; }); }
  714. return tickValues;
  715. };
  716. c3_axis_fn.generateTransitions = function generateTransitions(duration) {
  717. var $$ = this.owner, axes = $$.axes;
  718. return {
  719. axisX: duration ? axes.x.transition().duration(duration) : axes.x,
  720. axisY: duration ? axes.y.transition().duration(duration) : axes.y,
  721. axisY2: duration ? axes.y2.transition().duration(duration) : axes.y2,
  722. axisSubX: duration ? axes.subx.transition().duration(duration) : axes.subx
  723. };
  724. };
  725. c3_axis_fn.redraw = function redraw(duration, isHidden) {
  726. var $$ = this.owner,
  727. transition = duration ? $$.d3.transition().duration(duration) : null;
  728. $$.axes.x.style("opacity", isHidden ? 0 : 1).call($$.xAxis, transition);
  729. $$.axes.y.style("opacity", isHidden ? 0 : 1).call($$.yAxis, transition);
  730. $$.axes.y2.style("opacity", isHidden ? 0 : 1).call($$.y2Axis, transition);
  731. $$.axes.subx.style("opacity", isHidden ? 0 : 1).call($$.subXAxis, transition);
  732. };