TimelineSeries.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. /* *
  2. *
  3. * Timeline Series.
  4. *
  5. * (c) 2010-2020 Highsoft AS
  6. *
  7. * Author: Daniel Studencki
  8. *
  9. * License: www.highcharts.com/license
  10. *
  11. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  12. *
  13. * */
  14. import BaseSeries from '../Core/Series/Series.js';
  15. var seriesTypes = BaseSeries.seriesTypes;
  16. import H from '../Core/Globals.js';
  17. import LegendSymbolMixin from '../Mixins/LegendSymbol.js';
  18. import Point from '../Core/Series/Point.js';
  19. import SVGElement from '../Core/Renderer/SVG/SVGElement.js';
  20. import U from '../Core/Utilities.js';
  21. var addEvent = U.addEvent, arrayMax = U.arrayMax, arrayMin = U.arrayMin, defined = U.defined, isNumber = U.isNumber, merge = U.merge, objectEach = U.objectEach, pick = U.pick;
  22. import '../Series/LineSeries.js';
  23. var TrackerMixin = H.TrackerMixin, Series = H.Series;
  24. /**
  25. * Callback JavaScript function to format the data label as a string. Note that
  26. * if a `format` is defined, the format takes precedence and the formatter is
  27. * ignored.
  28. *
  29. * @callback Highcharts.TimelineDataLabelsFormatterCallbackFunction
  30. *
  31. * @param {Highcharts.PointLabelObject|Highcharts.TimelineDataLabelsFormatterContextObject} this
  32. * Data label context to format
  33. *
  34. * @return {number|string|null|undefined}
  35. * Formatted data label text
  36. */
  37. /**
  38. * @interface Highcharts.TimelineDataLabelsFormatterContextObject
  39. * @extends Highcharts.PointLabelObject
  40. */ /**
  41. * @name Highcharts.TimelineDataLabelsFormatterContextObject#key
  42. * @type {string|undefined}
  43. */ /**
  44. * @name Highcharts.TimelineDataLabelsFormatterContextObject#point
  45. * @type {Highcharts.Point}
  46. */ /**
  47. * @name Highcharts.TimelineDataLabelsFormatterContextObject#series
  48. * @type {Highcharts.Series}
  49. */
  50. ''; // dettach doclets above
  51. /**
  52. * The timeline series type.
  53. *
  54. * @private
  55. * @class
  56. * @name Highcharts.seriesTypes.timeline
  57. *
  58. * @augments Highcharts.Series
  59. */
  60. BaseSeries.seriesType('timeline', 'line',
  61. /**
  62. * The timeline series presents given events along a drawn line.
  63. *
  64. * @sample highcharts/series-timeline/alternate-labels
  65. * Timeline series
  66. * @sample highcharts/series-timeline/inverted
  67. * Inverted timeline
  68. * @sample highcharts/series-timeline/datetime-axis
  69. * With true datetime axis
  70. *
  71. * @extends plotOptions.line
  72. * @since 7.0.0
  73. * @product highcharts
  74. * @excluding animationLimit, boostThreshold, connectEnds, connectNulls,
  75. * cropThreshold, dashStyle, findNearestPointBy,
  76. * getExtremesFromAll, lineWidth, negativeColor,
  77. * pointInterval, pointIntervalUnit, pointPlacement,
  78. * pointStart, softThreshold, stacking, step, threshold,
  79. * turboThreshold, zoneAxis, zones, dataSorting,
  80. * boostBlending
  81. * @requires modules/timeline
  82. * @optionparent plotOptions.timeline
  83. */
  84. {
  85. colorByPoint: true,
  86. stickyTracking: false,
  87. ignoreHiddenPoint: true,
  88. legendType: 'point',
  89. lineWidth: 4,
  90. tooltip: {
  91. headerFormat: '<span style="color:{point.color}">\u25CF</span> ' +
  92. '<span style="font-size: 10px"> {point.key}</span><br/>',
  93. pointFormat: '{point.description}'
  94. },
  95. states: {
  96. hover: {
  97. lineWidthPlus: 0
  98. }
  99. },
  100. /**
  101. * @declare Highcharts.TimelineDataLabelsOptionsObject
  102. *
  103. * @private
  104. */
  105. dataLabels: {
  106. enabled: true,
  107. allowOverlap: true,
  108. /**
  109. * Whether to position data labels alternately. For example, if
  110. * [distance](#plotOptions.timeline.dataLabels.distance)
  111. * is set equal to `100`, then data labels will be positioned
  112. * alternately (on both sides of the point) at a distance of 100px.
  113. *
  114. * @sample {highcharts} highcharts/series-timeline/alternate-disabled
  115. * Alternate disabled
  116. */
  117. alternate: true,
  118. backgroundColor: '#ffffff',
  119. borderWidth: 1,
  120. borderColor: '#999999',
  121. borderRadius: 3,
  122. color: '#333333',
  123. /**
  124. * The color of the line connecting the data label to the point.
  125. * The default color is the same as the point's color.
  126. *
  127. * In styled mode, the connector stroke is given in the
  128. * `.highcharts-data-label-connector` class.
  129. *
  130. * @sample {highcharts} highcharts/series-timeline/connector-styles
  131. * Custom connector width and color
  132. *
  133. * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
  134. * @apioption plotOptions.timeline.dataLabels.connectorColor
  135. */
  136. /**
  137. * The width of the line connecting the data label to the point.
  138. *
  139. * In styled mode, the connector stroke width is given in the
  140. * `.highcharts-data-label-connector` class.
  141. *
  142. * @sample {highcharts} highcharts/series-timeline/connector-styles
  143. * Custom connector width and color
  144. */
  145. connectorWidth: 1,
  146. /**
  147. * A pixel value defining the distance between the data label and
  148. * the point. Negative numbers puts the label on top of the point.
  149. */
  150. distance: 100,
  151. // eslint-disable-next-line valid-jsdoc
  152. /**
  153. * @type {Highcharts.TimelineDataLabelsFormatterCallbackFunction}
  154. * @default function () {
  155. * var format;
  156. *
  157. * if (!this.series.chart.styledMode) {
  158. * format = '<span style="color:' + this.point.color +
  159. * '">● </span>';
  160. * } else {
  161. * format = '<span>● </span>';
  162. * }
  163. * format += '<span>' + (this.key || '') + '</span><br/>' +
  164. * (this.point.label || '');
  165. * return format;
  166. * }
  167. */
  168. formatter: function () {
  169. var format;
  170. if (!this.series.chart.styledMode) {
  171. format = '<span style="color:' + this.point.color +
  172. '">● </span>';
  173. }
  174. else {
  175. format = '<span>● </span>';
  176. }
  177. format += '<span class="highcharts-strong">' +
  178. (this.key || '') + '</span><br/>' +
  179. (this.point.label || '');
  180. return format;
  181. },
  182. style: {
  183. /** @internal */
  184. textOutline: 'none',
  185. /** @internal */
  186. fontWeight: 'normal',
  187. /** @internal */
  188. fontSize: '12px'
  189. },
  190. /**
  191. * Shadow options for the data label.
  192. *
  193. * @type {boolean|Highcharts.CSSObject}
  194. */
  195. shadow: false,
  196. /**
  197. * @type {number}
  198. * @apioption plotOptions.timeline.dataLabels.width
  199. */
  200. verticalAlign: 'middle'
  201. },
  202. marker: {
  203. enabledThreshold: 0,
  204. symbol: 'square',
  205. radius: 6,
  206. lineWidth: 2,
  207. height: 15
  208. },
  209. showInLegend: false,
  210. colorKey: 'x'
  211. },
  212. /**
  213. * @lends Highcharts.Series#
  214. */
  215. {
  216. trackerGroups: ['markerGroup', 'dataLabelsGroup'],
  217. // Use a simple symbol from LegendSymbolMixin
  218. drawLegendSymbol: LegendSymbolMixin.drawRectangle,
  219. // Use a group of trackers from TrackerMixin
  220. drawTracker: TrackerMixin.drawTrackerPoint,
  221. init: function () {
  222. var series = this;
  223. Series.prototype.init.apply(series, arguments);
  224. addEvent(series, 'afterTranslate', function () {
  225. var lastPlotX, closestPointRangePx = Number.MAX_VALUE;
  226. series.points.forEach(function (point) {
  227. // Set the isInside parameter basing also on the real point
  228. // visibility, in order to avoid showing hidden points
  229. // in drawPoints method.
  230. point.isInside = point.isInside && point.visible;
  231. // New way of calculating closestPointRangePx value, which
  232. // respects the real point visibility is needed.
  233. if (point.visible && !point.isNull) {
  234. if (defined(lastPlotX)) {
  235. closestPointRangePx = Math.min(closestPointRangePx, Math.abs(point.plotX - lastPlotX));
  236. }
  237. lastPlotX = point.plotX;
  238. }
  239. });
  240. series.closestPointRangePx = closestPointRangePx;
  241. });
  242. // Distribute data labels before rendering them. Distribution is
  243. // based on the 'dataLabels.distance' and 'dataLabels.alternate'
  244. // property.
  245. addEvent(series, 'drawDataLabels', function () {
  246. // Distribute data labels basing on defined algorithm.
  247. series.distributeDL(); // @todo use this scope for series
  248. });
  249. addEvent(series, 'afterDrawDataLabels', function () {
  250. var dataLabel; // @todo use this scope for series
  251. // Draw or align connector for each point.
  252. series.points.forEach(function (point) {
  253. dataLabel = point.dataLabel;
  254. if (dataLabel) {
  255. // Within this wrap method is necessary to save the
  256. // current animation params, because the data label
  257. // target position (after animation) is needed to align
  258. // connectors.
  259. dataLabel.animate = function (params) {
  260. if (this.targetPosition) {
  261. this.targetPosition = params;
  262. }
  263. return SVGElement.prototype.animate.apply(this, arguments);
  264. };
  265. // Initialize the targetPosition field within data label
  266. // object. It's necessary because there is need to know
  267. // expected position of specific data label, when
  268. // aligning connectors. This field is overrided inside
  269. // of SVGElement.animate() wrapped method.
  270. if (!dataLabel.targetPosition) {
  271. dataLabel.targetPosition = {};
  272. }
  273. return point.drawConnector();
  274. }
  275. });
  276. });
  277. addEvent(series.chart, 'afterHideOverlappingLabel', function () {
  278. series.points.forEach(function (p) {
  279. if (p.connector &&
  280. p.dataLabel &&
  281. p.dataLabel.oldOpacity !== p.dataLabel.newOpacity) {
  282. p.alignConnector();
  283. }
  284. });
  285. });
  286. },
  287. alignDataLabel: function (point, dataLabel, options, alignTo) {
  288. var series = this, isInverted = series.chart.inverted, visiblePoints = series.visibilityMap.filter(function (point) {
  289. return point;
  290. }), visiblePointsCount = series.visiblePointsCount, pointIndex = visiblePoints.indexOf(point), isFirstOrLast = (!pointIndex || pointIndex === visiblePointsCount - 1), dataLabelsOptions = series.options.dataLabels, userDLOptions = point.userDLOptions || {},
  291. // Define multiplier which is used to calculate data label
  292. // width. If data labels are alternate, they have two times more
  293. // space to adapt (excepting first and last ones, which has only
  294. // one and half), than in case of placing all data labels side
  295. // by side.
  296. multiplier = dataLabelsOptions.alternate ?
  297. (isFirstOrLast ? 1.5 : 2) :
  298. 1, distance, availableSpace = Math.floor(series.xAxis.len / visiblePointsCount), pad = dataLabel.padding, targetDLWidth, styles;
  299. // Adjust data label width to the currently available space.
  300. if (point.visible) {
  301. distance = Math.abs(userDLOptions.x || point.options.dataLabels.x);
  302. if (isInverted) {
  303. targetDLWidth = ((distance - pad) * 2 - (point.itemHeight / 2));
  304. styles = {
  305. width: targetDLWidth + 'px',
  306. // Apply ellipsis when data label height is exceeded.
  307. textOverflow: dataLabel.width / targetDLWidth *
  308. dataLabel.height / 2 > availableSpace * multiplier ?
  309. 'ellipsis' : 'none'
  310. };
  311. }
  312. else {
  313. styles = {
  314. width: (userDLOptions.width ||
  315. dataLabelsOptions.width ||
  316. availableSpace * multiplier - (pad * 2)) + 'px'
  317. };
  318. }
  319. dataLabel.css(styles);
  320. if (!series.chart.styledMode) {
  321. dataLabel.shadow(dataLabelsOptions.shadow);
  322. }
  323. }
  324. Series.prototype.alignDataLabel.apply(series, arguments);
  325. },
  326. processData: function () {
  327. var series = this, visiblePoints = 0, i;
  328. series.visibilityMap = series.getVisibilityMap();
  329. // Calculate currently visible points.
  330. series.visibilityMap.forEach(function (point) {
  331. if (point) {
  332. visiblePoints++;
  333. }
  334. });
  335. series.visiblePointsCount = visiblePoints;
  336. for (i = 0; i < series.xData.length; i++) {
  337. series.yData[i] = 1;
  338. }
  339. Series.prototype.processData.call(this, arguments);
  340. return;
  341. },
  342. getXExtremes: function (xData) {
  343. var series = this, filteredData = xData.filter(function (x, i) {
  344. return series.points[i].isValid() &&
  345. series.points[i].visible;
  346. });
  347. return {
  348. min: arrayMin(filteredData),
  349. max: arrayMax(filteredData)
  350. };
  351. },
  352. generatePoints: function () {
  353. var series = this;
  354. Series.prototype.generatePoints.apply(series);
  355. series.points.forEach(function (point, i) {
  356. point.applyOptions({
  357. x: series.xData[i]
  358. }, series.xData[i]);
  359. });
  360. },
  361. getVisibilityMap: function () {
  362. var series = this, map = (series.data.length ?
  363. series.data : series.userOptions.data).map(function (point) {
  364. return (point &&
  365. point.visible !== false &&
  366. !point.isNull) ? point : false;
  367. });
  368. return map;
  369. },
  370. distributeDL: function () {
  371. var series = this, dataLabelsOptions = series.options.dataLabels, options, pointDLOptions, newOptions = {}, visibilityIndex = 1, distance = dataLabelsOptions.distance;
  372. series.points.forEach(function (point) {
  373. if (point.visible && !point.isNull) {
  374. options = point.options;
  375. pointDLOptions = point.options.dataLabels;
  376. if (!series.hasRendered) {
  377. point.userDLOptions =
  378. merge({}, pointDLOptions);
  379. }
  380. newOptions[series.chart.inverted ? 'x' : 'y'] =
  381. dataLabelsOptions.alternate && visibilityIndex % 2 ?
  382. -distance : distance;
  383. options.dataLabels = merge(newOptions, point.userDLOptions);
  384. visibilityIndex++;
  385. }
  386. });
  387. },
  388. markerAttribs: function (point, state) {
  389. var series = this, seriesMarkerOptions = series.options.marker, seriesStateOptions, pointMarkerOptions = point.marker || {}, symbol = (pointMarkerOptions.symbol || seriesMarkerOptions.symbol), pointStateOptions, width = pick(pointMarkerOptions.width, seriesMarkerOptions.width, series.closestPointRangePx), height = pick(pointMarkerOptions.height, seriesMarkerOptions.height), radius = 0, attribs;
  390. // Call default markerAttribs method, when the xAxis type
  391. // is set to datetime.
  392. if (series.xAxis.dateTime) {
  393. return seriesTypes.line.prototype.markerAttribs
  394. .call(this, point, state);
  395. }
  396. // Handle hover and select states
  397. if (state) {
  398. seriesStateOptions =
  399. seriesMarkerOptions.states[state] || {};
  400. pointStateOptions = pointMarkerOptions.states &&
  401. pointMarkerOptions.states[state] || {};
  402. radius = pick(pointStateOptions.radius, seriesStateOptions.radius, radius + (seriesStateOptions.radiusPlus || 0));
  403. }
  404. point.hasImage = (symbol && symbol.indexOf('url') === 0);
  405. attribs = {
  406. x: Math.floor(point.plotX) - (width / 2) - (radius / 2),
  407. y: point.plotY - (height / 2) - (radius / 2),
  408. width: width + radius,
  409. height: height + radius
  410. };
  411. return attribs;
  412. },
  413. bindAxes: function () {
  414. var series = this;
  415. Series.prototype.bindAxes.call(series);
  416. ['xAxis', 'yAxis'].forEach(function (axis) {
  417. // Initially set the linked xAxis type to category.
  418. if (axis === 'xAxis' && !series[axis].userOptions.type) {
  419. series[axis].categories = series[axis].hasNames = true;
  420. }
  421. });
  422. }
  423. },
  424. /**
  425. * @lends Highcharts.Point#
  426. */
  427. {
  428. init: function () {
  429. var point = Point.prototype.init.apply(this, arguments);
  430. point.name = pick(point.name, 'Event');
  431. point.y = 1;
  432. return point;
  433. },
  434. isValid: function () {
  435. return this.options.y !== null;
  436. },
  437. setVisible: function (vis, redraw) {
  438. var point = this, series = point.series;
  439. redraw = pick(redraw, series.options.ignoreHiddenPoint);
  440. seriesTypes.pie.prototype.pointClass.prototype
  441. .setVisible.call(point, vis, false);
  442. // Process new data
  443. series.processData();
  444. if (redraw) {
  445. series.chart.redraw();
  446. }
  447. },
  448. setState: function () {
  449. var proceed = Series.prototype.pointClass.prototype.setState;
  450. // Prevent triggering the setState method on null points.
  451. if (!this.isNull) {
  452. proceed.apply(this, arguments);
  453. }
  454. },
  455. getConnectorPath: function () {
  456. var point = this, chart = point.series.chart, xAxisLen = point.series.xAxis.len, inverted = chart.inverted, direction = inverted ? 'x2' : 'y2', dl = point.dataLabel, targetDLPos = dl.targetPosition, coords = {
  457. x1: point.plotX,
  458. y1: point.plotY,
  459. x2: point.plotX,
  460. y2: isNumber(targetDLPos.y) ? targetDLPos.y : dl.y
  461. }, negativeDistance = ((dl.alignAttr || dl)[direction[0]] <
  462. point.series.yAxis.len / 2), path;
  463. // Recalculate coords when the chart is inverted.
  464. if (inverted) {
  465. coords = {
  466. x1: point.plotY,
  467. y1: xAxisLen - point.plotX,
  468. x2: targetDLPos.x || dl.x,
  469. y2: xAxisLen - point.plotX
  470. };
  471. }
  472. // Subtract data label width or height from expected coordinate so
  473. // that the connector would start from the appropriate edge.
  474. if (negativeDistance) {
  475. coords[direction] += dl[inverted ? 'width' : 'height'];
  476. }
  477. // Change coordinates so that they will be relative to data label.
  478. objectEach(coords, function (_coord, i) {
  479. coords[i] -= (dl.alignAttr || dl)[i[0]];
  480. });
  481. path = chart.renderer.crispLine([
  482. ['M', coords.x1, coords.y1],
  483. ['L', coords.x2, coords.y2]
  484. ], dl.options.connectorWidth);
  485. return path;
  486. },
  487. drawConnector: function () {
  488. var point = this, series = point.series;
  489. if (!point.connector) {
  490. point.connector = series.chart.renderer
  491. .path(point.getConnectorPath())
  492. .attr({
  493. zIndex: -1
  494. })
  495. .add(point.dataLabel);
  496. }
  497. if (point.series.chart.isInsidePlot(// #10507
  498. point.dataLabel.x, point.dataLabel.y)) {
  499. point.alignConnector();
  500. }
  501. },
  502. alignConnector: function () {
  503. var point = this, series = point.series, connector = point.connector, dl = point.dataLabel, dlOptions = point.dataLabel.options = merge(series.options.dataLabels, point.options.dataLabels), chart = point.series.chart, bBox = connector.getBBox(), plotPos = {
  504. x: bBox.x + dl.translateX,
  505. y: bBox.y + dl.translateY
  506. }, isVisible;
  507. // Include a half of connector width in order to run animation,
  508. // when connectors are aligned to the plot area edge.
  509. if (chart.inverted) {
  510. plotPos.y -= dl.options.connectorWidth / 2;
  511. }
  512. else {
  513. plotPos.x += dl.options.connectorWidth / 2;
  514. }
  515. isVisible = chart.isInsidePlot(plotPos.x, plotPos.y);
  516. connector[isVisible ? 'animate' : 'attr']({
  517. d: point.getConnectorPath()
  518. });
  519. if (!series.chart.styledMode) {
  520. connector.attr({
  521. stroke: dlOptions.connectorColor || point.color,
  522. 'stroke-width': dlOptions.connectorWidth,
  523. opacity: dl[defined(dl.newOpacity) ? 'newOpacity' : 'opacity']
  524. });
  525. }
  526. }
  527. });
  528. /**
  529. * The `timeline` series. If the [type](#series.timeline.type) option is
  530. * not specified, it is inherited from [chart.type](#chart.type).
  531. *
  532. * @extends series,plotOptions.timeline
  533. * @excluding animationLimit, boostThreshold, connectEnds, connectNulls,
  534. * cropThreshold, dashStyle, dataParser, dataURL, findNearestPointBy,
  535. * getExtremesFromAll, lineWidth, negativeColor,
  536. * pointInterval, pointIntervalUnit, pointPlacement, pointStart,
  537. * softThreshold, stacking, stack, step, threshold, turboThreshold,
  538. * zoneAxis, zones, dataSorting, boostBlending
  539. * @product highcharts
  540. * @requires modules/timeline
  541. * @apioption series.timeline
  542. */
  543. /**
  544. * An array of data points for the series. For the `timeline` series type,
  545. * points can be given with three general parameters, `name`, `label`,
  546. * and `description`:
  547. *
  548. * Example:
  549. *
  550. * ```js
  551. * series: [{
  552. * type: 'timeline',
  553. * data: [{
  554. * name: 'Jan 2018',
  555. * label: 'Some event label',
  556. * description: 'Description to show in tooltip'
  557. * }]
  558. * }]
  559. * ```
  560. * If all points additionally have the `x` values, and xAxis type is set to
  561. * `datetime`, then events are laid out on a true time axis, where their
  562. * placement reflects the actual time between them.
  563. *
  564. * @sample {highcharts} highcharts/series-timeline/alternate-labels
  565. * Alternate labels
  566. * @sample {highcharts} highcharts/series-timeline/datetime-axis
  567. * Real time intervals
  568. *
  569. * @type {Array<*>}
  570. * @extends series.line.data
  571. * @excluding marker, y
  572. * @product highcharts
  573. * @apioption series.timeline.data
  574. */
  575. /**
  576. * The name of event.
  577. *
  578. * @type {string}
  579. * @product highcharts
  580. * @apioption series.timeline.data.name
  581. */
  582. /**
  583. * The label of event.
  584. *
  585. * @type {string}
  586. * @product highcharts
  587. * @apioption series.timeline.data.label
  588. */
  589. /**
  590. * The description of event. This description will be shown in tooltip.
  591. *
  592. * @type {string}
  593. * @product highcharts
  594. * @apioption series.timeline.data.description
  595. */
  596. ''; // adds doclets above to transpiled file