grid-axis.src.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. /**
  2. * @license Highcharts JS v5.0.6 (2016-12-07)
  3. * GridAxis
  4. *
  5. * (c) 2016 Lars A. V. Cabrera
  6. *
  7. * --- WORK IN PROGRESS ---
  8. *
  9. * License: www.highcharts.com/license
  10. */
  11. (function(factory) {
  12. if (typeof module === 'object' && module.exports) {
  13. module.exports = factory;
  14. } else {
  15. factory(Highcharts);
  16. }
  17. }(function(Highcharts) {
  18. (function(H) {
  19. /**
  20. * (c) 2016 Highsoft AS
  21. * Authors: Lars A. V. Cabrera
  22. *
  23. * License: www.highcharts.com/license
  24. */
  25. 'use strict';
  26. var dateFormat = H.dateFormat,
  27. each = H.each,
  28. isObject = H.isObject,
  29. pick = H.pick,
  30. wrap = H.wrap,
  31. Axis = H.Axis,
  32. Chart = H.Chart,
  33. Tick = H.Tick;
  34. // Enum for which side the axis is on.
  35. // Maps to axis.side
  36. var axisSide = {
  37. top: 0,
  38. right: 1,
  39. bottom: 2,
  40. left: 3,
  41. 0: 'top',
  42. 1: 'right',
  43. 2: 'bottom',
  44. 3: 'left'
  45. };
  46. /**
  47. * Checks if an axis is the outer axis in its dimension. Since
  48. * axes are placed outwards in order, the axis with the highest
  49. * index is the outermost axis.
  50. *
  51. * Example: If there are multiple x-axes at the top of the chart,
  52. * this function returns true if the axis supplied is the last
  53. * of the x-axes.
  54. *
  55. * @return true if the axis is the outermost axis in its dimension;
  56. * false if not
  57. */
  58. Axis.prototype.isOuterAxis = function() {
  59. var axis = this,
  60. thisIndex = -1,
  61. isOuter = true;
  62. each(this.chart.axes, function(otherAxis, index) {
  63. if (otherAxis.side === axis.side) {
  64. if (otherAxis === axis) {
  65. // Get the index of the axis in question
  66. thisIndex = index;
  67. // Check thisIndex >= 0 in case thisIndex has
  68. // not been found yet
  69. } else if (thisIndex >= 0 && index > thisIndex) {
  70. // There was an axis on the same side with a
  71. // higher index. Exit the loop.
  72. isOuter = false;
  73. return;
  74. }
  75. }
  76. });
  77. // There were either no other axes on the same side,
  78. // or the other axes were not farther from the chart
  79. return isOuter;
  80. };
  81. /**
  82. * Shortcut function to Tick.label.getBBox().width.
  83. *
  84. * @return {number} width - the width of the tick label
  85. */
  86. Tick.prototype.getLabelWidth = function() {
  87. return this.label.getBBox().width;
  88. };
  89. /**
  90. * Get the maximum label length.
  91. * This function can be used in states where the axis.maxLabelLength has not
  92. * been set.
  93. *
  94. * @param {boolean} force - Optional parameter to force a new calculation, even
  95. * if a value has already been set
  96. * @return {number} maxLabelLength - the maximum label length of the axis
  97. */
  98. Axis.prototype.getMaxLabelLength = function(force) {
  99. var tickPositions = this.tickPositions,
  100. ticks = this.ticks,
  101. maxLabelLength = 0;
  102. if (!this.maxLabelLength || force) {
  103. each(tickPositions, function(tick) {
  104. tick = ticks[tick];
  105. if (tick && tick.labelLength > maxLabelLength) {
  106. maxLabelLength = tick.labelLength;
  107. }
  108. });
  109. this.maxLabelLength = maxLabelLength;
  110. }
  111. return this.maxLabelLength;
  112. };
  113. /**
  114. * Adds the axis defined in axis.options.title
  115. */
  116. Axis.prototype.addTitle = function() {
  117. var axis = this,
  118. renderer = axis.chart.renderer,
  119. axisParent = axis.axisParent,
  120. horiz = axis.horiz,
  121. opposite = axis.opposite,
  122. options = axis.options,
  123. axisTitleOptions = options.title,
  124. hasData,
  125. showAxis,
  126. textAlign;
  127. // For reuse in Axis.render
  128. hasData = axis.hasData();
  129. axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
  130. // Disregard title generation in original Axis.getOffset()
  131. options.title = '';
  132. if (!axis.axisTitle) {
  133. textAlign = axisTitleOptions.textAlign;
  134. if (!textAlign) {
  135. textAlign = (horiz ? {
  136. low: 'left',
  137. middle: 'center',
  138. high: 'right'
  139. } : {
  140. low: opposite ? 'right' : 'left',
  141. middle: 'center',
  142. high: opposite ? 'left' : 'right'
  143. })[axisTitleOptions.align];
  144. }
  145. axis.axisTitle = renderer.text(
  146. axisTitleOptions.text,
  147. 0,
  148. 0,
  149. axisTitleOptions.useHTML
  150. )
  151. .attr({
  152. zIndex: 7,
  153. rotation: axisTitleOptions.rotation || 0,
  154. align: textAlign
  155. })
  156. .addClass('highcharts-axis-title')
  157. // Add to axisParent instead of axisGroup, to ignore the space
  158. // it takes
  159. .add(axisParent);
  160. axis.axisTitle.isNew = true;
  161. }
  162. // hide or show the title depending on whether showEmpty is set
  163. axis.axisTitle[showAxis ? 'show' : 'hide'](true);
  164. };
  165. /**
  166. * Add custom date formats
  167. */
  168. H.dateFormats = {
  169. // Week number
  170. W: function(timestamp) {
  171. var date = new Date(timestamp),
  172. day = date.getUTCDay() === 0 ? 7 : date.getUTCDay(),
  173. time = date.getTime(),
  174. startOfYear = new Date(date.getUTCFullYear(), 0, 1, -6),
  175. dayNumber;
  176. date.setDate(date.getUTCDate() + 4 - day);
  177. dayNumber = Math.floor((time - startOfYear) / 86400000);
  178. return 1 + Math.floor(dayNumber / 7);
  179. },
  180. // First letter of the day of the week, e.g. 'M' for 'Monday'.
  181. E: function(timestamp) {
  182. return dateFormat('%a', timestamp, true).charAt(0);
  183. }
  184. };
  185. /**
  186. * Prevents adding the last tick label if the axis is not a category axis.
  187. *
  188. * Since numeric labels are normally placed at starts and ends of a range of
  189. * value, and this module makes the label point at the value, an "extra" label
  190. * would appear.
  191. *
  192. * @param {function} proceed - the original function
  193. */
  194. wrap(Tick.prototype, 'addLabel', function(proceed) {
  195. var axis = this.axis,
  196. isCategoryAxis = axis.options.categories !== undefined,
  197. tickPositions = axis.tickPositions,
  198. lastTick = tickPositions[tickPositions.length - 1],
  199. isLastTick = this.pos !== lastTick;
  200. if (!axis.options.grid || isCategoryAxis || isLastTick) {
  201. proceed.apply(this);
  202. }
  203. });
  204. /**
  205. * Center tick labels vertically and horizontally between ticks
  206. *
  207. * @param {function} proceed - the original function
  208. *
  209. * @return {object} object - an object containing x and y positions
  210. * for the tick
  211. */
  212. wrap(Tick.prototype, 'getLabelPosition', function(proceed, x, y, label) {
  213. var retVal = proceed.apply(this, Array.prototype.slice.call(arguments, 1)),
  214. axis = this.axis,
  215. options = axis.options,
  216. tickInterval = options.tickInterval || 1,
  217. newX,
  218. newPos,
  219. axisHeight,
  220. fontSize,
  221. labelMetrics,
  222. lblB,
  223. lblH,
  224. labelCenter;
  225. // Only center tick labels if axis has option grid: true
  226. if (options.grid) {
  227. fontSize = options.labels.style.fontSize;
  228. labelMetrics = axis.chart.renderer.fontMetrics(fontSize, label);
  229. lblB = labelMetrics.b;
  230. lblH = labelMetrics.h;
  231. if (axis.horiz && options.categories === undefined) {
  232. // Center x position
  233. axisHeight = axis.axisGroup.getBBox().height;
  234. newPos = this.pos + tickInterval / 2;
  235. retVal.x = axis.translate(newPos) + axis.left;
  236. labelCenter = (axisHeight / 2) + (lblH / 2) - Math.abs(lblH - lblB);
  237. // Center y position
  238. if (axis.side === axisSide.top) {
  239. retVal.y = y - labelCenter;
  240. } else {
  241. retVal.y = y + labelCenter;
  242. }
  243. } else {
  244. // Center y position
  245. if (options.categories === undefined) {
  246. newPos = this.pos + (tickInterval / 2);
  247. retVal.y = axis.translate(newPos) + axis.top + (lblB / 2);
  248. }
  249. // Center x position
  250. newX = (this.getLabelWidth() / 2) - (axis.maxLabelLength / 2);
  251. if (axis.side === axisSide.left) {
  252. retVal.x += newX;
  253. } else {
  254. retVal.x -= newX;
  255. }
  256. }
  257. }
  258. return retVal;
  259. });
  260. /**
  261. * Draw vertical ticks extra long to create cell floors and roofs.
  262. * Overrides the tickLength for vertical axes.
  263. *
  264. * @param {function} proceed - the original function
  265. * @returns {array} retVal -
  266. */
  267. wrap(Axis.prototype, 'tickSize', function(proceed) {
  268. var axis = this,
  269. retVal = proceed.apply(axis, Array.prototype.slice.call(arguments, 1)),
  270. labelPadding,
  271. distance;
  272. if (axis.options.grid && !axis.horiz) {
  273. labelPadding = (Math.abs(axis.defaultLeftAxisOptions.labels.x) * 2);
  274. if (!axis.maxLabelLength) {
  275. axis.maxLabelLength = axis.getMaxLabelLength();
  276. }
  277. distance = axis.maxLabelLength + labelPadding;
  278. retVal[0] = distance;
  279. }
  280. return retVal;
  281. });
  282. /**
  283. * Disregards space required by axisTitle, by adding axisTitle to axisParent
  284. * instead of axisGroup, and disregarding margins and offsets related to
  285. * axisTitle.
  286. *
  287. * @param {function} proceed - the original function
  288. */
  289. wrap(Axis.prototype, 'getOffset', function(proceed) {
  290. var axis = this,
  291. axisOffset = axis.chart.axisOffset,
  292. side = axis.side,
  293. axisHeight,
  294. tickSize,
  295. options = axis.options,
  296. axisTitleOptions = options.title,
  297. addTitle = axisTitleOptions &&
  298. axisTitleOptions.text &&
  299. axisTitleOptions.enabled !== false;
  300. if (axis.options.grid && isObject(axis.options.title)) {
  301. tickSize = axis.tickSize('tick')[0];
  302. if (axisOffset[side] && tickSize) {
  303. axisHeight = axisOffset[side] + tickSize;
  304. }
  305. if (addTitle) {
  306. // Use the custom addTitle() to add it, while preventing making room
  307. // for it
  308. axis.addTitle();
  309. }
  310. proceed.apply(axis, Array.prototype.slice.call(arguments, 1));
  311. axisOffset[side] = pick(axisHeight, axisOffset[side]);
  312. // Put axis options back after original Axis.getOffset() has been called
  313. options.title = axisTitleOptions;
  314. } else {
  315. proceed.apply(axis, Array.prototype.slice.call(arguments, 1));
  316. }
  317. });
  318. /**
  319. * Prevents rotation of labels when squished, as rotating them would not
  320. * help.
  321. *
  322. * @param {function} proceed - the original function
  323. */
  324. wrap(Axis.prototype, 'renderUnsquish', function(proceed) {
  325. if (this.options.grid) {
  326. this.labelRotation = 0;
  327. this.options.labels.rotation = 0;
  328. }
  329. proceed.apply(this);
  330. });
  331. /**
  332. * Places leftmost tick at the start of the axis, to create a left wall.
  333. *
  334. * @param {function} proceed - the original function
  335. */
  336. wrap(Axis.prototype, 'setOptions', function(proceed, userOptions) {
  337. var axis = this;
  338. if (userOptions.grid && axis.horiz) {
  339. userOptions.startOnTick = true;
  340. userOptions.minPadding = 0;
  341. userOptions.endOnTick = true;
  342. }
  343. proceed.apply(this, Array.prototype.slice.call(arguments, 1));
  344. });
  345. /**
  346. * Draw an extra line on the far side of the the axisLine,
  347. * creating cell roofs of a grid.
  348. *
  349. * @param {function} proceed - the original function
  350. */
  351. wrap(Axis.prototype, 'render', function(proceed) {
  352. var axis = this,
  353. options = axis.options,
  354. labelPadding,
  355. distance,
  356. lineWidth,
  357. linePath,
  358. yStartIndex,
  359. yEndIndex,
  360. xStartIndex,
  361. xEndIndex,
  362. renderer = axis.chart.renderer,
  363. axisGroupBox;
  364. if (options.grid) {
  365. labelPadding = (Math.abs(axis.defaultLeftAxisOptions.labels.x) * 2);
  366. distance = axis.maxLabelLength + labelPadding;
  367. lineWidth = options.lineWidth;
  368. // Remove right wall before rendering
  369. if (axis.rightWall) {
  370. axis.rightWall.destroy();
  371. }
  372. // Call original Axis.render() to obtain axis.axisLine and
  373. // axis.axisGroup
  374. proceed.apply(axis);
  375. axisGroupBox = axis.axisGroup.getBBox();
  376. // Add right wall on horizontal axes
  377. if (axis.horiz) {
  378. axis.rightWall = renderer.path([
  379. 'M',
  380. axisGroupBox.x + axis.width + 1, // account for left wall
  381. axisGroupBox.y,
  382. 'L',
  383. axisGroupBox.x + axis.width + 1, // account for left wall
  384. axisGroupBox.y + axisGroupBox.height
  385. ])
  386. .attr({
  387. stroke: options.tickColor || '#ccd6eb',
  388. 'stroke-width': options.tickWidth || 1,
  389. zIndex: 7,
  390. class: 'grid-wall'
  391. })
  392. .add(axis.axisGroup);
  393. }
  394. if (axis.isOuterAxis() && axis.axisLine) {
  395. if (axis.horiz) {
  396. // -1 to avoid adding distance each time the chart updates
  397. distance = axisGroupBox.height - 1;
  398. }
  399. if (lineWidth) {
  400. linePath = axis.getLinePath(lineWidth);
  401. xStartIndex = linePath.indexOf('M') + 1;
  402. xEndIndex = linePath.indexOf('L') + 1;
  403. yStartIndex = linePath.indexOf('M') + 2;
  404. yEndIndex = linePath.indexOf('L') + 2;
  405. // Negate distance if top or left axis
  406. if (axis.side === axisSide.top || axis.side === axisSide.left) {
  407. distance = -distance;
  408. }
  409. // If axis is horizontal, reposition line path vertically
  410. if (axis.horiz) {
  411. linePath[yStartIndex] = linePath[yStartIndex] + distance;
  412. linePath[yEndIndex] = linePath[yEndIndex] + distance;
  413. } else {
  414. // If axis is vertical, reposition line path horizontally
  415. linePath[xStartIndex] = linePath[xStartIndex] + distance;
  416. linePath[xEndIndex] = linePath[xEndIndex] + distance;
  417. }
  418. if (!axis.axisLineExtra) {
  419. axis.axisLineExtra = renderer.path(linePath)
  420. .attr({
  421. stroke: options.lineColor,
  422. 'stroke-width': lineWidth,
  423. zIndex: 7
  424. })
  425. .add(axis.axisGroup);
  426. } else {
  427. axis.axisLineExtra.animate({
  428. d: linePath
  429. });
  430. }
  431. // show or hide the line depending on options.showEmpty
  432. axis.axisLine[axis.showAxis ? 'show' : 'hide'](true);
  433. }
  434. }
  435. } else {
  436. proceed.apply(axis);
  437. }
  438. });
  439. /**
  440. * Wraps chart rendering with the following customizations:
  441. * 1. Prohibit timespans of multitudes of a time unit
  442. * 2. Draw cell walls on vertical axes
  443. *
  444. * @param {function} proceed - the original function
  445. */
  446. wrap(Chart.prototype, 'render', function(proceed) {
  447. // 25 is optimal height for default fontSize (11px)
  448. // 25 / 11 ≈ 2.28
  449. var fontSizeToCellHeightRatio = 25 / 11,
  450. fontMetrics,
  451. fontSize;
  452. each(this.axes, function(axis) {
  453. var options = axis.options;
  454. if (options.grid) {
  455. fontSize = options.labels.style.fontSize;
  456. fontMetrics = axis.chart.renderer.fontMetrics(fontSize);
  457. // Prohibit timespans of multitudes of a time unit,
  458. // e.g. two days, three weeks, etc.
  459. if (options.type === 'datetime') {
  460. options.units = [
  461. ['millisecond', [1]],
  462. ['second', [1]],
  463. ['minute', [1]],
  464. ['hour', [1]],
  465. ['day', [1]],
  466. ['week', [1]],
  467. ['month', [1]],
  468. ['year', null]
  469. ];
  470. }
  471. // Make tick marks taller, creating cell walls of a grid.
  472. // Use cellHeight axis option if set
  473. if (axis.horiz) {
  474. options.tickLength = options.cellHeight ||
  475. fontMetrics.h * fontSizeToCellHeightRatio;
  476. } else {
  477. options.tickWidth = 1;
  478. if (!options.lineWidth) {
  479. options.lineWidth = 1;
  480. }
  481. }
  482. }
  483. });
  484. // Call original Chart.render()
  485. proceed.apply(this);
  486. });
  487. }(Highcharts));
  488. }));