Legend.js 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. /* *
  2. *
  3. * (c) 2010-2020 Torstein Honsi
  4. *
  5. * License: www.highcharts.com/license
  6. *
  7. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  8. *
  9. * */
  10. 'use strict';
  11. import H from './Globals.js';
  12. /**
  13. * Gets fired when the legend item belonging to a point is clicked. The default
  14. * action is to toggle the visibility of the point. This can be prevented by
  15. * returning `false` or calling `event.preventDefault()`.
  16. *
  17. * @callback Highcharts.PointLegendItemClickCallbackFunction
  18. *
  19. * @param {Highcharts.Point} this
  20. * The point on which the event occured.
  21. *
  22. * @param {Highcharts.PointLegendItemClickEventObject} event
  23. * The event that occured.
  24. */
  25. /**
  26. * Information about the legend click event.
  27. *
  28. * @interface Highcharts.PointLegendItemClickEventObject
  29. */ /**
  30. * Related browser event.
  31. * @name Highcharts.PointLegendItemClickEventObject#browserEvent
  32. * @type {Highcharts.PointerEvent}
  33. */ /**
  34. * Prevent the default action of toggle the visibility of the point.
  35. * @name Highcharts.PointLegendItemClickEventObject#preventDefault
  36. * @type {Function}
  37. */ /**
  38. * Related point.
  39. * @name Highcharts.PointLegendItemClickEventObject#target
  40. * @type {Highcharts.Point}
  41. */ /**
  42. * Event type.
  43. * @name Highcharts.PointLegendItemClickEventObject#type
  44. * @type {"legendItemClick"}
  45. */
  46. /**
  47. * Gets fired when the legend item belonging to a series is clicked. The default
  48. * action is to toggle the visibility of the series. This can be prevented by
  49. * returning `false` or calling `event.preventDefault()`.
  50. *
  51. * @callback Highcharts.SeriesLegendItemClickCallbackFunction
  52. *
  53. * @param {Highcharts.Series} this
  54. * The series where the event occured.
  55. *
  56. * @param {Highcharts.SeriesLegendItemClickEventObject} event
  57. * The event that occured.
  58. */
  59. /**
  60. * Information about the legend click event.
  61. *
  62. * @interface Highcharts.SeriesLegendItemClickEventObject
  63. */ /**
  64. * Related browser event.
  65. * @name Highcharts.SeriesLegendItemClickEventObject#browserEvent
  66. * @type {Highcharts.PointerEvent}
  67. */ /**
  68. * Prevent the default action of toggle the visibility of the series.
  69. * @name Highcharts.SeriesLegendItemClickEventObject#preventDefault
  70. * @type {Function}
  71. */ /**
  72. * Related series.
  73. * @name Highcharts.SeriesLegendItemClickEventObject#target
  74. * @type {Highcharts.Series}
  75. */ /**
  76. * Event type.
  77. * @name Highcharts.SeriesLegendItemClickEventObject#type
  78. * @type {"legendItemClick"}
  79. */
  80. import U from './Utilities.js';
  81. var addEvent = U.addEvent, animObject = U.animObject, css = U.css, defined = U.defined, discardElement = U.discardElement, find = U.find, fireEvent = U.fireEvent, format = U.format, isNumber = U.isNumber, merge = U.merge, pick = U.pick, relativeLength = U.relativeLength, setAnimation = U.setAnimation, stableSort = U.stableSort, syncTimeout = U.syncTimeout, wrap = U.wrap;
  82. var isFirefox = H.isFirefox, marginNames = H.marginNames, win = H.win;
  83. /* eslint-disable no-invalid-this, valid-jsdoc */
  84. /**
  85. * The overview of the chart's series. The legend object is instanciated
  86. * internally in the chart constructor, and is available from the `chart.legend`
  87. * property. Each chart has only one legend.
  88. *
  89. * @class
  90. * @name Highcharts.Legend
  91. *
  92. * @param {Highcharts.Chart} chart
  93. * The chart instance.
  94. *
  95. * @param {Highcharts.LegendOptions} options
  96. * Legend options.
  97. */
  98. var Legend = /** @class */ (function () {
  99. /* *
  100. *
  101. * Constructors
  102. *
  103. * */
  104. function Legend(chart, options) {
  105. /* *
  106. *
  107. * Properties
  108. *
  109. * */
  110. this.allItems = [];
  111. this.box = void 0;
  112. this.contentGroup = void 0;
  113. this.display = false;
  114. this.group = void 0;
  115. this.initialItemY = 0;
  116. this.itemHeight = 0;
  117. this.itemMarginBottom = 0;
  118. this.itemMarginTop = 0;
  119. this.itemX = 0;
  120. this.itemY = 0;
  121. this.lastItemY = 0;
  122. this.lastLineHeight = 0;
  123. this.legendHeight = 0;
  124. this.legendWidth = 0;
  125. this.maxItemWidth = 0;
  126. this.maxLegendWidth = 0;
  127. this.offsetWidth = 0;
  128. this.options = {};
  129. this.padding = 0;
  130. this.pages = [];
  131. this.proximate = false;
  132. this.scrollGroup = void 0;
  133. this.symbolHeight = 0;
  134. this.symbolWidth = 0;
  135. this.titleHeight = 0;
  136. this.totalItemWidth = 0;
  137. this.widthOption = 0;
  138. this.chart = chart;
  139. this.init(chart, options);
  140. }
  141. /* *
  142. *
  143. * Functions
  144. *
  145. * */
  146. /**
  147. * Initialize the legend.
  148. *
  149. * @private
  150. * @function Highcharts.Legend#init
  151. *
  152. * @param {Highcharts.Chart} chart
  153. * The chart instance.
  154. *
  155. * @param {Highcharts.LegendOptions} options
  156. * Legend options.
  157. */
  158. Legend.prototype.init = function (chart, options) {
  159. /**
  160. * Chart of this legend.
  161. *
  162. * @readonly
  163. * @name Highcharts.Legend#chart
  164. * @type {Highcharts.Chart}
  165. */
  166. this.chart = chart;
  167. this.setOptions(options);
  168. if (options.enabled) {
  169. // Render it
  170. this.render();
  171. // move checkboxes
  172. addEvent(this.chart, 'endResize', function () {
  173. this.legend.positionCheckboxes();
  174. });
  175. if (this.proximate) {
  176. this.unchartrender = addEvent(this.chart, 'render', function () {
  177. this.legend.proximatePositions();
  178. this.legend.positionItems();
  179. });
  180. }
  181. else if (this.unchartrender) {
  182. this.unchartrender();
  183. }
  184. }
  185. };
  186. /**
  187. * @private
  188. * @function Highcharts.Legend#setOptions
  189. * @param {Highcharts.LegendOptions} options
  190. */
  191. Legend.prototype.setOptions = function (options) {
  192. var padding = pick(options.padding, 8);
  193. /**
  194. * Legend options.
  195. *
  196. * @readonly
  197. * @name Highcharts.Legend#options
  198. * @type {Highcharts.LegendOptions}
  199. */
  200. this.options = options;
  201. if (!this.chart.styledMode) {
  202. this.itemStyle = options.itemStyle;
  203. this.itemHiddenStyle = merge(this.itemStyle, options.itemHiddenStyle);
  204. }
  205. this.itemMarginTop = options.itemMarginTop || 0;
  206. this.itemMarginBottom = options.itemMarginBottom || 0;
  207. this.padding = padding;
  208. this.initialItemY = padding - 5; // 5 is pixels above the text
  209. this.symbolWidth = pick(options.symbolWidth, 16);
  210. this.pages = [];
  211. this.proximate = options.layout === 'proximate' && !this.chart.inverted;
  212. this.baseline = void 0; // #12705: baseline has to be reset on every update
  213. };
  214. /**
  215. * Update the legend with new options. Equivalent to running `chart.update`
  216. * with a legend configuration option.
  217. *
  218. * @sample highcharts/legend/legend-update/
  219. * Legend update
  220. *
  221. * @function Highcharts.Legend#update
  222. *
  223. * @param {Highcharts.LegendOptions} options
  224. * Legend options.
  225. *
  226. * @param {boolean} [redraw=true]
  227. * Whether to redraw the chart after the axis is altered. If doing more
  228. * operations on the chart, it is a good idea to set redraw to false and
  229. * call {@link Chart#redraw} after. Whether to redraw the chart.
  230. *
  231. * @fires Highcharts.Legends#event:afterUpdate
  232. */
  233. Legend.prototype.update = function (options, redraw) {
  234. var chart = this.chart;
  235. this.setOptions(merge(true, this.options, options));
  236. this.destroy();
  237. chart.isDirtyLegend = chart.isDirtyBox = true;
  238. if (pick(redraw, true)) {
  239. chart.redraw();
  240. }
  241. fireEvent(this, 'afterUpdate');
  242. };
  243. /**
  244. * Set the colors for the legend item.
  245. *
  246. * @private
  247. * @function Highcharts.Legend#colorizeItem
  248. * @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item
  249. * A Series or Point instance
  250. * @param {boolean} [visible=false]
  251. * Dimmed or colored
  252. *
  253. * @todo
  254. * Make events official: Fires the event `afterColorizeItem`.
  255. */
  256. Legend.prototype.colorizeItem = function (item, visible) {
  257. item.legendGroup[visible ? 'removeClass' : 'addClass']('highcharts-legend-item-hidden');
  258. if (!this.chart.styledMode) {
  259. var legend = this, options = legend.options, legendItem = item.legendItem, legendLine = item.legendLine, legendSymbol = item.legendSymbol, hiddenColor = legend.itemHiddenStyle.color, textColor = visible ?
  260. options.itemStyle.color :
  261. hiddenColor, symbolColor = visible ?
  262. (item.color || hiddenColor) :
  263. hiddenColor, markerOptions = item.options && item.options.marker, symbolAttr = { fill: symbolColor };
  264. if (legendItem) {
  265. legendItem.css({
  266. fill: textColor,
  267. color: textColor // #1553, oldIE
  268. });
  269. }
  270. if (legendLine) {
  271. legendLine.attr({ stroke: symbolColor });
  272. }
  273. if (legendSymbol) {
  274. // Apply marker options
  275. if (markerOptions && legendSymbol.isMarker) { // #585
  276. symbolAttr = item.pointAttribs();
  277. if (!visible) {
  278. // #6769
  279. symbolAttr.stroke = symbolAttr.fill = hiddenColor;
  280. }
  281. }
  282. legendSymbol.attr(symbolAttr);
  283. }
  284. }
  285. fireEvent(this, 'afterColorizeItem', { item: item, visible: visible });
  286. };
  287. /**
  288. * @private
  289. * @function Highcharts.Legend#positionItems
  290. */
  291. Legend.prototype.positionItems = function () {
  292. // Now that the legend width and height are established, put the items
  293. // in the final position
  294. this.allItems.forEach(this.positionItem, this);
  295. if (!this.chart.isResizing) {
  296. this.positionCheckboxes();
  297. }
  298. };
  299. /**
  300. * Position the legend item.
  301. *
  302. * @private
  303. * @function Highcharts.Legend#positionItem
  304. * @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item
  305. * The item to position
  306. */
  307. Legend.prototype.positionItem = function (item) {
  308. var _this = this;
  309. var legend = this, options = legend.options, symbolPadding = options.symbolPadding, ltr = !options.rtl, legendItemPos = item._legendItemPos, itemX = legendItemPos[0], itemY = legendItemPos[1], checkbox = item.checkbox, legendGroup = item.legendGroup;
  310. if (legendGroup && legendGroup.element) {
  311. var attribs = {
  312. translateX: ltr ?
  313. itemX :
  314. legend.legendWidth - itemX - 2 * symbolPadding - 4,
  315. translateY: itemY
  316. };
  317. var complete = function () {
  318. fireEvent(_this, 'afterPositionItem', { item: item });
  319. };
  320. if (defined(legendGroup.translateY)) {
  321. legendGroup.animate(attribs, { complete: complete });
  322. }
  323. else {
  324. legendGroup.attr(attribs);
  325. complete();
  326. }
  327. }
  328. if (checkbox) {
  329. checkbox.x = itemX;
  330. checkbox.y = itemY;
  331. }
  332. };
  333. /**
  334. * Destroy a single legend item, used internally on removing series items.
  335. *
  336. * @private
  337. * @function Highcharts.Legend#destroyItem
  338. * @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item
  339. * The item to remove
  340. */
  341. Legend.prototype.destroyItem = function (item) {
  342. var checkbox = item.checkbox;
  343. // destroy SVG elements
  344. ['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'].forEach(function (key) {
  345. if (item[key]) {
  346. item[key] = item[key].destroy();
  347. }
  348. });
  349. if (checkbox) {
  350. discardElement(item.checkbox);
  351. }
  352. };
  353. /**
  354. * Destroy the legend. Used internally. To reflow objects, `chart.redraw`
  355. * must be called after destruction.
  356. *
  357. * @private
  358. * @function Highcharts.Legend#destroy
  359. */
  360. Legend.prototype.destroy = function () {
  361. /**
  362. * @private
  363. * @param {string} key
  364. * @return {void}
  365. */
  366. function destroyItems(key) {
  367. if (this[key]) {
  368. this[key] = this[key].destroy();
  369. }
  370. }
  371. // Destroy items
  372. this.getAllItems().forEach(function (item) {
  373. ['legendItem', 'legendGroup'].forEach(destroyItems, item);
  374. });
  375. // Destroy legend elements
  376. [
  377. 'clipRect',
  378. 'up',
  379. 'down',
  380. 'pager',
  381. 'nav',
  382. 'box',
  383. 'title',
  384. 'group'
  385. ].forEach(destroyItems, this);
  386. this.display = null; // Reset in .render on update.
  387. };
  388. /**
  389. * Position the checkboxes after the width is determined.
  390. *
  391. * @private
  392. * @function Highcharts.Legend#positionCheckboxes
  393. */
  394. Legend.prototype.positionCheckboxes = function () {
  395. var alignAttr = this.group && this.group.alignAttr, translateY, clipHeight = this.clipHeight || this.legendHeight, titleHeight = this.titleHeight;
  396. if (alignAttr) {
  397. translateY = alignAttr.translateY;
  398. this.allItems.forEach(function (item) {
  399. var checkbox = item.checkbox, top;
  400. if (checkbox) {
  401. top = translateY + titleHeight + checkbox.y +
  402. (this.scrollOffset || 0) + 3;
  403. css(checkbox, {
  404. left: (alignAttr.translateX + item.checkboxOffset +
  405. checkbox.x - 20) + 'px',
  406. top: top + 'px',
  407. display: this.proximate || (top > translateY - 6 &&
  408. top < translateY + clipHeight - 6) ?
  409. '' :
  410. 'none'
  411. });
  412. }
  413. }, this);
  414. }
  415. };
  416. /**
  417. * Render the legend title on top of the legend.
  418. *
  419. * @private
  420. * @function Highcharts.Legend#renderTitle
  421. */
  422. Legend.prototype.renderTitle = function () {
  423. var options = this.options, padding = this.padding, titleOptions = options.title, titleHeight = 0, bBox;
  424. if (titleOptions.text) {
  425. if (!this.title) {
  426. /**
  427. * SVG element of the legend title.
  428. *
  429. * @readonly
  430. * @name Highcharts.Legend#title
  431. * @type {Highcharts.SVGElement}
  432. */
  433. this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, options.useHTML, null, 'legend-title')
  434. .attr({ zIndex: 1 });
  435. if (!this.chart.styledMode) {
  436. this.title.css(titleOptions.style);
  437. }
  438. this.title.add(this.group);
  439. }
  440. // Set the max title width (#7253)
  441. if (!titleOptions.width) {
  442. this.title.css({
  443. width: this.maxLegendWidth + 'px'
  444. });
  445. }
  446. bBox = this.title.getBBox();
  447. titleHeight = bBox.height;
  448. this.offsetWidth = bBox.width; // #1717
  449. this.contentGroup.attr({ translateY: titleHeight });
  450. }
  451. this.titleHeight = titleHeight;
  452. };
  453. /**
  454. * Set the legend item text.
  455. *
  456. * @function Highcharts.Legend#setText
  457. * @param {Highcharts.Point|Highcharts.Series} item
  458. * The item for which to update the text in the legend.
  459. */
  460. Legend.prototype.setText = function (item) {
  461. var options = this.options;
  462. item.legendItem.attr({
  463. text: options.labelFormat ?
  464. format(options.labelFormat, item, this.chart) :
  465. options.labelFormatter.call(item)
  466. });
  467. };
  468. /**
  469. * Render a single specific legend item. Called internally from the `render`
  470. * function.
  471. *
  472. * @private
  473. * @function Highcharts.Legend#renderItem
  474. * @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item
  475. * The item to render.
  476. */
  477. Legend.prototype.renderItem = function (item) {
  478. var legend = this, chart = legend.chart, renderer = chart.renderer, options = legend.options, horizontal = options.layout === 'horizontal', symbolWidth = legend.symbolWidth, symbolPadding = options.symbolPadding, itemStyle = legend.itemStyle, itemHiddenStyle = legend.itemHiddenStyle, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, ltr = !options.rtl, bBox, li = item.legendItem, isSeries = !item.series, series = !isSeries && item.series.drawLegendSymbol ?
  479. item.series :
  480. item, seriesOptions = series.options, showCheckbox = legend.createCheckboxForItem &&
  481. seriesOptions &&
  482. seriesOptions.showCheckbox,
  483. // full width minus text width
  484. itemExtraWidth = symbolWidth + symbolPadding +
  485. itemDistance + (showCheckbox ? 20 : 0), useHTML = options.useHTML, itemClassName = item.options.className;
  486. if (!li) { // generate it once, later move it
  487. // Generate the group box, a group to hold the symbol and text. Text
  488. // is to be appended in Legend class.
  489. item.legendGroup = renderer
  490. .g('legend-item')
  491. .addClass('highcharts-' + series.type + '-series ' +
  492. 'highcharts-color-' + item.colorIndex +
  493. (itemClassName ? ' ' + itemClassName : '') +
  494. (isSeries ?
  495. ' highcharts-series-' + item.index :
  496. ''))
  497. .attr({ zIndex: 1 })
  498. .add(legend.scrollGroup);
  499. // Generate the list item text and add it to the group
  500. item.legendItem = li = renderer.text('', ltr ?
  501. symbolWidth + symbolPadding :
  502. -symbolPadding, legend.baseline || 0, useHTML);
  503. if (!chart.styledMode) {
  504. // merge to prevent modifying original (#1021)
  505. li.css(merge(item.visible ?
  506. itemStyle :
  507. itemHiddenStyle));
  508. }
  509. li
  510. .attr({
  511. align: ltr ? 'left' : 'right',
  512. zIndex: 2
  513. })
  514. .add(item.legendGroup);
  515. // Get the baseline for the first item - the font size is equal for
  516. // all
  517. if (!legend.baseline) {
  518. legend.fontMetrics = renderer.fontMetrics(chart.styledMode ? 12 : itemStyle.fontSize, li);
  519. legend.baseline =
  520. legend.fontMetrics.f + 3 + legend.itemMarginTop;
  521. li.attr('y', legend.baseline);
  522. }
  523. // Draw the legend symbol inside the group box
  524. legend.symbolHeight =
  525. options.symbolHeight || legend.fontMetrics.f;
  526. series.drawLegendSymbol(legend, item);
  527. if (legend.setItemEvents) {
  528. legend.setItemEvents(item, li, useHTML);
  529. }
  530. }
  531. // Add the HTML checkbox on top
  532. if (showCheckbox && !item.checkbox && legend.createCheckboxForItem) {
  533. legend.createCheckboxForItem(item);
  534. }
  535. // Colorize the items
  536. legend.colorizeItem(item, item.visible);
  537. // Take care of max width and text overflow (#6659)
  538. if (chart.styledMode || !itemStyle.width) {
  539. li.css({
  540. width: ((options.itemWidth ||
  541. legend.widthOption ||
  542. chart.spacingBox.width) - itemExtraWidth) + 'px'
  543. });
  544. }
  545. // Always update the text
  546. legend.setText(item);
  547. // calculate the positions for the next line
  548. bBox = li.getBBox();
  549. item.itemWidth = item.checkboxOffset =
  550. options.itemWidth ||
  551. item.legendItemWidth ||
  552. bBox.width + itemExtraWidth;
  553. legend.maxItemWidth = Math.max(legend.maxItemWidth, item.itemWidth);
  554. legend.totalItemWidth += item.itemWidth;
  555. legend.itemHeight = item.itemHeight = Math.round(item.legendItemHeight || bBox.height || legend.symbolHeight);
  556. };
  557. /**
  558. * Get the position of the item in the layout. We now know the
  559. * maxItemWidth from the previous loop.
  560. *
  561. * @private
  562. * @function Highcharts.Legend#layoutItem
  563. * @param {Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series} item
  564. */
  565. Legend.prototype.layoutItem = function (item) {
  566. var options = this.options, padding = this.padding, horizontal = options.layout === 'horizontal', itemHeight = item.itemHeight, itemMarginBottom = this.itemMarginBottom, itemMarginTop = this.itemMarginTop, itemDistance = horizontal ? pick(options.itemDistance, 20) : 0, maxLegendWidth = this.maxLegendWidth, itemWidth = (options.alignColumns &&
  567. this.totalItemWidth > maxLegendWidth) ?
  568. this.maxItemWidth :
  569. item.itemWidth;
  570. // If the item exceeds the width, start a new line
  571. if (horizontal &&
  572. this.itemX - padding + itemWidth > maxLegendWidth) {
  573. this.itemX = padding;
  574. if (this.lastLineHeight) { // Not for the first line (#10167)
  575. this.itemY += (itemMarginTop +
  576. this.lastLineHeight +
  577. itemMarginBottom);
  578. }
  579. this.lastLineHeight = 0; // reset for next line (#915, #3976)
  580. }
  581. // Set the edge positions
  582. this.lastItemY = itemMarginTop + this.itemY + itemMarginBottom;
  583. this.lastLineHeight = Math.max(// #915
  584. itemHeight, this.lastLineHeight);
  585. // cache the position of the newly generated or reordered items
  586. item._legendItemPos = [this.itemX, this.itemY];
  587. // advance
  588. if (horizontal) {
  589. this.itemX += itemWidth;
  590. }
  591. else {
  592. this.itemY +=
  593. itemMarginTop + itemHeight + itemMarginBottom;
  594. this.lastLineHeight = itemHeight;
  595. }
  596. // the width of the widest item
  597. this.offsetWidth = this.widthOption || Math.max((horizontal ? this.itemX - padding - (item.checkbox ?
  598. // decrease by itemDistance only when no checkbox #4853
  599. 0 :
  600. itemDistance) : itemWidth) + padding, this.offsetWidth);
  601. };
  602. /**
  603. * Get all items, which is one item per series for most series and one
  604. * item per point for pie series and its derivatives. Fires the event
  605. * `afterGetAllItems`.
  606. *
  607. * @private
  608. * @function Highcharts.Legend#getAllItems
  609. * @return {Array<(Highcharts.BubbleLegend|Highcharts.Point|Highcharts.Series)>}
  610. * The current items in the legend.
  611. * @fires Highcharts.Legend#event:afterGetAllItems
  612. */
  613. Legend.prototype.getAllItems = function () {
  614. var allItems = [];
  615. this.chart.series.forEach(function (series) {
  616. var seriesOptions = series && series.options;
  617. // Handle showInLegend. If the series is linked to another series,
  618. // defaults to false.
  619. if (series && pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? void 0 : false, true)) {
  620. // Use points or series for the legend item depending on
  621. // legendType
  622. allItems = allItems.concat(series.legendItems ||
  623. (seriesOptions.legendType === 'point' ?
  624. series.data :
  625. series));
  626. }
  627. });
  628. fireEvent(this, 'afterGetAllItems', { allItems: allItems });
  629. return allItems;
  630. };
  631. /**
  632. * Get a short, three letter string reflecting the alignment and layout.
  633. *
  634. * @private
  635. * @function Highcharts.Legend#getAlignment
  636. * @return {string}
  637. * The alignment, empty string if floating
  638. */
  639. Legend.prototype.getAlignment = function () {
  640. var options = this.options;
  641. // Use the first letter of each alignment option in order to detect
  642. // the side. (#4189 - use charAt(x) notation instead of [x] for IE7)
  643. if (this.proximate) {
  644. return options.align.charAt(0) + 'tv';
  645. }
  646. return options.floating ? '' : (options.align.charAt(0) +
  647. options.verticalAlign.charAt(0) +
  648. options.layout.charAt(0));
  649. };
  650. /**
  651. * Adjust the chart margins by reserving space for the legend on only one
  652. * side of the chart. If the position is set to a corner, top or bottom is
  653. * reserved for horizontal legends and left or right for vertical ones.
  654. *
  655. * @private
  656. * @function Highcharts.Legend#adjustMargins
  657. * @param {Array<number>} margin
  658. * @param {Array<number>} spacing
  659. */
  660. Legend.prototype.adjustMargins = function (margin, spacing) {
  661. var chart = this.chart, options = this.options, alignment = this.getAlignment();
  662. if (alignment) {
  663. ([
  664. /(lth|ct|rth)/,
  665. /(rtv|rm|rbv)/,
  666. /(rbh|cb|lbh)/,
  667. /(lbv|lm|ltv)/
  668. ]).forEach(function (alignments, side) {
  669. if (alignments.test(alignment) && !defined(margin[side])) {
  670. // Now we have detected on which side of the chart we should
  671. // reserve space for the legend
  672. chart[marginNames[side]] = Math.max(chart[marginNames[side]], (chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] +
  673. [1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] +
  674. pick(options.margin, 12) +
  675. spacing[side] +
  676. (chart.titleOffset[side] || 0)));
  677. }
  678. });
  679. }
  680. };
  681. /**
  682. * @private
  683. * @function Highcharts.Legend#proximatePositions
  684. */
  685. Legend.prototype.proximatePositions = function () {
  686. var chart = this.chart, boxes = [], alignLeft = this.options.align === 'left';
  687. this.allItems.forEach(function (item) {
  688. var lastPoint, height, useFirstPoint = alignLeft, target, top;
  689. if (item.yAxis && item.points) {
  690. if (item.xAxis.options.reversed) {
  691. useFirstPoint = !useFirstPoint;
  692. }
  693. lastPoint = find(useFirstPoint ?
  694. item.points :
  695. item.points.slice(0).reverse(), function (item) {
  696. return isNumber(item.plotY);
  697. });
  698. height = this.itemMarginTop +
  699. item.legendItem.getBBox().height +
  700. this.itemMarginBottom;
  701. top = item.yAxis.top - chart.plotTop;
  702. if (item.visible) {
  703. target = lastPoint ?
  704. lastPoint.plotY :
  705. item.yAxis.height;
  706. target += top - 0.3 * height;
  707. }
  708. else {
  709. target = top + item.yAxis.height;
  710. }
  711. boxes.push({
  712. target: target,
  713. size: height,
  714. item: item
  715. });
  716. }
  717. }, this);
  718. H.distribute(boxes, chart.plotHeight);
  719. boxes.forEach(function (box) {
  720. box.item._legendItemPos[1] =
  721. chart.plotTop - chart.spacing[0] + box.pos;
  722. });
  723. };
  724. /**
  725. * Render the legend. This method can be called both before and after
  726. * `chart.render`. If called after, it will only rearrange items instead
  727. * of creating new ones. Called internally on initial render and after
  728. * redraws.
  729. *
  730. * @private
  731. * @function Highcharts.Legend#render
  732. */
  733. Legend.prototype.render = function () {
  734. var legend = this, chart = legend.chart, renderer = chart.renderer, legendGroup = legend.group, allItems, display, legendWidth, legendHeight, box = legend.box, options = legend.options, padding = legend.padding, allowedWidth;
  735. legend.itemX = padding;
  736. legend.itemY = legend.initialItemY;
  737. legend.offsetWidth = 0;
  738. legend.lastItemY = 0;
  739. legend.widthOption = relativeLength(options.width, chart.spacingBox.width - padding);
  740. // Compute how wide the legend is allowed to be
  741. allowedWidth =
  742. chart.spacingBox.width - 2 * padding - options.x;
  743. if (['rm', 'lm'].indexOf(legend.getAlignment().substring(0, 2)) > -1) {
  744. allowedWidth /= 2;
  745. }
  746. legend.maxLegendWidth = legend.widthOption || allowedWidth;
  747. if (!legendGroup) {
  748. /**
  749. * SVG group of the legend.
  750. *
  751. * @readonly
  752. * @name Highcharts.Legend#group
  753. * @type {Highcharts.SVGElement}
  754. */
  755. legend.group = legendGroup = renderer.g('legend')
  756. .attr({ zIndex: 7 })
  757. .add();
  758. legend.contentGroup = renderer.g()
  759. .attr({ zIndex: 1 }) // above background
  760. .add(legendGroup);
  761. legend.scrollGroup = renderer.g()
  762. .add(legend.contentGroup);
  763. }
  764. legend.renderTitle();
  765. // add each series or point
  766. allItems = legend.getAllItems();
  767. // sort by legendIndex
  768. stableSort(allItems, function (a, b) {
  769. return ((a.options && a.options.legendIndex) || 0) -
  770. ((b.options && b.options.legendIndex) || 0);
  771. });
  772. // reversed legend
  773. if (options.reversed) {
  774. allItems.reverse();
  775. }
  776. /**
  777. * All items for the legend, which is an array of series for most series
  778. * and an array of points for pie series and its derivatives.
  779. *
  780. * @readonly
  781. * @name Highcharts.Legend#allItems
  782. * @type {Array<(Highcharts.Point|Highcharts.Series)>}
  783. */
  784. legend.allItems = allItems;
  785. legend.display = display = !!allItems.length;
  786. // Render the items. First we run a loop to set the text and properties
  787. // and read all the bounding boxes. The next loop computes the item
  788. // positions based on the bounding boxes.
  789. legend.lastLineHeight = 0;
  790. legend.maxItemWidth = 0;
  791. legend.totalItemWidth = 0;
  792. legend.itemHeight = 0;
  793. allItems.forEach(legend.renderItem, legend);
  794. allItems.forEach(legend.layoutItem, legend);
  795. // Get the box
  796. legendWidth = (legend.widthOption || legend.offsetWidth) + padding;
  797. legendHeight = legend.lastItemY + legend.lastLineHeight +
  798. legend.titleHeight;
  799. legendHeight = legend.handleOverflow(legendHeight);
  800. legendHeight += padding;
  801. // Draw the border and/or background
  802. if (!box) {
  803. /**
  804. * SVG element of the legend box.
  805. *
  806. * @readonly
  807. * @name Highcharts.Legend#box
  808. * @type {Highcharts.SVGElement}
  809. */
  810. legend.box = box = renderer.rect()
  811. .addClass('highcharts-legend-box')
  812. .attr({
  813. r: options.borderRadius
  814. })
  815. .add(legendGroup);
  816. box.isNew = true;
  817. }
  818. // Presentational
  819. if (!chart.styledMode) {
  820. box
  821. .attr({
  822. stroke: options.borderColor,
  823. 'stroke-width': options.borderWidth || 0,
  824. fill: options.backgroundColor || 'none'
  825. })
  826. .shadow(options.shadow);
  827. }
  828. if (legendWidth > 0 && legendHeight > 0) {
  829. box[box.isNew ? 'attr' : 'animate'](box.crisp.call({}, {
  830. x: 0,
  831. y: 0,
  832. width: legendWidth,
  833. height: legendHeight
  834. }, box.strokeWidth()));
  835. box.isNew = false;
  836. }
  837. // hide the border if no items
  838. box[display ? 'show' : 'hide']();
  839. // Open for responsiveness
  840. if (chart.styledMode && legendGroup.getStyle('display') === 'none') {
  841. legendWidth = legendHeight = 0;
  842. }
  843. legend.legendWidth = legendWidth;
  844. legend.legendHeight = legendHeight;
  845. if (display) {
  846. legend.align();
  847. }
  848. if (!this.proximate) {
  849. this.positionItems();
  850. }
  851. fireEvent(this, 'afterRender');
  852. };
  853. /**
  854. * Align the legend to chart's box.
  855. *
  856. * @private
  857. * @function Highcharts.align
  858. * @param {Highcharts.BBoxObject} alignTo
  859. * @return {void}
  860. */
  861. Legend.prototype.align = function (alignTo) {
  862. if (alignTo === void 0) { alignTo = this.chart.spacingBox; }
  863. var chart = this.chart, options = this.options;
  864. // If aligning to the top and the layout is horizontal, adjust for
  865. // the title (#7428)
  866. var y = alignTo.y;
  867. if (/(lth|ct|rth)/.test(this.getAlignment()) &&
  868. chart.titleOffset[0] > 0) {
  869. y += chart.titleOffset[0];
  870. }
  871. else if (/(lbh|cb|rbh)/.test(this.getAlignment()) &&
  872. chart.titleOffset[2] > 0) {
  873. y -= chart.titleOffset[2];
  874. }
  875. if (y !== alignTo.y) {
  876. alignTo = merge(alignTo, { y: y });
  877. }
  878. this.group.align(merge(options, {
  879. width: this.legendWidth,
  880. height: this.legendHeight,
  881. verticalAlign: this.proximate ? 'top' : options.verticalAlign
  882. }), true, alignTo);
  883. };
  884. /**
  885. * Set up the overflow handling by adding navigation with up and down arrows
  886. * below the legend.
  887. *
  888. * @private
  889. * @function Highcharts.Legend#handleOverflow
  890. * @param {number} legendHeight
  891. * @return {number}
  892. */
  893. Legend.prototype.handleOverflow = function (legendHeight) {
  894. var legend = this, chart = this.chart, renderer = chart.renderer, options = this.options, optionsY = options.y, alignTop = options.verticalAlign === 'top', padding = this.padding, spaceHeight = (chart.spacingBox.height +
  895. (alignTop ? -optionsY : optionsY) - padding), maxHeight = options.maxHeight, clipHeight, clipRect = this.clipRect, navOptions = options.navigation, animation = pick(navOptions.animation, true), arrowSize = navOptions.arrowSize || 12, nav = this.nav, pages = this.pages, lastY, allItems = this.allItems, clipToHeight = function (height) {
  896. if (typeof height === 'number') {
  897. clipRect.attr({
  898. height: height
  899. });
  900. }
  901. else if (clipRect) { // Reset (#5912)
  902. legend.clipRect = clipRect.destroy();
  903. legend.contentGroup.clip();
  904. }
  905. // useHTML
  906. if (legend.contentGroup.div) {
  907. legend.contentGroup.div.style.clip = height ?
  908. 'rect(' + padding + 'px,9999px,' +
  909. (padding + height) + 'px,0)' :
  910. 'auto';
  911. }
  912. }, addTracker = function (key) {
  913. legend[key] = renderer
  914. .circle(0, 0, arrowSize * 1.3)
  915. .translate(arrowSize / 2, arrowSize / 2)
  916. .add(nav);
  917. if (!chart.styledMode) {
  918. legend[key].attr('fill', 'rgba(0,0,0,0.0001)');
  919. }
  920. return legend[key];
  921. };
  922. // Adjust the height
  923. if (options.layout === 'horizontal' &&
  924. options.verticalAlign !== 'middle' &&
  925. !options.floating) {
  926. spaceHeight /= 2;
  927. }
  928. if (maxHeight) {
  929. spaceHeight = Math.min(spaceHeight, maxHeight);
  930. }
  931. // Reset the legend height and adjust the clipping rectangle
  932. pages.length = 0;
  933. if (legendHeight > spaceHeight &&
  934. navOptions.enabled !== false) {
  935. this.clipHeight = clipHeight =
  936. Math.max(spaceHeight - 20 - this.titleHeight - padding, 0);
  937. this.currentPage = pick(this.currentPage, 1);
  938. this.fullHeight = legendHeight;
  939. // Fill pages with Y positions so that the top of each a legend item
  940. // defines the scroll top for each page (#2098)
  941. allItems.forEach(function (item, i) {
  942. var y = item._legendItemPos[1], h = Math.round(item.legendItem.getBBox().height), len = pages.length;
  943. if (!len || (y - pages[len - 1] > clipHeight &&
  944. (lastY || y) !== pages[len - 1])) {
  945. pages.push(lastY || y);
  946. len++;
  947. }
  948. // Keep track of which page each item is on
  949. item.pageIx = len - 1;
  950. if (lastY) {
  951. allItems[i - 1].pageIx = len - 1;
  952. }
  953. if (i === allItems.length - 1 &&
  954. y + h - pages[len - 1] > clipHeight &&
  955. y !== lastY // #2617
  956. ) {
  957. pages.push(y);
  958. item.pageIx = len;
  959. }
  960. if (y !== lastY) {
  961. lastY = y;
  962. }
  963. });
  964. // Only apply clipping if needed. Clipping causes blurred legend in
  965. // PDF export (#1787)
  966. if (!clipRect) {
  967. clipRect = legend.clipRect =
  968. renderer.clipRect(0, padding, 9999, 0);
  969. legend.contentGroup.clip(clipRect);
  970. }
  971. clipToHeight(clipHeight);
  972. // Add navigation elements
  973. if (!nav) {
  974. this.nav = nav = renderer.g()
  975. .attr({ zIndex: 1 })
  976. .add(this.group);
  977. this.up = renderer
  978. .symbol('triangle', 0, 0, arrowSize, arrowSize)
  979. .add(nav);
  980. addTracker('upTracker')
  981. .on('click', function () {
  982. legend.scroll(-1, animation);
  983. });
  984. this.pager = renderer.text('', 15, 10)
  985. .addClass('highcharts-legend-navigation');
  986. if (!chart.styledMode) {
  987. this.pager.css(navOptions.style);
  988. }
  989. this.pager.add(nav);
  990. this.down = renderer
  991. .symbol('triangle-down', 0, 0, arrowSize, arrowSize)
  992. .add(nav);
  993. addTracker('downTracker')
  994. .on('click', function () {
  995. legend.scroll(1, animation);
  996. });
  997. }
  998. // Set initial position
  999. legend.scroll(0);
  1000. legendHeight = spaceHeight;
  1001. // Reset
  1002. }
  1003. else if (nav) {
  1004. clipToHeight();
  1005. this.nav = nav.destroy(); // #6322
  1006. this.scrollGroup.attr({
  1007. translateY: 1
  1008. });
  1009. this.clipHeight = 0; // #1379
  1010. }
  1011. return legendHeight;
  1012. };
  1013. /**
  1014. * Scroll the legend by a number of pages.
  1015. *
  1016. * @private
  1017. * @function Highcharts.Legend#scroll
  1018. *
  1019. * @param {number} scrollBy
  1020. * The number of pages to scroll.
  1021. *
  1022. * @param {boolean|Highcharts.AnimationOptionsObject} [animation]
  1023. * Whether and how to apply animation.
  1024. *
  1025. * @return {void}
  1026. */
  1027. Legend.prototype.scroll = function (scrollBy, animation) {
  1028. var _this = this;
  1029. var chart = this.chart, pages = this.pages, pageCount = pages.length, currentPage = this.currentPage + scrollBy, clipHeight = this.clipHeight, navOptions = this.options.navigation, pager = this.pager, padding = this.padding;
  1030. // When resizing while looking at the last page
  1031. if (currentPage > pageCount) {
  1032. currentPage = pageCount;
  1033. }
  1034. if (currentPage > 0) {
  1035. if (typeof animation !== 'undefined') {
  1036. setAnimation(animation, chart);
  1037. }
  1038. this.nav.attr({
  1039. translateX: padding,
  1040. translateY: clipHeight + this.padding + 7 + this.titleHeight,
  1041. visibility: 'visible'
  1042. });
  1043. [this.up, this.upTracker].forEach(function (elem) {
  1044. elem.attr({
  1045. 'class': currentPage === 1 ?
  1046. 'highcharts-legend-nav-inactive' :
  1047. 'highcharts-legend-nav-active'
  1048. });
  1049. });
  1050. pager.attr({
  1051. text: currentPage + '/' + pageCount
  1052. });
  1053. [this.down, this.downTracker].forEach(function (elem) {
  1054. elem.attr({
  1055. // adjust to text width
  1056. x: 18 + this.pager.getBBox().width,
  1057. 'class': currentPage === pageCount ?
  1058. 'highcharts-legend-nav-inactive' :
  1059. 'highcharts-legend-nav-active'
  1060. });
  1061. }, this);
  1062. if (!chart.styledMode) {
  1063. this.up
  1064. .attr({
  1065. fill: currentPage === 1 ?
  1066. navOptions.inactiveColor :
  1067. navOptions.activeColor
  1068. });
  1069. this.upTracker
  1070. .css({
  1071. cursor: currentPage === 1 ? 'default' : 'pointer'
  1072. });
  1073. this.down
  1074. .attr({
  1075. fill: currentPage === pageCount ?
  1076. navOptions.inactiveColor :
  1077. navOptions.activeColor
  1078. });
  1079. this.downTracker
  1080. .css({
  1081. cursor: currentPage === pageCount ?
  1082. 'default' :
  1083. 'pointer'
  1084. });
  1085. }
  1086. this.scrollOffset = -pages[currentPage - 1] + this.initialItemY;
  1087. this.scrollGroup.animate({
  1088. translateY: this.scrollOffset
  1089. });
  1090. this.currentPage = currentPage;
  1091. this.positionCheckboxes();
  1092. // Fire event after scroll animation is complete
  1093. var animOptions = animObject(pick(animation, chart.renderer.globalAnimation, true));
  1094. syncTimeout(function () {
  1095. fireEvent(_this, 'afterScroll', { currentPage: currentPage });
  1096. }, animOptions.duration || 0);
  1097. }
  1098. };
  1099. return Legend;
  1100. }());
  1101. // Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
  1102. // and for #2580, a similar drawing flaw in Firefox 26.
  1103. // Explore if there's a general cause for this. The problem may be related
  1104. // to nested group elements, as the legend item texts are within 4 group
  1105. // elements.
  1106. if (/Trident\/7\.0/.test(win.navigator && win.navigator.userAgent) ||
  1107. isFirefox) {
  1108. wrap(Legend.prototype, 'positionItem', function (proceed, item) {
  1109. var legend = this,
  1110. // If chart destroyed in sync, this is undefined (#2030)
  1111. runPositionItem = function () {
  1112. if (item._legendItemPos) {
  1113. proceed.call(legend, item);
  1114. }
  1115. };
  1116. // Do it now, for export and to get checkbox placement
  1117. runPositionItem();
  1118. // Do it after to work around the core issue
  1119. if (!legend.bubbleLegend) {
  1120. setTimeout(runPositionItem);
  1121. }
  1122. });
  1123. }
  1124. H.Legend = Legend;
  1125. export default H.Legend;