series-label.src.js 39 KB

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