Legend.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127
  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, void 0, 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) {
  690. if (item.xAxis.options.reversed) {
  691. useFirstPoint = !useFirstPoint;
  692. }
  693. if (item.points) {
  694. lastPoint = find(useFirstPoint ?
  695. item.points :
  696. item.points.slice(0).reverse(), function (item) {
  697. return isNumber(item.plotY);
  698. });
  699. }
  700. height = this.itemMarginTop +
  701. item.legendItem.getBBox().height +
  702. this.itemMarginBottom;
  703. top = item.yAxis.top - chart.plotTop;
  704. if (item.visible) {
  705. target = lastPoint ?
  706. lastPoint.plotY :
  707. item.yAxis.height;
  708. target += top - 0.3 * height;
  709. }
  710. else {
  711. target = top + item.yAxis.height;
  712. }
  713. boxes.push({
  714. target: target,
  715. size: height,
  716. item: item
  717. });
  718. }
  719. }, this);
  720. H.distribute(boxes, chart.plotHeight);
  721. boxes.forEach(function (box) {
  722. box.item._legendItemPos[1] =
  723. chart.plotTop - chart.spacing[0] + box.pos;
  724. });
  725. };
  726. /**
  727. * Render the legend. This method can be called both before and after
  728. * `chart.render`. If called after, it will only rearrange items instead
  729. * of creating new ones. Called internally on initial render and after
  730. * redraws.
  731. *
  732. * @private
  733. * @function Highcharts.Legend#render
  734. */
  735. Legend.prototype.render = function () {
  736. 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;
  737. legend.itemX = padding;
  738. legend.itemY = legend.initialItemY;
  739. legend.offsetWidth = 0;
  740. legend.lastItemY = 0;
  741. legend.widthOption = relativeLength(options.width, chart.spacingBox.width - padding);
  742. // Compute how wide the legend is allowed to be
  743. allowedWidth =
  744. chart.spacingBox.width - 2 * padding - options.x;
  745. if (['rm', 'lm'].indexOf(legend.getAlignment().substring(0, 2)) > -1) {
  746. allowedWidth /= 2;
  747. }
  748. legend.maxLegendWidth = legend.widthOption || allowedWidth;
  749. if (!legendGroup) {
  750. /**
  751. * SVG group of the legend.
  752. *
  753. * @readonly
  754. * @name Highcharts.Legend#group
  755. * @type {Highcharts.SVGElement}
  756. */
  757. legend.group = legendGroup = renderer.g('legend')
  758. .attr({ zIndex: 7 })
  759. .add();
  760. legend.contentGroup = renderer.g()
  761. .attr({ zIndex: 1 }) // above background
  762. .add(legendGroup);
  763. legend.scrollGroup = renderer.g()
  764. .add(legend.contentGroup);
  765. }
  766. legend.renderTitle();
  767. // add each series or point
  768. allItems = legend.getAllItems();
  769. // sort by legendIndex
  770. stableSort(allItems, function (a, b) {
  771. return ((a.options && a.options.legendIndex) || 0) -
  772. ((b.options && b.options.legendIndex) || 0);
  773. });
  774. // reversed legend
  775. if (options.reversed) {
  776. allItems.reverse();
  777. }
  778. /**
  779. * All items for the legend, which is an array of series for most series
  780. * and an array of points for pie series and its derivatives.
  781. *
  782. * @readonly
  783. * @name Highcharts.Legend#allItems
  784. * @type {Array<(Highcharts.Point|Highcharts.Series)>}
  785. */
  786. legend.allItems = allItems;
  787. legend.display = display = !!allItems.length;
  788. // Render the items. First we run a loop to set the text and properties
  789. // and read all the bounding boxes. The next loop computes the item
  790. // positions based on the bounding boxes.
  791. legend.lastLineHeight = 0;
  792. legend.maxItemWidth = 0;
  793. legend.totalItemWidth = 0;
  794. legend.itemHeight = 0;
  795. allItems.forEach(legend.renderItem, legend);
  796. allItems.forEach(legend.layoutItem, legend);
  797. // Get the box
  798. legendWidth = (legend.widthOption || legend.offsetWidth) + padding;
  799. legendHeight = legend.lastItemY + legend.lastLineHeight +
  800. legend.titleHeight;
  801. legendHeight = legend.handleOverflow(legendHeight);
  802. legendHeight += padding;
  803. // Draw the border and/or background
  804. if (!box) {
  805. /**
  806. * SVG element of the legend box.
  807. *
  808. * @readonly
  809. * @name Highcharts.Legend#box
  810. * @type {Highcharts.SVGElement}
  811. */
  812. legend.box = box = renderer.rect()
  813. .addClass('highcharts-legend-box')
  814. .attr({
  815. r: options.borderRadius
  816. })
  817. .add(legendGroup);
  818. box.isNew = true;
  819. }
  820. // Presentational
  821. if (!chart.styledMode) {
  822. box
  823. .attr({
  824. stroke: options.borderColor,
  825. 'stroke-width': options.borderWidth || 0,
  826. fill: options.backgroundColor || 'none'
  827. })
  828. .shadow(options.shadow);
  829. }
  830. if (legendWidth > 0 && legendHeight > 0) {
  831. box[box.isNew ? 'attr' : 'animate'](box.crisp.call({}, {
  832. x: 0,
  833. y: 0,
  834. width: legendWidth,
  835. height: legendHeight
  836. }, box.strokeWidth()));
  837. box.isNew = false;
  838. }
  839. // hide the border if no items
  840. box[display ? 'show' : 'hide']();
  841. // Open for responsiveness
  842. if (chart.styledMode && legendGroup.getStyle('display') === 'none') {
  843. legendWidth = legendHeight = 0;
  844. }
  845. legend.legendWidth = legendWidth;
  846. legend.legendHeight = legendHeight;
  847. if (display) {
  848. legend.align();
  849. }
  850. if (!this.proximate) {
  851. this.positionItems();
  852. }
  853. fireEvent(this, 'afterRender');
  854. };
  855. /**
  856. * Align the legend to chart's box.
  857. *
  858. * @private
  859. * @function Highcharts.align
  860. * @param {Highcharts.BBoxObject} alignTo
  861. * @return {void}
  862. */
  863. Legend.prototype.align = function (alignTo) {
  864. if (alignTo === void 0) { alignTo = this.chart.spacingBox; }
  865. var chart = this.chart, options = this.options;
  866. // If aligning to the top and the layout is horizontal, adjust for
  867. // the title (#7428)
  868. var y = alignTo.y;
  869. if (/(lth|ct|rth)/.test(this.getAlignment()) &&
  870. chart.titleOffset[0] > 0) {
  871. y += chart.titleOffset[0];
  872. }
  873. else if (/(lbh|cb|rbh)/.test(this.getAlignment()) &&
  874. chart.titleOffset[2] > 0) {
  875. y -= chart.titleOffset[2];
  876. }
  877. if (y !== alignTo.y) {
  878. alignTo = merge(alignTo, { y: y });
  879. }
  880. this.group.align(merge(options, {
  881. width: this.legendWidth,
  882. height: this.legendHeight,
  883. verticalAlign: this.proximate ? 'top' : options.verticalAlign
  884. }), true, alignTo);
  885. };
  886. /**
  887. * Set up the overflow handling by adding navigation with up and down arrows
  888. * below the legend.
  889. *
  890. * @private
  891. * @function Highcharts.Legend#handleOverflow
  892. * @param {number} legendHeight
  893. * @return {number}
  894. */
  895. Legend.prototype.handleOverflow = function (legendHeight) {
  896. 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 +
  897. (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) {
  898. if (typeof height === 'number') {
  899. clipRect.attr({
  900. height: height
  901. });
  902. }
  903. else if (clipRect) { // Reset (#5912)
  904. legend.clipRect = clipRect.destroy();
  905. legend.contentGroup.clip();
  906. }
  907. // useHTML
  908. if (legend.contentGroup.div) {
  909. legend.contentGroup.div.style.clip = height ?
  910. 'rect(' + padding + 'px,9999px,' +
  911. (padding + height) + 'px,0)' :
  912. 'auto';
  913. }
  914. }, addTracker = function (key) {
  915. legend[key] = renderer
  916. .circle(0, 0, arrowSize * 1.3)
  917. .translate(arrowSize / 2, arrowSize / 2)
  918. .add(nav);
  919. if (!chart.styledMode) {
  920. legend[key].attr('fill', 'rgba(0,0,0,0.0001)');
  921. }
  922. return legend[key];
  923. };
  924. // Adjust the height
  925. if (options.layout === 'horizontal' &&
  926. options.verticalAlign !== 'middle' &&
  927. !options.floating) {
  928. spaceHeight /= 2;
  929. }
  930. if (maxHeight) {
  931. spaceHeight = Math.min(spaceHeight, maxHeight);
  932. }
  933. // Reset the legend height and adjust the clipping rectangle
  934. pages.length = 0;
  935. if (legendHeight > spaceHeight &&
  936. navOptions.enabled !== false) {
  937. this.clipHeight = clipHeight =
  938. Math.max(spaceHeight - 20 - this.titleHeight - padding, 0);
  939. this.currentPage = pick(this.currentPage, 1);
  940. this.fullHeight = legendHeight;
  941. // Fill pages with Y positions so that the top of each a legend item
  942. // defines the scroll top for each page (#2098)
  943. allItems.forEach(function (item, i) {
  944. var y = item._legendItemPos[1], h = Math.round(item.legendItem.getBBox().height), len = pages.length;
  945. if (!len || (y - pages[len - 1] > clipHeight &&
  946. (lastY || y) !== pages[len - 1])) {
  947. pages.push(lastY || y);
  948. len++;
  949. }
  950. // Keep track of which page each item is on
  951. item.pageIx = len - 1;
  952. if (lastY) {
  953. allItems[i - 1].pageIx = len - 1;
  954. }
  955. if (i === allItems.length - 1 &&
  956. y + h - pages[len - 1] > clipHeight &&
  957. y !== lastY // #2617
  958. ) {
  959. pages.push(y);
  960. item.pageIx = len;
  961. }
  962. if (y !== lastY) {
  963. lastY = y;
  964. }
  965. });
  966. // Only apply clipping if needed. Clipping causes blurred legend in
  967. // PDF export (#1787)
  968. if (!clipRect) {
  969. clipRect = legend.clipRect =
  970. renderer.clipRect(0, padding, 9999, 0);
  971. legend.contentGroup.clip(clipRect);
  972. }
  973. clipToHeight(clipHeight);
  974. // Add navigation elements
  975. if (!nav) {
  976. this.nav = nav = renderer.g()
  977. .attr({ zIndex: 1 })
  978. .add(this.group);
  979. this.up = renderer
  980. .symbol('triangle', 0, 0, arrowSize, arrowSize)
  981. .add(nav);
  982. addTracker('upTracker')
  983. .on('click', function () {
  984. legend.scroll(-1, animation);
  985. });
  986. this.pager = renderer.text('', 15, 10)
  987. .addClass('highcharts-legend-navigation');
  988. if (!chart.styledMode) {
  989. this.pager.css(navOptions.style);
  990. }
  991. this.pager.add(nav);
  992. this.down = renderer
  993. .symbol('triangle-down', 0, 0, arrowSize, arrowSize)
  994. .add(nav);
  995. addTracker('downTracker')
  996. .on('click', function () {
  997. legend.scroll(1, animation);
  998. });
  999. }
  1000. // Set initial position
  1001. legend.scroll(0);
  1002. legendHeight = spaceHeight;
  1003. // Reset
  1004. }
  1005. else if (nav) {
  1006. clipToHeight();
  1007. this.nav = nav.destroy(); // #6322
  1008. this.scrollGroup.attr({
  1009. translateY: 1
  1010. });
  1011. this.clipHeight = 0; // #1379
  1012. }
  1013. return legendHeight;
  1014. };
  1015. /**
  1016. * Scroll the legend by a number of pages.
  1017. *
  1018. * @private
  1019. * @function Highcharts.Legend#scroll
  1020. *
  1021. * @param {number} scrollBy
  1022. * The number of pages to scroll.
  1023. *
  1024. * @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation]
  1025. * Whether and how to apply animation.
  1026. *
  1027. * @return {void}
  1028. */
  1029. Legend.prototype.scroll = function (scrollBy, animation) {
  1030. var _this = this;
  1031. 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;
  1032. // When resizing while looking at the last page
  1033. if (currentPage > pageCount) {
  1034. currentPage = pageCount;
  1035. }
  1036. if (currentPage > 0) {
  1037. if (typeof animation !== 'undefined') {
  1038. setAnimation(animation, chart);
  1039. }
  1040. this.nav.attr({
  1041. translateX: padding,
  1042. translateY: clipHeight + this.padding + 7 + this.titleHeight,
  1043. visibility: 'visible'
  1044. });
  1045. [this.up, this.upTracker].forEach(function (elem) {
  1046. elem.attr({
  1047. 'class': currentPage === 1 ?
  1048. 'highcharts-legend-nav-inactive' :
  1049. 'highcharts-legend-nav-active'
  1050. });
  1051. });
  1052. pager.attr({
  1053. text: currentPage + '/' + pageCount
  1054. });
  1055. [this.down, this.downTracker].forEach(function (elem) {
  1056. elem.attr({
  1057. // adjust to text width
  1058. x: 18 + this.pager.getBBox().width,
  1059. 'class': currentPage === pageCount ?
  1060. 'highcharts-legend-nav-inactive' :
  1061. 'highcharts-legend-nav-active'
  1062. });
  1063. }, this);
  1064. if (!chart.styledMode) {
  1065. this.up
  1066. .attr({
  1067. fill: currentPage === 1 ?
  1068. navOptions.inactiveColor :
  1069. navOptions.activeColor
  1070. });
  1071. this.upTracker
  1072. .css({
  1073. cursor: currentPage === 1 ? 'default' : 'pointer'
  1074. });
  1075. this.down
  1076. .attr({
  1077. fill: currentPage === pageCount ?
  1078. navOptions.inactiveColor :
  1079. navOptions.activeColor
  1080. });
  1081. this.downTracker
  1082. .css({
  1083. cursor: currentPage === pageCount ?
  1084. 'default' :
  1085. 'pointer'
  1086. });
  1087. }
  1088. this.scrollOffset = -pages[currentPage - 1] + this.initialItemY;
  1089. this.scrollGroup.animate({
  1090. translateY: this.scrollOffset
  1091. });
  1092. this.currentPage = currentPage;
  1093. this.positionCheckboxes();
  1094. // Fire event after scroll animation is complete
  1095. var animOptions = animObject(pick(animation, chart.renderer.globalAnimation, true));
  1096. syncTimeout(function () {
  1097. fireEvent(_this, 'afterScroll', { currentPage: currentPage });
  1098. }, animOptions.duration);
  1099. }
  1100. };
  1101. return Legend;
  1102. }());
  1103. // Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
  1104. // and for #2580, a similar drawing flaw in Firefox 26.
  1105. // Explore if there's a general cause for this. The problem may be related
  1106. // to nested group elements, as the legend item texts are within 4 group
  1107. // elements.
  1108. if (/Trident\/7\.0/.test(win.navigator && win.navigator.userAgent) ||
  1109. isFirefox) {
  1110. wrap(Legend.prototype, 'positionItem', function (proceed, item) {
  1111. var legend = this,
  1112. // If chart destroyed in sync, this is undefined (#2030)
  1113. runPositionItem = function () {
  1114. if (item._legendItemPos) {
  1115. proceed.call(legend, item);
  1116. }
  1117. };
  1118. // Do it now, for export and to get checkbox placement
  1119. runPositionItem();
  1120. // Do it after to work around the core issue
  1121. if (!legend.bubbleLegend) {
  1122. setTimeout(runPositionItem);
  1123. }
  1124. });
  1125. }
  1126. H.Legend = Legend;
  1127. export default H.Legend;