timeline.src.js 22 KB

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