Legend.js 43 KB

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