data.src.js 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364
  1. /**
  2. * @license Highcharts JS v8.2.2 (2020-10-22)
  3. *
  4. * Data module
  5. *
  6. * (c) 2012-2019 Torstein Honsi
  7. *
  8. * License: www.highcharts.com/license
  9. */
  10. 'use strict';
  11. (function (factory) {
  12. if (typeof module === 'object' && module.exports) {
  13. factory['default'] = factory;
  14. module.exports = factory;
  15. } else if (typeof define === 'function' && define.amd) {
  16. define('highcharts/modules/data', ['highcharts'], function (Highcharts) {
  17. factory(Highcharts);
  18. factory.Highcharts = Highcharts;
  19. return factory;
  20. });
  21. } else {
  22. factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
  23. }
  24. }(function (Highcharts) {
  25. var _modules = Highcharts ? Highcharts._modules : {};
  26. function _registerModule(obj, path, args, fn) {
  27. if (!obj.hasOwnProperty(path)) {
  28. obj[path] = fn.apply(null, args);
  29. }
  30. }
  31. _registerModule(_modules, 'Extensions/Ajax.js', [_modules['Core/Globals.js'], _modules['Core/Utilities.js']], function (H, U) {
  32. /* *
  33. *
  34. * (c) 2010-2017 Christer Vasseng, Torstein Honsi
  35. *
  36. * License: www.highcharts.com/license
  37. *
  38. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  39. *
  40. * */
  41. var merge = U.merge,
  42. objectEach = U.objectEach;
  43. /**
  44. * @interface Highcharts.AjaxSettingsObject
  45. */ /**
  46. * The payload to send.
  47. *
  48. * @name Highcharts.AjaxSettingsObject#data
  49. * @type {string|Highcharts.Dictionary<any>}
  50. */ /**
  51. * The data type expected.
  52. * @name Highcharts.AjaxSettingsObject#dataType
  53. * @type {"json"|"xml"|"text"|"octet"}
  54. */ /**
  55. * Function to call on error.
  56. * @name Highcharts.AjaxSettingsObject#error
  57. * @type {Function}
  58. */ /**
  59. * The headers; keyed on header name.
  60. * @name Highcharts.AjaxSettingsObject#headers
  61. * @type {Highcharts.Dictionary<string>}
  62. */ /**
  63. * Function to call on success.
  64. * @name Highcharts.AjaxSettingsObject#success
  65. * @type {Function}
  66. */ /**
  67. * The HTTP method to use. For example GET or POST.
  68. * @name Highcharts.AjaxSettingsObject#type
  69. * @type {string}
  70. */ /**
  71. * The URL to call.
  72. * @name Highcharts.AjaxSettingsObject#url
  73. * @type {string}
  74. */
  75. /**
  76. * Perform an Ajax call.
  77. *
  78. * @function Highcharts.ajax
  79. *
  80. * @param {Partial<Highcharts.AjaxSettingsObject>} attr
  81. * The Ajax settings to use.
  82. *
  83. * @return {false|undefined}
  84. * Returns false, if error occured.
  85. */
  86. H.ajax = function (attr) {
  87. var options = merge(true, {
  88. url: false,
  89. type: 'get',
  90. dataType: 'json',
  91. success: false,
  92. error: false,
  93. data: false,
  94. headers: {}
  95. },
  96. attr),
  97. headers = {
  98. json: 'application/json',
  99. xml: 'application/xml',
  100. text: 'text/plain',
  101. octet: 'application/octet-stream'
  102. },
  103. r = new XMLHttpRequest();
  104. /**
  105. * @private
  106. * @param {XMLHttpRequest} xhr - Internal request object.
  107. * @param {string|Error} err - Occured error.
  108. * @return {void}
  109. */
  110. function handleError(xhr, err) {
  111. if (options.error) {
  112. options.error(xhr, err);
  113. }
  114. else {
  115. // @todo Maybe emit a highcharts error event here
  116. }
  117. }
  118. if (!options.url) {
  119. return false;
  120. }
  121. r.open(options.type.toUpperCase(), options.url, true);
  122. if (!options.headers['Content-Type']) {
  123. r.setRequestHeader('Content-Type', headers[options.dataType] || headers.text);
  124. }
  125. objectEach(options.headers, function (val, key) {
  126. r.setRequestHeader(key, val);
  127. });
  128. // @todo lacking timeout handling
  129. r.onreadystatechange = function () {
  130. var res;
  131. if (r.readyState === 4) {
  132. if (r.status === 200) {
  133. res = r.responseText;
  134. if (options.dataType === 'json') {
  135. try {
  136. res = JSON.parse(res);
  137. }
  138. catch (e) {
  139. return handleError(r, e);
  140. }
  141. }
  142. return options.success && options.success(res);
  143. }
  144. handleError(r, r.responseText);
  145. }
  146. };
  147. try {
  148. options.data = JSON.stringify(options.data);
  149. }
  150. catch (e) {
  151. // empty
  152. }
  153. r.send(options.data || true);
  154. };
  155. /**
  156. * Get a JSON resource over XHR, also supporting CORS without preflight.
  157. *
  158. * @function Highcharts.getJSON
  159. * @param {string} url
  160. * The URL to load.
  161. * @param {Function} success
  162. * The success callback. For error handling, use the `Highcharts.ajax`
  163. * function instead.
  164. * @return {void}
  165. */
  166. H.getJSON = function (url, success) {
  167. H.ajax({
  168. url: url,
  169. success: success,
  170. dataType: 'json',
  171. headers: {
  172. // Override the Content-Type to avoid preflight problems with CORS
  173. // in the Highcharts demos
  174. 'Content-Type': 'text/plain'
  175. }
  176. });
  177. };
  178. var exports = {
  179. ajax: H.ajax,
  180. getJSON: H.getJSON
  181. };
  182. return exports;
  183. });
  184. _registerModule(_modules, 'Extensions/Data.js', [_modules['Extensions/Ajax.js'], _modules['Core/Series/Series.js'], _modules['Core/Chart/Chart.js'], _modules['Core/Globals.js'], _modules['Core/Series/Point.js'], _modules['Core/Utilities.js']], function (Ajax, BaseSeries, Chart, H, Point, U) {
  185. /* *
  186. *
  187. * Data module
  188. *
  189. * (c) 2012-2020 Torstein Honsi
  190. *
  191. * License: www.highcharts.com/license
  192. *
  193. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  194. *
  195. * */
  196. var ajax = Ajax.ajax;
  197. var doc = H.doc;
  198. var addEvent = U.addEvent,
  199. defined = U.defined,
  200. extend = U.extend,
  201. fireEvent = U.fireEvent,
  202. isNumber = U.isNumber,
  203. merge = U.merge,
  204. objectEach = U.objectEach,
  205. pick = U.pick,
  206. splat = U.splat;
  207. var seriesTypes = BaseSeries.seriesTypes;
  208. /**
  209. * Callback function to modify the CSV before parsing it by the data module.
  210. *
  211. * @callback Highcharts.DataBeforeParseCallbackFunction
  212. *
  213. * @param {string} csv
  214. * The CSV to modify.
  215. *
  216. * @return {string}
  217. * The CSV to parse.
  218. */
  219. /**
  220. * Callback function that gets called after parsing data.
  221. *
  222. * @callback Highcharts.DataCompleteCallbackFunction
  223. *
  224. * @param {Highcharts.Options} chartOptions
  225. * The chart options that were used.
  226. */
  227. /**
  228. * Callback function that returns the correspondig Date object to a match.
  229. *
  230. * @callback Highcharts.DataDateFormatCallbackFunction
  231. *
  232. * @param {Array<number>} match
  233. *
  234. * @return {number}
  235. */
  236. /**
  237. * Structure for alternative date formats to parse.
  238. *
  239. * @interface Highcharts.DataDateFormatObject
  240. */ /**
  241. * @name Highcharts.DataDateFormatObject#alternative
  242. * @type {string|undefined}
  243. */ /**
  244. * @name Highcharts.DataDateFormatObject#parser
  245. * @type {Highcharts.DataDateFormatCallbackFunction}
  246. */ /**
  247. * @name Highcharts.DataDateFormatObject#regex
  248. * @type {global.RegExp}
  249. */
  250. /**
  251. * Possible types for a data item in a column or row.
  252. *
  253. * @typedef {number|string|null} Highcharts.DataValueType
  254. */
  255. /**
  256. * Callback function to parse string representations of dates into
  257. * JavaScript timestamps (milliseconds since 1.1.1970).
  258. *
  259. * @callback Highcharts.DataParseDateCallbackFunction
  260. *
  261. * @param {string} dateValue
  262. *
  263. * @return {number}
  264. * Timestamp (milliseconds since 1.1.1970) as integer for Date class.
  265. */
  266. /**
  267. * Callback function to access the parsed columns, the two-dimentional
  268. * input data array directly, before they are interpreted into series
  269. * data and categories.
  270. *
  271. * @callback Highcharts.DataParsedCallbackFunction
  272. *
  273. * @param {Array<Array<*>>} columns
  274. * The parsed columns by the data module.
  275. *
  276. * @return {boolean|undefined}
  277. * Return `false` to stop completion, or call `this.complete()` to
  278. * continue async.
  279. */
  280. /**
  281. * The Data module provides a simplified interface for adding data to
  282. * a chart from sources like CVS, HTML tables or grid views. See also
  283. * the [tutorial article on the Data module](
  284. * https://www.highcharts.com/docs/working-with-data/data-module).
  285. *
  286. * It requires the `modules/data.js` file to be loaded.
  287. *
  288. * Please note that the default way of adding data in Highcharts, without
  289. * the need of a module, is through the [series._type_.data](#series.line.data)
  290. * option.
  291. *
  292. * @sample {highcharts} highcharts/demo/column-parsed/
  293. * HTML table
  294. * @sample {highcharts} highcharts/data/csv/
  295. * CSV
  296. *
  297. * @since 4.0
  298. * @requires modules/data
  299. * @apioption data
  300. */
  301. /**
  302. * A callback function to modify the CSV before parsing it. Return the modified
  303. * string.
  304. *
  305. * @sample {highcharts} highcharts/demo/line-ajax/
  306. * Modify CSV before parse
  307. *
  308. * @type {Highcharts.DataBeforeParseCallbackFunction}
  309. * @since 6.1
  310. * @apioption data.beforeParse
  311. */
  312. /**
  313. * A two-dimensional array representing the input data on tabular form.
  314. * This input can be used when the data is already parsed, for example
  315. * from a grid view component. Each cell can be a string or number.
  316. * If not switchRowsAndColumns is set, the columns are interpreted as
  317. * series.
  318. *
  319. * @see [data.rows](#data.rows)
  320. *
  321. * @sample {highcharts} highcharts/data/columns/
  322. * Columns
  323. *
  324. * @type {Array<Array<Highcharts.DataValueType>>}
  325. * @since 4.0
  326. * @apioption data.columns
  327. */
  328. /**
  329. * The callback that is evaluated when the data is finished loading,
  330. * optionally from an external source, and parsed. The first argument
  331. * passed is a finished chart options object, containing the series.
  332. * These options can be extended with additional options and passed
  333. * directly to the chart constructor.
  334. *
  335. * @see [data.parsed](#data.parsed)
  336. *
  337. * @sample {highcharts} highcharts/data/complete/
  338. * Modify data on complete
  339. *
  340. * @type {Highcharts.DataCompleteCallbackFunction}
  341. * @since 4.0
  342. * @apioption data.complete
  343. */
  344. /**
  345. * A comma delimited string to be parsed. Related options are [startRow](
  346. * #data.startRow), [endRow](#data.endRow), [startColumn](#data.startColumn)
  347. * and [endColumn](#data.endColumn) to delimit what part of the table
  348. * is used. The [lineDelimiter](#data.lineDelimiter) and [itemDelimiter](
  349. * #data.itemDelimiter) options define the CSV delimiter formats.
  350. *
  351. * The built-in CSV parser doesn't support all flavours of CSV, so in
  352. * some cases it may be necessary to use an external CSV parser. See
  353. * [this example](https://jsfiddle.net/highcharts/u59176h4/) of parsing
  354. * CSV through the MIT licensed [Papa Parse](http://papaparse.com/)
  355. * library.
  356. *
  357. * @sample {highcharts} highcharts/data/csv/
  358. * Data from CSV
  359. *
  360. * @type {string}
  361. * @since 4.0
  362. * @apioption data.csv
  363. */
  364. /**
  365. * Which of the predefined date formats in Date.prototype.dateFormats
  366. * to use to parse date values. Defaults to a best guess based on what
  367. * format gives valid and ordered dates. Valid options include: `YYYY/mm/dd`,
  368. * `dd/mm/YYYY`, `mm/dd/YYYY`, `dd/mm/YY`, `mm/dd/YY`.
  369. *
  370. * @see [data.parseDate](#data.parseDate)
  371. *
  372. * @sample {highcharts} highcharts/data/dateformat-auto/
  373. * Best guess date format
  374. *
  375. * @type {string}
  376. * @since 4.0
  377. * @validvalue ["YYYY/mm/dd", "dd/mm/YYYY", "mm/dd/YYYY", "dd/mm/YYYY",
  378. * "dd/mm/YY", "mm/dd/YY"]
  379. * @apioption data.dateFormat
  380. */
  381. /**
  382. * The decimal point used for parsing numbers in the CSV.
  383. *
  384. * If both this and data.delimiter is set to `undefined`, the parser will
  385. * attempt to deduce the decimal point automatically.
  386. *
  387. * @sample {highcharts} highcharts/data/delimiters/
  388. * Comma as decimal point
  389. *
  390. * @type {string}
  391. * @default .
  392. * @since 4.1.0
  393. * @apioption data.decimalPoint
  394. */
  395. /**
  396. * In tabular input data, the last column (indexed by 0) to use. Defaults
  397. * to the last column containing data.
  398. *
  399. * @sample {highcharts} highcharts/data/start-end/
  400. * Limited data
  401. *
  402. * @type {number}
  403. * @since 4.0
  404. * @apioption data.endColumn
  405. */
  406. /**
  407. * In tabular input data, the last row (indexed by 0) to use. Defaults
  408. * to the last row containing data.
  409. *
  410. * @sample {highcharts} highcharts/data/start-end/
  411. * Limited data
  412. *
  413. * @type {number}
  414. * @since 4.0.4
  415. * @apioption data.endRow
  416. */
  417. /**
  418. * Whether to use the first row in the data set as series names.
  419. *
  420. * @sample {highcharts} highcharts/data/start-end/
  421. * Don't get series names from the CSV
  422. * @sample {highstock} highcharts/data/start-end/
  423. * Don't get series names from the CSV
  424. *
  425. * @type {boolean}
  426. * @default true
  427. * @since 4.1.0
  428. * @product highcharts highstock gantt
  429. * @apioption data.firstRowAsNames
  430. */
  431. /**
  432. * The key for a Google Spreadsheet to load. See [general information
  433. * on GS](https://developers.google.com/gdata/samples/spreadsheet_sample).
  434. *
  435. * @sample {highcharts} highcharts/data/google-spreadsheet/
  436. * Load a Google Spreadsheet
  437. *
  438. * @type {string}
  439. * @since 4.0
  440. * @apioption data.googleSpreadsheetKey
  441. */
  442. /**
  443. * The Google Spreadsheet worksheet to use in combination with
  444. * [googleSpreadsheetKey](#data.googleSpreadsheetKey). The available id's from
  445. * your sheet can be read from `https://spreadsheets.google.com/feeds/worksheets/{key}/public/basic`.
  446. *
  447. * @sample {highcharts} highcharts/data/google-spreadsheet/
  448. * Load a Google Spreadsheet
  449. *
  450. * @type {string}
  451. * @since 4.0
  452. * @apioption data.googleSpreadsheetWorksheet
  453. */
  454. /**
  455. * Item or cell delimiter for parsing CSV. Defaults to the tab character
  456. * `\t` if a tab character is found in the CSV string, if not it defaults
  457. * to `,`.
  458. *
  459. * If this is set to false or undefined, the parser will attempt to deduce
  460. * the delimiter automatically.
  461. *
  462. * @sample {highcharts} highcharts/data/delimiters/
  463. * Delimiters
  464. *
  465. * @type {string}
  466. * @since 4.0
  467. * @apioption data.itemDelimiter
  468. */
  469. /**
  470. * Line delimiter for parsing CSV.
  471. *
  472. * @sample {highcharts} highcharts/data/delimiters/
  473. * Delimiters
  474. *
  475. * @type {string}
  476. * @default \n
  477. * @since 4.0
  478. * @apioption data.lineDelimiter
  479. */
  480. /**
  481. * A callback function to access the parsed columns, the two-dimentional
  482. * input data array directly, before they are interpreted into series
  483. * data and categories. Return `false` to stop completion, or call
  484. * `this.complete()` to continue async.
  485. *
  486. * @see [data.complete](#data.complete)
  487. *
  488. * @sample {highcharts} highcharts/data/parsed/
  489. * Modify data after parse
  490. *
  491. * @type {Highcharts.DataParsedCallbackFunction}
  492. * @since 4.0
  493. * @apioption data.parsed
  494. */
  495. /**
  496. * A callback function to parse string representations of dates into
  497. * JavaScript timestamps. Should return an integer timestamp on success.
  498. *
  499. * @see [dateFormat](#data.dateFormat)
  500. *
  501. * @type {Highcharts.DataParseDateCallbackFunction}
  502. * @since 4.0
  503. * @apioption data.parseDate
  504. */
  505. /**
  506. * The same as the columns input option, but defining rows intead of
  507. * columns.
  508. *
  509. * @see [data.columns](#data.columns)
  510. *
  511. * @sample {highcharts} highcharts/data/rows/
  512. * Data in rows
  513. *
  514. * @type {Array<Array<Highcharts.DataValueType>>}
  515. * @since 4.0
  516. * @apioption data.rows
  517. */
  518. /**
  519. * An array containing dictionaries for each series. A dictionary exists of
  520. * Point property names as the key and the CSV column index as the value.
  521. *
  522. * @sample {highcharts} highcharts/data/seriesmapping-label/
  523. * Label from data set
  524. *
  525. * @type {Array<Highcharts.Dictionary<number>>}
  526. * @since 4.0.4
  527. * @apioption data.seriesMapping
  528. */
  529. /**
  530. * In tabular input data, the first column (indexed by 0) to use.
  531. *
  532. * @sample {highcharts} highcharts/data/start-end/
  533. * Limited data
  534. *
  535. * @type {number}
  536. * @default 0
  537. * @since 4.0
  538. * @apioption data.startColumn
  539. */
  540. /**
  541. * In tabular input data, the first row (indexed by 0) to use.
  542. *
  543. * @sample {highcharts} highcharts/data/start-end/
  544. * Limited data
  545. *
  546. * @type {number}
  547. * @default 0
  548. * @since 4.0
  549. * @apioption data.startRow
  550. */
  551. /**
  552. * Switch rows and columns of the input data, so that `this.columns`
  553. * effectively becomes the rows of the data set, and the rows are interpreted
  554. * as series.
  555. *
  556. * @sample {highcharts} highcharts/data/switchrowsandcolumns/
  557. * Switch rows and columns
  558. *
  559. * @type {boolean}
  560. * @default false
  561. * @since 4.0
  562. * @apioption data.switchRowsAndColumns
  563. */
  564. /**
  565. * An HTML table or the id of such to be parsed as input data. Related
  566. * options are `startRow`, `endRow`, `startColumn` and `endColumn` to
  567. * delimit what part of the table is used.
  568. *
  569. * @sample {highcharts} highcharts/demo/column-parsed/
  570. * Parsed table
  571. *
  572. * @type {string|global.HTMLElement}
  573. * @since 4.0
  574. * @apioption data.table
  575. */
  576. /**
  577. * An URL to a remote CSV dataset. Will be fetched when the chart is created
  578. * using Ajax.
  579. *
  580. * @sample highcharts/data/livedata-columns
  581. * Categorized bar chart with CSV and live polling
  582. * @sample highcharts/data/livedata-csv
  583. * Time based line chart with CSV and live polling
  584. *
  585. * @type {string}
  586. * @apioption data.csvURL
  587. */
  588. /**
  589. * A URL to a remote JSON dataset, structured as a row array.
  590. * Will be fetched when the chart is created using Ajax.
  591. *
  592. * @sample highcharts/data/livedata-rows
  593. * Rows with live polling
  594. *
  595. * @type {string}
  596. * @apioption data.rowsURL
  597. */
  598. /**
  599. * A URL to a remote JSON dataset, structured as a column array.
  600. * Will be fetched when the chart is created using Ajax.
  601. *
  602. * @sample highcharts/data/livedata-columns
  603. * Columns with live polling
  604. *
  605. * @type {string}
  606. * @apioption data.columnsURL
  607. */
  608. /**
  609. * Sets the refresh rate for data polling when importing remote dataset by
  610. * setting [data.csvURL](data.csvURL), [data.rowsURL](data.rowsURL),
  611. * [data.columnsURL](data.columnsURL), or
  612. * [data.googleSpreadsheetKey](data.googleSpreadsheetKey).
  613. *
  614. * Note that polling must be enabled by setting
  615. * [data.enablePolling](data.enablePolling) to true.
  616. *
  617. * The value is the number of seconds between pollings.
  618. * It cannot be set to less than 1 second.
  619. *
  620. * @sample highcharts/demo/live-data
  621. * Live data with user set refresh rate
  622. *
  623. * @default 1
  624. * @type {number}
  625. * @apioption data.dataRefreshRate
  626. */
  627. /**
  628. * Enables automatic refetching of remote datasets every _n_ seconds (defined by
  629. * setting [data.dataRefreshRate](data.dataRefreshRate)).
  630. *
  631. * Only works when either [data.csvURL](data.csvURL),
  632. * [data.rowsURL](data.rowsURL), [data.columnsURL](data.columnsURL), or
  633. * [data.googleSpreadsheetKey](data.googleSpreadsheetKey).
  634. *
  635. * @sample highcharts/demo/live-data
  636. * Live data
  637. * @sample highcharts/data/livedata-columns
  638. * Categorized bar chart with CSV and live polling
  639. *
  640. * @type {boolean}
  641. * @default false
  642. * @apioption data.enablePolling
  643. */
  644. /* eslint-disable valid-jsdoc */
  645. /**
  646. * The Data class
  647. *
  648. * @requires module:modules/data
  649. *
  650. * @class
  651. * @name Highcharts.Data
  652. *
  653. * @param {Highcharts.DataOptions} dataOptions
  654. *
  655. * @param {Highcharts.Options} [chartOptions]
  656. *
  657. * @param {Highcharts.Chart} [chart]
  658. */
  659. var Data = /** @class */ (function () {
  660. function Data(dataOptions, chartOptions, chart) {
  661. this.chart = void 0;
  662. this.chartOptions = void 0;
  663. this.firstRowAsNames = void 0;
  664. this.rawColumns = void 0;
  665. this.options = void 0;
  666. /**
  667. * A collection of available date formats, extendable from the outside to
  668. * support custom date formats.
  669. *
  670. * @name Highcharts.Data#dateFormats
  671. * @type {Highcharts.Dictionary<Highcharts.DataDateFormatObject>}
  672. */
  673. this.dateFormats = {
  674. 'YYYY/mm/dd': {
  675. regex: /^([0-9]{4})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{1,2})$/,
  676. parser: function (match) {
  677. return (match ?
  678. Date.UTC(+match[1], match[2] - 1, +match[3]) :
  679. NaN);
  680. }
  681. },
  682. 'dd/mm/YYYY': {
  683. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{4})$/,
  684. parser: function (match) {
  685. return (match ?
  686. Date.UTC(+match[3], match[2] - 1, +match[1]) :
  687. NaN);
  688. },
  689. alternative: 'mm/dd/YYYY' // different format with the same regex
  690. },
  691. 'mm/dd/YYYY': {
  692. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{4})$/,
  693. parser: function (match) {
  694. return (match ?
  695. Date.UTC(+match[3], match[1] - 1, +match[2]) :
  696. NaN);
  697. }
  698. },
  699. 'dd/mm/YY': {
  700. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{2})$/,
  701. parser: function (match) {
  702. if (!match) {
  703. return NaN;
  704. }
  705. var year = +match[3],
  706. d = new Date();
  707. if (year > (d.getFullYear() - 2000)) {
  708. year += 1900;
  709. }
  710. else {
  711. year += 2000;
  712. }
  713. return Date.UTC(year, match[2] - 1, +match[1]);
  714. },
  715. alternative: 'mm/dd/YY' // different format with the same regex
  716. },
  717. 'mm/dd/YY': {
  718. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{2})$/,
  719. parser: function (match) {
  720. return (match ?
  721. Date.UTC(+match[3] + 2000, match[1] - 1, +match[2]) :
  722. NaN);
  723. }
  724. }
  725. };
  726. this.init(dataOptions, chartOptions, chart);
  727. }
  728. /**
  729. * Initialize the Data object with the given options
  730. *
  731. * @private
  732. * @function Highcharts.Data#init
  733. * @param {Highcharts.DataOptions} options
  734. * @param {Highcharts.Options} [chartOptions]
  735. * @param {Highcharts.Chart} [chart]
  736. */
  737. Data.prototype.init = function (options, chartOptions, chart) {
  738. var decimalPoint = options.decimalPoint,
  739. hasData;
  740. if (chartOptions) {
  741. this.chartOptions = chartOptions;
  742. }
  743. if (chart) {
  744. this.chart = chart;
  745. }
  746. if (decimalPoint !== '.' && decimalPoint !== ',') {
  747. decimalPoint = void 0;
  748. }
  749. this.options = options;
  750. this.columns = (options.columns ||
  751. this.rowsToColumns(options.rows) ||
  752. []);
  753. this.firstRowAsNames = pick(options.firstRowAsNames, this.firstRowAsNames, true);
  754. this.decimalRegex = (decimalPoint &&
  755. new RegExp('^(-?[0-9]+)' + decimalPoint + '([0-9]+)$'));
  756. // This is a two-dimensional array holding the raw, trimmed string
  757. // values with the same organisation as the columns array. It makes it
  758. // possible for example to revert from interpreted timestamps to
  759. // string-based categories.
  760. this.rawColumns = [];
  761. // No need to parse or interpret anything
  762. if (this.columns.length) {
  763. this.dataFound();
  764. hasData = true;
  765. }
  766. if (this.hasURLOption(options)) {
  767. clearTimeout(this.liveDataTimeout);
  768. hasData = false;
  769. }
  770. if (!hasData) {
  771. // Fetch live data
  772. hasData = this.fetchLiveData();
  773. }
  774. if (!hasData) {
  775. // Parse a CSV string if options.csv is given. The parseCSV function
  776. // returns a columns array, if it has no length, we have no data
  777. hasData = Boolean(this.parseCSV().length);
  778. }
  779. if (!hasData) {
  780. // Parse a HTML table if options.table is given
  781. hasData = Boolean(this.parseTable().length);
  782. }
  783. if (!hasData) {
  784. // Parse a Google Spreadsheet
  785. hasData = this.parseGoogleSpreadsheet();
  786. }
  787. if (!hasData && options.afterComplete) {
  788. options.afterComplete();
  789. }
  790. };
  791. Data.prototype.hasURLOption = function (options) {
  792. return Boolean(options &&
  793. (options.rowsURL || options.csvURL || options.columnsURL));
  794. };
  795. /**
  796. * Get the column distribution. For example, a line series takes a single
  797. * column for Y values. A range series takes two columns for low and high
  798. * values respectively, and an OHLC series takes four columns.
  799. *
  800. * @function Highcharts.Data#getColumnDistribution
  801. */
  802. Data.prototype.getColumnDistribution = function () {
  803. var chartOptions = this.chartOptions,
  804. options = this.options,
  805. xColumns = [],
  806. getValueCount = function (type) {
  807. return (seriesTypes[type || 'line'].prototype.pointArrayMap || [0]).length;
  808. }, getPointArrayMap = function (type) {
  809. return seriesTypes[type || 'line'].prototype.pointArrayMap;
  810. }, globalType = (chartOptions &&
  811. chartOptions.chart &&
  812. chartOptions.chart.type), individualCounts = [], seriesBuilders = [], seriesIndex = 0,
  813. // If no series mapping is defined, check if the series array is
  814. // defined with types.
  815. seriesMapping = ((options && options.seriesMapping) ||
  816. (chartOptions &&
  817. chartOptions.series &&
  818. chartOptions.series.map(function () {
  819. return { x: 0 };
  820. })) ||
  821. []), i;
  822. ((chartOptions && chartOptions.series) || []).forEach(function (series) {
  823. individualCounts.push(getValueCount(series.type || globalType));
  824. });
  825. // Collect the x-column indexes from seriesMapping
  826. seriesMapping.forEach(function (mapping) {
  827. xColumns.push(mapping.x || 0);
  828. });
  829. // If there are no defined series with x-columns, use the first column
  830. // as x column
  831. if (xColumns.length === 0) {
  832. xColumns.push(0);
  833. }
  834. // Loop all seriesMappings and constructs SeriesBuilders from
  835. // the mapping options.
  836. seriesMapping.forEach(function (mapping) {
  837. var builder = new SeriesBuilder(),
  838. numberOfValueColumnsNeeded = individualCounts[seriesIndex] ||
  839. getValueCount(globalType),
  840. seriesArr = (chartOptions && chartOptions.series) || [],
  841. series = seriesArr[seriesIndex] || {},
  842. defaultPointArrayMap = getPointArrayMap(series.type || globalType),
  843. pointArrayMap = defaultPointArrayMap || ['y'];
  844. if (
  845. // User-defined x.mapping
  846. defined(mapping.x) ||
  847. // All non cartesian don't need 'x'
  848. series.isCartesian ||
  849. // Except pie series:
  850. !defaultPointArrayMap) {
  851. // Add an x reader from the x property or from an undefined
  852. // column if the property is not set. It will then be auto
  853. // populated later.
  854. builder.addColumnReader(mapping.x, 'x');
  855. }
  856. // Add all column mappings
  857. objectEach(mapping, function (val, name) {
  858. if (name !== 'x') {
  859. builder.addColumnReader(val, name);
  860. }
  861. });
  862. // Add missing columns
  863. for (i = 0; i < numberOfValueColumnsNeeded; i++) {
  864. if (!builder.hasReader(pointArrayMap[i])) {
  865. // Create and add a column reader for the next free column
  866. // index
  867. builder.addColumnReader(void 0, pointArrayMap[i]);
  868. }
  869. }
  870. seriesBuilders.push(builder);
  871. seriesIndex++;
  872. });
  873. var globalPointArrayMap = getPointArrayMap(globalType);
  874. if (typeof globalPointArrayMap === 'undefined') {
  875. globalPointArrayMap = ['y'];
  876. }
  877. this.valueCount = {
  878. global: getValueCount(globalType),
  879. xColumns: xColumns,
  880. individual: individualCounts,
  881. seriesBuilders: seriesBuilders,
  882. globalPointArrayMap: globalPointArrayMap
  883. };
  884. };
  885. /**
  886. * When the data is parsed into columns, either by CSV, table, GS or direct
  887. * input, continue with other operations.
  888. *
  889. * @private
  890. * @function Highcharts.Data#dataFound
  891. */
  892. Data.prototype.dataFound = function () {
  893. if (this.options.switchRowsAndColumns) {
  894. this.columns = this.rowsToColumns(this.columns);
  895. }
  896. // Interpret the info about series and columns
  897. this.getColumnDistribution();
  898. // Interpret the values into right types
  899. this.parseTypes();
  900. // Handle columns if a handleColumns callback is given
  901. if (this.parsed() !== false) {
  902. // Complete if a complete callback is given
  903. this.complete();
  904. }
  905. };
  906. /**
  907. * Parse a CSV input string
  908. *
  909. * @function Highcharts.Data#parseCSV
  910. *
  911. * @param {Highcharts.DataOptions} [inOptions]
  912. *
  913. * @return {Array<Array<Highcharts.DataValueType>>}
  914. */
  915. Data.prototype.parseCSV = function (inOptions) {
  916. var self = this, options = inOptions || this.options, csv = options.csv, columns, startRow = (typeof options.startRow !== 'undefined' && options.startRow ?
  917. options.startRow :
  918. 0), endRow = options.endRow || Number.MAX_VALUE, startColumn = (typeof options.startColumn !== 'undefined' &&
  919. options.startColumn) ? options.startColumn : 0, endColumn = options.endColumn || Number.MAX_VALUE, itemDelimiter, lines, rowIt = 0,
  920. // activeRowNo = 0,
  921. dataTypes = [],
  922. // We count potential delimiters in the prepass, and use the
  923. // result as the basis of half-intelligent guesses.
  924. potDelimiters = {
  925. ',': 0,
  926. ';': 0,
  927. '\t': 0
  928. };
  929. columns = this.columns = [];
  930. /*
  931. This implementation is quite verbose. It will be shortened once
  932. it's stable and passes all the test.
  933. It's also not written with speed in mind, instead everything is
  934. very seggregated, and there a several redundant loops.
  935. This is to make it easier to stabilize the code initially.
  936. We do a pre-pass on the first 4 rows to make some intelligent
  937. guesses on the set. Guessed delimiters are in this pass counted.
  938. Auto detecting delimiters
  939. - If we meet a quoted string, the next symbol afterwards
  940. (that's not \s, \t) is the delimiter
  941. - If we meet a date, the next symbol afterwards is the delimiter
  942. Date formats
  943. - If we meet a column with date formats, check all of them to
  944. see if one of the potential months crossing 12. If it does,
  945. we now know the format
  946. It would make things easier to guess the delimiter before
  947. doing the actual parsing.
  948. General rules:
  949. - Quoting is allowed, e.g: "Col 1",123,321
  950. - Quoting is optional, e.g.: Col1,123,321
  951. - Doubble quoting is escaping, e.g. "Col ""Hello world""",123
  952. - Spaces are considered part of the data: Col1 ,123
  953. - New line is always the row delimiter
  954. - Potential column delimiters are , ; \t
  955. - First row may optionally contain headers
  956. - The last row may or may not have a row delimiter
  957. - Comments are optionally supported, in which case the comment
  958. must start at the first column, and the rest of the line will
  959. be ignored
  960. */
  961. /**
  962. * Parse a single row.
  963. * @private
  964. */
  965. function parseRow(columnStr, rowNumber, noAdd, callbacks) {
  966. var i = 0, c = '', cl = '', cn = '', token = '', actualColumn = 0, column = 0;
  967. /**
  968. * @private
  969. */
  970. function read(j) {
  971. c = columnStr[j];
  972. cl = columnStr[j - 1];
  973. cn = columnStr[j + 1];
  974. }
  975. /**
  976. * @private
  977. */
  978. function pushType(type) {
  979. if (dataTypes.length < column + 1) {
  980. dataTypes.push([type]);
  981. }
  982. if (dataTypes[column][dataTypes[column].length - 1] !== type) {
  983. dataTypes[column].push(type);
  984. }
  985. }
  986. /**
  987. * @private
  988. */
  989. function push() {
  990. if (startColumn > actualColumn || actualColumn > endColumn) {
  991. // Skip this column, but increment the column count (#7272)
  992. ++actualColumn;
  993. token = '';
  994. return;
  995. }
  996. if (!isNaN(parseFloat(token)) && isFinite(token)) {
  997. token = parseFloat(token);
  998. pushType('number');
  999. }
  1000. else if (!isNaN(Date.parse(token))) {
  1001. token = token.replace(/\//g, '-');
  1002. pushType('date');
  1003. }
  1004. else {
  1005. pushType('string');
  1006. }
  1007. if (columns.length < column + 1) {
  1008. columns.push([]);
  1009. }
  1010. if (!noAdd) {
  1011. // Don't push - if there's a varrying amount of columns
  1012. // for each row, pushing will skew everything down n slots
  1013. columns[column][rowNumber] = token;
  1014. }
  1015. token = '';
  1016. ++column;
  1017. ++actualColumn;
  1018. }
  1019. if (!columnStr.trim().length) {
  1020. return;
  1021. }
  1022. if (columnStr.trim()[0] === '#') {
  1023. return;
  1024. }
  1025. for (; i < columnStr.length; i++) {
  1026. read(i);
  1027. // Quoted string
  1028. if (c === '#') {
  1029. // The rest of the row is a comment
  1030. push();
  1031. return;
  1032. }
  1033. if (c === '"') {
  1034. read(++i);
  1035. while (i < columnStr.length) {
  1036. if (c === '"' && cl !== '"' && cn !== '"') {
  1037. break;
  1038. }
  1039. if (c !== '"' || (c === '"' && cl !== '"')) {
  1040. token += c;
  1041. }
  1042. read(++i);
  1043. }
  1044. // Perform "plugin" handling
  1045. }
  1046. else if (callbacks && callbacks[c]) {
  1047. if (callbacks[c](c, token)) {
  1048. push();
  1049. }
  1050. // Delimiter - push current token
  1051. }
  1052. else if (c === itemDelimiter) {
  1053. push();
  1054. // Actual column data
  1055. }
  1056. else {
  1057. token += c;
  1058. }
  1059. }
  1060. push();
  1061. }
  1062. /**
  1063. * Attempt to guess the delimiter. We do a separate parse pass here
  1064. * because we need to count potential delimiters softly without making
  1065. * any assumptions.
  1066. * @private
  1067. */
  1068. function guessDelimiter(lines) {
  1069. var points = 0,
  1070. commas = 0,
  1071. guessed = false;
  1072. lines.some(function (columnStr, i) {
  1073. var inStr = false,
  1074. c,
  1075. cn,
  1076. cl,
  1077. token = '';
  1078. // We should be able to detect dateformats within 13 rows
  1079. if (i > 13) {
  1080. return true;
  1081. }
  1082. for (var j = 0; j < columnStr.length; j++) {
  1083. c = columnStr[j];
  1084. cn = columnStr[j + 1];
  1085. cl = columnStr[j - 1];
  1086. if (c === '#') {
  1087. // Skip the rest of the line - it's a comment
  1088. return;
  1089. }
  1090. if (c === '"') {
  1091. if (inStr) {
  1092. if (cl !== '"' && cn !== '"') {
  1093. while (cn === ' ' && j < columnStr.length) {
  1094. cn = columnStr[++j];
  1095. }
  1096. // After parsing a string, the next non-blank
  1097. // should be a delimiter if the CSV is properly
  1098. // formed.
  1099. if (typeof potDelimiters[cn] !== 'undefined') {
  1100. potDelimiters[cn]++;
  1101. }
  1102. inStr = false;
  1103. }
  1104. }
  1105. else {
  1106. inStr = true;
  1107. }
  1108. }
  1109. else if (typeof potDelimiters[c] !== 'undefined') {
  1110. token = token.trim();
  1111. if (!isNaN(Date.parse(token))) {
  1112. potDelimiters[c]++;
  1113. }
  1114. else if (isNaN(token) ||
  1115. !isFinite(token)) {
  1116. potDelimiters[c]++;
  1117. }
  1118. token = '';
  1119. }
  1120. else {
  1121. token += c;
  1122. }
  1123. if (c === ',') {
  1124. commas++;
  1125. }
  1126. if (c === '.') {
  1127. points++;
  1128. }
  1129. }
  1130. });
  1131. // Count the potential delimiters.
  1132. // This could be improved by checking if the number of delimiters
  1133. // equals the number of columns - 1
  1134. if (potDelimiters[';'] > potDelimiters[',']) {
  1135. guessed = ';';
  1136. }
  1137. else if (potDelimiters[','] > potDelimiters[';']) {
  1138. guessed = ',';
  1139. }
  1140. else {
  1141. // No good guess could be made..
  1142. guessed = ',';
  1143. }
  1144. // Try to deduce the decimal point if it's not explicitly set.
  1145. // If both commas or points is > 0 there is likely an issue
  1146. if (!options.decimalPoint) {
  1147. if (points > commas) {
  1148. options.decimalPoint = '.';
  1149. }
  1150. else {
  1151. options.decimalPoint = ',';
  1152. }
  1153. // Apply a new decimal regex based on the presumed decimal sep.
  1154. self.decimalRegex = new RegExp('^(-?[0-9]+)' +
  1155. options.decimalPoint +
  1156. '([0-9]+)$');
  1157. }
  1158. return guessed;
  1159. }
  1160. /**
  1161. * Tries to guess the date format
  1162. * - Check if either month candidate exceeds 12
  1163. * - Check if year is missing (use current year)
  1164. * - Check if a shortened year format is used (e.g. 1/1/99)
  1165. * - If no guess can be made, the user must be prompted
  1166. * data is the data to deduce a format based on
  1167. * @private
  1168. */
  1169. function deduceDateFormat(data, limit) {
  1170. var format = 'YYYY/mm/dd',
  1171. thing,
  1172. guessedFormat = [],
  1173. calculatedFormat,
  1174. i = 0,
  1175. madeDeduction = false,
  1176. // candidates = {},
  1177. stable = [],
  1178. max = [],
  1179. j;
  1180. if (!limit || limit > data.length) {
  1181. limit = data.length;
  1182. }
  1183. for (; i < limit; i++) {
  1184. if (typeof data[i] !== 'undefined' &&
  1185. data[i] && data[i].length) {
  1186. thing = data[i]
  1187. .trim()
  1188. .replace(/\//g, ' ')
  1189. .replace(/\-/g, ' ')
  1190. .replace(/\./g, ' ')
  1191. .split(' ');
  1192. guessedFormat = [
  1193. '',
  1194. '',
  1195. ''
  1196. ];
  1197. for (j = 0; j < thing.length; j++) {
  1198. if (j < guessedFormat.length) {
  1199. thing[j] = parseInt(thing[j], 10);
  1200. if (thing[j]) {
  1201. max[j] = (!max[j] || max[j] < thing[j]) ?
  1202. thing[j] :
  1203. max[j];
  1204. if (typeof stable[j] !== 'undefined') {
  1205. if (stable[j] !== thing[j]) {
  1206. stable[j] = false;
  1207. }
  1208. }
  1209. else {
  1210. stable[j] = thing[j];
  1211. }
  1212. if (thing[j] > 31) {
  1213. if (thing[j] < 100) {
  1214. guessedFormat[j] = 'YY';
  1215. }
  1216. else {
  1217. guessedFormat[j] = 'YYYY';
  1218. }
  1219. // madeDeduction = true;
  1220. }
  1221. else if (thing[j] > 12 &&
  1222. thing[j] <= 31) {
  1223. guessedFormat[j] = 'dd';
  1224. madeDeduction = true;
  1225. }
  1226. else if (!guessedFormat[j].length) {
  1227. guessedFormat[j] = 'mm';
  1228. }
  1229. }
  1230. }
  1231. }
  1232. }
  1233. }
  1234. if (madeDeduction) {
  1235. // This handles a few edge cases with hard to guess dates
  1236. for (j = 0; j < stable.length; j++) {
  1237. if (stable[j] !== false) {
  1238. if (max[j] > 12 &&
  1239. guessedFormat[j] !== 'YY' &&
  1240. guessedFormat[j] !== 'YYYY') {
  1241. guessedFormat[j] = 'YY';
  1242. }
  1243. }
  1244. else if (max[j] > 12 && guessedFormat[j] === 'mm') {
  1245. guessedFormat[j] = 'dd';
  1246. }
  1247. }
  1248. // If the middle one is dd, and the last one is dd,
  1249. // the last should likely be year.
  1250. if (guessedFormat.length === 3 &&
  1251. guessedFormat[1] === 'dd' &&
  1252. guessedFormat[2] === 'dd') {
  1253. guessedFormat[2] = 'YY';
  1254. }
  1255. calculatedFormat = guessedFormat.join('/');
  1256. // If the caculated format is not valid, we need to present an
  1257. // error.
  1258. if (!(options.dateFormats || self.dateFormats)[calculatedFormat]) {
  1259. // This should emit an event instead
  1260. fireEvent('deduceDateFailed');
  1261. return format;
  1262. }
  1263. return calculatedFormat;
  1264. }
  1265. return format;
  1266. }
  1267. /**
  1268. * @todo
  1269. * Figure out the best axis types for the data
  1270. * - If the first column is a number, we're good
  1271. * - If the first column is a date, set to date/time
  1272. * - If the first column is a string, set to categories
  1273. * @private
  1274. */
  1275. function deduceAxisTypes() {
  1276. }
  1277. if (csv && options.beforeParse) {
  1278. csv = options.beforeParse.call(this, csv);
  1279. }
  1280. if (csv) {
  1281. lines = csv
  1282. .replace(/\r\n/g, '\n') // Unix
  1283. .replace(/\r/g, '\n') // Mac
  1284. .split(options.lineDelimiter || '\n');
  1285. if (!startRow || startRow < 0) {
  1286. startRow = 0;
  1287. }
  1288. if (!endRow || endRow >= lines.length) {
  1289. endRow = lines.length - 1;
  1290. }
  1291. if (options.itemDelimiter) {
  1292. itemDelimiter = options.itemDelimiter;
  1293. }
  1294. else {
  1295. itemDelimiter = null;
  1296. itemDelimiter = guessDelimiter(lines);
  1297. }
  1298. var offset = 0;
  1299. for (rowIt = startRow; rowIt <= endRow; rowIt++) {
  1300. if (lines[rowIt][0] === '#') {
  1301. offset++;
  1302. }
  1303. else {
  1304. parseRow(lines[rowIt], rowIt - startRow - offset);
  1305. }
  1306. }
  1307. // //Make sure that there's header columns for everything
  1308. // columns.forEach(function (col) {
  1309. // });
  1310. deduceAxisTypes();
  1311. if ((!options.columnTypes || options.columnTypes.length === 0) &&
  1312. dataTypes.length &&
  1313. dataTypes[0].length &&
  1314. dataTypes[0][1] === 'date' &&
  1315. !options.dateFormat) {
  1316. options.dateFormat = deduceDateFormat(columns[0]);
  1317. }
  1318. // lines.forEach(function (line, rowNo) {
  1319. // var trimmed = self.trim(line),
  1320. // isComment = trimmed.indexOf('#') === 0,
  1321. // isBlank = trimmed === '',
  1322. // items;
  1323. // if (
  1324. // rowNo >= startRow &&
  1325. // rowNo <= endRow &&
  1326. // !isComment && !isBlank
  1327. // ) {
  1328. // items = line.split(itemDelimiter);
  1329. // items.forEach(function (item, colNo) {
  1330. // if (colNo >= startColumn && colNo <= endColumn) {
  1331. // if (!columns[colNo - startColumn]) {
  1332. // columns[colNo - startColumn] = [];
  1333. // }
  1334. // columns[colNo - startColumn][activeRowNo] = item;
  1335. // }
  1336. // });
  1337. // activeRowNo += 1;
  1338. // }
  1339. // });
  1340. //
  1341. this.dataFound();
  1342. }
  1343. return columns;
  1344. };
  1345. /**
  1346. * Parse a HTML table
  1347. *
  1348. * @function Highcharts.Data#parseTable
  1349. *
  1350. * @return {Array<Array<Highcharts.DataValueType>>}
  1351. */
  1352. Data.prototype.parseTable = function () {
  1353. var options = this.options,
  1354. table = options.table,
  1355. columns = this.columns || [],
  1356. startRow = options.startRow || 0,
  1357. endRow = options.endRow || Number.MAX_VALUE,
  1358. startColumn = options.startColumn || 0,
  1359. endColumn = options.endColumn || Number.MAX_VALUE;
  1360. if (table) {
  1361. if (typeof table === 'string') {
  1362. table = doc.getElementById(table);
  1363. }
  1364. [].forEach.call(table.getElementsByTagName('tr'), function (tr, rowNo) {
  1365. if (rowNo >= startRow && rowNo <= endRow) {
  1366. [].forEach.call(tr.children, function (item, colNo) {
  1367. var row = columns[colNo - startColumn];
  1368. var i = 1;
  1369. if ((item.tagName === 'TD' ||
  1370. item.tagName === 'TH') &&
  1371. colNo >= startColumn &&
  1372. colNo <= endColumn) {
  1373. if (!columns[colNo - startColumn]) {
  1374. columns[colNo - startColumn] = [];
  1375. }
  1376. columns[colNo - startColumn][rowNo - startRow] = item.innerHTML;
  1377. // Loop over all previous indices and make sure
  1378. // they are nulls, not undefined.
  1379. while (rowNo - startRow >= i &&
  1380. row[rowNo - startRow - i] === void 0) {
  1381. row[rowNo - startRow - i] = null;
  1382. i++;
  1383. }
  1384. }
  1385. });
  1386. }
  1387. });
  1388. this.dataFound(); // continue
  1389. }
  1390. return columns;
  1391. };
  1392. /**
  1393. * Fetch or refetch live data
  1394. *
  1395. * @function Highcharts.Data#fetchLiveData
  1396. *
  1397. * @return {boolean}
  1398. * The URLs that were tried can be found in the options
  1399. */
  1400. Data.prototype.fetchLiveData = function () {
  1401. var data = this,
  1402. chart = this.chart,
  1403. options = this.options,
  1404. maxRetries = 3,
  1405. currentRetries = 0,
  1406. pollingEnabled = options.enablePolling,
  1407. updateIntervalMs = (options.dataRefreshRate || 2) * 1000,
  1408. originalOptions = merge(options);
  1409. if (!this.hasURLOption(options)) {
  1410. return false;
  1411. }
  1412. // Do not allow polling more than once a second
  1413. if (updateIntervalMs < 1000) {
  1414. updateIntervalMs = 1000;
  1415. }
  1416. delete options.csvURL;
  1417. delete options.rowsURL;
  1418. delete options.columnsURL;
  1419. /**
  1420. * @private
  1421. */
  1422. function performFetch(initialFetch) {
  1423. /**
  1424. * Helper function for doing the data fetch + polling.
  1425. * @private
  1426. */
  1427. function request(url, done, tp) {
  1428. if (!url || url.indexOf('http') !== 0) {
  1429. if (url && options.error) {
  1430. options.error('Invalid URL');
  1431. }
  1432. return false;
  1433. }
  1434. if (initialFetch) {
  1435. clearTimeout(data.liveDataTimeout);
  1436. chart.liveDataURL = url;
  1437. }
  1438. /**
  1439. * @private
  1440. */
  1441. function poll() {
  1442. // Poll
  1443. if (pollingEnabled && chart.liveDataURL === url) {
  1444. // We need to stop doing this if the URL has changed
  1445. data.liveDataTimeout =
  1446. setTimeout(performFetch, updateIntervalMs);
  1447. }
  1448. }
  1449. ajax({
  1450. url: url,
  1451. dataType: tp || 'json',
  1452. success: function (res) {
  1453. if (chart && chart.series) {
  1454. done(res);
  1455. }
  1456. poll();
  1457. },
  1458. error: function (xhr, text) {
  1459. if (++currentRetries < maxRetries) {
  1460. poll();
  1461. }
  1462. return options.error && options.error(text, xhr);
  1463. }
  1464. });
  1465. return true;
  1466. }
  1467. if (!request(originalOptions.csvURL, function (res) {
  1468. chart.update({
  1469. data: {
  1470. csv: res
  1471. }
  1472. });
  1473. }, 'text')) {
  1474. if (!request(originalOptions.rowsURL, function (res) {
  1475. chart.update({
  1476. data: {
  1477. rows: res
  1478. }
  1479. });
  1480. })) {
  1481. request(originalOptions.columnsURL, function (res) {
  1482. chart.update({
  1483. data: {
  1484. columns: res
  1485. }
  1486. });
  1487. });
  1488. }
  1489. }
  1490. }
  1491. performFetch(true);
  1492. return this.hasURLOption(options);
  1493. };
  1494. /**
  1495. * Parse a Google spreadsheet.
  1496. *
  1497. * @function Highcharts.Data#parseGoogleSpreadsheet
  1498. *
  1499. * @return {boolean}
  1500. * Always returns false, because it is an intermediate fetch.
  1501. */
  1502. Data.prototype.parseGoogleSpreadsheet = function () {
  1503. var data = this,
  1504. options = this.options,
  1505. googleSpreadsheetKey = options.googleSpreadsheetKey,
  1506. chart = this.chart,
  1507. // use sheet 1 as the default rather than od6
  1508. // as the latter sometimes cause issues (it looks like it can
  1509. // be renamed in some cases, ref. a fogbugz case).
  1510. worksheet = options.googleSpreadsheetWorksheet || 1,
  1511. startRow = options.startRow || 0,
  1512. endRow = options.endRow || Number.MAX_VALUE,
  1513. startColumn = options.startColumn || 0,
  1514. endColumn = options.endColumn || Number.MAX_VALUE,
  1515. refreshRate = (options.dataRefreshRate || 2) * 1000;
  1516. if (refreshRate < 4000) {
  1517. refreshRate = 4000;
  1518. }
  1519. /**
  1520. * Fetch the actual spreadsheet using XMLHttpRequest.
  1521. * @private
  1522. */
  1523. function fetchSheet(fn) {
  1524. var url = [
  1525. 'https://spreadsheets.google.com/feeds/cells',
  1526. googleSpreadsheetKey,
  1527. worksheet,
  1528. 'public/values?alt=json'
  1529. ].join('/');
  1530. ajax({
  1531. url: url,
  1532. dataType: 'json',
  1533. success: function (json) {
  1534. fn(json);
  1535. if (options.enablePolling) {
  1536. setTimeout(function () {
  1537. fetchSheet(fn);
  1538. }, (options.dataRefreshRate || 2) * 1000);
  1539. }
  1540. },
  1541. error: function (xhr, text) {
  1542. return options.error && options.error(text, xhr);
  1543. }
  1544. });
  1545. }
  1546. if (googleSpreadsheetKey) {
  1547. delete options.googleSpreadsheetKey;
  1548. fetchSheet(function (json) {
  1549. // Prepare the data from the spreadsheat
  1550. var columns = [],
  1551. cells = json.feed.entry,
  1552. cell,
  1553. cellCount = (cells || []).length,
  1554. colCount = 0,
  1555. rowCount = 0,
  1556. val,
  1557. gr,
  1558. gc,
  1559. cellInner,
  1560. i;
  1561. if (!cells || cells.length === 0) {
  1562. return false;
  1563. }
  1564. // First, find the total number of columns and rows that
  1565. // are actually filled with data
  1566. for (i = 0; i < cellCount; i++) {
  1567. cell = cells[i];
  1568. colCount = Math.max(colCount, cell.gs$cell.col);
  1569. rowCount = Math.max(rowCount, cell.gs$cell.row);
  1570. }
  1571. // Set up arrays containing the column data
  1572. for (i = 0; i < colCount; i++) {
  1573. if (i >= startColumn && i <= endColumn) {
  1574. // Create new columns with the length of either
  1575. // end-start or rowCount
  1576. columns[i - startColumn] = [];
  1577. }
  1578. }
  1579. // Loop over the cells and assign the value to the right
  1580. // place in the column arrays
  1581. for (i = 0; i < cellCount; i++) {
  1582. cell = cells[i];
  1583. gr = cell.gs$cell.row - 1; // rows start at 1
  1584. gc = cell.gs$cell.col - 1; // columns start at 1
  1585. // If both row and col falls inside start and end set the
  1586. // transposed cell value in the newly created columns
  1587. if (gc >= startColumn && gc <= endColumn &&
  1588. gr >= startRow && gr <= endRow) {
  1589. cellInner = cell.gs$cell || cell.content;
  1590. val = null;
  1591. if (cellInner.numericValue) {
  1592. if (cellInner.$t.indexOf('/') >= 0 ||
  1593. cellInner.$t.indexOf('-') >= 0) {
  1594. // This is a date - for future reference.
  1595. val = cellInner.$t;
  1596. }
  1597. else if (cellInner.$t.indexOf('%') > 0) {
  1598. // Percentage
  1599. val = parseFloat(cellInner.numericValue) * 100;
  1600. }
  1601. else {
  1602. val = parseFloat(cellInner.numericValue);
  1603. }
  1604. }
  1605. else if (cellInner.$t && cellInner.$t.length) {
  1606. val = cellInner.$t;
  1607. }
  1608. columns[gc - startColumn][gr - startRow] = val;
  1609. }
  1610. }
  1611. // Insert null for empty spreadsheet cells (#5298)
  1612. columns.forEach(function (column) {
  1613. for (i = 0; i < column.length; i++) {
  1614. if (typeof column[i] === 'undefined') {
  1615. column[i] = null;
  1616. }
  1617. }
  1618. });
  1619. if (chart && chart.series) {
  1620. chart.update({
  1621. data: {
  1622. columns: columns
  1623. }
  1624. });
  1625. }
  1626. else { // #8245
  1627. data.columns = columns;
  1628. data.dataFound();
  1629. }
  1630. });
  1631. }
  1632. // This is an intermediate fetch, so always return false.
  1633. return false;
  1634. };
  1635. /**
  1636. * Trim a string from whitespaces.
  1637. *
  1638. * @function Highcharts.Data#trim
  1639. *
  1640. * @param {string} str
  1641. * String to trim
  1642. *
  1643. * @param {boolean} [inside=false]
  1644. * Remove all spaces between numbers.
  1645. *
  1646. * @return {string}
  1647. * Trimed string
  1648. */
  1649. Data.prototype.trim = function (str, inside) {
  1650. if (typeof str === 'string') {
  1651. str = str.replace(/^\s+|\s+$/g, '');
  1652. // Clear white space insdie the string, like thousands separators
  1653. if (inside && /^[0-9\s]+$/.test(str)) {
  1654. str = str.replace(/\s/g, '');
  1655. }
  1656. if (this.decimalRegex) {
  1657. str = str.replace(this.decimalRegex, '$1.$2');
  1658. }
  1659. }
  1660. return str;
  1661. };
  1662. /**
  1663. * Parse numeric cells in to number types and date types in to true dates.
  1664. *
  1665. * @function Highcharts.Data#parseTypes
  1666. */
  1667. Data.prototype.parseTypes = function () {
  1668. var columns = this.columns,
  1669. col = columns.length;
  1670. while (col--) {
  1671. this.parseColumn(columns[col], col);
  1672. }
  1673. };
  1674. /**
  1675. * Parse a single column. Set properties like .isDatetime and .isNumeric.
  1676. *
  1677. * @function Highcharts.Data#parseColumn
  1678. *
  1679. * @param {Array<Highcharts.DataValueType>} column
  1680. * Column to parse
  1681. *
  1682. * @param {number} col
  1683. * Column index
  1684. */
  1685. Data.prototype.parseColumn = function (column, col) {
  1686. var rawColumns = this.rawColumns,
  1687. columns = this.columns,
  1688. row = column.length,
  1689. val,
  1690. floatVal,
  1691. trimVal,
  1692. trimInsideVal,
  1693. firstRowAsNames = this.firstRowAsNames,
  1694. isXColumn = this.valueCount.xColumns.indexOf(col) !== -1,
  1695. dateVal,
  1696. backup = [],
  1697. diff,
  1698. chartOptions = this.chartOptions,
  1699. descending,
  1700. columnTypes = this.options.columnTypes || [],
  1701. columnType = columnTypes[col],
  1702. forceCategory = isXColumn && ((chartOptions &&
  1703. chartOptions.xAxis &&
  1704. splat(chartOptions.xAxis)[0].type === 'category') || columnType === 'string');
  1705. if (!rawColumns[col]) {
  1706. rawColumns[col] = [];
  1707. }
  1708. while (row--) {
  1709. val = backup[row] || column[row];
  1710. trimVal = this.trim(val);
  1711. trimInsideVal = this.trim(val, true);
  1712. floatVal = parseFloat(trimInsideVal);
  1713. // Set it the first time
  1714. if (typeof rawColumns[col][row] === 'undefined') {
  1715. rawColumns[col][row] = trimVal;
  1716. }
  1717. // Disable number or date parsing by setting the X axis type to
  1718. // category
  1719. if (forceCategory || (row === 0 && firstRowAsNames)) {
  1720. column[row] = '' + trimVal;
  1721. }
  1722. else if (+trimInsideVal === floatVal) { // is numeric
  1723. column[row] = floatVal;
  1724. // If the number is greater than milliseconds in a year, assume
  1725. // datetime
  1726. if (floatVal > 365 * 24 * 3600 * 1000 &&
  1727. columnType !== 'float') {
  1728. column.isDatetime = true;
  1729. }
  1730. else {
  1731. column.isNumeric = true;
  1732. }
  1733. if (typeof column[row + 1] !== 'undefined') {
  1734. descending = floatVal > column[row + 1];
  1735. }
  1736. // String, continue to determine if it is a date string or really a
  1737. // string
  1738. }
  1739. else {
  1740. if (trimVal && trimVal.length) {
  1741. dateVal = this.parseDate(val);
  1742. }
  1743. // Only allow parsing of dates if this column is an x-column
  1744. if (isXColumn && isNumber(dateVal) && columnType !== 'float') {
  1745. backup[row] = val;
  1746. column[row] = dateVal;
  1747. column.isDatetime = true;
  1748. // Check if the dates are uniformly descending or ascending.
  1749. // If they are not, chances are that they are a different
  1750. // time format, so check for alternative.
  1751. if (typeof column[row + 1] !== 'undefined') {
  1752. diff = dateVal > column[row + 1];
  1753. if (diff !== descending &&
  1754. typeof descending !== 'undefined') {
  1755. if (this.alternativeFormat) {
  1756. this.dateFormat = this.alternativeFormat;
  1757. row = column.length;
  1758. this.alternativeFormat =
  1759. this.dateFormats[this.dateFormat]
  1760. .alternative;
  1761. }
  1762. else {
  1763. column.unsorted = true;
  1764. }
  1765. }
  1766. descending = diff;
  1767. }
  1768. }
  1769. else { // string
  1770. column[row] = trimVal === '' ? null : trimVal;
  1771. if (row !== 0 &&
  1772. (column.isDatetime ||
  1773. column.isNumeric)) {
  1774. column.mixed = true;
  1775. }
  1776. }
  1777. }
  1778. }
  1779. // If strings are intermixed with numbers or dates in a parsed column,
  1780. // it is an indication that parsing went wrong or the data was not
  1781. // intended to display as numbers or dates and parsing is too
  1782. // aggressive. Fall back to categories. Demonstrated in the
  1783. // highcharts/demo/column-drilldown sample.
  1784. if (isXColumn && column.mixed) {
  1785. columns[col] = rawColumns[col];
  1786. }
  1787. // If the 0 column is date or number and descending, reverse all
  1788. // columns.
  1789. if (isXColumn && descending && this.options.sort) {
  1790. for (col = 0; col < columns.length; col++) {
  1791. columns[col].reverse();
  1792. if (firstRowAsNames) {
  1793. columns[col].unshift(columns[col].pop());
  1794. }
  1795. }
  1796. }
  1797. };
  1798. /**
  1799. * Parse a date and return it as a number. Overridable through
  1800. * `options.parseDate`.
  1801. *
  1802. * @function Highcharts.Data#parseDate
  1803. *
  1804. * @param {string} val
  1805. *
  1806. * @return {number}
  1807. */
  1808. Data.prototype.parseDate = function (val) {
  1809. var parseDate = this.options.parseDate,
  1810. ret,
  1811. key,
  1812. format,
  1813. dateFormat = this.options.dateFormat || this.dateFormat,
  1814. match;
  1815. if (parseDate) {
  1816. ret = parseDate(val);
  1817. }
  1818. else if (typeof val === 'string') {
  1819. // Auto-detect the date format the first time
  1820. if (!dateFormat) {
  1821. for (key in this.dateFormats) { // eslint-disable-line guard-for-in
  1822. format = this.dateFormats[key];
  1823. match = val.match(format.regex);
  1824. if (match) {
  1825. this.dateFormat = dateFormat = key;
  1826. this.alternativeFormat = format.alternative;
  1827. ret = format.parser(match);
  1828. break;
  1829. }
  1830. }
  1831. // Next time, use the one previously found
  1832. }
  1833. else {
  1834. format = this.dateFormats[dateFormat];
  1835. if (!format) {
  1836. // The selected format is invalid
  1837. format = this.dateFormats['YYYY/mm/dd'];
  1838. }
  1839. match = val.match(format.regex);
  1840. if (match) {
  1841. ret = format.parser(match);
  1842. }
  1843. }
  1844. // Fall back to Date.parse
  1845. if (!match) {
  1846. match = Date.parse(val);
  1847. // External tools like Date.js and MooTools extend Date object
  1848. // and returns a date.
  1849. if (typeof match === 'object' &&
  1850. match !== null &&
  1851. match.getTime) {
  1852. ret = (match.getTime() -
  1853. match.getTimezoneOffset() *
  1854. 60000);
  1855. // Timestamp
  1856. }
  1857. else if (isNumber(match)) {
  1858. ret = match - (new Date(match)).getTimezoneOffset() * 60000;
  1859. }
  1860. }
  1861. }
  1862. return ret;
  1863. };
  1864. /**
  1865. * Reorganize rows into columns.
  1866. *
  1867. * @function Highcharts.Data#rowsToColumns
  1868. *
  1869. * @param {Array<Array<Highcharts.DataValueType>>} rows
  1870. *
  1871. * @return {Array<Array<Highcharts.DataValueType>>|undefined}
  1872. */
  1873. Data.prototype.rowsToColumns = function (rows) {
  1874. var row,
  1875. rowsLength,
  1876. col,
  1877. colsLength,
  1878. columns;
  1879. if (rows) {
  1880. columns = [];
  1881. rowsLength = rows.length;
  1882. for (row = 0; row < rowsLength; row++) {
  1883. colsLength = rows[row].length;
  1884. for (col = 0; col < colsLength; col++) {
  1885. if (!columns[col]) {
  1886. columns[col] = [];
  1887. }
  1888. columns[col][row] = rows[row][col];
  1889. }
  1890. }
  1891. }
  1892. return columns;
  1893. };
  1894. /**
  1895. * Get the parsed data in a form that we can apply directly to the
  1896. * `series.data` config. Array positions can be mapped using the
  1897. * `series.keys` option.
  1898. *
  1899. * @example
  1900. * const data = Highcharts.data({
  1901. * csv: document.getElementById('data').innerHTML
  1902. * }).getData();
  1903. *
  1904. * @function Highcharts.Data#getData
  1905. *
  1906. * @return {Array<Array<(number|string)>>|undefined} Data rows
  1907. */
  1908. Data.prototype.getData = function () {
  1909. if (this.columns) {
  1910. return this.rowsToColumns(this.columns).slice(1);
  1911. }
  1912. };
  1913. /**
  1914. * A hook for working directly on the parsed columns
  1915. *
  1916. * @function Highcharts.Data#parsed
  1917. *
  1918. * @return {boolean|undefined}
  1919. */
  1920. Data.prototype.parsed = function () {
  1921. if (this.options.parsed) {
  1922. return this.options.parsed.call(this, this.columns);
  1923. }
  1924. };
  1925. /**
  1926. * @private
  1927. * @function Highcharts.Data#getFreeIndexes
  1928. */
  1929. Data.prototype.getFreeIndexes = function (numberOfColumns, seriesBuilders) {
  1930. var s,
  1931. i,
  1932. freeIndexes = [],
  1933. freeIndexValues = [],
  1934. referencedIndexes;
  1935. // Add all columns as free
  1936. for (i = 0; i < numberOfColumns; i = i + 1) {
  1937. freeIndexes.push(true);
  1938. }
  1939. // Loop all defined builders and remove their referenced columns
  1940. for (s = 0; s < seriesBuilders.length; s = s + 1) {
  1941. referencedIndexes = seriesBuilders[s].getReferencedColumnIndexes();
  1942. for (i = 0; i < referencedIndexes.length; i = i + 1) {
  1943. freeIndexes[referencedIndexes[i]] = false;
  1944. }
  1945. }
  1946. // Collect the values for the free indexes
  1947. for (i = 0; i < freeIndexes.length; i = i + 1) {
  1948. if (freeIndexes[i]) {
  1949. freeIndexValues.push(i);
  1950. }
  1951. }
  1952. return freeIndexValues;
  1953. };
  1954. /**
  1955. * If a complete callback function is provided in the options, interpret the
  1956. * columns into a Highcharts options object.
  1957. *
  1958. * @function Highcharts.Data#complete
  1959. */
  1960. Data.prototype.complete = function () {
  1961. var columns = this.columns,
  1962. xColumns = [],
  1963. type,
  1964. options = this.options,
  1965. series,
  1966. data,
  1967. i,
  1968. j,
  1969. r,
  1970. seriesIndex,
  1971. chartOptions,
  1972. allSeriesBuilders = [],
  1973. builder,
  1974. freeIndexes,
  1975. typeCol,
  1976. index;
  1977. xColumns.length = columns.length;
  1978. if (options.complete || options.afterComplete) {
  1979. // Get the names and shift the top row
  1980. if (this.firstRowAsNames) {
  1981. for (i = 0; i < columns.length; i++) {
  1982. columns[i].name = columns[i].shift();
  1983. }
  1984. }
  1985. // Use the next columns for series
  1986. series = [];
  1987. freeIndexes = this.getFreeIndexes(columns.length, this.valueCount.seriesBuilders);
  1988. // Populate defined series
  1989. for (seriesIndex = 0; seriesIndex < this.valueCount.seriesBuilders.length; seriesIndex++) {
  1990. builder = this.valueCount.seriesBuilders[seriesIndex];
  1991. // If the builder can be populated with remaining columns, then
  1992. // add it to allBuilders
  1993. if (builder.populateColumns(freeIndexes)) {
  1994. allSeriesBuilders.push(builder);
  1995. }
  1996. }
  1997. // Populate dynamic series
  1998. while (freeIndexes.length > 0) {
  1999. builder = new SeriesBuilder();
  2000. builder.addColumnReader(0, 'x');
  2001. // Mark index as used (not free)
  2002. index = freeIndexes.indexOf(0);
  2003. if (index !== -1) {
  2004. freeIndexes.splice(index, 1);
  2005. }
  2006. for (i = 0; i < this.valueCount.global; i++) {
  2007. // Create and add a column reader for the next free column
  2008. // index
  2009. builder.addColumnReader(void 0, this.valueCount.globalPointArrayMap[i]);
  2010. }
  2011. // If the builder can be populated with remaining columns, then
  2012. // add it to allBuilders
  2013. if (builder.populateColumns(freeIndexes)) {
  2014. allSeriesBuilders.push(builder);
  2015. }
  2016. }
  2017. // Get the data-type from the first series x column
  2018. if (allSeriesBuilders.length > 0 &&
  2019. allSeriesBuilders[0].readers.length > 0) {
  2020. typeCol = columns[allSeriesBuilders[0].readers[0].columnIndex];
  2021. if (typeof typeCol !== 'undefined') {
  2022. if (typeCol.isDatetime) {
  2023. type = 'datetime';
  2024. }
  2025. else if (!typeCol.isNumeric) {
  2026. type = 'category';
  2027. }
  2028. }
  2029. }
  2030. // Axis type is category, then the "x" column should be called
  2031. // "name"
  2032. if (type === 'category') {
  2033. for (seriesIndex = 0; seriesIndex < allSeriesBuilders.length; seriesIndex++) {
  2034. builder = allSeriesBuilders[seriesIndex];
  2035. for (r = 0; r < builder.readers.length; r++) {
  2036. if (builder.readers[r].configName === 'x') {
  2037. builder.readers[r].configName = 'name';
  2038. }
  2039. }
  2040. }
  2041. }
  2042. // Read data for all builders
  2043. for (seriesIndex = 0; seriesIndex < allSeriesBuilders.length; seriesIndex++) {
  2044. builder = allSeriesBuilders[seriesIndex];
  2045. // Iterate down the cells of each column and add data to the
  2046. // series
  2047. data = [];
  2048. for (j = 0; j < columns[0].length; j++) {
  2049. data[j] = builder.read(columns, j);
  2050. }
  2051. // Add the series
  2052. series[seriesIndex] = {
  2053. data: data
  2054. };
  2055. if (builder.name) {
  2056. series[seriesIndex].name = builder.name;
  2057. }
  2058. if (type === 'category') {
  2059. series[seriesIndex].turboThreshold = 0;
  2060. }
  2061. }
  2062. // Do the callback
  2063. chartOptions = {
  2064. series: series
  2065. };
  2066. if (type) {
  2067. chartOptions.xAxis = {
  2068. type: type
  2069. };
  2070. if (type === 'category') {
  2071. chartOptions.xAxis.uniqueNames = false;
  2072. }
  2073. }
  2074. if (options.complete) {
  2075. options.complete(chartOptions);
  2076. }
  2077. // The afterComplete hook is used internally to avoid conflict with
  2078. // the externally available complete option.
  2079. if (options.afterComplete) {
  2080. options.afterComplete(chartOptions);
  2081. }
  2082. }
  2083. };
  2084. /**
  2085. * Updates the chart with new data options.
  2086. *
  2087. * @function Highcharts.Data#update
  2088. *
  2089. * @param {Highcharts.DataOptions} options
  2090. *
  2091. * @param {boolean} [redraw=true]
  2092. */
  2093. Data.prototype.update = function (options, redraw) {
  2094. var chart = this.chart;
  2095. if (options) {
  2096. // Set the complete handler
  2097. options.afterComplete = function (dataOptions) {
  2098. // Avoid setting axis options unless the type changes. Running
  2099. // Axis.update will cause the whole structure to be destroyed
  2100. // and rebuilt, and animation is lost.
  2101. if (dataOptions) {
  2102. if (dataOptions.xAxis &&
  2103. chart.xAxis[0] &&
  2104. dataOptions.xAxis.type ===
  2105. chart.xAxis[0].options.type) {
  2106. delete dataOptions.xAxis;
  2107. }
  2108. // @todo looks not right:
  2109. chart.update(dataOptions, redraw, true);
  2110. }
  2111. };
  2112. // Apply it
  2113. merge(true, chart.options.data, options);
  2114. this.init(chart.options.data);
  2115. }
  2116. };
  2117. return Data;
  2118. }());
  2119. // Register the Data prototype and data function on Highcharts
  2120. // Highcharts.Data = Data as any;
  2121. /**
  2122. * Creates a data object to parse data for a chart.
  2123. *
  2124. * @function Highcharts.data
  2125. *
  2126. * @param {Highcharts.DataOptions} dataOptions
  2127. *
  2128. * @param {Highcharts.Options} [chartOptions]
  2129. *
  2130. * @param {Highcharts.Chart} [chart]
  2131. *
  2132. * @return {Highcharts.Data}
  2133. */
  2134. H.data = function (dataOptions, chartOptions, chart) {
  2135. return new H.Data(dataOptions, chartOptions, chart);
  2136. };
  2137. // Extend Chart.init so that the Chart constructor accepts a new configuration
  2138. // option group, data.
  2139. addEvent(Chart, 'init', function (e) {
  2140. var chart = this, // eslint-disable-line no-invalid-this
  2141. userOptions = (e.args[0] || {}),
  2142. callback = e.args[1];
  2143. if (userOptions && userOptions.data && !chart.hasDataDef) {
  2144. chart.hasDataDef = true;
  2145. /**
  2146. * The data parser for this chart.
  2147. *
  2148. * @name Highcharts.Chart#data
  2149. * @type {Highcharts.Data|undefined}
  2150. */
  2151. chart.data = new H.Data(extend(userOptions.data, {
  2152. afterComplete: function (dataOptions) {
  2153. var i,
  2154. series;
  2155. // Merge series configs
  2156. if (Object.hasOwnProperty.call(userOptions, 'series')) {
  2157. if (typeof userOptions.series === 'object') {
  2158. i = Math.max(userOptions.series.length, dataOptions && dataOptions.series ?
  2159. dataOptions.series.length :
  2160. 0);
  2161. while (i--) {
  2162. series = userOptions.series[i] || {};
  2163. userOptions.series[i] = merge(series, dataOptions && dataOptions.series ?
  2164. dataOptions.series[i] :
  2165. {});
  2166. }
  2167. }
  2168. else { // Allow merging in dataOptions.series (#2856)
  2169. delete userOptions.series;
  2170. }
  2171. }
  2172. // Do the merge
  2173. userOptions = merge(dataOptions, userOptions);
  2174. // Run chart.init again
  2175. chart.init(userOptions, callback);
  2176. }
  2177. }), userOptions, chart);
  2178. e.preventDefault();
  2179. }
  2180. });
  2181. /**
  2182. * Creates a new SeriesBuilder. A SeriesBuilder consists of a number
  2183. * of ColumnReaders that reads columns and give them a name.
  2184. * Ex: A series builder can be constructed to read column 3 as 'x' and
  2185. * column 7 and 8 as 'y1' and 'y2'.
  2186. * The output would then be points/rows of the form {x: 11, y1: 22, y2: 33}
  2187. *
  2188. * The name of the builder is taken from the second column. In the above
  2189. * example it would be the column with index 7.
  2190. *
  2191. * @private
  2192. * @class
  2193. * @name SeriesBuilder
  2194. */
  2195. var SeriesBuilder = /** @class */ (function () {
  2196. function SeriesBuilder() {
  2197. /* eslint-disable no-invalid-this */
  2198. this.readers = [];
  2199. this.pointIsArray = true;
  2200. /* eslint-enable no-invalid-this */
  2201. this.name = void 0;
  2202. }
  2203. /**
  2204. * Populates readers with column indexes. A reader can be added without
  2205. * a specific index and for those readers the index is taken sequentially
  2206. * from the free columns (this is handled by the ColumnCursor instance).
  2207. *
  2208. * @function SeriesBuilder#populateColumns
  2209. *
  2210. * @param {Array<number>} freeIndexes
  2211. *
  2212. * @returns {boolean}
  2213. */
  2214. SeriesBuilder.prototype.populateColumns = function (freeIndexes) {
  2215. var builder = this,
  2216. enoughColumns = true;
  2217. // Loop each reader and give it an index if its missing.
  2218. // The freeIndexes.shift() will return undefined if there
  2219. // are no more columns.
  2220. builder.readers.forEach(function (reader) {
  2221. if (typeof reader.columnIndex === 'undefined') {
  2222. reader.columnIndex = freeIndexes.shift();
  2223. }
  2224. });
  2225. // Now, all readers should have columns mapped. If not
  2226. // then return false to signal that this series should
  2227. // not be added.
  2228. builder.readers.forEach(function (reader) {
  2229. if (typeof reader.columnIndex === 'undefined') {
  2230. enoughColumns = false;
  2231. }
  2232. });
  2233. return enoughColumns;
  2234. };
  2235. /**
  2236. * Reads a row from the dataset and returns a point or array depending
  2237. * on the names of the readers.
  2238. *
  2239. * @function SeriesBuilder#read<T>
  2240. *
  2241. * @param {Array<Array<T>>} columns
  2242. *
  2243. * @param {number} rowIndex
  2244. *
  2245. * @returns {Array<T>|Highcharts.Dictionary<T>}
  2246. */
  2247. SeriesBuilder.prototype.read = function (columns, rowIndex) {
  2248. var builder = this,
  2249. pointIsArray = builder.pointIsArray,
  2250. point = pointIsArray ? [] : {},
  2251. columnIndexes;
  2252. // Loop each reader and ask it to read its value.
  2253. // Then, build an array or point based on the readers names.
  2254. builder.readers.forEach(function (reader) {
  2255. var value = columns[reader.columnIndex][rowIndex];
  2256. if (pointIsArray) {
  2257. point.push(value);
  2258. }
  2259. else {
  2260. if (reader.configName.indexOf('.') > 0) {
  2261. // Handle nested property names
  2262. Point.prototype.setNestedProperty(point, value, reader.configName);
  2263. }
  2264. else {
  2265. point[reader.configName] = value;
  2266. }
  2267. }
  2268. });
  2269. // The name comes from the first column (excluding the x column)
  2270. if (typeof this.name === 'undefined' && builder.readers.length >= 2) {
  2271. columnIndexes = builder.getReferencedColumnIndexes();
  2272. if (columnIndexes.length >= 2) {
  2273. // remove the first one (x col)
  2274. columnIndexes.shift();
  2275. // Sort the remaining
  2276. columnIndexes.sort(function (a, b) {
  2277. return a - b;
  2278. });
  2279. // Now use the lowest index as name column
  2280. this.name = columns[columnIndexes.shift()].name;
  2281. }
  2282. }
  2283. return point;
  2284. };
  2285. /**
  2286. * Creates and adds ColumnReader from the given columnIndex and configName.
  2287. * ColumnIndex can be undefined and in that case the reader will be given
  2288. * an index when columns are populated.
  2289. *
  2290. * @function SeriesBuilder#addColumnReader
  2291. *
  2292. * @param {number} columnIndex
  2293. *
  2294. * @param {string} configName
  2295. */
  2296. SeriesBuilder.prototype.addColumnReader = function (columnIndex, configName) {
  2297. this.readers.push({
  2298. columnIndex: columnIndex,
  2299. configName: configName
  2300. });
  2301. if (!(configName === 'x' ||
  2302. configName === 'y' ||
  2303. typeof configName === 'undefined')) {
  2304. this.pointIsArray = false;
  2305. }
  2306. };
  2307. /**
  2308. * Returns an array of column indexes that the builder will use when
  2309. * reading data.
  2310. *
  2311. * @function SeriesBuilder#getReferencedColumnIndexes
  2312. *
  2313. * @returns {Array<number>}
  2314. */
  2315. SeriesBuilder.prototype.getReferencedColumnIndexes = function () {
  2316. var i,
  2317. referencedColumnIndexes = [],
  2318. columnReader;
  2319. for (i = 0; i < this.readers.length; i = i + 1) {
  2320. columnReader = this.readers[i];
  2321. if (typeof columnReader.columnIndex !== 'undefined') {
  2322. referencedColumnIndexes.push(columnReader.columnIndex);
  2323. }
  2324. }
  2325. return referencedColumnIndexes;
  2326. };
  2327. /**
  2328. * Returns true if the builder has a reader for the given configName.
  2329. *
  2330. * @function SeriesBuider#hasReader
  2331. *
  2332. * @param {string} configName
  2333. *
  2334. * @returns {boolean|undefined}
  2335. */
  2336. SeriesBuilder.prototype.hasReader = function (configName) {
  2337. var i,
  2338. columnReader;
  2339. for (i = 0; i < this.readers.length; i = i + 1) {
  2340. columnReader = this.readers[i];
  2341. if (columnReader.configName === configName) {
  2342. return true;
  2343. }
  2344. }
  2345. // Else return undefined
  2346. };
  2347. return SeriesBuilder;
  2348. }());
  2349. H.Data = Data;
  2350. return H.Data;
  2351. });
  2352. _registerModule(_modules, 'masters/modules/data.src.js', [], function () {
  2353. });
  2354. }));