Data.js 76 KB

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