Tick.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. /**
  2. * (c) 2010-2019 Torstein Honsi
  3. *
  4. * License: www.highcharts.com/license
  5. */
  6. 'use strict';
  7. import H from './Globals.js';
  8. import './Utilities.js';
  9. var correctFloat = H.correctFloat,
  10. defined = H.defined,
  11. destroyObjectProperties = H.destroyObjectProperties,
  12. fireEvent = H.fireEvent,
  13. isNumber = H.isNumber,
  14. merge = H.merge,
  15. pick = H.pick,
  16. deg2rad = H.deg2rad;
  17. /**
  18. * The Tick class.
  19. *
  20. * @private
  21. * @class
  22. * @name Highcharts.Tick
  23. *
  24. * @param {Highcharts.Axis} axis
  25. *
  26. * @param {number} pos The position of the tick on the axis.
  27. *
  28. * @param {string} [type] The type of tick.
  29. *
  30. * @param {boolean} [noLabel=false] Wether to disable the label or not. Defaults to
  31. * false.
  32. *
  33. * @param {object} [parameters] Optional parameters for the tick.
  34. *
  35. * @param {object} [parameters.tickmarkOffset] Set tickmarkOffset for the tick.
  36. *
  37. * @param {object} [parameters.category] Set category for the tick.
  38. */
  39. H.Tick = function (axis, pos, type, noLabel, parameters) {
  40. this.axis = axis;
  41. this.pos = pos;
  42. this.type = type || '';
  43. this.isNew = true;
  44. this.isNewLabel = true;
  45. this.parameters = parameters || {};
  46. // Usually undefined, numeric for grid axes
  47. this.tickmarkOffset = this.parameters.tickmarkOffset;
  48. this.options = this.parameters.options;
  49. if (!type && !noLabel) {
  50. this.addLabel();
  51. }
  52. };
  53. /** @lends Highcharts.Tick.prototype */
  54. H.Tick.prototype = {
  55. /**
  56. * Write the tick label.
  57. *
  58. * @private
  59. * @function Highcharts.Tick#addLabel
  60. */
  61. addLabel: function () {
  62. var tick = this,
  63. axis = tick.axis,
  64. options = axis.options,
  65. chart = axis.chart,
  66. categories = axis.categories,
  67. names = axis.names,
  68. pos = tick.pos,
  69. labelOptions = pick(
  70. tick.options && tick.options.labels,
  71. options.labels
  72. ),
  73. str,
  74. tickPositions = axis.tickPositions,
  75. isFirst = pos === tickPositions[0],
  76. isLast = pos === tickPositions[tickPositions.length - 1],
  77. value = this.parameters.category || (
  78. categories ?
  79. pick(categories[pos], names[pos], pos) :
  80. pos
  81. ),
  82. label = tick.label,
  83. tickPositionInfo = tickPositions.info,
  84. dateTimeLabelFormat,
  85. dateTimeLabelFormats,
  86. i,
  87. list;
  88. // Set the datetime label format. If a higher rank is set for this
  89. // position, use that. If not, use the general format.
  90. if (axis.isDatetimeAxis && tickPositionInfo) {
  91. dateTimeLabelFormats = chart.time.resolveDTLFormat(
  92. options.dateTimeLabelFormats[
  93. (
  94. !options.grid &&
  95. tickPositionInfo.higherRanks[pos]
  96. ) ||
  97. tickPositionInfo.unitName
  98. ]
  99. );
  100. dateTimeLabelFormat = dateTimeLabelFormats.main;
  101. }
  102. // set properties for access in render method
  103. tick.isFirst = isFirst;
  104. tick.isLast = isLast;
  105. // Get the string
  106. tick.formatCtx = {
  107. axis: axis,
  108. chart: chart,
  109. isFirst: isFirst,
  110. isLast: isLast,
  111. dateTimeLabelFormat: dateTimeLabelFormat,
  112. tickPositionInfo: tickPositionInfo,
  113. value: axis.isLog ? correctFloat(axis.lin2log(value)) : value,
  114. pos: pos
  115. };
  116. str = axis.labelFormatter.call(tick.formatCtx, this.formatCtx);
  117. // Set up conditional formatting based on the format list if existing.
  118. list = dateTimeLabelFormats && dateTimeLabelFormats.list;
  119. if (list) {
  120. tick.shortenLabel = function () {
  121. for (i = 0; i < list.length; i++) {
  122. label.attr({
  123. text: axis.labelFormatter.call(H.extend(
  124. tick.formatCtx,
  125. { dateTimeLabelFormat: list[i] }
  126. ))
  127. });
  128. if (
  129. label.getBBox().width <
  130. axis.getSlotWidth(tick) - 2 *
  131. pick(labelOptions.padding, 5)
  132. ) {
  133. return;
  134. }
  135. }
  136. label.attr({
  137. text: ''
  138. });
  139. };
  140. }
  141. // first call
  142. if (!defined(label)) {
  143. tick.label = label =
  144. defined(str) && labelOptions.enabled ?
  145. chart.renderer
  146. .text(
  147. str,
  148. 0,
  149. 0,
  150. labelOptions.useHTML
  151. )
  152. .add(axis.labelGroup) :
  153. null;
  154. // Un-rotated length
  155. if (label) {
  156. // Without position absolute, IE export sometimes is wrong
  157. if (!chart.styledMode) {
  158. label.css(merge(labelOptions.style));
  159. }
  160. label.textPxLength = label.getBBox().width;
  161. }
  162. // Base value to detect change for new calls to getBBox
  163. tick.rotation = 0;
  164. // update
  165. } else if (label && label.textStr !== str) {
  166. // When resetting text, also reset the width if dynamically set
  167. // (#8809)
  168. if (
  169. label.textWidth &&
  170. !(labelOptions.style && labelOptions.style.width) &&
  171. !label.styles.width
  172. ) {
  173. label.css({ width: null });
  174. }
  175. label.attr({ text: str });
  176. }
  177. },
  178. /**
  179. * Get the offset height or width of the label
  180. *
  181. * @private
  182. * @function Highcharts.Tick#getLabelSize
  183. *
  184. * @return {number}
  185. */
  186. getLabelSize: function () {
  187. return this.label ?
  188. this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] :
  189. 0;
  190. },
  191. /**
  192. * Handle the label overflow by adjusting the labels to the left and right
  193. * edge, or hide them if they collide into the neighbour label.
  194. *
  195. * @private
  196. * @function Highcharts.Tick#handleOverflow
  197. *
  198. * @param {Highcharts.PositionObject} xy
  199. */
  200. handleOverflow: function (xy) {
  201. var tick = this,
  202. axis = this.axis,
  203. labelOptions = axis.options.labels,
  204. pxPos = xy.x,
  205. chartWidth = axis.chart.chartWidth,
  206. spacing = axis.chart.spacing,
  207. leftBound = pick(axis.labelLeft, Math.min(axis.pos, spacing[3])),
  208. rightBound = pick(
  209. axis.labelRight,
  210. Math.max(
  211. !axis.isRadial ? axis.pos + axis.len : 0,
  212. chartWidth - spacing[1]
  213. )
  214. ),
  215. label = this.label,
  216. rotation = this.rotation,
  217. factor = { left: 0, center: 0.5, right: 1 }[
  218. axis.labelAlign || label.attr('align')
  219. ],
  220. labelWidth = label.getBBox().width,
  221. slotWidth = axis.getSlotWidth(tick),
  222. modifiedSlotWidth = slotWidth,
  223. xCorrection = factor,
  224. goRight = 1,
  225. leftPos,
  226. rightPos,
  227. textWidth,
  228. css = {};
  229. // Check if the label overshoots the chart spacing box. If it does, move
  230. // it. If it now overshoots the slotWidth, add ellipsis.
  231. if (!rotation && pick(labelOptions.overflow, 'justify') === 'justify') {
  232. leftPos = pxPos - factor * labelWidth;
  233. rightPos = pxPos + (1 - factor) * labelWidth;
  234. if (leftPos < leftBound) {
  235. modifiedSlotWidth =
  236. xy.x + modifiedSlotWidth * (1 - factor) - leftBound;
  237. } else if (rightPos > rightBound) {
  238. modifiedSlotWidth =
  239. rightBound - xy.x + modifiedSlotWidth * factor;
  240. goRight = -1;
  241. }
  242. modifiedSlotWidth = Math.min(slotWidth, modifiedSlotWidth); // #4177
  243. if (modifiedSlotWidth < slotWidth && axis.labelAlign === 'center') {
  244. xy.x += (
  245. goRight *
  246. (
  247. slotWidth -
  248. modifiedSlotWidth -
  249. xCorrection * (
  250. slotWidth - Math.min(labelWidth, modifiedSlotWidth)
  251. )
  252. )
  253. );
  254. }
  255. // If the label width exceeds the available space, set a text width
  256. // to be picked up below. Also, if a width has been set before, we
  257. // need to set a new one because the reported labelWidth will be
  258. // limited by the box (#3938).
  259. if (
  260. labelWidth > modifiedSlotWidth ||
  261. (axis.autoRotation && (label.styles || {}).width)
  262. ) {
  263. textWidth = modifiedSlotWidth;
  264. }
  265. // Add ellipsis to prevent rotated labels to be clipped against the edge
  266. // of the chart
  267. } else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) {
  268. textWidth = Math.round(
  269. pxPos / Math.cos(rotation * deg2rad) - leftBound
  270. );
  271. } else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) {
  272. textWidth = Math.round(
  273. (chartWidth - pxPos) / Math.cos(rotation * deg2rad)
  274. );
  275. }
  276. if (textWidth) {
  277. if (tick.shortenLabel) {
  278. tick.shortenLabel();
  279. } else {
  280. css.width = Math.floor(textWidth);
  281. if (!(labelOptions.style || {}).textOverflow) {
  282. css.textOverflow = 'ellipsis';
  283. }
  284. label.css(css);
  285. }
  286. }
  287. },
  288. /**
  289. * Get the x and y position for ticks and labels
  290. *
  291. * @private
  292. * @function Highcharts.Tick#getPosition
  293. *
  294. * @param {boolean} horiz
  295. *
  296. * @param {number} tickPos
  297. *
  298. * @param {number} tickmarkOffset
  299. *
  300. * @param {boolean} [old]
  301. *
  302. * @return {number}
  303. *
  304. * @fires Highcharts.Tick#event:afterGetPosition
  305. */
  306. getPosition: function (horiz, tickPos, tickmarkOffset, old) {
  307. var axis = this.axis,
  308. chart = axis.chart,
  309. cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
  310. pos;
  311. pos = {
  312. x: horiz ?
  313. H.correctFloat(
  314. axis.translate(tickPos + tickmarkOffset, null, null, old) +
  315. axis.transB
  316. ) :
  317. (
  318. axis.left +
  319. axis.offset +
  320. (
  321. axis.opposite ?
  322. (
  323. (
  324. (old && chart.oldChartWidth) ||
  325. chart.chartWidth
  326. ) -
  327. axis.right -
  328. axis.left
  329. ) :
  330. 0
  331. )
  332. ),
  333. y: horiz ?
  334. (
  335. cHeight -
  336. axis.bottom +
  337. axis.offset -
  338. (axis.opposite ? axis.height : 0)
  339. ) :
  340. H.correctFloat(
  341. cHeight -
  342. axis.translate(tickPos + tickmarkOffset, null, null, old) -
  343. axis.transB
  344. )
  345. };
  346. fireEvent(this, 'afterGetPosition', { pos: pos });
  347. return pos;
  348. },
  349. /**
  350. * Get the x, y position of the tick label
  351. *
  352. * @private
  353. *
  354. */
  355. getLabelPosition: function (
  356. x,
  357. y,
  358. label,
  359. horiz,
  360. labelOptions,
  361. tickmarkOffset,
  362. index,
  363. step
  364. ) {
  365. var axis = this.axis,
  366. transA = axis.transA,
  367. reversed = axis.reversed,
  368. staggerLines = axis.staggerLines,
  369. rotCorr = axis.tickRotCorr || { x: 0, y: 0 },
  370. yOffset = labelOptions.y,
  371. // Adjust for label alignment if we use reserveSpace: true (#5286)
  372. labelOffsetCorrection = (
  373. !horiz && !axis.reserveSpaceDefault ?
  374. -axis.labelOffset * (
  375. axis.labelAlign === 'center' ? 0.5 : 1
  376. ) :
  377. 0
  378. ),
  379. line,
  380. pos = {};
  381. if (!defined(yOffset)) {
  382. if (axis.side === 0) {
  383. yOffset = label.rotation ? -8 : -label.getBBox().height;
  384. } else if (axis.side === 2) {
  385. yOffset = rotCorr.y + 8;
  386. } else {
  387. // #3140, #3140
  388. yOffset = Math.cos(label.rotation * deg2rad) *
  389. (rotCorr.y - label.getBBox(false, 0).height / 2);
  390. }
  391. }
  392. x = x +
  393. labelOptions.x +
  394. labelOffsetCorrection +
  395. rotCorr.x -
  396. (
  397. tickmarkOffset && horiz ?
  398. tickmarkOffset * transA * (reversed ? -1 : 1) :
  399. 0
  400. );
  401. y = y + yOffset - (tickmarkOffset && !horiz ?
  402. tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
  403. // Correct for staggered labels
  404. if (staggerLines) {
  405. line = (index / (step || 1) % staggerLines);
  406. if (axis.opposite) {
  407. line = staggerLines - line - 1;
  408. }
  409. y += line * (axis.labelOffset / staggerLines);
  410. }
  411. pos.x = x;
  412. pos.y = Math.round(y);
  413. fireEvent(
  414. this,
  415. 'afterGetLabelPosition',
  416. { pos: pos, tickmarkOffset: tickmarkOffset, index: index }
  417. );
  418. return pos;
  419. },
  420. /**
  421. * Extendible method to return the path of the marker
  422. *
  423. * @private
  424. *
  425. */
  426. getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
  427. return renderer.crispLine([
  428. 'M',
  429. x,
  430. y,
  431. 'L',
  432. x + (horiz ? 0 : -tickLength),
  433. y + (horiz ? tickLength : 0)
  434. ], tickWidth);
  435. },
  436. /**
  437. * Renders the gridLine.
  438. *
  439. * @private
  440. *
  441. * @param {Boolean} old Whether or not the tick is old
  442. * @param {number} opacity The opacity of the grid line
  443. * @param {number} reverseCrisp Modifier for avoiding overlapping 1 or -1
  444. * @return {undefined}
  445. */
  446. renderGridLine: function (old, opacity, reverseCrisp) {
  447. var tick = this,
  448. axis = tick.axis,
  449. options = axis.options,
  450. gridLine = tick.gridLine,
  451. gridLinePath,
  452. attribs = {},
  453. pos = tick.pos,
  454. type = tick.type,
  455. tickmarkOffset = pick(tick.tickmarkOffset, axis.tickmarkOffset),
  456. renderer = axis.chart.renderer,
  457. gridPrefix = type ? type + 'Grid' : 'grid',
  458. gridLineWidth = options[gridPrefix + 'LineWidth'],
  459. gridLineColor = options[gridPrefix + 'LineColor'],
  460. dashStyle = options[gridPrefix + 'LineDashStyle'];
  461. if (!gridLine) {
  462. if (!axis.chart.styledMode) {
  463. attribs.stroke = gridLineColor;
  464. attribs['stroke-width'] = gridLineWidth;
  465. if (dashStyle) {
  466. attribs.dashstyle = dashStyle;
  467. }
  468. }
  469. if (!type) {
  470. attribs.zIndex = 1;
  471. }
  472. if (old) {
  473. opacity = 0;
  474. }
  475. tick.gridLine = gridLine = renderer.path()
  476. .attr(attribs)
  477. .addClass(
  478. 'highcharts-' + (type ? type + '-' : '') + 'grid-line'
  479. )
  480. .add(axis.gridGroup);
  481. }
  482. if (gridLine) {
  483. gridLinePath = axis.getPlotLinePath(
  484. pos + tickmarkOffset,
  485. gridLine.strokeWidth() * reverseCrisp,
  486. old,
  487. 'pass'
  488. );
  489. // If the parameter 'old' is set, the current call will be followed
  490. // by another call, therefore do not do any animations this time
  491. if (gridLinePath) {
  492. gridLine[old || tick.isNew ? 'attr' : 'animate']({
  493. d: gridLinePath,
  494. opacity: opacity
  495. });
  496. }
  497. }
  498. },
  499. /**
  500. * Renders the tick mark.
  501. *
  502. * @private
  503. *
  504. * @param {Object} xy The position vector of the mark
  505. * @param {number} xy.x The x position of the mark
  506. * @param {number} xy.y The y position of the mark
  507. * @param {number} opacity The opacity of the mark
  508. * @param {number} reverseCrisp Modifier for avoiding overlapping 1 or -1
  509. * @return {undefined}
  510. */
  511. renderMark: function (xy, opacity, reverseCrisp) {
  512. var tick = this,
  513. axis = tick.axis,
  514. options = axis.options,
  515. renderer = axis.chart.renderer,
  516. type = tick.type,
  517. tickPrefix = type ? type + 'Tick' : 'tick',
  518. tickSize = axis.tickSize(tickPrefix),
  519. mark = tick.mark,
  520. isNewMark = !mark,
  521. x = xy.x,
  522. y = xy.y,
  523. tickWidth = pick(
  524. options[tickPrefix + 'Width'],
  525. !type && axis.isXAxis ? 1 : 0
  526. ), // X axis defaults to 1
  527. tickColor = options[tickPrefix + 'Color'];
  528. if (tickSize) {
  529. // negate the length
  530. if (axis.opposite) {
  531. tickSize[0] = -tickSize[0];
  532. }
  533. // First time, create it
  534. if (isNewMark) {
  535. tick.mark = mark = renderer.path()
  536. .addClass('highcharts-' + (type ? type + '-' : '') + 'tick')
  537. .add(axis.axisGroup);
  538. if (!axis.chart.styledMode) {
  539. mark.attr({
  540. stroke: tickColor,
  541. 'stroke-width': tickWidth
  542. });
  543. }
  544. }
  545. mark[isNewMark ? 'attr' : 'animate']({
  546. d: tick.getMarkPath(
  547. x,
  548. y,
  549. tickSize[0],
  550. mark.strokeWidth() * reverseCrisp,
  551. axis.horiz,
  552. renderer
  553. ),
  554. opacity: opacity
  555. });
  556. }
  557. },
  558. /**
  559. * Renders the tick label.
  560. * Note: The label should already be created in init(), so it should only
  561. * have to be moved into place.
  562. *
  563. * @private
  564. *
  565. * @param {Object} xy The position vector of the label
  566. * @param {number} xy.x The x position of the label
  567. * @param {number} xy.y The y position of the label
  568. * @param {Boolean} old Whether or not the tick is old
  569. * @param {number} opacity The opacity of the label
  570. * @param {number} index The index of the tick
  571. * @return {undefined}
  572. */
  573. renderLabel: function (xy, old, opacity, index) {
  574. var tick = this,
  575. axis = tick.axis,
  576. horiz = axis.horiz,
  577. options = axis.options,
  578. label = tick.label,
  579. labelOptions = options.labels,
  580. step = labelOptions.step,
  581. tickmarkOffset = pick(tick.tickmarkOffset, axis.tickmarkOffset),
  582. show = true,
  583. x = xy.x,
  584. y = xy.y;
  585. if (label && isNumber(x)) {
  586. label.xy = xy = tick.getLabelPosition(
  587. x,
  588. y,
  589. label,
  590. horiz,
  591. labelOptions,
  592. tickmarkOffset,
  593. index,
  594. step
  595. );
  596. // Apply show first and show last. If the tick is both first and
  597. // last, it is a single centered tick, in which case we show the
  598. // label anyway (#2100).
  599. if (
  600. (
  601. tick.isFirst &&
  602. !tick.isLast &&
  603. !pick(options.showFirstLabel, 1)
  604. ) ||
  605. (
  606. tick.isLast &&
  607. !tick.isFirst &&
  608. !pick(options.showLastLabel, 1)
  609. )
  610. ) {
  611. show = false;
  612. // Handle label overflow and show or hide accordingly
  613. } else if (
  614. horiz &&
  615. !labelOptions.step &&
  616. !labelOptions.rotation &&
  617. !old &&
  618. opacity !== 0
  619. ) {
  620. tick.handleOverflow(xy);
  621. }
  622. // apply step
  623. if (step && index % step) {
  624. // show those indices dividable by step
  625. show = false;
  626. }
  627. // Set the new position, and show or hide
  628. if (show && isNumber(xy.y)) {
  629. xy.opacity = opacity;
  630. label[tick.isNewLabel ? 'attr' : 'animate'](xy);
  631. tick.isNewLabel = false;
  632. } else {
  633. label.attr('y', -9999); // #1338
  634. tick.isNewLabel = true;
  635. }
  636. }
  637. },
  638. /**
  639. * Put everything in place
  640. *
  641. * @private
  642. *
  643. * @param index {Number}
  644. * @param old {Boolean} Use old coordinates to prepare an animation into new
  645. * position
  646. */
  647. render: function (index, old, opacity) {
  648. var tick = this,
  649. axis = tick.axis,
  650. horiz = axis.horiz,
  651. pos = tick.pos,
  652. tickmarkOffset = pick(tick.tickmarkOffset, axis.tickmarkOffset),
  653. xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
  654. x = xy.x,
  655. y = xy.y,
  656. reverseCrisp = ((horiz && x === axis.pos + axis.len) ||
  657. (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
  658. opacity = pick(opacity, 1);
  659. this.isActive = true;
  660. // Create the grid line
  661. this.renderGridLine(old, opacity, reverseCrisp);
  662. // create the tick mark
  663. this.renderMark(xy, opacity, reverseCrisp);
  664. // the label is created on init - now move it into place
  665. this.renderLabel(xy, old, opacity, index);
  666. tick.isNew = false;
  667. H.fireEvent(this, 'afterRender');
  668. },
  669. /**
  670. * Destructor for the tick prototype
  671. *
  672. * @private
  673. * @function Highcharts.Tick#destroy
  674. */
  675. destroy: function () {
  676. destroyObjectProperties(this, this.axis);
  677. }
  678. };