TimelineSeries.js 23 KB

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