timeline.src.js 22 KB

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