series-label.src.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. /**
  2. * @license Highcharts JS v9.0.1 (2021-02-16)
  3. *
  4. * (c) 2009-2021 Torstein Honsi
  5. *
  6. * License: www.highcharts.com/license
  7. */
  8. 'use strict';
  9. (function (factory) {
  10. if (typeof module === 'object' && module.exports) {
  11. factory['default'] = factory;
  12. module.exports = factory;
  13. } else if (typeof define === 'function' && define.amd) {
  14. define('highcharts/modules/series-label', ['highcharts'], function (Highcharts) {
  15. factory(Highcharts);
  16. factory.Highcharts = Highcharts;
  17. return factory;
  18. });
  19. } else {
  20. factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
  21. }
  22. }(function (Highcharts) {
  23. var _modules = Highcharts ? Highcharts._modules : {};
  24. function _registerModule(obj, path, args, fn) {
  25. if (!obj.hasOwnProperty(path)) {
  26. obj[path] = fn.apply(null, args);
  27. }
  28. }
  29. _registerModule(_modules, 'Extensions/SeriesLabel.js', [_modules['Core/Animation/AnimationUtilities.js'], _modules['Core/Chart/Chart.js'], _modules['Core/Series/Series.js'], _modules['Core/Renderer/SVG/SVGRenderer.js'], _modules['Core/Utilities.js']], function (A, Chart, Series, SVGRenderer, U) {
  30. /* *
  31. *
  32. * (c) 2009-2021 Torstein Honsi
  33. *
  34. * License: www.highcharts.com/license
  35. *
  36. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  37. *
  38. * */
  39. var animObject = A.animObject;
  40. var addEvent = U.addEvent,
  41. extend = U.extend,
  42. fireEvent = U.fireEvent,
  43. format = U.format,
  44. isNumber = U.isNumber,
  45. pick = U.pick,
  46. setOptions = U.setOptions,
  47. syncTimeout = U.syncTimeout;
  48. /**
  49. * Containing the position of a box that should be avoided by labels.
  50. *
  51. * @interface Highcharts.LabelIntersectBoxObject
  52. */ /**
  53. * @name Highcharts.LabelIntersectBoxObject#bottom
  54. * @type {number}
  55. */ /**
  56. * @name Highcharts.LabelIntersectBoxObject#left
  57. * @type {number}
  58. */ /**
  59. * @name Highcharts.LabelIntersectBoxObject#right
  60. * @type {number}
  61. */ /**
  62. * @name Highcharts.LabelIntersectBoxObject#top
  63. * @type {number}
  64. */
  65. /*
  66. * Highcharts module to place labels next to a series in a natural position.
  67. *
  68. * TODO:
  69. * - add column support (box collision detection, boxesToAvoid logic)
  70. * - avoid data labels, when data labels above, show series label below.
  71. * - add more options (connector, format, formatter)
  72. *
  73. * https://jsfiddle.net/highcharts/L2u9rpwr/
  74. * https://jsfiddle.net/highcharts/y5A37/
  75. * https://jsfiddle.net/highcharts/264Nm/
  76. * https://jsfiddle.net/highcharts/y5A37/
  77. */
  78. ''; // detach doclets above
  79. var labelDistance = 3;
  80. setOptions({
  81. /**
  82. * @optionparent plotOptions
  83. *
  84. * @private
  85. */
  86. plotOptions: {
  87. series: {
  88. /**
  89. * Series labels are placed as close to the series as possible in a
  90. * natural way, seeking to avoid other series. The goal of this
  91. * feature is to make the chart more easily readable, like if a
  92. * human designer placed the labels in the optimal position.
  93. *
  94. * The series labels currently work with series types having a
  95. * `graph` or an `area`.
  96. *
  97. * @sample highcharts/series-label/line-chart
  98. * Line chart
  99. * @sample highcharts/demo/streamgraph
  100. * Stream graph
  101. * @sample highcharts/series-label/stock-chart
  102. * Stock chart
  103. *
  104. * @declare Highcharts.SeriesLabelOptionsObject
  105. * @since 6.0.0
  106. * @product highcharts highstock gantt
  107. * @requires modules/series-label
  108. */
  109. label: {
  110. /**
  111. * Enable the series label per series.
  112. */
  113. enabled: true,
  114. /**
  115. * Allow labels to be placed distant to the graph if necessary,
  116. * and draw a connector line to the graph. Setting this option
  117. * to true may decrease the performance significantly, since the
  118. * algorithm with systematically search for open spaces in the
  119. * whole plot area. Visually, it may also result in a more
  120. * cluttered chart, though more of the series will be labeled.
  121. */
  122. connectorAllowed: false,
  123. /**
  124. * If the label is closer than this to a neighbour graph, draw a
  125. * connector.
  126. */
  127. connectorNeighbourDistance: 24,
  128. /**
  129. * A format string for the label, with support for a subset of
  130. * HTML. Variables are enclosed by curly brackets. Available
  131. * variables are `name`, `options.xxx`, `color` and other
  132. * members from the `series` object. Use this option also to set
  133. * a static text for the label.
  134. *
  135. * @type string
  136. * @since 8.1.0
  137. */
  138. format: void 0,
  139. /**
  140. * Callback function to format each of the series' labels. The
  141. * `this` keyword refers to the series object. By default the
  142. * `formatter` is undefined and the `series.name` is rendered.
  143. *
  144. * @type {Highcharts.FormatterCallbackFunction<Series>}
  145. * @since 8.1.0
  146. */
  147. formatter: void 0,
  148. /**
  149. * For area-like series, allow the font size to vary so that
  150. * small areas get a smaller font size. The default applies this
  151. * effect to area-like series but not line-like series.
  152. *
  153. * @type {number|null}
  154. */
  155. minFontSize: null,
  156. /**
  157. * For area-like series, allow the font size to vary so that
  158. * small areas get a smaller font size. The default applies this
  159. * effect to area-like series but not line-like series.
  160. *
  161. * @type {number|null}
  162. */
  163. maxFontSize: null,
  164. /**
  165. * Draw the label on the area of an area series. By default it
  166. * is drawn on the area. Set it to `false` to draw it next to
  167. * the graph instead.
  168. *
  169. * @type {boolean|null}
  170. */
  171. onArea: null,
  172. /**
  173. * Styles for the series label. The color defaults to the series
  174. * color, or a contrast color if `onArea`.
  175. *
  176. * @type {Highcharts.CSSObject}
  177. */
  178. style: {
  179. /** @internal */
  180. fontWeight: 'bold'
  181. },
  182. /**
  183. * An array of boxes to avoid when laying out the labels. Each
  184. * item has a `left`, `right`, `top` and `bottom` property.
  185. *
  186. * @type {Array<Highcharts.LabelIntersectBoxObject>}
  187. */
  188. boxesToAvoid: []
  189. }
  190. }
  191. }
  192. });
  193. /* eslint-disable valid-jsdoc */
  194. /**
  195. * Counter-clockwise, part of the fast line intersection logic.
  196. *
  197. * @private
  198. * @function ccw
  199. */
  200. function ccw(x1, y1, x2, y2, x3, y3) {
  201. var cw = ((y3 - y1) * (x2 - x1)) - ((y2 - y1) * (x3 - x1));
  202. return cw > 0 ? true : !(cw < 0);
  203. }
  204. /**
  205. * Detect if two lines intersect.
  206. *
  207. * @private
  208. * @function intersectLine
  209. */
  210. function intersectLine(x1, y1, x2, y2, x3, y3, x4, y4) {
  211. return ccw(x1, y1, x3, y3, x4, y4) !== ccw(x2, y2, x3, y3, x4, y4) &&
  212. ccw(x1, y1, x2, y2, x3, y3) !== ccw(x1, y1, x2, y2, x4, y4);
  213. }
  214. /**
  215. * Detect if a box intersects with a line.
  216. *
  217. * @private
  218. * @function boxIntersectLine
  219. */
  220. function boxIntersectLine(x, y, w, h, x1, y1, x2, y2) {
  221. return (intersectLine(x, y, x + w, y, x1, y1, x2, y2) || // top of label
  222. intersectLine(x + w, y, x + w, y + h, x1, y1, x2, y2) || // right
  223. intersectLine(x, y + h, x + w, y + h, x1, y1, x2, y2) || // bottom
  224. intersectLine(x, y, x, y + h, x1, y1, x2, y2) // left of label
  225. );
  226. }
  227. /**
  228. * General symbol definition for labels with connector.
  229. *
  230. * @private
  231. * @function Highcharts.SVGRenderer#symbols.connector
  232. */
  233. SVGRenderer.prototype.symbols.connector = function (x, y, w, h, options) {
  234. var anchorX = options && options.anchorX,
  235. anchorY = options && options.anchorY,
  236. path,
  237. yOffset,
  238. lateral = w / 2;
  239. if (isNumber(anchorX) && isNumber(anchorY)) {
  240. path = [['M', anchorX, anchorY]];
  241. // Prefer 45 deg connectors
  242. yOffset = y - anchorY;
  243. if (yOffset < 0) {
  244. yOffset = -h - yOffset;
  245. }
  246. if (yOffset < w) {
  247. lateral = anchorX < x + (w / 2) ? yOffset : w - yOffset;
  248. }
  249. // Anchor below label
  250. if (anchorY > y + h) {
  251. path.push(['L', x + lateral, y + h]);
  252. // Anchor above label
  253. }
  254. else if (anchorY < y) {
  255. path.push(['L', x + lateral, y]);
  256. // Anchor left of label
  257. }
  258. else if (anchorX < x) {
  259. path.push(['L', x, y + h / 2]);
  260. // Anchor right of label
  261. }
  262. else if (anchorX > x + w) {
  263. path.push(['L', x + w, y + h / 2]);
  264. }
  265. }
  266. return path || [];
  267. };
  268. /**
  269. * Points to avoid. In addition to actual data points, the label should avoid
  270. * interpolated positions.
  271. *
  272. * @private
  273. * @function Highcharts.Series#getPointsOnGraph
  274. */
  275. Series.prototype.getPointsOnGraph = function () {
  276. if (!this.xAxis && !this.yAxis) {
  277. return;
  278. }
  279. var distance = 16,
  280. points = this.points,
  281. point,
  282. last,
  283. interpolated = [],
  284. i,
  285. deltaX,
  286. deltaY,
  287. delta,
  288. len,
  289. n,
  290. j,
  291. d,
  292. graph = this.graph || this.area,
  293. node = graph.element,
  294. inverted = this.chart.inverted,
  295. xAxis = this.xAxis,
  296. yAxis = this.yAxis,
  297. paneLeft = inverted ? yAxis.pos : xAxis.pos,
  298. paneTop = inverted ? xAxis.pos : yAxis.pos,
  299. onArea = pick(this.options.label.onArea, !!this.area),
  300. translatedThreshold = yAxis.getThreshold(this.options.threshold),
  301. grid = {};
  302. /**
  303. * Push the point to the interpolated points, but only if that position in
  304. * the grid has not been occupied. As a performance optimization, we divide
  305. * the plot area into a grid and only add one point per series (#9815).
  306. * @private
  307. */
  308. function pushDiscrete(point) {
  309. var cellSize = 8, key = Math.round(point.plotX / cellSize) + ',' +
  310. Math.round(point.plotY / cellSize);
  311. if (!grid[key]) {
  312. grid[key] = 1;
  313. interpolated.push(point);
  314. }
  315. }
  316. // For splines, get the point at length (possible caveat: peaks are not
  317. // correctly detected)
  318. if (this.getPointSpline &&
  319. node.getPointAtLength &&
  320. !onArea &&
  321. // Not performing well on complex series, node.getPointAtLength is too
  322. // heavy (#9815)
  323. points.length < this.chart.plotSizeX / distance) {
  324. // If it is animating towards a path definition, use that briefly, and
  325. // reset
  326. if (graph.toD) {
  327. d = graph.attr('d');
  328. graph.attr({ d: graph.toD });
  329. }
  330. len = node.getTotalLength();
  331. for (i = 0; i < len; i += distance) {
  332. point = node.getPointAtLength(i);
  333. pushDiscrete({
  334. chartX: paneLeft + point.x,
  335. chartY: paneTop + point.y,
  336. plotX: point.x,
  337. plotY: point.y
  338. });
  339. }
  340. if (d) {
  341. graph.attr({ d: d });
  342. }
  343. // Last point
  344. point = points[points.length - 1];
  345. point.chartX = paneLeft + point.plotX;
  346. point.chartY = paneTop + point.plotY;
  347. pushDiscrete(point);
  348. // Interpolate
  349. }
  350. else {
  351. len = points.length;
  352. for (i = 0; i < len; i += 1) {
  353. point = points[i];
  354. last = points[i - 1];
  355. // Absolute coordinates so we can compare different panes
  356. point.chartX = paneLeft + point.plotX;
  357. point.chartY = paneTop + point.plotY;
  358. if (onArea) {
  359. // Vertically centered inside area
  360. point.chartCenterY = paneTop + (point.plotY +
  361. pick(point.yBottom, translatedThreshold)) / 2;
  362. }
  363. // Add interpolated points
  364. if (i > 0) {
  365. deltaX = Math.abs(point.chartX - last.chartX);
  366. deltaY = Math.abs(point.chartY - last.chartY);
  367. delta = Math.max(deltaX, deltaY);
  368. if (delta > distance) {
  369. n = Math.ceil(delta / distance);
  370. for (j = 1; j < n; j += 1) {
  371. pushDiscrete({
  372. chartX: last.chartX +
  373. (point.chartX - last.chartX) *
  374. (j / n),
  375. chartY: last.chartY +
  376. (point.chartY - last.chartY) *
  377. (j / n),
  378. chartCenterY: last.chartCenterY +
  379. (point.chartCenterY -
  380. last.chartCenterY) * (j / n),
  381. plotX: last.plotX +
  382. (point.plotX - last.plotX) *
  383. (j / n),
  384. plotY: last.plotY +
  385. (point.plotY - last.plotY) *
  386. (j / n)
  387. });
  388. }
  389. }
  390. }
  391. // Add the real point in order to find positive and negative peaks
  392. if (isNumber(point.plotY)) {
  393. pushDiscrete(point);
  394. }
  395. }
  396. }
  397. // Get the bounding box so we can do a quick check first if the bounding
  398. // boxes overlap.
  399. /*
  400. interpolated.bBox = node.getBBox();
  401. interpolated.bBox.x += paneLeft;
  402. interpolated.bBox.y += paneTop;
  403. */
  404. return interpolated;
  405. };
  406. /**
  407. * Overridable function to return series-specific font sizes for the labels. By
  408. * default it returns bigger font sizes for series with the greater sum of y
  409. * values.
  410. *
  411. * @private
  412. * @function Highcharts.Series#labelFontSize
  413. */
  414. Series.prototype.labelFontSize = function (minFontSize, maxFontSize) {
  415. return minFontSize + ((this.sum / this.chart.labelSeriesMaxSum) *
  416. (maxFontSize - minFontSize)) + 'px';
  417. };
  418. /**
  419. * Check whether a proposed label position is clear of other elements.
  420. *
  421. * @private
  422. * @function Highcharts.Series#checkClearPoint
  423. */
  424. Series.prototype.checkClearPoint = function (x, y, bBox, checkDistance) {
  425. var distToOthersSquared = Number.MAX_VALUE, // distance to other graphs
  426. distToPointSquared = Number.MAX_VALUE,
  427. dist,
  428. connectorPoint,
  429. onArea = pick(this.options.label.onArea, !!this.area),
  430. findDistanceToOthers = (onArea || this.options.label.connectorAllowed),
  431. chart = this.chart,
  432. series,
  433. points,
  434. leastDistance = 16,
  435. withinRange,
  436. xDist,
  437. yDist,
  438. i,
  439. j;
  440. /**
  441. * @private
  442. */
  443. function intersectRect(r1, r2) {
  444. return !(r2.left > r1.right ||
  445. r2.right < r1.left ||
  446. r2.top > r1.bottom ||
  447. r2.bottom < r1.top);
  448. }
  449. /**
  450. * Get the weight in order to determine the ideal position. Larger distance
  451. * to other series gives more weight. Smaller distance to the actual point
  452. * (connector points only) gives more weight.
  453. * @private
  454. */
  455. function getWeight(distToOthersSquared, distToPointSquared) {
  456. return distToOthersSquared - distToPointSquared;
  457. }
  458. // First check for collision with existing labels
  459. for (i = 0; i < chart.boxesToAvoid.length; i += 1) {
  460. if (intersectRect(chart.boxesToAvoid[i], {
  461. left: x,
  462. right: x + bBox.width,
  463. top: y,
  464. bottom: y + bBox.height
  465. })) {
  466. return false;
  467. }
  468. }
  469. // For each position, check if the lines around the label intersect with any
  470. // of the graphs.
  471. for (i = 0; i < chart.series.length; i += 1) {
  472. series = chart.series[i];
  473. points = series.interpolatedPoints;
  474. if (series.visible && points) {
  475. for (j = 1; j < points.length; j += 1) {
  476. if (
  477. // To avoid processing, only check intersection if the X
  478. // values are close to the box.
  479. points[j].chartX >= x - leastDistance &&
  480. points[j - 1].chartX <= x + bBox.width +
  481. leastDistance
  482. /* @todo condition above is not the same as below
  483. (
  484. (points[j].chartX as any) >=
  485. (x - leastDistance)
  486. ) && (
  487. (points[j - 1].chartX as any) <=
  488. (x + bBox.width + leastDistance)
  489. ) */
  490. ) {
  491. // If any of the box sides intersect with the line, return.
  492. if (boxIntersectLine(x, y, bBox.width, bBox.height, points[j - 1].chartX, points[j - 1].chartY, points[j].chartX, points[j].chartY)) {
  493. return false;
  494. }
  495. // But if it is too far away (a padded box doesn't
  496. // intersect), also return.
  497. if (this === series && !withinRange && checkDistance) {
  498. withinRange = boxIntersectLine(x - leastDistance, y - leastDistance, bBox.width + 2 * leastDistance, bBox.height + 2 * leastDistance, points[j - 1].chartX, points[j - 1].chartY, points[j].chartX, points[j].chartY);
  499. }
  500. }
  501. // Find the squared distance from the center of the label. On
  502. // area series, avoid its own graph.
  503. if ((findDistanceToOthers || withinRange) &&
  504. (this !== series || onArea)) {
  505. xDist = x + bBox.width / 2 - points[j].chartX;
  506. yDist = y + bBox.height / 2 - points[j].chartY;
  507. distToOthersSquared = Math.min(distToOthersSquared, xDist * xDist + yDist * yDist);
  508. }
  509. }
  510. // Do we need a connector?
  511. if (!onArea &&
  512. findDistanceToOthers &&
  513. this === series &&
  514. ((checkDistance && !withinRange) ||
  515. distToOthersSquared < Math.pow(this.options.label.connectorNeighbourDistance, 2))) {
  516. for (j = 1; j < points.length; j += 1) {
  517. dist = Math.min((Math.pow(x + bBox.width / 2 - points[j].chartX, 2) +
  518. Math.pow(y + bBox.height / 2 - points[j].chartY, 2)), (Math.pow(x - points[j].chartX, 2) +
  519. Math.pow(y - points[j].chartY, 2)), (Math.pow(x + bBox.width - points[j].chartX, 2) +
  520. Math.pow(y - points[j].chartY, 2)), (Math.pow(x + bBox.width - points[j].chartX, 2) +
  521. Math.pow(y + bBox.height - points[j].chartY, 2)), (Math.pow(x - points[j].chartX, 2) +
  522. Math.pow(y + bBox.height - points[j].chartY, 2)));
  523. if (dist < distToPointSquared) {
  524. distToPointSquared = dist;
  525. connectorPoint = points[j];
  526. }
  527. }
  528. withinRange = true;
  529. }
  530. }
  531. }
  532. return !checkDistance || withinRange ? {
  533. x: x,
  534. y: y,
  535. weight: getWeight(distToOthersSquared, connectorPoint ? distToPointSquared : 0),
  536. connectorPoint: connectorPoint
  537. } : false;
  538. };
  539. /**
  540. * The main initialize method that runs on chart level after initialization and
  541. * redraw. It runs in a timeout to prevent locking, and loops over all series,
  542. * taking all series and labels into account when placing the labels.
  543. *
  544. * @private
  545. * @function Highcharts.Chart#drawSeriesLabels
  546. */
  547. Chart.prototype.drawSeriesLabels = function () {
  548. // console.time('drawSeriesLabels');
  549. var chart = this,
  550. labelSeries = this.labelSeries;
  551. chart.boxesToAvoid = [];
  552. // Build the interpolated points
  553. labelSeries.forEach(function (series) {
  554. series.interpolatedPoints = series.getPointsOnGraph();
  555. (series.options.label.boxesToAvoid || []).forEach(function (box) {
  556. chart.boxesToAvoid.push(box);
  557. });
  558. });
  559. chart.series.forEach(function (series) {
  560. var labelOptions = series.options.label;
  561. if (!labelOptions || (!series.xAxis && !series.yAxis)) {
  562. return;
  563. }
  564. var bBox, x, y, results = [], clearPoint, i, best, inverted = chart.inverted, paneLeft = (inverted ? series.yAxis.pos : series.xAxis.pos), paneTop = (inverted ? series.xAxis.pos : series.yAxis.pos), paneWidth = chart.inverted ? series.yAxis.len : series.xAxis.len, paneHeight = chart.inverted ? series.xAxis.len : series.yAxis.len, points = series.interpolatedPoints, onArea = pick(labelOptions.onArea, !!series.area), label = series.labelBySeries, isNew = !label, minFontSize = labelOptions.minFontSize, maxFontSize = labelOptions.maxFontSize, dataExtremes, areaMin, areaMax, colorClass = 'highcharts-color-' + pick(series.colorIndex, 'none');
  565. // Stay within the area data bounds (#10038)
  566. if (onArea && !inverted) {
  567. dataExtremes = [
  568. series.xAxis.toPixels(series.xData[0]),
  569. series.xAxis.toPixels(series.xData[series.xData.length - 1])
  570. ];
  571. areaMin = Math.min.apply(Math, dataExtremes);
  572. areaMax = Math.max.apply(Math, dataExtremes);
  573. }
  574. /**
  575. * @private
  576. */
  577. function insidePane(x, y, bBox) {
  578. var leftBound = Math.max(paneLeft,
  579. pick(areaMin, -Infinity)),
  580. rightBound = Math.min(paneLeft + paneWidth,
  581. pick(areaMax,
  582. Infinity));
  583. return (x > leftBound &&
  584. x <= rightBound - bBox.width &&
  585. y >= paneTop &&
  586. y <= paneTop + paneHeight - bBox.height);
  587. }
  588. /**
  589. * @private
  590. */
  591. function destroyLabel() {
  592. if (label) {
  593. series.labelBySeries = label.destroy();
  594. }
  595. }
  596. if (series.visible && !series.isSeriesBoosting && points) {
  597. if (!label) {
  598. var labelText = series.name;
  599. if (typeof labelOptions.format === 'string') {
  600. labelText = format(labelOptions.format, series, chart);
  601. }
  602. else if (labelOptions.formatter) {
  603. labelText = labelOptions.formatter.call(series);
  604. }
  605. series.labelBySeries = label = chart.renderer
  606. .label(labelText, 0, -9999, 'connector')
  607. .addClass('highcharts-series-label ' +
  608. 'highcharts-series-label-' + series.index + ' ' +
  609. (series.options.className || '') + ' ' +
  610. colorClass);
  611. if (!chart.renderer.styledMode) {
  612. label.css(extend({
  613. color: onArea ?
  614. chart.renderer.getContrast(series.color) :
  615. series.color
  616. }, labelOptions.style || {}));
  617. label.attr({
  618. opacity: chart.renderer.forExport ? 1 : 0,
  619. stroke: series.color,
  620. 'stroke-width': 1
  621. });
  622. }
  623. // Adapt label sizes to the sum of the data
  624. if (minFontSize && maxFontSize) {
  625. label.css({
  626. fontSize: series.labelFontSize(minFontSize, maxFontSize)
  627. });
  628. }
  629. label
  630. .attr({
  631. padding: 0,
  632. zIndex: 3
  633. })
  634. .add();
  635. }
  636. bBox = label.getBBox();
  637. bBox.width = Math.round(bBox.width);
  638. // Ideal positions are centered above or below a point on right side
  639. // of chart
  640. for (i = points.length - 1; i > 0; i -= 1) {
  641. if (onArea) {
  642. // Centered
  643. x = points[i].chartX - bBox.width / 2;
  644. y = points[i].chartCenterY - bBox.height / 2;
  645. if (insidePane(x, y, bBox)) {
  646. best = series.checkClearPoint(x, y, bBox);
  647. }
  648. if (best) {
  649. results.push(best);
  650. }
  651. }
  652. else {
  653. // Right - up
  654. x = points[i].chartX + labelDistance;
  655. y = points[i].chartY - bBox.height - labelDistance;
  656. if (insidePane(x, y, bBox)) {
  657. best = series.checkClearPoint(x, y, bBox, true);
  658. }
  659. if (best) {
  660. results.push(best);
  661. }
  662. // Right - down
  663. x = points[i].chartX + labelDistance;
  664. y = points[i].chartY + labelDistance;
  665. if (insidePane(x, y, bBox)) {
  666. best = series.checkClearPoint(x, y, bBox, true);
  667. }
  668. if (best) {
  669. results.push(best);
  670. }
  671. // Left - down
  672. x = points[i].chartX - bBox.width - labelDistance;
  673. y = points[i].chartY + labelDistance;
  674. if (insidePane(x, y, bBox)) {
  675. best = series.checkClearPoint(x, y, bBox, true);
  676. }
  677. if (best) {
  678. results.push(best);
  679. }
  680. // Left - up
  681. x = points[i].chartX - bBox.width - labelDistance;
  682. y = points[i].chartY - bBox.height - labelDistance;
  683. if (insidePane(x, y, bBox)) {
  684. best = series.checkClearPoint(x, y, bBox, true);
  685. }
  686. if (best) {
  687. results.push(best);
  688. }
  689. }
  690. }
  691. // Brute force, try all positions on the chart in a 16x16 grid
  692. if (labelOptions.connectorAllowed && !results.length && !onArea) {
  693. for (x = paneLeft + paneWidth - bBox.width; x >= paneLeft; x -= 16) {
  694. for (y = paneTop; y < paneTop + paneHeight - bBox.height; y += 16) {
  695. clearPoint = series.checkClearPoint(x, y, bBox, true);
  696. if (clearPoint) {
  697. results.push(clearPoint);
  698. }
  699. }
  700. }
  701. }
  702. if (results.length) {
  703. results.sort(function (a, b) {
  704. return b.weight - a.weight;
  705. });
  706. best = results[0];
  707. chart.boxesToAvoid.push({
  708. left: best.x,
  709. right: best.x + bBox.width,
  710. top: best.y,
  711. bottom: best.y + bBox.height
  712. });
  713. // Move it if needed
  714. var dist = Math.sqrt(Math.pow(Math.abs(best.x - (label.x || 0)), 2) +
  715. Math.pow(Math.abs(best.y - (label.y || 0)), 2));
  716. if (dist && series.labelBySeries) {
  717. // Move fast and fade in - pure animation movement is
  718. // distractive...
  719. var attr = {
  720. opacity: chart.renderer.forExport ? 1 : 0,
  721. x: best.x,
  722. y: best.y
  723. },
  724. anim = {
  725. opacity: 1
  726. };
  727. // ... unless we're just moving a short distance
  728. if (dist <= 10) {
  729. anim = {
  730. x: attr.x,
  731. y: attr.y
  732. };
  733. attr = {};
  734. }
  735. // Default initial animation to a fraction of the series
  736. // animation (#9396)
  737. var animationOptions = void 0;
  738. if (isNew) {
  739. animationOptions = animObject(series.options.animation);
  740. // @todo: Safely remove any cast after merging #13005
  741. animationOptions.duration *= 0.2;
  742. }
  743. series.labelBySeries
  744. .attr(extend(attr, {
  745. anchorX: best.connectorPoint &&
  746. best.connectorPoint.plotX + paneLeft,
  747. anchorY: best.connectorPoint &&
  748. best.connectorPoint.plotY + paneTop
  749. }))
  750. .animate(anim, animationOptions);
  751. // Record closest point to stick to for sync redraw
  752. series.options.kdNow = true;
  753. series.buildKDTree();
  754. var closest = series.searchPoint({
  755. chartX: best.x,
  756. chartY: best.y
  757. },
  758. true);
  759. if (closest) {
  760. label.closest = [
  761. closest,
  762. best.x - (closest.plotX || 0),
  763. best.y - (closest.plotY || 0)
  764. ];
  765. }
  766. }
  767. }
  768. else {
  769. destroyLabel();
  770. }
  771. }
  772. else {
  773. destroyLabel();
  774. }
  775. });
  776. fireEvent(chart, 'afterDrawSeriesLabels');
  777. // console.timeEnd('drawSeriesLabels');
  778. };
  779. /* eslint-disable no-invalid-this */
  780. /**
  781. * Prepare drawing series labels.
  782. *
  783. * @private
  784. * @function drawLabels
  785. */
  786. function drawLabels(e) {
  787. if (this.renderer) {
  788. var chart = this,
  789. delay = animObject(chart.renderer.globalAnimation).duration;
  790. chart.labelSeries = [];
  791. chart.labelSeriesMaxSum = 0;
  792. U.clearTimeout(chart.seriesLabelTimer);
  793. // Which series should have labels
  794. chart.series.forEach(function (series) {
  795. var options = series.options.label,
  796. label = series.labelBySeries,
  797. closest = label && label.closest;
  798. if (options.enabled &&
  799. series.visible &&
  800. (series.graph || series.area) &&
  801. !series.isSeriesBoosting) {
  802. chart.labelSeries.push(series);
  803. if (options.minFontSize && options.maxFontSize) {
  804. series.sum = series.yData.reduce(function (pv, cv) {
  805. return (pv || 0) + (cv || 0);
  806. }, 0);
  807. chart.labelSeriesMaxSum = Math.max(chart.labelSeriesMaxSum, series.sum);
  808. }
  809. // The labels are processing heavy, wait until the animation is
  810. // done
  811. if (e.type === 'load') {
  812. delay = Math.max(delay, animObject(series.options.animation).duration);
  813. }
  814. // Keep the position updated to the axis while redrawing
  815. if (closest) {
  816. if (typeof closest[0].plotX !== 'undefined') {
  817. label.animate({
  818. x: closest[0].plotX + closest[1],
  819. y: closest[0].plotY + closest[2]
  820. });
  821. }
  822. else {
  823. label.attr({ opacity: 0 });
  824. }
  825. }
  826. }
  827. });
  828. chart.seriesLabelTimer = syncTimeout(function () {
  829. if (chart.series && chart.labelSeries) { // #7931, chart destroyed
  830. chart.drawSeriesLabels();
  831. }
  832. }, chart.renderer.forExport || !delay ? 0 : delay);
  833. }
  834. }
  835. // Leave both events, we handle animation differently (#9815)
  836. addEvent(Chart, 'load', drawLabels);
  837. addEvent(Chart, 'redraw', drawLabels);
  838. });
  839. _registerModule(_modules, 'masters/modules/series-label.src.js', [], function () {
  840. });
  841. }));