Chart.js 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036
  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 Axis from '../Axis/Axis.js';
  12. import H from '../Globals.js';
  13. var charts = H.charts, doc = H.doc, seriesTypes = H.seriesTypes, win = H.win;
  14. import Legend from '../Legend.js';
  15. import MSPointer from '../MSPointer.js';
  16. import O from '../Options.js';
  17. var defaultOptions = O.defaultOptions;
  18. import Pointer from '../Pointer.js';
  19. import Time from '../Time.js';
  20. import U from '../Utilities.js';
  21. var addEvent = U.addEvent, animate = U.animate, animObject = U.animObject, attr = U.attr, createElement = U.createElement, css = U.css, defined = U.defined, discardElement = U.discardElement, erase = U.erase, error = U.error, extend = U.extend, find = U.find, fireEvent = U.fireEvent, getStyle = U.getStyle, isArray = U.isArray, isFunction = U.isFunction, isNumber = U.isNumber, isObject = U.isObject, isString = U.isString, merge = U.merge, numberFormat = U.numberFormat, objectEach = U.objectEach, pick = U.pick, pInt = U.pInt, relativeLength = U.relativeLength, removeEvent = U.removeEvent, setAnimation = U.setAnimation, splat = U.splat, syncTimeout = U.syncTimeout, uniqueKey = U.uniqueKey;
  22. /**
  23. * Callback for chart constructors.
  24. *
  25. * @callback Highcharts.ChartCallbackFunction
  26. *
  27. * @param {Highcharts.Chart} chart
  28. * Created chart.
  29. */
  30. /**
  31. * Format a number and return a string based on input settings.
  32. *
  33. * @callback Highcharts.NumberFormatterCallbackFunction
  34. *
  35. * @param {number} number
  36. * The input number to format.
  37. *
  38. * @param {number} decimals
  39. * The amount of decimals. A value of -1 preserves the amount in the
  40. * input number.
  41. *
  42. * @param {string} [decimalPoint]
  43. * The decimal point, defaults to the one given in the lang options, or
  44. * a dot.
  45. *
  46. * @param {string} [thousandsSep]
  47. * The thousands separator, defaults to the one given in the lang
  48. * options, or a space character.
  49. *
  50. * @return {string} The formatted number.
  51. */
  52. /**
  53. * The chart title. The title has an `update` method that allows modifying the
  54. * options directly or indirectly via `chart.update`.
  55. *
  56. * @interface Highcharts.TitleObject
  57. * @extends Highcharts.SVGElement
  58. */ /**
  59. * Modify options for the title.
  60. *
  61. * @function Highcharts.TitleObject#update
  62. *
  63. * @param {Highcharts.TitleOptions} titleOptions
  64. * Options to modify.
  65. *
  66. * @param {boolean} [redraw=true]
  67. * Whether to redraw the chart after the title is altered. If doing more
  68. * operations on the chart, it is a good idea to set redraw to false and
  69. * call {@link Chart#redraw} after.
  70. */
  71. /**
  72. * The chart subtitle. The subtitle has an `update` method that
  73. * allows modifying the options directly or indirectly via
  74. * `chart.update`.
  75. *
  76. * @interface Highcharts.SubtitleObject
  77. * @extends Highcharts.SVGElement
  78. */ /**
  79. * Modify options for the subtitle.
  80. *
  81. * @function Highcharts.SubtitleObject#update
  82. *
  83. * @param {Highcharts.SubtitleOptions} subtitleOptions
  84. * Options to modify.
  85. *
  86. * @param {boolean} [redraw=true]
  87. * Whether to redraw the chart after the subtitle is altered. If doing
  88. * more operations on the chart, it is a good idea to set redraw to false
  89. * and call {@link Chart#redraw} after.
  90. */
  91. /**
  92. * The chart caption. The caption has an `update` method that
  93. * allows modifying the options directly or indirectly via
  94. * `chart.update`.
  95. *
  96. * @interface Highcharts.CaptionObject
  97. * @extends Highcharts.SVGElement
  98. */ /**
  99. * Modify options for the caption.
  100. *
  101. * @function Highcharts.CaptionObject#update
  102. *
  103. * @param {Highcharts.CaptionOptions} captionOptions
  104. * Options to modify.
  105. *
  106. * @param {boolean} [redraw=true]
  107. * Whether to redraw the chart after the caption is altered. If doing
  108. * more operations on the chart, it is a good idea to set redraw to false
  109. * and call {@link Chart#redraw} after.
  110. */
  111. var marginNames = H.marginNames;
  112. /* eslint-disable no-invalid-this, valid-jsdoc */
  113. /**
  114. * The Chart class. The recommended constructor is {@link Highcharts#chart}.
  115. *
  116. * @example
  117. * var chart = Highcharts.chart('container', {
  118. * title: {
  119. * text: 'My chart'
  120. * },
  121. * series: [{
  122. * data: [1, 3, 2, 4]
  123. * }]
  124. * })
  125. *
  126. * @class
  127. * @name Highcharts.Chart
  128. *
  129. * @param {string|Highcharts.HTMLDOMElement} [renderTo]
  130. * The DOM element to render to, or its id.
  131. *
  132. * @param {Highcharts.Options} options
  133. * The chart options structure.
  134. *
  135. * @param {Highcharts.ChartCallbackFunction} [callback]
  136. * Function to run when the chart has loaded and and all external images
  137. * are loaded. Defining a
  138. * [chart.events.load](https://api.highcharts.com/highcharts/chart.events.load)
  139. * handler is equivalent.
  140. */
  141. var Chart = /** @class */ (function () {
  142. function Chart(a, b, c) {
  143. this.axes = void 0;
  144. this.axisOffset = void 0;
  145. this.bounds = void 0;
  146. this.chartHeight = void 0;
  147. this.chartWidth = void 0;
  148. this.clipBox = void 0;
  149. this.colorCounter = void 0;
  150. this.container = void 0;
  151. this.index = void 0;
  152. this.isResizing = void 0;
  153. this.labelCollectors = void 0;
  154. this.legend = void 0;
  155. this.margin = void 0;
  156. this.numberFormatter = void 0;
  157. this.options = void 0;
  158. this.plotBox = void 0;
  159. this.plotHeight = void 0;
  160. this.plotLeft = void 0;
  161. this.plotTop = void 0;
  162. this.plotWidth = void 0;
  163. this.pointCount = void 0;
  164. this.pointer = void 0;
  165. this.renderer = void 0;
  166. this.renderTo = void 0;
  167. this.series = void 0;
  168. this.spacing = void 0;
  169. this.spacingBox = void 0;
  170. this.symbolCounter = void 0;
  171. this.time = void 0;
  172. this.titleOffset = void 0;
  173. this.userOptions = void 0;
  174. this.xAxis = void 0;
  175. this.yAxis = void 0;
  176. this.getArgs(a, b, c);
  177. }
  178. /* *
  179. *
  180. * Functions
  181. *
  182. * */
  183. /**
  184. * Handle the arguments passed to the constructor.
  185. *
  186. * @private
  187. * @function Highcharts.Chart#getArgs
  188. *
  189. * @param {...Array<*>} arguments
  190. * All arguments for the constructor.
  191. *
  192. * @fires Highcharts.Chart#event:init
  193. * @fires Highcharts.Chart#event:afterInit
  194. */
  195. Chart.prototype.getArgs = function (a, b, c) {
  196. // Remove the optional first argument, renderTo, and
  197. // set it on this.
  198. if (isString(a) || a.nodeName) {
  199. this.renderTo = a;
  200. this.init(b, c);
  201. }
  202. else {
  203. this.init(a, b);
  204. }
  205. };
  206. /**
  207. * Overridable function that initializes the chart. The constructor's
  208. * arguments are passed on directly.
  209. *
  210. * @function Highcharts.Chart#init
  211. *
  212. * @param {Highcharts.Options} userOptions
  213. * Custom options.
  214. *
  215. * @param {Function} [callback]
  216. * Function to run when the chart has loaded and and all external
  217. * images are loaded.
  218. *
  219. * @return {void}
  220. *
  221. * @fires Highcharts.Chart#event:init
  222. * @fires Highcharts.Chart#event:afterInit
  223. */
  224. Chart.prototype.init = function (userOptions, callback) {
  225. // Handle regular options
  226. var options,
  227. // skip merging data points to increase performance
  228. seriesOptions = userOptions.series, userPlotOptions = userOptions.plotOptions || {};
  229. // Fire the event with a default function
  230. fireEvent(this, 'init', { args: arguments }, function () {
  231. userOptions.series = null;
  232. options = merge(defaultOptions, userOptions); // do the merge
  233. var optionsChart = options.chart || {};
  234. // Override (by copy of user options) or clear tooltip options
  235. // in chart.options.plotOptions (#6218)
  236. objectEach(options.plotOptions, function (typeOptions, type) {
  237. if (isObject(typeOptions)) { // #8766
  238. typeOptions.tooltip = (userPlotOptions[type] && // override by copy:
  239. merge(userPlotOptions[type].tooltip)) || void 0; // or clear
  240. }
  241. });
  242. // User options have higher priority than default options
  243. // (#6218). In case of exporting: path is changed
  244. options.tooltip.userOptions = (userOptions.chart &&
  245. userOptions.chart.forExport &&
  246. userOptions.tooltip.userOptions) || userOptions.tooltip;
  247. // set back the series data
  248. options.series = userOptions.series = seriesOptions;
  249. /**
  250. * The original options given to the constructor or a chart factory
  251. * like {@link Highcharts.chart} and {@link Highcharts.stockChart}.
  252. *
  253. * @name Highcharts.Chart#userOptions
  254. * @type {Highcharts.Options}
  255. */
  256. this.userOptions = userOptions;
  257. var chartEvents = optionsChart.events;
  258. this.margin = [];
  259. this.spacing = [];
  260. // Pixel data bounds for touch zoom
  261. this.bounds = { h: {}, v: {} };
  262. // An array of functions that returns labels that should be
  263. // considered for anti-collision
  264. this.labelCollectors = [];
  265. this.callback = callback;
  266. this.isResizing = 0;
  267. /**
  268. * The options structure for the chart after merging
  269. * {@link #defaultOptions} and {@link #userOptions}. It contains
  270. * members for the sub elements like series, legend, tooltip etc.
  271. *
  272. * @name Highcharts.Chart#options
  273. * @type {Highcharts.Options}
  274. */
  275. this.options = options;
  276. /**
  277. * All the axes in the chart.
  278. *
  279. * @see Highcharts.Chart.xAxis
  280. * @see Highcharts.Chart.yAxis
  281. *
  282. * @name Highcharts.Chart#axes
  283. * @type {Array<Highcharts.Axis>}
  284. */
  285. this.axes = [];
  286. /**
  287. * All the current series in the chart.
  288. *
  289. * @name Highcharts.Chart#series
  290. * @type {Array<Highcharts.Series>}
  291. */
  292. this.series = [];
  293. /**
  294. * The `Time` object associated with the chart. Since v6.0.5,
  295. * time settings can be applied individually for each chart. If
  296. * no individual settings apply, the `Time` object is shared by
  297. * all instances.
  298. *
  299. * @name Highcharts.Chart#time
  300. * @type {Highcharts.Time}
  301. */
  302. this.time =
  303. userOptions.time && Object.keys(userOptions.time).length ?
  304. new Time(userOptions.time) :
  305. H.time;
  306. /**
  307. * Callback function to override the default function that formats
  308. * all the numbers in the chart. Returns a string with the formatted
  309. * number.
  310. *
  311. * @name Highcharts.Chart#numberFormatter
  312. * @type {Highcharts.NumberFormatterCallbackFunction}
  313. */
  314. this.numberFormatter = optionsChart.numberFormatter || numberFormat;
  315. /**
  316. * Whether the chart is in styled mode, meaning all presentatinoal
  317. * attributes are avoided.
  318. *
  319. * @name Highcharts.Chart#styledMode
  320. * @type {boolean}
  321. */
  322. this.styledMode = optionsChart.styledMode;
  323. this.hasCartesianSeries = optionsChart.showAxes;
  324. var chart = this;
  325. /**
  326. * Index position of the chart in the {@link Highcharts#charts}
  327. * property.
  328. *
  329. * @name Highcharts.Chart#index
  330. * @type {number}
  331. * @readonly
  332. */
  333. chart.index = charts.length; // Add the chart to the global lookup
  334. charts.push(chart);
  335. H.chartCount++;
  336. // Chart event handlers
  337. if (chartEvents) {
  338. objectEach(chartEvents, function (event, eventType) {
  339. if (isFunction(event)) {
  340. addEvent(chart, eventType, event);
  341. }
  342. });
  343. }
  344. /**
  345. * A collection of the X axes in the chart.
  346. *
  347. * @name Highcharts.Chart#xAxis
  348. * @type {Array<Highcharts.Axis>}
  349. */
  350. chart.xAxis = [];
  351. /**
  352. * A collection of the Y axes in the chart.
  353. *
  354. * @name Highcharts.Chart#yAxis
  355. * @type {Array<Highcharts.Axis>}
  356. *
  357. * @todo
  358. * Make events official: Fire the event `afterInit`.
  359. */
  360. chart.yAxis = [];
  361. chart.pointCount = chart.colorCounter = chart.symbolCounter = 0;
  362. // Fire after init but before first render, before axes and series
  363. // have been initialized.
  364. fireEvent(chart, 'afterInit');
  365. chart.firstRender();
  366. });
  367. };
  368. /**
  369. * Internal function to unitialize an individual series.
  370. *
  371. * @private
  372. * @function Highcharts.Chart#initSeries
  373. */
  374. Chart.prototype.initSeries = function (options) {
  375. var chart = this, optionsChart = chart.options.chart, type = (options.type ||
  376. optionsChart.type ||
  377. optionsChart.defaultSeriesType), series, Constr = seriesTypes[type];
  378. // No such series type
  379. if (!Constr) {
  380. error(17, true, chart, { missingModuleFor: type });
  381. }
  382. series = new Constr();
  383. series.init(this, options);
  384. return series;
  385. };
  386. /**
  387. * Internal function to set data for all series with enabled sorting.
  388. *
  389. * @private
  390. * @function Highcharts.Chart#setSeriesData
  391. */
  392. Chart.prototype.setSeriesData = function () {
  393. this.getSeriesOrderByLinks().forEach(function (series) {
  394. // We need to set data for series with sorting after series init
  395. if (!series.points && !series.data && series.enabledDataSorting) {
  396. series.setData(series.options.data, false);
  397. }
  398. });
  399. };
  400. /**
  401. * Sort and return chart series in order depending on the number of linked
  402. * series.
  403. *
  404. * @private
  405. * @function Highcharts.Series#getSeriesOrderByLinks
  406. * @return {Array<Highcharts.Series>}
  407. */
  408. Chart.prototype.getSeriesOrderByLinks = function () {
  409. return this.series.concat().sort(function (a, b) {
  410. if (a.linkedSeries.length || b.linkedSeries.length) {
  411. return b.linkedSeries.length - a.linkedSeries.length;
  412. }
  413. return 0;
  414. });
  415. };
  416. /**
  417. * Order all series above a given index. When series are added and ordered
  418. * by configuration, only the last series is handled (#248, #1123, #2456,
  419. * #6112). This function is called on series initialization and destroy.
  420. *
  421. * @private
  422. * @function Highcharts.Series#orderSeries
  423. * @param {number} [fromIndex]
  424. * If this is given, only the series above this index are handled.
  425. */
  426. Chart.prototype.orderSeries = function (fromIndex) {
  427. var series = this.series, i = fromIndex || 0;
  428. for (; i < series.length; i++) {
  429. if (series[i]) {
  430. /**
  431. * Contains the series' index in the `Chart.series` array.
  432. *
  433. * @name Highcharts.Series#index
  434. * @type {number}
  435. * @readonly
  436. */
  437. series[i].index = i;
  438. series[i].name = series[i].getName();
  439. }
  440. }
  441. };
  442. /**
  443. * Check whether a given point is within the plot area.
  444. *
  445. * @function Highcharts.Chart#isInsidePlot
  446. *
  447. * @param {number} plotX
  448. * Pixel x relative to the plot area.
  449. *
  450. * @param {number} plotY
  451. * Pixel y relative to the plot area.
  452. *
  453. * @param {boolean} [inverted]
  454. * Whether the chart is inverted.
  455. *
  456. * @return {boolean}
  457. * Returns true if the given point is inside the plot area.
  458. */
  459. Chart.prototype.isInsidePlot = function (plotX, plotY, inverted) {
  460. var x = inverted ? plotY : plotX, y = inverted ? plotX : plotY, e = {
  461. x: x,
  462. y: y,
  463. isInsidePlot: x >= 0 &&
  464. x <= this.plotWidth &&
  465. y >= 0 &&
  466. y <= this.plotHeight
  467. };
  468. fireEvent(this, 'afterIsInsidePlot', e);
  469. return e.isInsidePlot;
  470. };
  471. /**
  472. * Redraw the chart after changes have been done to the data, axis extremes
  473. * chart size or chart elements. All methods for updating axes, series or
  474. * points have a parameter for redrawing the chart. This is `true` by
  475. * default. But in many cases you want to do more than one operation on the
  476. * chart before redrawing, for example add a number of points. In those
  477. * cases it is a waste of resources to redraw the chart for each new point
  478. * added. So you add the points and call `chart.redraw()` after.
  479. *
  480. * @function Highcharts.Chart#redraw
  481. *
  482. * @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation]
  483. * If or how to apply animation to the redraw.
  484. *
  485. * @fires Highcharts.Chart#event:afterSetExtremes
  486. * @fires Highcharts.Chart#event:beforeRedraw
  487. * @fires Highcharts.Chart#event:predraw
  488. * @fires Highcharts.Chart#event:redraw
  489. * @fires Highcharts.Chart#event:render
  490. * @fires Highcharts.Chart#event:updatedData
  491. */
  492. Chart.prototype.redraw = function (animation) {
  493. fireEvent(this, 'beforeRedraw');
  494. var chart = this, axes = chart.axes, series = chart.series, pointer = chart.pointer, legend = chart.legend, legendUserOptions = chart.userOptions.legend, redrawLegend = chart.isDirtyLegend, hasStackedSeries, hasDirtyStacks, hasCartesianSeries = chart.hasCartesianSeries, isDirtyBox = chart.isDirtyBox, i, serie, renderer = chart.renderer, isHiddenChart = renderer.isHidden(), afterRedraw = [];
  495. // Handle responsive rules, not only on resize (#6130)
  496. if (chart.setResponsive) {
  497. chart.setResponsive(false);
  498. }
  499. // Set the global animation. When chart.hasRendered is not true, the
  500. // redraw call comes from a responsive rule and animation should not
  501. // occur.
  502. setAnimation(chart.hasRendered ? animation : false, chart);
  503. if (isHiddenChart) {
  504. chart.temporaryDisplay();
  505. }
  506. // Adjust title layout (reflow multiline text)
  507. chart.layOutTitles();
  508. // link stacked series
  509. i = series.length;
  510. while (i--) {
  511. serie = series[i];
  512. if (serie.options.stacking) {
  513. hasStackedSeries = true;
  514. if (serie.isDirty) {
  515. hasDirtyStacks = true;
  516. break;
  517. }
  518. }
  519. }
  520. if (hasDirtyStacks) { // mark others as dirty
  521. i = series.length;
  522. while (i--) {
  523. serie = series[i];
  524. if (serie.options.stacking) {
  525. serie.isDirty = true;
  526. }
  527. }
  528. }
  529. // Handle updated data in the series
  530. series.forEach(function (serie) {
  531. if (serie.isDirty) {
  532. if (serie.options.legendType === 'point') {
  533. if (serie.updateTotals) {
  534. serie.updateTotals();
  535. }
  536. redrawLegend = true;
  537. }
  538. else if (legendUserOptions &&
  539. (legendUserOptions.labelFormatter ||
  540. legendUserOptions.labelFormat)) {
  541. redrawLegend = true; // #2165
  542. }
  543. }
  544. if (serie.isDirtyData) {
  545. fireEvent(serie, 'updatedData');
  546. }
  547. });
  548. // handle added or removed series
  549. if (redrawLegend && legend && legend.options.enabled) {
  550. // draw legend graphics
  551. legend.render();
  552. chart.isDirtyLegend = false;
  553. }
  554. // reset stacks
  555. if (hasStackedSeries) {
  556. chart.getStacks();
  557. }
  558. if (hasCartesianSeries) {
  559. // set axes scales
  560. axes.forEach(function (axis) {
  561. // Don't do setScale again if we're only resizing. Regression
  562. // #13507. But we need it after chart.update (responsive), as
  563. // axis is initialized again (#12137).
  564. if (!chart.isResizing || !isNumber(axis.min)) {
  565. axis.updateNames();
  566. axis.setScale();
  567. }
  568. });
  569. }
  570. chart.getMargins(); // #3098
  571. if (hasCartesianSeries) {
  572. // If one axis is dirty, all axes must be redrawn (#792, #2169)
  573. axes.forEach(function (axis) {
  574. if (axis.isDirty) {
  575. isDirtyBox = true;
  576. }
  577. });
  578. // redraw axes
  579. axes.forEach(function (axis) {
  580. // Fire 'afterSetExtremes' only if extremes are set
  581. var key = axis.min + ',' + axis.max;
  582. if (axis.extKey !== key) { // #821, #4452
  583. axis.extKey = key;
  584. // prevent a recursive call to chart.redraw() (#1119)
  585. afterRedraw.push(function () {
  586. fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
  587. delete axis.eventArgs;
  588. });
  589. }
  590. if (isDirtyBox || hasStackedSeries) {
  591. axis.redraw();
  592. }
  593. });
  594. }
  595. // the plot areas size has changed
  596. if (isDirtyBox) {
  597. chart.drawChartBox();
  598. }
  599. // Fire an event before redrawing series, used by the boost module to
  600. // clear previous series renderings.
  601. fireEvent(chart, 'predraw');
  602. // redraw affected series
  603. series.forEach(function (serie) {
  604. if ((isDirtyBox || serie.isDirty) && serie.visible) {
  605. serie.redraw();
  606. }
  607. // Set it here, otherwise we will have unlimited 'updatedData' calls
  608. // for a hidden series after setData(). Fixes #6012
  609. serie.isDirtyData = false;
  610. });
  611. // move tooltip or reset
  612. if (pointer) {
  613. pointer.reset(true);
  614. }
  615. // redraw if canvas
  616. renderer.draw();
  617. // Fire the events
  618. fireEvent(chart, 'redraw');
  619. fireEvent(chart, 'render');
  620. if (isHiddenChart) {
  621. chart.temporaryDisplay(true);
  622. }
  623. // Fire callbacks that are put on hold until after the redraw
  624. afterRedraw.forEach(function (callback) {
  625. callback.call();
  626. });
  627. };
  628. /**
  629. * Get an axis, series or point object by `id` as given in the configuration
  630. * options. Returns `undefined` if no item is found.
  631. *
  632. * @sample highcharts/plotoptions/series-id/
  633. * Get series by id
  634. *
  635. * @function Highcharts.Chart#get
  636. *
  637. * @param {string} id
  638. * The id as given in the configuration options.
  639. *
  640. * @return {Highcharts.Axis|Highcharts.Series|Highcharts.Point|undefined}
  641. * The retrieved item.
  642. */
  643. Chart.prototype.get = function (id) {
  644. var ret, series = this.series, i;
  645. /**
  646. * @private
  647. * @param {Highcharts.Axis|Highcharts.Series} item
  648. * @return {boolean}
  649. */
  650. function itemById(item) {
  651. return (item.id === id ||
  652. (item.options && item.options.id === id));
  653. }
  654. ret =
  655. // Search axes
  656. find(this.axes, itemById) ||
  657. // Search series
  658. find(this.series, itemById);
  659. // Search points
  660. for (i = 0; !ret && i < series.length; i++) {
  661. ret = find(series[i].points || [], itemById);
  662. }
  663. return ret;
  664. };
  665. /**
  666. * Create the Axis instances based on the config options.
  667. *
  668. * @private
  669. * @function Highcharts.Chart#getAxes
  670. * @fires Highcharts.Chart#event:afterGetAxes
  671. * @fires Highcharts.Chart#event:getAxes
  672. */
  673. Chart.prototype.getAxes = function () {
  674. var chart = this, options = this.options, xAxisOptions = options.xAxis = splat(options.xAxis || {}), yAxisOptions = options.yAxis = splat(options.yAxis || {}), optionsArray;
  675. fireEvent(this, 'getAxes');
  676. // make sure the options are arrays and add some members
  677. xAxisOptions.forEach(function (axis, i) {
  678. axis.index = i;
  679. axis.isX = true;
  680. });
  681. yAxisOptions.forEach(function (axis, i) {
  682. axis.index = i;
  683. });
  684. // concatenate all axis options into one array
  685. optionsArray = xAxisOptions.concat(yAxisOptions);
  686. optionsArray.forEach(function (axisOptions) {
  687. new Axis(chart, axisOptions); // eslint-disable-line no-new
  688. });
  689. fireEvent(this, 'afterGetAxes');
  690. };
  691. /**
  692. * Returns an array of all currently selected points in the chart. Points
  693. * can be selected by clicking or programmatically by the
  694. * {@link Highcharts.Point#select}
  695. * function.
  696. *
  697. * @sample highcharts/plotoptions/series-allowpointselect-line/
  698. * Get selected points
  699. *
  700. * @function Highcharts.Chart#getSelectedPoints
  701. *
  702. * @return {Array<Highcharts.Point>}
  703. * The currently selected points.
  704. */
  705. Chart.prototype.getSelectedPoints = function () {
  706. var points = [];
  707. this.series.forEach(function (serie) {
  708. // For one-to-one points inspect series.data in order to retrieve
  709. // points outside the visible range (#6445). For grouped data,
  710. // inspect the generated series.points.
  711. points = points.concat(serie.getPointsCollection().filter(function (point) {
  712. return pick(point.selectedStaging, point.selected);
  713. }));
  714. });
  715. return points;
  716. };
  717. /**
  718. * Returns an array of all currently selected series in the chart. Series
  719. * can be selected either programmatically by the
  720. * {@link Highcharts.Series#select}
  721. * function or by checking the checkbox next to the legend item if
  722. * [series.showCheckBox](https://api.highcharts.com/highcharts/plotOptions.series.showCheckbox)
  723. * is true.
  724. *
  725. * @sample highcharts/members/chart-getselectedseries/
  726. * Get selected series
  727. *
  728. * @function Highcharts.Chart#getSelectedSeries
  729. *
  730. * @return {Array<Highcharts.Series>}
  731. * The currently selected series.
  732. */
  733. Chart.prototype.getSelectedSeries = function () {
  734. return this.series.filter(function (serie) {
  735. return serie.selected;
  736. });
  737. };
  738. /**
  739. * Set a new title or subtitle for the chart.
  740. *
  741. * @sample highcharts/members/chart-settitle/
  742. * Set title text and styles
  743. *
  744. * @function Highcharts.Chart#setTitle
  745. *
  746. * @param {Highcharts.TitleOptions} [titleOptions]
  747. * New title options. The title text itself is set by the
  748. * `titleOptions.text` property.
  749. *
  750. * @param {Highcharts.SubtitleOptions} [subtitleOptions]
  751. * New subtitle options. The subtitle text itself is set by the
  752. * `subtitleOptions.text` property.
  753. *
  754. * @param {boolean} [redraw]
  755. * Whether to redraw the chart or wait for a later call to
  756. * `chart.redraw()`.
  757. */
  758. Chart.prototype.setTitle = function (titleOptions, subtitleOptions, redraw) {
  759. this.applyDescription('title', titleOptions);
  760. this.applyDescription('subtitle', subtitleOptions);
  761. // The initial call also adds the caption. On update, chart.update will
  762. // relay to Chart.setCaption.
  763. this.applyDescription('caption', void 0);
  764. this.layOutTitles(redraw);
  765. };
  766. /**
  767. * Apply a title, subtitle or caption for the chart
  768. *
  769. * @private
  770. * @function Highcharts.Chart#applyDescription
  771. * @param name {string}
  772. * Either title, subtitle or caption
  773. * @param {Highcharts.TitleOptions|Highcharts.SubtitleOptions|Highcharts.CaptionOptions|undefined} explicitOptions
  774. * The options to set, will be merged with default options.
  775. */
  776. Chart.prototype.applyDescription = function (name, explicitOptions) {
  777. var chart = this;
  778. // Default style
  779. var style = name === 'title' ? {
  780. color: '#333333',
  781. fontSize: this.options.isStock ? '16px' : '18px' // #2944
  782. } : {
  783. color: '#666666'
  784. };
  785. // Merge default options with explicit options
  786. var options = this.options[name] = merge(
  787. // Default styles
  788. (!this.styledMode && { style: style }), this.options[name], explicitOptions);
  789. var elem = this[name];
  790. if (elem && explicitOptions) {
  791. this[name] = elem = elem.destroy(); // remove old
  792. }
  793. if (options && !elem) {
  794. elem = this.renderer.text(options.text, 0, 0, options.useHTML)
  795. .attr({
  796. align: options.align,
  797. 'class': 'highcharts-' + name,
  798. zIndex: options.zIndex || 4
  799. })
  800. .add();
  801. // Update methods, shortcut to Chart.setTitle, Chart.setSubtitle and
  802. // Chart.setCaption
  803. elem.update = function (updateOptions) {
  804. var fn = {
  805. title: 'setTitle',
  806. subtitle: 'setSubtitle',
  807. caption: 'setCaption'
  808. }[name];
  809. chart[fn](updateOptions);
  810. };
  811. // Presentational
  812. if (!this.styledMode) {
  813. elem.css(options.style);
  814. }
  815. /**
  816. * The chart title. The title has an `update` method that allows
  817. * modifying the options directly or indirectly via
  818. * `chart.update`.
  819. *
  820. * @sample highcharts/members/title-update/
  821. * Updating titles
  822. *
  823. * @name Highcharts.Chart#title
  824. * @type {Highcharts.TitleObject}
  825. */
  826. /**
  827. * The chart subtitle. The subtitle has an `update` method that
  828. * allows modifying the options directly or indirectly via
  829. * `chart.update`.
  830. *
  831. * @name Highcharts.Chart#subtitle
  832. * @type {Highcharts.SubtitleObject}
  833. */
  834. this[name] = elem;
  835. }
  836. };
  837. /**
  838. * Internal function to lay out the chart title, subtitle and caption, and
  839. * cache the full offset height for use in `getMargins`. The result is
  840. * stored in `this.titleOffset`.
  841. *
  842. * @private
  843. * @function Highcharts.Chart#layOutTitles
  844. *
  845. * @param {boolean} [redraw=true]
  846. * @fires Highcharts.Chart#event:afterLayOutTitles
  847. */
  848. Chart.prototype.layOutTitles = function (redraw) {
  849. var titleOffset = [0, 0, 0], requiresDirtyBox, renderer = this.renderer, spacingBox = this.spacingBox;
  850. // Lay out the title and the subtitle respectively
  851. ['title', 'subtitle', 'caption'].forEach(function (key) {
  852. var title = this[key], titleOptions = this.options[key], verticalAlign = titleOptions.verticalAlign || 'top', offset = key === 'title' ? -3 :
  853. // Floating subtitle (#6574)
  854. verticalAlign === 'top' ? titleOffset[0] + 2 : 0, titleSize, height;
  855. if (title) {
  856. if (!this.styledMode) {
  857. titleSize = titleOptions.style.fontSize;
  858. }
  859. titleSize = renderer.fontMetrics(titleSize, title).b;
  860. title
  861. .css({
  862. width: (titleOptions.width ||
  863. spacingBox.width + (titleOptions.widthAdjust || 0)) + 'px'
  864. });
  865. // Skip the cache for HTML (#3481, #11666)
  866. height = Math.round(title.getBBox(titleOptions.useHTML).height);
  867. title.align(extend({
  868. y: verticalAlign === 'bottom' ?
  869. titleSize :
  870. offset + titleSize,
  871. height: height
  872. }, titleOptions), false, 'spacingBox');
  873. if (!titleOptions.floating) {
  874. if (verticalAlign === 'top') {
  875. titleOffset[0] = Math.ceil(titleOffset[0] +
  876. height);
  877. }
  878. else if (verticalAlign === 'bottom') {
  879. titleOffset[2] = Math.ceil(titleOffset[2] +
  880. height);
  881. }
  882. }
  883. }
  884. }, this);
  885. // Handle title.margin and caption.margin
  886. if (titleOffset[0] &&
  887. (this.options.title.verticalAlign || 'top') === 'top') {
  888. titleOffset[0] += this.options.title.margin;
  889. }
  890. if (titleOffset[2] &&
  891. this.options.caption.verticalAlign === 'bottom') {
  892. titleOffset[2] += this.options.caption.margin;
  893. }
  894. requiresDirtyBox = (!this.titleOffset ||
  895. this.titleOffset.join(',') !== titleOffset.join(','));
  896. // Used in getMargins
  897. this.titleOffset = titleOffset;
  898. fireEvent(this, 'afterLayOutTitles');
  899. if (!this.isDirtyBox && requiresDirtyBox) {
  900. this.isDirtyBox = this.isDirtyLegend = requiresDirtyBox;
  901. // Redraw if necessary (#2719, #2744)
  902. if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) {
  903. this.redraw();
  904. }
  905. }
  906. };
  907. /**
  908. * Internal function to get the chart width and height according to options
  909. * and container size. Sets {@link Chart.chartWidth} and
  910. * {@link Chart.chartHeight}.
  911. *
  912. * @private
  913. * @function Highcharts.Chart#getChartSize
  914. */
  915. Chart.prototype.getChartSize = function () {
  916. var chart = this, optionsChart = chart.options.chart, widthOption = optionsChart.width, heightOption = optionsChart.height, renderTo = chart.renderTo;
  917. // Get inner width and height
  918. if (!defined(widthOption)) {
  919. chart.containerWidth = getStyle(renderTo, 'width');
  920. }
  921. if (!defined(heightOption)) {
  922. chart.containerHeight = getStyle(renderTo, 'height');
  923. }
  924. /**
  925. * The current pixel width of the chart.
  926. *
  927. * @name Highcharts.Chart#chartWidth
  928. * @type {number}
  929. */
  930. chart.chartWidth = Math.max(// #1393
  931. 0, widthOption || chart.containerWidth || 600 // #1460
  932. );
  933. /**
  934. * The current pixel height of the chart.
  935. *
  936. * @name Highcharts.Chart#chartHeight
  937. * @type {number}
  938. */
  939. chart.chartHeight = Math.max(0, relativeLength(heightOption, chart.chartWidth) ||
  940. (chart.containerHeight > 1 ?
  941. chart.containerHeight :
  942. 400));
  943. };
  944. /**
  945. * If the renderTo element has no offsetWidth, most likely one or more of
  946. * its parents are hidden. Loop up the DOM tree to temporarily display the
  947. * parents, then save the original display properties, and when the true
  948. * size is retrieved, reset them. Used on first render and on redraws.
  949. *
  950. * @private
  951. * @function Highcharts.Chart#temporaryDisplay
  952. *
  953. * @param {boolean} [revert]
  954. * Revert to the saved original styles.
  955. */
  956. Chart.prototype.temporaryDisplay = function (revert) {
  957. var node = this.renderTo, tempStyle;
  958. if (!revert) {
  959. while (node && node.style) {
  960. // When rendering to a detached node, it needs to be temporarily
  961. // attached in order to read styling and bounding boxes (#5783,
  962. // #7024).
  963. if (!doc.body.contains(node) && !node.parentNode) {
  964. node.hcOrigDetached = true;
  965. doc.body.appendChild(node);
  966. }
  967. if (getStyle(node, 'display', false) === 'none' ||
  968. node.hcOricDetached) {
  969. node.hcOrigStyle = {
  970. display: node.style.display,
  971. height: node.style.height,
  972. overflow: node.style.overflow
  973. };
  974. tempStyle = {
  975. display: 'block',
  976. overflow: 'hidden'
  977. };
  978. if (node !== this.renderTo) {
  979. tempStyle.height = 0;
  980. }
  981. css(node, tempStyle);
  982. // If it still doesn't have an offset width after setting
  983. // display to block, it probably has an !important priority
  984. // #2631, 6803
  985. if (!node.offsetWidth) {
  986. node.style.setProperty('display', 'block', 'important');
  987. }
  988. }
  989. node = node.parentNode;
  990. if (node === doc.body) {
  991. break;
  992. }
  993. }
  994. }
  995. else {
  996. while (node && node.style) {
  997. if (node.hcOrigStyle) {
  998. css(node, node.hcOrigStyle);
  999. delete node.hcOrigStyle;
  1000. }
  1001. if (node.hcOrigDetached) {
  1002. doc.body.removeChild(node);
  1003. node.hcOrigDetached = false;
  1004. }
  1005. node = node.parentNode;
  1006. }
  1007. }
  1008. };
  1009. /**
  1010. * Set the {@link Chart.container|chart container's} class name, in
  1011. * addition to `highcharts-container`.
  1012. *
  1013. * @function Highcharts.Chart#setClassName
  1014. *
  1015. * @param {string} [className]
  1016. * The additional class name.
  1017. */
  1018. Chart.prototype.setClassName = function (className) {
  1019. this.container.className = 'highcharts-container ' + (className || '');
  1020. };
  1021. /**
  1022. * Get the containing element, determine the size and create the inner
  1023. * container div to hold the chart.
  1024. *
  1025. * @private
  1026. * @function Highcharts.Chart#afterGetContainer
  1027. * @fires Highcharts.Chart#event:afterGetContainer
  1028. */
  1029. Chart.prototype.getContainer = function () {
  1030. var chart = this, container, options = chart.options, optionsChart = options.chart, chartWidth, chartHeight, renderTo = chart.renderTo, indexAttrName = 'data-highcharts-chart', oldChartIndex, Ren, containerId = uniqueKey(), containerStyle, key;
  1031. if (!renderTo) {
  1032. chart.renderTo = renderTo =
  1033. optionsChart.renderTo;
  1034. }
  1035. if (isString(renderTo)) {
  1036. chart.renderTo = renderTo =
  1037. doc.getElementById(renderTo);
  1038. }
  1039. // Display an error if the renderTo is wrong
  1040. if (!renderTo) {
  1041. error(13, true, chart);
  1042. }
  1043. // If the container already holds a chart, destroy it. The check for
  1044. // hasRendered is there because web pages that are saved to disk from
  1045. // the browser, will preserve the data-highcharts-chart attribute and
  1046. // the SVG contents, but not an interactive chart. So in this case,
  1047. // charts[oldChartIndex] will point to the wrong chart if any (#2609).
  1048. oldChartIndex = pInt(attr(renderTo, indexAttrName));
  1049. if (isNumber(oldChartIndex) &&
  1050. charts[oldChartIndex] &&
  1051. charts[oldChartIndex].hasRendered) {
  1052. charts[oldChartIndex].destroy();
  1053. }
  1054. // Make a reference to the chart from the div
  1055. attr(renderTo, indexAttrName, chart.index);
  1056. // remove previous chart
  1057. renderTo.innerHTML = '';
  1058. // If the container doesn't have an offsetWidth, it has or is a child of
  1059. // a node that has display:none. We need to temporarily move it out to a
  1060. // visible state to determine the size, else the legend and tooltips
  1061. // won't render properly. The skipClone option is used in sparklines as
  1062. // a micro optimization, saving about 1-2 ms each chart.
  1063. if (!optionsChart.skipClone && !renderTo.offsetWidth) {
  1064. chart.temporaryDisplay();
  1065. }
  1066. // get the width and height
  1067. chart.getChartSize();
  1068. chartWidth = chart.chartWidth;
  1069. chartHeight = chart.chartHeight;
  1070. // Allow table cells and flex-boxes to shrink without the chart blocking
  1071. // them out (#6427)
  1072. css(renderTo, { overflow: 'hidden' });
  1073. // Create the inner container
  1074. if (!chart.styledMode) {
  1075. containerStyle = extend({
  1076. position: 'relative',
  1077. // needed for context menu (avoidscrollbars) and content
  1078. // overflow in IE
  1079. overflow: 'hidden',
  1080. width: chartWidth + 'px',
  1081. height: chartHeight + 'px',
  1082. textAlign: 'left',
  1083. lineHeight: 'normal',
  1084. zIndex: 0,
  1085. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)',
  1086. userSelect: 'none' // #13503
  1087. }, optionsChart.style);
  1088. }
  1089. /**
  1090. * The containing HTML element of the chart. The container is
  1091. * dynamically inserted into the element given as the `renderTo`
  1092. * parameter in the {@link Highcharts#chart} constructor.
  1093. *
  1094. * @name Highcharts.Chart#container
  1095. * @type {Highcharts.HTMLDOMElement}
  1096. */
  1097. container = createElement('div', {
  1098. id: containerId
  1099. }, containerStyle, renderTo);
  1100. chart.container = container;
  1101. // cache the cursor (#1650)
  1102. chart._cursor = container.style.cursor;
  1103. // Initialize the renderer
  1104. Ren = H[optionsChart.renderer] || H.Renderer;
  1105. /**
  1106. * The renderer instance of the chart. Each chart instance has only one
  1107. * associated renderer.
  1108. *
  1109. * @name Highcharts.Chart#renderer
  1110. * @type {Highcharts.SVGRenderer}
  1111. */
  1112. chart.renderer = new Ren(container, chartWidth, chartHeight, null, optionsChart.forExport, options.exporting && options.exporting.allowHTML, chart.styledMode);
  1113. // Set the initial animation from the options
  1114. setAnimation(void 0, chart);
  1115. chart.setClassName(optionsChart.className);
  1116. if (!chart.styledMode) {
  1117. chart.renderer.setStyle(optionsChart.style);
  1118. }
  1119. else {
  1120. // Initialize definitions
  1121. for (key in options.defs) { // eslint-disable-line guard-for-in
  1122. this.renderer.definition(options.defs[key]);
  1123. }
  1124. }
  1125. // Add a reference to the charts index
  1126. chart.renderer.chartIndex = chart.index;
  1127. fireEvent(this, 'afterGetContainer');
  1128. };
  1129. /**
  1130. * Calculate margins by rendering axis labels in a preliminary position.
  1131. * Title, subtitle and legend have already been rendered at this stage, but
  1132. * will be moved into their final positions.
  1133. *
  1134. * @private
  1135. * @function Highcharts.Chart#getMargins
  1136. * @fires Highcharts.Chart#event:getMargins
  1137. */
  1138. Chart.prototype.getMargins = function (skipAxes) {
  1139. var _a = this, spacing = _a.spacing, margin = _a.margin, titleOffset = _a.titleOffset;
  1140. this.resetMargins();
  1141. // Adjust for title and subtitle
  1142. if (titleOffset[0] && !defined(margin[0])) {
  1143. this.plotTop = Math.max(this.plotTop, titleOffset[0] + spacing[0]);
  1144. }
  1145. if (titleOffset[2] && !defined(margin[2])) {
  1146. this.marginBottom = Math.max(this.marginBottom, titleOffset[2] + spacing[2]);
  1147. }
  1148. // Adjust for legend
  1149. if (this.legend && this.legend.display) {
  1150. this.legend.adjustMargins(margin, spacing);
  1151. }
  1152. fireEvent(this, 'getMargins');
  1153. if (!skipAxes) {
  1154. this.getAxisMargins();
  1155. }
  1156. };
  1157. /**
  1158. * @private
  1159. * @function Highcharts.Chart#getAxisMargins
  1160. */
  1161. Chart.prototype.getAxisMargins = function () {
  1162. var chart = this,
  1163. // [top, right, bottom, left]
  1164. axisOffset = chart.axisOffset = [0, 0, 0, 0], colorAxis = chart.colorAxis, margin = chart.margin, getOffset = function (axes) {
  1165. axes.forEach(function (axis) {
  1166. if (axis.visible) {
  1167. axis.getOffset();
  1168. }
  1169. });
  1170. };
  1171. // pre-render axes to get labels offset width
  1172. if (chart.hasCartesianSeries) {
  1173. getOffset(chart.axes);
  1174. }
  1175. else if (colorAxis && colorAxis.length) {
  1176. getOffset(colorAxis);
  1177. }
  1178. // Add the axis offsets
  1179. marginNames.forEach(function (m, side) {
  1180. if (!defined(margin[side])) {
  1181. chart[m] += axisOffset[side];
  1182. }
  1183. });
  1184. chart.setChartSize();
  1185. };
  1186. /**
  1187. * Reflows the chart to its container. By default, the chart reflows
  1188. * automatically to its container following a `window.resize` event, as per
  1189. * the [chart.reflow](https://api.highcharts.com/highcharts/chart.reflow)
  1190. * option. However, there are no reliable events for div resize, so if the
  1191. * container is resized without a window resize event, this must be called
  1192. * explicitly.
  1193. *
  1194. * @sample highcharts/members/chart-reflow/
  1195. * Resize div and reflow
  1196. * @sample highcharts/chart/events-container/
  1197. * Pop up and reflow
  1198. *
  1199. * @function Highcharts.Chart#reflow
  1200. *
  1201. * @param {global.Event} [e]
  1202. * Event arguments. Used primarily when the function is called
  1203. * internally as a response to window resize.
  1204. */
  1205. Chart.prototype.reflow = function (e) {
  1206. var chart = this, optionsChart = chart.options.chart, renderTo = chart.renderTo, hasUserSize = (defined(optionsChart.width) &&
  1207. defined(optionsChart.height)), width = optionsChart.width || getStyle(renderTo, 'width'), height = optionsChart.height || getStyle(renderTo, 'height'), target = e ? e.target : win;
  1208. // Width and height checks for display:none. Target is doc in IE8 and
  1209. // Opera, win in Firefox, Chrome and IE9.
  1210. if (!hasUserSize &&
  1211. !chart.isPrinting &&
  1212. width &&
  1213. height &&
  1214. (target === win || target === doc)) {
  1215. if (width !== chart.containerWidth ||
  1216. height !== chart.containerHeight) {
  1217. U.clearTimeout(chart.reflowTimeout);
  1218. // When called from window.resize, e is set, else it's called
  1219. // directly (#2224)
  1220. chart.reflowTimeout = syncTimeout(function () {
  1221. // Set size, it may have been destroyed in the meantime
  1222. // (#1257)
  1223. if (chart.container) {
  1224. chart.setSize(void 0, void 0, false);
  1225. }
  1226. }, e ? 100 : 0);
  1227. }
  1228. chart.containerWidth = width;
  1229. chart.containerHeight = height;
  1230. }
  1231. };
  1232. /**
  1233. * Toggle the event handlers necessary for auto resizing, depending on the
  1234. * `chart.reflow` option.
  1235. *
  1236. * @private
  1237. * @function Highcharts.Chart#setReflow
  1238. */
  1239. Chart.prototype.setReflow = function (reflow) {
  1240. var chart = this;
  1241. if (reflow !== false && !this.unbindReflow) {
  1242. this.unbindReflow = addEvent(win, 'resize', function (e) {
  1243. // a removed event listener still runs in Edge and IE if the
  1244. // listener was removed while the event runs, so check if the
  1245. // chart is not destroyed (#11609)
  1246. if (chart.options) {
  1247. chart.reflow(e);
  1248. }
  1249. });
  1250. addEvent(this, 'destroy', this.unbindReflow);
  1251. }
  1252. else if (reflow === false && this.unbindReflow) {
  1253. // Unbind and unset
  1254. this.unbindReflow = this.unbindReflow();
  1255. }
  1256. // The following will add listeners to re-fit the chart before and after
  1257. // printing (#2284). However it only works in WebKit. Should have worked
  1258. // in Firefox, but not supported in IE.
  1259. /*
  1260. if (win.matchMedia) {
  1261. win.matchMedia('print').addListener(function reflow() {
  1262. chart.reflow();
  1263. });
  1264. }
  1265. //*/
  1266. };
  1267. /**
  1268. * Resize the chart to a given width and height. In order to set the width
  1269. * only, the height argument may be skipped. To set the height only, pass
  1270. * `undefined` for the width.
  1271. *
  1272. * @sample highcharts/members/chart-setsize-button/
  1273. * Test resizing from buttons
  1274. * @sample highcharts/members/chart-setsize-jquery-resizable/
  1275. * Add a jQuery UI resizable
  1276. * @sample stock/members/chart-setsize/
  1277. * Highstock with UI resizable
  1278. *
  1279. * @function Highcharts.Chart#setSize
  1280. *
  1281. * @param {number|null} [width]
  1282. * The new pixel width of the chart. Since v4.2.6, the argument can
  1283. * be `undefined` in order to preserve the current value (when
  1284. * setting height only), or `null` to adapt to the width of the
  1285. * containing element.
  1286. *
  1287. * @param {number|null} [height]
  1288. * The new pixel height of the chart. Since v4.2.6, the argument can
  1289. * be `undefined` in order to preserve the current value, or `null`
  1290. * in order to adapt to the height of the containing element.
  1291. *
  1292. * @param {boolean|Partial<Highcharts.AnimationOptionsObject>} [animation=true]
  1293. * Whether and how to apply animation.
  1294. *
  1295. * @return {void}
  1296. *
  1297. * @fires Highcharts.Chart#event:endResize
  1298. * @fires Highcharts.Chart#event:resize
  1299. */
  1300. Chart.prototype.setSize = function (width, height, animation) {
  1301. var chart = this, renderer = chart.renderer, globalAnimation;
  1302. // Handle the isResizing counter
  1303. chart.isResizing += 1;
  1304. // set the animation for the current process
  1305. setAnimation(animation, chart);
  1306. globalAnimation = renderer.globalAnimation;
  1307. chart.oldChartHeight = chart.chartHeight;
  1308. chart.oldChartWidth = chart.chartWidth;
  1309. if (typeof width !== 'undefined') {
  1310. chart.options.chart.width = width;
  1311. }
  1312. if (typeof height !== 'undefined') {
  1313. chart.options.chart.height = height;
  1314. }
  1315. chart.getChartSize();
  1316. // Resize the container with the global animation applied if enabled
  1317. // (#2503)
  1318. if (!chart.styledMode) {
  1319. (globalAnimation ? animate : css)(chart.container, {
  1320. width: chart.chartWidth + 'px',
  1321. height: chart.chartHeight + 'px'
  1322. }, globalAnimation);
  1323. }
  1324. chart.setChartSize(true);
  1325. renderer.setSize(chart.chartWidth, chart.chartHeight, globalAnimation);
  1326. // handle axes
  1327. chart.axes.forEach(function (axis) {
  1328. axis.isDirty = true;
  1329. axis.setScale();
  1330. });
  1331. chart.isDirtyLegend = true; // force legend redraw
  1332. chart.isDirtyBox = true; // force redraw of plot and chart border
  1333. chart.layOutTitles(); // #2857
  1334. chart.getMargins();
  1335. chart.redraw(globalAnimation);
  1336. chart.oldChartHeight = null;
  1337. fireEvent(chart, 'resize');
  1338. // Fire endResize and set isResizing back. If animation is disabled,
  1339. // fire without delay
  1340. syncTimeout(function () {
  1341. if (chart) {
  1342. fireEvent(chart, 'endResize', null, function () {
  1343. chart.isResizing -= 1;
  1344. });
  1345. }
  1346. }, animObject(globalAnimation).duration);
  1347. };
  1348. /**
  1349. * Set the public chart properties. This is done before and after the
  1350. * pre-render to determine margin sizes.
  1351. *
  1352. * @private
  1353. * @function Highcharts.Chart#setChartSize
  1354. * @fires Highcharts.Chart#event:afterSetChartSize
  1355. */
  1356. Chart.prototype.setChartSize = function (skipAxes) {
  1357. var chart = this, inverted = chart.inverted, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, optionsChart = chart.options.chart, spacing = chart.spacing, clipOffset = chart.clipOffset, clipX, clipY, plotLeft, plotTop, plotWidth, plotHeight, plotBorderWidth;
  1358. /**
  1359. * The current left position of the plot area in pixels.
  1360. *
  1361. * @name Highcharts.Chart#plotLeft
  1362. * @type {number}
  1363. */
  1364. chart.plotLeft = plotLeft = Math.round(chart.plotLeft);
  1365. /**
  1366. * The current top position of the plot area in pixels.
  1367. *
  1368. * @name Highcharts.Chart#plotTop
  1369. * @type {number}
  1370. */
  1371. chart.plotTop = plotTop = Math.round(chart.plotTop);
  1372. /**
  1373. * The current width of the plot area in pixels.
  1374. *
  1375. * @name Highcharts.Chart#plotWidth
  1376. * @type {number}
  1377. */
  1378. chart.plotWidth = plotWidth = Math.max(0, Math.round(chartWidth - plotLeft - chart.marginRight));
  1379. /**
  1380. * The current height of the plot area in pixels.
  1381. *
  1382. * @name Highcharts.Chart#plotHeight
  1383. * @type {number}
  1384. */
  1385. chart.plotHeight = plotHeight = Math.max(0, Math.round(chartHeight - plotTop - chart.marginBottom));
  1386. chart.plotSizeX = inverted ? plotHeight : plotWidth;
  1387. chart.plotSizeY = inverted ? plotWidth : plotHeight;
  1388. chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
  1389. // Set boxes used for alignment
  1390. chart.spacingBox = renderer.spacingBox = {
  1391. x: spacing[3],
  1392. y: spacing[0],
  1393. width: chartWidth - spacing[3] - spacing[1],
  1394. height: chartHeight - spacing[0] - spacing[2]
  1395. };
  1396. chart.plotBox = renderer.plotBox = {
  1397. x: plotLeft,
  1398. y: plotTop,
  1399. width: plotWidth,
  1400. height: plotHeight
  1401. };
  1402. plotBorderWidth = 2 * Math.floor(chart.plotBorderWidth / 2);
  1403. clipX = Math.ceil(Math.max(plotBorderWidth, clipOffset[3]) / 2);
  1404. clipY = Math.ceil(Math.max(plotBorderWidth, clipOffset[0]) / 2);
  1405. chart.clipBox = {
  1406. x: clipX,
  1407. y: clipY,
  1408. width: Math.floor(chart.plotSizeX -
  1409. Math.max(plotBorderWidth, clipOffset[1]) / 2 -
  1410. clipX),
  1411. height: Math.max(0, Math.floor(chart.plotSizeY -
  1412. Math.max(plotBorderWidth, clipOffset[2]) / 2 -
  1413. clipY))
  1414. };
  1415. if (!skipAxes) {
  1416. chart.axes.forEach(function (axis) {
  1417. axis.setAxisSize();
  1418. axis.setAxisTranslation();
  1419. });
  1420. }
  1421. fireEvent(chart, 'afterSetChartSize', { skipAxes: skipAxes });
  1422. };
  1423. /**
  1424. * Initial margins before auto size margins are applied.
  1425. *
  1426. * @private
  1427. * @function Highcharts.Chart#resetMargins
  1428. */
  1429. Chart.prototype.resetMargins = function () {
  1430. fireEvent(this, 'resetMargins');
  1431. var chart = this, chartOptions = chart.options.chart;
  1432. // Create margin and spacing array
  1433. ['margin', 'spacing'].forEach(function splashArrays(target) {
  1434. var value = chartOptions[target], values = isObject(value) ? value : [value, value, value, value];
  1435. [
  1436. 'Top',
  1437. 'Right',
  1438. 'Bottom',
  1439. 'Left'
  1440. ].forEach(function (sideName, side) {
  1441. chart[target][side] = pick(chartOptions[target + sideName], values[side]);
  1442. });
  1443. });
  1444. // Set margin names like chart.plotTop, chart.plotLeft,
  1445. // chart.marginRight, chart.marginBottom.
  1446. marginNames.forEach(function (m, side) {
  1447. chart[m] = pick(chart.margin[side], chart.spacing[side]);
  1448. });
  1449. chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
  1450. chart.clipOffset = [0, 0, 0, 0];
  1451. };
  1452. /**
  1453. * Internal function to draw or redraw the borders and backgrounds for chart
  1454. * and plot area.
  1455. *
  1456. * @private
  1457. * @function Highcharts.Chart#drawChartBox
  1458. * @fires Highcharts.Chart#event:afterDrawChartBox
  1459. */
  1460. Chart.prototype.drawChartBox = function () {
  1461. var chart = this, optionsChart = chart.options.chart, renderer = chart.renderer, chartWidth = chart.chartWidth, chartHeight = chart.chartHeight, chartBackground = chart.chartBackground, plotBackground = chart.plotBackground, plotBorder = chart.plotBorder, chartBorderWidth, styledMode = chart.styledMode, plotBGImage = chart.plotBGImage, chartBackgroundColor = optionsChart.backgroundColor, plotBackgroundColor = optionsChart.plotBackgroundColor, plotBackgroundImage = optionsChart.plotBackgroundImage, mgn, bgAttr, plotLeft = chart.plotLeft, plotTop = chart.plotTop, plotWidth = chart.plotWidth, plotHeight = chart.plotHeight, plotBox = chart.plotBox, clipRect = chart.clipRect, clipBox = chart.clipBox, verb = 'animate';
  1462. // Chart area
  1463. if (!chartBackground) {
  1464. chart.chartBackground = chartBackground = renderer.rect()
  1465. .addClass('highcharts-background')
  1466. .add();
  1467. verb = 'attr';
  1468. }
  1469. if (!styledMode) {
  1470. // Presentational
  1471. chartBorderWidth = optionsChart.borderWidth || 0;
  1472. mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
  1473. bgAttr = {
  1474. fill: chartBackgroundColor || 'none'
  1475. };
  1476. if (chartBorderWidth || chartBackground['stroke-width']) { // #980
  1477. bgAttr.stroke = optionsChart.borderColor;
  1478. bgAttr['stroke-width'] = chartBorderWidth;
  1479. }
  1480. chartBackground
  1481. .attr(bgAttr)
  1482. .shadow(optionsChart.shadow);
  1483. }
  1484. else {
  1485. chartBorderWidth = mgn = chartBackground.strokeWidth();
  1486. }
  1487. chartBackground[verb]({
  1488. x: mgn / 2,
  1489. y: mgn / 2,
  1490. width: chartWidth - mgn - chartBorderWidth % 2,
  1491. height: chartHeight - mgn - chartBorderWidth % 2,
  1492. r: optionsChart.borderRadius
  1493. });
  1494. // Plot background
  1495. verb = 'animate';
  1496. if (!plotBackground) {
  1497. verb = 'attr';
  1498. chart.plotBackground = plotBackground = renderer.rect()
  1499. .addClass('highcharts-plot-background')
  1500. .add();
  1501. }
  1502. plotBackground[verb](plotBox);
  1503. if (!styledMode) {
  1504. // Presentational attributes for the background
  1505. plotBackground
  1506. .attr({
  1507. fill: plotBackgroundColor || 'none'
  1508. })
  1509. .shadow(optionsChart.plotShadow);
  1510. // Create the background image
  1511. if (plotBackgroundImage) {
  1512. if (!plotBGImage) {
  1513. chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight).add();
  1514. }
  1515. else {
  1516. if (plotBackgroundImage !== plotBGImage.attr('href')) {
  1517. plotBGImage.attr('href', plotBackgroundImage);
  1518. }
  1519. plotBGImage.animate(plotBox);
  1520. }
  1521. }
  1522. }
  1523. // Plot clip
  1524. if (!clipRect) {
  1525. chart.clipRect = renderer.clipRect(clipBox);
  1526. }
  1527. else {
  1528. clipRect.animate({
  1529. width: clipBox.width,
  1530. height: clipBox.height
  1531. });
  1532. }
  1533. // Plot area border
  1534. verb = 'animate';
  1535. if (!plotBorder) {
  1536. verb = 'attr';
  1537. chart.plotBorder = plotBorder = renderer.rect()
  1538. .addClass('highcharts-plot-border')
  1539. .attr({
  1540. zIndex: 1 // Above the grid
  1541. })
  1542. .add();
  1543. }
  1544. if (!styledMode) {
  1545. // Presentational
  1546. plotBorder.attr({
  1547. stroke: optionsChart.plotBorderColor,
  1548. 'stroke-width': optionsChart.plotBorderWidth || 0,
  1549. fill: 'none'
  1550. });
  1551. }
  1552. plotBorder[verb](plotBorder.crisp({
  1553. x: plotLeft,
  1554. y: plotTop,
  1555. width: plotWidth,
  1556. height: plotHeight
  1557. }, -plotBorder.strokeWidth())); // #3282 plotBorder should be negative;
  1558. // reset
  1559. chart.isDirtyBox = false;
  1560. fireEvent(this, 'afterDrawChartBox');
  1561. };
  1562. /**
  1563. * Detect whether a certain chart property is needed based on inspecting its
  1564. * options and series. This mainly applies to the chart.inverted property,
  1565. * and in extensions to the chart.angular and chart.polar properties.
  1566. *
  1567. * @private
  1568. * @function Highcharts.Chart#propFromSeries
  1569. * @return {void}
  1570. */
  1571. Chart.prototype.propFromSeries = function () {
  1572. var chart = this, optionsChart = chart.options.chart, klass, seriesOptions = chart.options.series, i, value;
  1573. /**
  1574. * The flag is set to `true` if a series of the chart is inverted.
  1575. *
  1576. * @name Highcharts.Chart#inverted
  1577. * @type {boolean|undefined}
  1578. */
  1579. ['inverted', 'angular', 'polar'].forEach(function (key) {
  1580. // The default series type's class
  1581. klass = seriesTypes[(optionsChart.type ||
  1582. optionsChart.defaultSeriesType)];
  1583. // Get the value from available chart-wide properties
  1584. value =
  1585. // It is set in the options:
  1586. optionsChart[key] ||
  1587. // The default series class:
  1588. (klass && klass.prototype[key]);
  1589. // requires it
  1590. // 4. Check if any the chart's series require it
  1591. i = seriesOptions && seriesOptions.length;
  1592. while (!value && i--) {
  1593. klass = seriesTypes[seriesOptions[i].type];
  1594. if (klass && klass.prototype[key]) {
  1595. value = true;
  1596. }
  1597. }
  1598. // Set the chart property
  1599. chart[key] = value;
  1600. });
  1601. };
  1602. /**
  1603. * Internal function to link two or more series together, based on the
  1604. * `linkedTo` option. This is done from `Chart.render`, and after
  1605. * `Chart.addSeries` and `Series.remove`.
  1606. *
  1607. * @private
  1608. * @function Highcharts.Chart#linkSeries
  1609. * @fires Highcharts.Chart#event:afterLinkSeries
  1610. */
  1611. Chart.prototype.linkSeries = function () {
  1612. var chart = this, chartSeries = chart.series;
  1613. // Reset links
  1614. chartSeries.forEach(function (series) {
  1615. series.linkedSeries.length = 0;
  1616. });
  1617. // Apply new links
  1618. chartSeries.forEach(function (series) {
  1619. var linkedTo = series.options.linkedTo;
  1620. if (isString(linkedTo)) {
  1621. if (linkedTo === ':previous') {
  1622. linkedTo = chart.series[series.index - 1];
  1623. }
  1624. else {
  1625. linkedTo = chart.get(linkedTo);
  1626. }
  1627. // #3341 avoid mutual linking
  1628. if (linkedTo && linkedTo.linkedParent !== series) {
  1629. linkedTo.linkedSeries.push(series);
  1630. series.linkedParent = linkedTo;
  1631. if (linkedTo.enabledDataSorting) {
  1632. series.setDataSortingOptions();
  1633. }
  1634. series.visible = pick(series.options.visible, linkedTo.options.visible, series.visible); // #3879
  1635. }
  1636. }
  1637. });
  1638. fireEvent(this, 'afterLinkSeries');
  1639. };
  1640. /**
  1641. * Render series for the chart.
  1642. *
  1643. * @private
  1644. * @function Highcharts.Chart#renderSeries
  1645. */
  1646. Chart.prototype.renderSeries = function () {
  1647. this.series.forEach(function (serie) {
  1648. serie.translate();
  1649. serie.render();
  1650. });
  1651. };
  1652. /**
  1653. * Render labels for the chart.
  1654. *
  1655. * @private
  1656. * @function Highcharts.Chart#renderLabels
  1657. */
  1658. Chart.prototype.renderLabels = function () {
  1659. var chart = this, labels = chart.options.labels;
  1660. if (labels.items) {
  1661. labels.items.forEach(function (label) {
  1662. var style = extend(labels.style, label.style), x = pInt(style.left) + chart.plotLeft, y = pInt(style.top) + chart.plotTop + 12;
  1663. // delete to prevent rewriting in IE
  1664. delete style.left;
  1665. delete style.top;
  1666. chart.renderer.text(label.html, x, y)
  1667. .attr({ zIndex: 2 })
  1668. .css(style)
  1669. .add();
  1670. });
  1671. }
  1672. };
  1673. /**
  1674. * Render all graphics for the chart. Runs internally on initialization.
  1675. *
  1676. * @private
  1677. * @function Highcharts.Chart#render
  1678. */
  1679. Chart.prototype.render = function () {
  1680. var chart = this, axes = chart.axes, colorAxis = chart.colorAxis, renderer = chart.renderer, options = chart.options, correction = 0, // correction for X axis labels
  1681. tempWidth, tempHeight, redoHorizontal, redoVertical, renderAxes = function (axes) {
  1682. axes.forEach(function (axis) {
  1683. if (axis.visible) {
  1684. axis.render();
  1685. }
  1686. });
  1687. };
  1688. // Title
  1689. chart.setTitle();
  1690. /**
  1691. * The overview of the chart's series.
  1692. *
  1693. * @name Highcharts.Chart#legend
  1694. * @type {Highcharts.Legend}
  1695. */
  1696. chart.legend = new Legend(chart, options.legend);
  1697. // Get stacks
  1698. if (chart.getStacks) {
  1699. chart.getStacks();
  1700. }
  1701. // Get chart margins
  1702. chart.getMargins(true);
  1703. chart.setChartSize();
  1704. // Record preliminary dimensions for later comparison
  1705. tempWidth = chart.plotWidth;
  1706. axes.some(function (axis) {
  1707. if (axis.horiz &&
  1708. axis.visible &&
  1709. axis.options.labels.enabled &&
  1710. axis.series.length) {
  1711. // 21 is the most common correction for X axis labels
  1712. correction = 21;
  1713. return true;
  1714. }
  1715. });
  1716. // use Math.max to prevent negative plotHeight
  1717. chart.plotHeight = Math.max(chart.plotHeight - correction, 0);
  1718. tempHeight = chart.plotHeight;
  1719. // Get margins by pre-rendering axes
  1720. axes.forEach(function (axis) {
  1721. axis.setScale();
  1722. });
  1723. chart.getAxisMargins();
  1724. // If the plot area size has changed significantly, calculate tick
  1725. // positions again
  1726. redoHorizontal = tempWidth / chart.plotWidth > 1.1;
  1727. // Height is more sensitive, use lower threshold
  1728. redoVertical = tempHeight / chart.plotHeight > 1.05;
  1729. if (redoHorizontal || redoVertical) {
  1730. axes.forEach(function (axis) {
  1731. if ((axis.horiz && redoHorizontal) ||
  1732. (!axis.horiz && redoVertical)) {
  1733. // update to reflect the new margins
  1734. axis.setTickInterval(true);
  1735. }
  1736. });
  1737. chart.getMargins(); // second pass to check for new labels
  1738. }
  1739. // Draw the borders and backgrounds
  1740. chart.drawChartBox();
  1741. // Axes
  1742. if (chart.hasCartesianSeries) {
  1743. renderAxes(axes);
  1744. }
  1745. else if (colorAxis && colorAxis.length) {
  1746. renderAxes(colorAxis);
  1747. }
  1748. // The series
  1749. if (!chart.seriesGroup) {
  1750. chart.seriesGroup = renderer.g('series-group')
  1751. .attr({ zIndex: 3 })
  1752. .add();
  1753. }
  1754. chart.renderSeries();
  1755. // Labels
  1756. chart.renderLabels();
  1757. // Credits
  1758. chart.addCredits();
  1759. // Handle responsiveness
  1760. if (chart.setResponsive) {
  1761. chart.setResponsive();
  1762. }
  1763. // Handle scaling
  1764. chart.updateContainerScaling();
  1765. // Set flag
  1766. chart.hasRendered = true;
  1767. };
  1768. /**
  1769. * Set a new credits label for the chart.
  1770. *
  1771. * @sample highcharts/credits/credits-update/
  1772. * Add and update credits
  1773. *
  1774. * @function Highcharts.Chart#addCredits
  1775. *
  1776. * @param {Highcharts.CreditsOptions} [credits]
  1777. * A configuration object for the new credits.
  1778. */
  1779. Chart.prototype.addCredits = function (credits) {
  1780. var chart = this, creds = merge(true, this.options.credits, credits);
  1781. if (creds.enabled && !this.credits) {
  1782. /**
  1783. * The chart's credits label. The label has an `update` method that
  1784. * allows setting new options as per the
  1785. * [credits options set](https://api.highcharts.com/highcharts/credits).
  1786. *
  1787. * @name Highcharts.Chart#credits
  1788. * @type {Highcharts.SVGElement}
  1789. */
  1790. this.credits = this.renderer.text(creds.text + (this.mapCredits || ''), 0, 0)
  1791. .addClass('highcharts-credits')
  1792. .on('click', function () {
  1793. if (creds.href) {
  1794. win.location.href = creds.href;
  1795. }
  1796. })
  1797. .attr({
  1798. align: creds.position.align,
  1799. zIndex: 8
  1800. });
  1801. if (!chart.styledMode) {
  1802. this.credits.css(creds.style);
  1803. }
  1804. this.credits
  1805. .add()
  1806. .align(creds.position);
  1807. // Dynamically update
  1808. this.credits.update = function (options) {
  1809. chart.credits = chart.credits.destroy();
  1810. chart.addCredits(options);
  1811. };
  1812. }
  1813. };
  1814. /**
  1815. * Handle scaling, #11329 - when there is scaling/transform on the container
  1816. * or on a parent element, we need to take this into account. We calculate
  1817. * the scaling once here and it is picked up where we need to use it
  1818. * (Pointer, Tooltip).
  1819. *
  1820. * @private
  1821. * @function Highcharts.Chart#updateContainerScaling
  1822. */
  1823. Chart.prototype.updateContainerScaling = function () {
  1824. var container = this.container;
  1825. // #13342 - tooltip was not visible in Chrome, when chart
  1826. // updates height.
  1827. if (container.offsetWidth > 2 && // #13342
  1828. container.offsetHeight > 2 && // #13342
  1829. container.getBoundingClientRect) {
  1830. var bb = container.getBoundingClientRect(), scaleX = bb.width / container.offsetWidth, scaleY = bb.height / container.offsetHeight;
  1831. if (scaleX !== 1 || scaleY !== 1) {
  1832. this.containerScaling = { scaleX: scaleX, scaleY: scaleY };
  1833. }
  1834. else {
  1835. delete this.containerScaling;
  1836. }
  1837. }
  1838. };
  1839. /**
  1840. * Remove the chart and purge memory. This method is called internally
  1841. * before adding a second chart into the same container, as well as on
  1842. * window unload to prevent leaks.
  1843. *
  1844. * @sample highcharts/members/chart-destroy/
  1845. * Destroy the chart from a button
  1846. * @sample stock/members/chart-destroy/
  1847. * Destroy with Highstock
  1848. *
  1849. * @function Highcharts.Chart#destroy
  1850. *
  1851. * @fires Highcharts.Chart#event:destroy
  1852. */
  1853. Chart.prototype.destroy = function () {
  1854. var chart = this, axes = chart.axes, series = chart.series, container = chart.container, i, parentNode = container && container.parentNode;
  1855. // fire the chart.destoy event
  1856. fireEvent(chart, 'destroy');
  1857. // Delete the chart from charts lookup array
  1858. if (chart.renderer.forExport) {
  1859. erase(charts, chart); // #6569
  1860. }
  1861. else {
  1862. charts[chart.index] = void 0;
  1863. }
  1864. H.chartCount--;
  1865. chart.renderTo.removeAttribute('data-highcharts-chart');
  1866. // remove events
  1867. removeEvent(chart);
  1868. // ==== Destroy collections:
  1869. // Destroy axes
  1870. i = axes.length;
  1871. while (i--) {
  1872. axes[i] = axes[i].destroy();
  1873. }
  1874. // Destroy scroller & scroller series before destroying base series
  1875. if (this.scroller && this.scroller.destroy) {
  1876. this.scroller.destroy();
  1877. }
  1878. // Destroy each series
  1879. i = series.length;
  1880. while (i--) {
  1881. series[i] = series[i].destroy();
  1882. }
  1883. // ==== Destroy chart properties:
  1884. [
  1885. 'title', 'subtitle', 'chartBackground', 'plotBackground',
  1886. 'plotBGImage', 'plotBorder', 'seriesGroup', 'clipRect', 'credits',
  1887. 'pointer', 'rangeSelector', 'legend', 'resetZoomButton', 'tooltip',
  1888. 'renderer'
  1889. ].forEach(function (name) {
  1890. var prop = chart[name];
  1891. if (prop && prop.destroy) {
  1892. chart[name] = prop.destroy();
  1893. }
  1894. });
  1895. // Remove container and all SVG, check container as it can break in IE
  1896. // when destroyed before finished loading
  1897. if (container) {
  1898. container.innerHTML = '';
  1899. removeEvent(container);
  1900. if (parentNode) {
  1901. discardElement(container);
  1902. }
  1903. }
  1904. // clean it all up
  1905. objectEach(chart, function (val, key) {
  1906. delete chart[key];
  1907. });
  1908. };
  1909. /**
  1910. * Prepare for first rendering after all data are loaded.
  1911. *
  1912. * @private
  1913. * @function Highcharts.Chart#firstRender
  1914. * @fires Highcharts.Chart#event:beforeRender
  1915. */
  1916. Chart.prototype.firstRender = function () {
  1917. var chart = this, options = chart.options;
  1918. // Hook for oldIE to check whether the chart is ready to render
  1919. if (chart.isReadyToRender && !chart.isReadyToRender()) {
  1920. return;
  1921. }
  1922. // Create the container
  1923. chart.getContainer();
  1924. chart.resetMargins();
  1925. chart.setChartSize();
  1926. // Set the common chart properties (mainly invert) from the given series
  1927. chart.propFromSeries();
  1928. // get axes
  1929. chart.getAxes();
  1930. // Initialize the series
  1931. (isArray(options.series) ? options.series : []).forEach(
  1932. // #9680
  1933. function (serieOptions) {
  1934. chart.initSeries(serieOptions);
  1935. });
  1936. chart.linkSeries();
  1937. chart.setSeriesData();
  1938. // Run an event after axes and series are initialized, but before
  1939. // render. At this stage, the series data is indexed and cached in the
  1940. // xData and yData arrays, so we can access those before rendering. Used
  1941. // in Highstock.
  1942. fireEvent(chart, 'beforeRender');
  1943. // depends on inverted and on margins being set
  1944. if (Pointer) {
  1945. if (!H.hasTouch && (win.PointerEvent || win.MSPointerEvent)) {
  1946. chart.pointer = new MSPointer(chart, options);
  1947. }
  1948. else {
  1949. /**
  1950. * The Pointer that keeps track of mouse and touch interaction.
  1951. *
  1952. * @memberof Highcharts.Chart
  1953. * @name pointer
  1954. * @type {Highcharts.Pointer}
  1955. * @instance
  1956. */
  1957. chart.pointer = new Pointer(chart, options);
  1958. }
  1959. }
  1960. chart.render();
  1961. // Fire the load event if there are no external images
  1962. if (!chart.renderer.imgCount && !chart.hasLoaded) {
  1963. chart.onload();
  1964. }
  1965. // If the chart was rendered outside the top container, put it back in
  1966. // (#3679)
  1967. chart.temporaryDisplay(true);
  1968. };
  1969. /**
  1970. * Internal function that runs on chart load, async if any images are loaded
  1971. * in the chart. Runs the callbacks and triggers the `load` and `render`
  1972. * events.
  1973. *
  1974. * @private
  1975. * @function Highcharts.Chart#onload
  1976. * @fires Highcharts.Chart#event:load
  1977. * @fires Highcharts.Chart#event:render
  1978. */
  1979. Chart.prototype.onload = function () {
  1980. // Run callbacks, first the ones registered by modules, then user's one
  1981. this.callbacks.concat([this.callback]).forEach(function (fn) {
  1982. // Chart destroyed in its own callback (#3600)
  1983. if (fn && typeof this.index !== 'undefined') {
  1984. fn.apply(this, [this]);
  1985. }
  1986. }, this);
  1987. fireEvent(this, 'load');
  1988. fireEvent(this, 'render');
  1989. // Set up auto resize, check for not destroyed (#6068)
  1990. if (defined(this.index)) {
  1991. this.setReflow(this.options.chart.reflow);
  1992. }
  1993. // Don't run again
  1994. this.hasLoaded = true;
  1995. };
  1996. return Chart;
  1997. }());
  1998. // Hook for adding callbacks in modules
  1999. Chart.prototype.callbacks = [];
  2000. /**
  2001. * Factory function for basic charts.
  2002. *
  2003. * @example
  2004. * // Render a chart in to div#container
  2005. * var chart = Highcharts.chart('container', {
  2006. * title: {
  2007. * text: 'My chart'
  2008. * },
  2009. * series: [{
  2010. * data: [1, 3, 2, 4]
  2011. * }]
  2012. * });
  2013. *
  2014. * @function Highcharts.chart
  2015. *
  2016. * @param {string|Highcharts.HTMLDOMElement} [renderTo]
  2017. * The DOM element to render to, or its id.
  2018. *
  2019. * @param {Highcharts.Options} options
  2020. * The chart options structure.
  2021. *
  2022. * @param {Highcharts.ChartCallbackFunction} [callback]
  2023. * Function to run when the chart has loaded and and all external images
  2024. * are loaded. Defining a
  2025. * [chart.events.load](https://api.highcharts.com/highcharts/chart.events.load)
  2026. * handler is equivalent.
  2027. *
  2028. * @return {Highcharts.Chart}
  2029. * Returns the Chart object.
  2030. */
  2031. function chart(a, b, c) {
  2032. return new Chart(a, b, c);
  2033. }
  2034. H.chart = chart;
  2035. H.Chart = Chart;
  2036. export default Chart;