data.src.js 98 KB

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