Data.js 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063
  1. /* *
  2. *
  3. * Data module
  4. *
  5. * (c) 2012-2020 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 BaseSeries from '../Core/Series/Series.js';
  16. import Chart from '../Core/Chart/Chart.js';
  17. import H from '../Core/Globals.js';
  18. var doc = H.doc;
  19. import Point from '../Core/Series/Point.js';
  20. import U from '../Core/Utilities.js';
  21. 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;
  22. var seriesTypes = BaseSeries.seriesTypes;
  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. function Data(dataOptions, chartOptions, chart) {
  476. this.chart = void 0;
  477. this.chartOptions = void 0;
  478. this.firstRowAsNames = void 0;
  479. this.rawColumns = void 0;
  480. this.options = void 0;
  481. /**
  482. * A collection of available date formats, extendable from the outside to
  483. * support custom date formats.
  484. *
  485. * @name Highcharts.Data#dateFormats
  486. * @type {Highcharts.Dictionary<Highcharts.DataDateFormatObject>}
  487. */
  488. this.dateFormats = {
  489. 'YYYY/mm/dd': {
  490. regex: /^([0-9]{4})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{1,2})$/,
  491. parser: function (match) {
  492. return (match ?
  493. Date.UTC(+match[1], match[2] - 1, +match[3]) :
  494. NaN);
  495. }
  496. },
  497. 'dd/mm/YYYY': {
  498. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{4})$/,
  499. parser: function (match) {
  500. return (match ?
  501. Date.UTC(+match[3], match[2] - 1, +match[1]) :
  502. NaN);
  503. },
  504. alternative: 'mm/dd/YYYY' // different format with the same regex
  505. },
  506. 'mm/dd/YYYY': {
  507. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{4})$/,
  508. parser: function (match) {
  509. return (match ?
  510. Date.UTC(+match[3], match[1] - 1, +match[2]) :
  511. NaN);
  512. }
  513. },
  514. 'dd/mm/YY': {
  515. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{2})$/,
  516. parser: function (match) {
  517. if (!match) {
  518. return NaN;
  519. }
  520. var year = +match[3], d = new Date();
  521. if (year > (d.getFullYear() - 2000)) {
  522. year += 1900;
  523. }
  524. else {
  525. year += 2000;
  526. }
  527. return Date.UTC(year, match[2] - 1, +match[1]);
  528. },
  529. alternative: 'mm/dd/YY' // different format with the same regex
  530. },
  531. 'mm/dd/YY': {
  532. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{2})$/,
  533. parser: function (match) {
  534. return (match ?
  535. Date.UTC(+match[3] + 2000, match[1] - 1, +match[2]) :
  536. NaN);
  537. }
  538. }
  539. };
  540. this.init(dataOptions, chartOptions, chart);
  541. }
  542. /**
  543. * Initialize the Data object with the given options
  544. *
  545. * @private
  546. * @function Highcharts.Data#init
  547. * @param {Highcharts.DataOptions} options
  548. * @param {Highcharts.Options} [chartOptions]
  549. * @param {Highcharts.Chart} [chart]
  550. */
  551. Data.prototype.init = function (options, chartOptions, chart) {
  552. var decimalPoint = options.decimalPoint, hasData;
  553. if (chartOptions) {
  554. this.chartOptions = chartOptions;
  555. }
  556. if (chart) {
  557. this.chart = chart;
  558. }
  559. if (decimalPoint !== '.' && decimalPoint !== ',') {
  560. decimalPoint = void 0;
  561. }
  562. this.options = options;
  563. this.columns = (options.columns ||
  564. this.rowsToColumns(options.rows) ||
  565. []);
  566. this.firstRowAsNames = pick(options.firstRowAsNames, this.firstRowAsNames, true);
  567. this.decimalRegex = (decimalPoint &&
  568. new RegExp('^(-?[0-9]+)' + decimalPoint + '([0-9]+)$'));
  569. // This is a two-dimensional array holding the raw, trimmed string
  570. // values with the same organisation as the columns array. It makes it
  571. // possible for example to revert from interpreted timestamps to
  572. // string-based categories.
  573. this.rawColumns = [];
  574. // No need to parse or interpret anything
  575. if (this.columns.length) {
  576. this.dataFound();
  577. hasData = true;
  578. }
  579. if (this.hasURLOption(options)) {
  580. clearTimeout(this.liveDataTimeout);
  581. hasData = false;
  582. }
  583. if (!hasData) {
  584. // Fetch live data
  585. hasData = this.fetchLiveData();
  586. }
  587. if (!hasData) {
  588. // Parse a CSV string if options.csv is given. The parseCSV function
  589. // returns a columns array, if it has no length, we have no data
  590. hasData = Boolean(this.parseCSV().length);
  591. }
  592. if (!hasData) {
  593. // Parse a HTML table if options.table is given
  594. hasData = Boolean(this.parseTable().length);
  595. }
  596. if (!hasData) {
  597. // Parse a Google Spreadsheet
  598. hasData = this.parseGoogleSpreadsheet();
  599. }
  600. if (!hasData && options.afterComplete) {
  601. options.afterComplete();
  602. }
  603. };
  604. Data.prototype.hasURLOption = function (options) {
  605. return Boolean(options &&
  606. (options.rowsURL || options.csvURL || options.columnsURL));
  607. };
  608. /**
  609. * Get the column distribution. For example, a line series takes a single
  610. * column for Y values. A range series takes two columns for low and high
  611. * values respectively, and an OHLC series takes four columns.
  612. *
  613. * @function Highcharts.Data#getColumnDistribution
  614. */
  615. Data.prototype.getColumnDistribution = function () {
  616. var chartOptions = this.chartOptions, options = this.options, xColumns = [], getValueCount = function (type) {
  617. return (seriesTypes[type || 'line'].prototype.pointArrayMap || [0]).length;
  618. }, getPointArrayMap = function (type) {
  619. return seriesTypes[type || 'line'].prototype.pointArrayMap;
  620. }, globalType = (chartOptions &&
  621. chartOptions.chart &&
  622. chartOptions.chart.type), individualCounts = [], seriesBuilders = [], seriesIndex = 0,
  623. // If no series mapping is defined, check if the series array is
  624. // defined with types.
  625. seriesMapping = ((options && options.seriesMapping) ||
  626. (chartOptions &&
  627. chartOptions.series &&
  628. chartOptions.series.map(function () {
  629. return { x: 0 };
  630. })) ||
  631. []), i;
  632. ((chartOptions && chartOptions.series) || []).forEach(function (series) {
  633. individualCounts.push(getValueCount(series.type || globalType));
  634. });
  635. // Collect the x-column indexes from seriesMapping
  636. seriesMapping.forEach(function (mapping) {
  637. xColumns.push(mapping.x || 0);
  638. });
  639. // If there are no defined series with x-columns, use the first column
  640. // as x column
  641. if (xColumns.length === 0) {
  642. xColumns.push(0);
  643. }
  644. // Loop all seriesMappings and constructs SeriesBuilders from
  645. // the mapping options.
  646. seriesMapping.forEach(function (mapping) {
  647. var builder = new SeriesBuilder(), numberOfValueColumnsNeeded = individualCounts[seriesIndex] ||
  648. getValueCount(globalType), seriesArr = (chartOptions && chartOptions.series) || [], series = seriesArr[seriesIndex] || {}, defaultPointArrayMap = getPointArrayMap(series.type || globalType), pointArrayMap = defaultPointArrayMap || ['y'];
  649. if (
  650. // User-defined x.mapping
  651. defined(mapping.x) ||
  652. // All non cartesian don't need 'x'
  653. series.isCartesian ||
  654. // Except pie series:
  655. !defaultPointArrayMap) {
  656. // Add an x reader from the x property or from an undefined
  657. // column if the property is not set. It will then be auto
  658. // populated later.
  659. builder.addColumnReader(mapping.x, 'x');
  660. }
  661. // Add all column mappings
  662. objectEach(mapping, function (val, name) {
  663. if (name !== 'x') {
  664. builder.addColumnReader(val, name);
  665. }
  666. });
  667. // Add missing columns
  668. for (i = 0; i < numberOfValueColumnsNeeded; i++) {
  669. if (!builder.hasReader(pointArrayMap[i])) {
  670. // Create and add a column reader for the next free column
  671. // index
  672. builder.addColumnReader(void 0, pointArrayMap[i]);
  673. }
  674. }
  675. seriesBuilders.push(builder);
  676. seriesIndex++;
  677. });
  678. var globalPointArrayMap = getPointArrayMap(globalType);
  679. if (typeof globalPointArrayMap === 'undefined') {
  680. globalPointArrayMap = ['y'];
  681. }
  682. this.valueCount = {
  683. global: getValueCount(globalType),
  684. xColumns: xColumns,
  685. individual: individualCounts,
  686. seriesBuilders: seriesBuilders,
  687. globalPointArrayMap: globalPointArrayMap
  688. };
  689. };
  690. /**
  691. * When the data is parsed into columns, either by CSV, table, GS or direct
  692. * input, continue with other operations.
  693. *
  694. * @private
  695. * @function Highcharts.Data#dataFound
  696. */
  697. Data.prototype.dataFound = function () {
  698. if (this.options.switchRowsAndColumns) {
  699. this.columns = this.rowsToColumns(this.columns);
  700. }
  701. // Interpret the info about series and columns
  702. this.getColumnDistribution();
  703. // Interpret the values into right types
  704. this.parseTypes();
  705. // Handle columns if a handleColumns callback is given
  706. if (this.parsed() !== false) {
  707. // Complete if a complete callback is given
  708. this.complete();
  709. }
  710. };
  711. /**
  712. * Parse a CSV input string
  713. *
  714. * @function Highcharts.Data#parseCSV
  715. *
  716. * @param {Highcharts.DataOptions} [inOptions]
  717. *
  718. * @return {Array<Array<Highcharts.DataValueType>>}
  719. */
  720. Data.prototype.parseCSV = function (inOptions) {
  721. var self = this, options = inOptions || this.options, csv = options.csv, columns, startRow = (typeof options.startRow !== 'undefined' && options.startRow ?
  722. options.startRow :
  723. 0), endRow = options.endRow || Number.MAX_VALUE, startColumn = (typeof options.startColumn !== 'undefined' &&
  724. options.startColumn) ? options.startColumn : 0, endColumn = options.endColumn || Number.MAX_VALUE, itemDelimiter, lines, rowIt = 0,
  725. // activeRowNo = 0,
  726. dataTypes = [],
  727. // We count potential delimiters in the prepass, and use the
  728. // result as the basis of half-intelligent guesses.
  729. potDelimiters = {
  730. ',': 0,
  731. ';': 0,
  732. '\t': 0
  733. };
  734. columns = this.columns = [];
  735. /*
  736. This implementation is quite verbose. It will be shortened once
  737. it's stable and passes all the test.
  738. It's also not written with speed in mind, instead everything is
  739. very seggregated, and there a several redundant loops.
  740. This is to make it easier to stabilize the code initially.
  741. We do a pre-pass on the first 4 rows to make some intelligent
  742. guesses on the set. Guessed delimiters are in this pass counted.
  743. Auto detecting delimiters
  744. - If we meet a quoted string, the next symbol afterwards
  745. (that's not \s, \t) is the delimiter
  746. - If we meet a date, the next symbol afterwards is the delimiter
  747. Date formats
  748. - If we meet a column with date formats, check all of them to
  749. see if one of the potential months crossing 12. If it does,
  750. we now know the format
  751. It would make things easier to guess the delimiter before
  752. doing the actual parsing.
  753. General rules:
  754. - Quoting is allowed, e.g: "Col 1",123,321
  755. - Quoting is optional, e.g.: Col1,123,321
  756. - Doubble quoting is escaping, e.g. "Col ""Hello world""",123
  757. - Spaces are considered part of the data: Col1 ,123
  758. - New line is always the row delimiter
  759. - Potential column delimiters are , ; \t
  760. - First row may optionally contain headers
  761. - The last row may or may not have a row delimiter
  762. - Comments are optionally supported, in which case the comment
  763. must start at the first column, and the rest of the line will
  764. be ignored
  765. */
  766. /**
  767. * Parse a single row.
  768. * @private
  769. */
  770. function parseRow(columnStr, rowNumber, noAdd, callbacks) {
  771. var i = 0, c = '', cl = '', cn = '', token = '', actualColumn = 0, column = 0;
  772. /**
  773. * @private
  774. */
  775. function read(j) {
  776. c = columnStr[j];
  777. cl = columnStr[j - 1];
  778. cn = columnStr[j + 1];
  779. }
  780. /**
  781. * @private
  782. */
  783. function pushType(type) {
  784. if (dataTypes.length < column + 1) {
  785. dataTypes.push([type]);
  786. }
  787. if (dataTypes[column][dataTypes[column].length - 1] !== type) {
  788. dataTypes[column].push(type);
  789. }
  790. }
  791. /**
  792. * @private
  793. */
  794. function push() {
  795. if (startColumn > actualColumn || actualColumn > endColumn) {
  796. // Skip this column, but increment the column count (#7272)
  797. ++actualColumn;
  798. token = '';
  799. return;
  800. }
  801. if (!isNaN(parseFloat(token)) && isFinite(token)) {
  802. token = parseFloat(token);
  803. pushType('number');
  804. }
  805. else if (!isNaN(Date.parse(token))) {
  806. token = token.replace(/\//g, '-');
  807. pushType('date');
  808. }
  809. else {
  810. pushType('string');
  811. }
  812. if (columns.length < column + 1) {
  813. columns.push([]);
  814. }
  815. if (!noAdd) {
  816. // Don't push - if there's a varrying amount of columns
  817. // for each row, pushing will skew everything down n slots
  818. columns[column][rowNumber] = token;
  819. }
  820. token = '';
  821. ++column;
  822. ++actualColumn;
  823. }
  824. if (!columnStr.trim().length) {
  825. return;
  826. }
  827. if (columnStr.trim()[0] === '#') {
  828. return;
  829. }
  830. for (; i < columnStr.length; i++) {
  831. read(i);
  832. // Quoted string
  833. if (c === '#') {
  834. // The rest of the row is a comment
  835. push();
  836. return;
  837. }
  838. if (c === '"') {
  839. read(++i);
  840. while (i < columnStr.length) {
  841. if (c === '"' && cl !== '"' && cn !== '"') {
  842. break;
  843. }
  844. if (c !== '"' || (c === '"' && cl !== '"')) {
  845. token += c;
  846. }
  847. read(++i);
  848. }
  849. // Perform "plugin" handling
  850. }
  851. else if (callbacks && callbacks[c]) {
  852. if (callbacks[c](c, token)) {
  853. push();
  854. }
  855. // Delimiter - push current token
  856. }
  857. else if (c === itemDelimiter) {
  858. push();
  859. // Actual column data
  860. }
  861. else {
  862. token += c;
  863. }
  864. }
  865. push();
  866. }
  867. /**
  868. * Attempt to guess the delimiter. We do a separate parse pass here
  869. * because we need to count potential delimiters softly without making
  870. * any assumptions.
  871. * @private
  872. */
  873. function guessDelimiter(lines) {
  874. var points = 0, commas = 0, guessed = false;
  875. lines.some(function (columnStr, i) {
  876. var inStr = false, c, cn, cl, token = '';
  877. // We should be able to detect dateformats within 13 rows
  878. if (i > 13) {
  879. return true;
  880. }
  881. for (var j = 0; j < columnStr.length; j++) {
  882. c = columnStr[j];
  883. cn = columnStr[j + 1];
  884. cl = columnStr[j - 1];
  885. if (c === '#') {
  886. // Skip the rest of the line - it's a comment
  887. return;
  888. }
  889. if (c === '"') {
  890. if (inStr) {
  891. if (cl !== '"' && cn !== '"') {
  892. while (cn === ' ' && j < columnStr.length) {
  893. cn = columnStr[++j];
  894. }
  895. // After parsing a string, the next non-blank
  896. // should be a delimiter if the CSV is properly
  897. // formed.
  898. if (typeof potDelimiters[cn] !== 'undefined') {
  899. potDelimiters[cn]++;
  900. }
  901. inStr = false;
  902. }
  903. }
  904. else {
  905. inStr = true;
  906. }
  907. }
  908. else if (typeof potDelimiters[c] !== 'undefined') {
  909. token = token.trim();
  910. if (!isNaN(Date.parse(token))) {
  911. potDelimiters[c]++;
  912. }
  913. else if (isNaN(token) ||
  914. !isFinite(token)) {
  915. potDelimiters[c]++;
  916. }
  917. token = '';
  918. }
  919. else {
  920. token += c;
  921. }
  922. if (c === ',') {
  923. commas++;
  924. }
  925. if (c === '.') {
  926. points++;
  927. }
  928. }
  929. });
  930. // Count the potential delimiters.
  931. // This could be improved by checking if the number of delimiters
  932. // equals the number of columns - 1
  933. if (potDelimiters[';'] > potDelimiters[',']) {
  934. guessed = ';';
  935. }
  936. else if (potDelimiters[','] > potDelimiters[';']) {
  937. guessed = ',';
  938. }
  939. else {
  940. // No good guess could be made..
  941. guessed = ',';
  942. }
  943. // Try to deduce the decimal point if it's not explicitly set.
  944. // If both commas or points is > 0 there is likely an issue
  945. if (!options.decimalPoint) {
  946. if (points > commas) {
  947. options.decimalPoint = '.';
  948. }
  949. else {
  950. options.decimalPoint = ',';
  951. }
  952. // Apply a new decimal regex based on the presumed decimal sep.
  953. self.decimalRegex = new RegExp('^(-?[0-9]+)' +
  954. options.decimalPoint +
  955. '([0-9]+)$');
  956. }
  957. return guessed;
  958. }
  959. /**
  960. * Tries to guess the date format
  961. * - Check if either month candidate exceeds 12
  962. * - Check if year is missing (use current year)
  963. * - Check if a shortened year format is used (e.g. 1/1/99)
  964. * - If no guess can be made, the user must be prompted
  965. * data is the data to deduce a format based on
  966. * @private
  967. */
  968. function deduceDateFormat(data, limit) {
  969. var format = 'YYYY/mm/dd', thing, guessedFormat = [], calculatedFormat, i = 0, madeDeduction = false,
  970. // candidates = {},
  971. stable = [], max = [], j;
  972. if (!limit || limit > data.length) {
  973. limit = data.length;
  974. }
  975. for (; i < limit; i++) {
  976. if (typeof data[i] !== 'undefined' &&
  977. data[i] && data[i].length) {
  978. thing = data[i]
  979. .trim()
  980. .replace(/\//g, ' ')
  981. .replace(/\-/g, ' ')
  982. .replace(/\./g, ' ')
  983. .split(' ');
  984. guessedFormat = [
  985. '',
  986. '',
  987. ''
  988. ];
  989. for (j = 0; j < thing.length; j++) {
  990. if (j < guessedFormat.length) {
  991. thing[j] = parseInt(thing[j], 10);
  992. if (thing[j]) {
  993. max[j] = (!max[j] || max[j] < thing[j]) ?
  994. thing[j] :
  995. max[j];
  996. if (typeof stable[j] !== 'undefined') {
  997. if (stable[j] !== thing[j]) {
  998. stable[j] = false;
  999. }
  1000. }
  1001. else {
  1002. stable[j] = thing[j];
  1003. }
  1004. if (thing[j] > 31) {
  1005. if (thing[j] < 100) {
  1006. guessedFormat[j] = 'YY';
  1007. }
  1008. else {
  1009. guessedFormat[j] = 'YYYY';
  1010. }
  1011. // madeDeduction = true;
  1012. }
  1013. else if (thing[j] > 12 &&
  1014. thing[j] <= 31) {
  1015. guessedFormat[j] = 'dd';
  1016. madeDeduction = true;
  1017. }
  1018. else if (!guessedFormat[j].length) {
  1019. guessedFormat[j] = 'mm';
  1020. }
  1021. }
  1022. }
  1023. }
  1024. }
  1025. }
  1026. if (madeDeduction) {
  1027. // This handles a few edge cases with hard to guess dates
  1028. for (j = 0; j < stable.length; j++) {
  1029. if (stable[j] !== false) {
  1030. if (max[j] > 12 &&
  1031. guessedFormat[j] !== 'YY' &&
  1032. guessedFormat[j] !== 'YYYY') {
  1033. guessedFormat[j] = 'YY';
  1034. }
  1035. }
  1036. else if (max[j] > 12 && guessedFormat[j] === 'mm') {
  1037. guessedFormat[j] = 'dd';
  1038. }
  1039. }
  1040. // If the middle one is dd, and the last one is dd,
  1041. // the last should likely be year.
  1042. if (guessedFormat.length === 3 &&
  1043. guessedFormat[1] === 'dd' &&
  1044. guessedFormat[2] === 'dd') {
  1045. guessedFormat[2] = 'YY';
  1046. }
  1047. calculatedFormat = guessedFormat.join('/');
  1048. // If the caculated format is not valid, we need to present an
  1049. // error.
  1050. if (!(options.dateFormats || self.dateFormats)[calculatedFormat]) {
  1051. // This should emit an event instead
  1052. fireEvent('deduceDateFailed');
  1053. return format;
  1054. }
  1055. return calculatedFormat;
  1056. }
  1057. return format;
  1058. }
  1059. /**
  1060. * @todo
  1061. * Figure out the best axis types for the data
  1062. * - If the first column is a number, we're good
  1063. * - If the first column is a date, set to date/time
  1064. * - If the first column is a string, set to categories
  1065. * @private
  1066. */
  1067. function deduceAxisTypes() {
  1068. }
  1069. if (csv && options.beforeParse) {
  1070. csv = options.beforeParse.call(this, csv);
  1071. }
  1072. if (csv) {
  1073. lines = csv
  1074. .replace(/\r\n/g, '\n') // Unix
  1075. .replace(/\r/g, '\n') // Mac
  1076. .split(options.lineDelimiter || '\n');
  1077. if (!startRow || startRow < 0) {
  1078. startRow = 0;
  1079. }
  1080. if (!endRow || endRow >= lines.length) {
  1081. endRow = lines.length - 1;
  1082. }
  1083. if (options.itemDelimiter) {
  1084. itemDelimiter = options.itemDelimiter;
  1085. }
  1086. else {
  1087. itemDelimiter = null;
  1088. itemDelimiter = guessDelimiter(lines);
  1089. }
  1090. var offset = 0;
  1091. for (rowIt = startRow; rowIt <= endRow; rowIt++) {
  1092. if (lines[rowIt][0] === '#') {
  1093. offset++;
  1094. }
  1095. else {
  1096. parseRow(lines[rowIt], rowIt - startRow - offset);
  1097. }
  1098. }
  1099. // //Make sure that there's header columns for everything
  1100. // columns.forEach(function (col) {
  1101. // });
  1102. deduceAxisTypes();
  1103. if ((!options.columnTypes || options.columnTypes.length === 0) &&
  1104. dataTypes.length &&
  1105. dataTypes[0].length &&
  1106. dataTypes[0][1] === 'date' &&
  1107. !options.dateFormat) {
  1108. options.dateFormat = deduceDateFormat(columns[0]);
  1109. }
  1110. // lines.forEach(function (line, rowNo) {
  1111. // var trimmed = self.trim(line),
  1112. // isComment = trimmed.indexOf('#') === 0,
  1113. // isBlank = trimmed === '',
  1114. // items;
  1115. // if (
  1116. // rowNo >= startRow &&
  1117. // rowNo <= endRow &&
  1118. // !isComment && !isBlank
  1119. // ) {
  1120. // items = line.split(itemDelimiter);
  1121. // items.forEach(function (item, colNo) {
  1122. // if (colNo >= startColumn && colNo <= endColumn) {
  1123. // if (!columns[colNo - startColumn]) {
  1124. // columns[colNo - startColumn] = [];
  1125. // }
  1126. // columns[colNo - startColumn][activeRowNo] = item;
  1127. // }
  1128. // });
  1129. // activeRowNo += 1;
  1130. // }
  1131. // });
  1132. //
  1133. this.dataFound();
  1134. }
  1135. return columns;
  1136. };
  1137. /**
  1138. * Parse a HTML table
  1139. *
  1140. * @function Highcharts.Data#parseTable
  1141. *
  1142. * @return {Array<Array<Highcharts.DataValueType>>}
  1143. */
  1144. Data.prototype.parseTable = function () {
  1145. 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;
  1146. if (table) {
  1147. if (typeof table === 'string') {
  1148. table = doc.getElementById(table);
  1149. }
  1150. [].forEach.call(table.getElementsByTagName('tr'), function (tr, rowNo) {
  1151. if (rowNo >= startRow && rowNo <= endRow) {
  1152. [].forEach.call(tr.children, function (item, colNo) {
  1153. var row = columns[colNo - startColumn];
  1154. var i = 1;
  1155. if ((item.tagName === 'TD' ||
  1156. item.tagName === 'TH') &&
  1157. colNo >= startColumn &&
  1158. colNo <= endColumn) {
  1159. if (!columns[colNo - startColumn]) {
  1160. columns[colNo - startColumn] = [];
  1161. }
  1162. columns[colNo - startColumn][rowNo - startRow] = item.innerHTML;
  1163. // Loop over all previous indices and make sure
  1164. // they are nulls, not undefined.
  1165. while (rowNo - startRow >= i &&
  1166. row[rowNo - startRow - i] === void 0) {
  1167. row[rowNo - startRow - i] = null;
  1168. i++;
  1169. }
  1170. }
  1171. });
  1172. }
  1173. });
  1174. this.dataFound(); // continue
  1175. }
  1176. return columns;
  1177. };
  1178. /**
  1179. * Fetch or refetch live data
  1180. *
  1181. * @function Highcharts.Data#fetchLiveData
  1182. *
  1183. * @return {boolean}
  1184. * The URLs that were tried can be found in the options
  1185. */
  1186. Data.prototype.fetchLiveData = function () {
  1187. var data = this, chart = this.chart, options = this.options, maxRetries = 3, currentRetries = 0, pollingEnabled = options.enablePolling, updateIntervalMs = (options.dataRefreshRate || 2) * 1000, originalOptions = merge(options);
  1188. if (!this.hasURLOption(options)) {
  1189. return false;
  1190. }
  1191. // Do not allow polling more than once a second
  1192. if (updateIntervalMs < 1000) {
  1193. updateIntervalMs = 1000;
  1194. }
  1195. delete options.csvURL;
  1196. delete options.rowsURL;
  1197. delete options.columnsURL;
  1198. /**
  1199. * @private
  1200. */
  1201. function performFetch(initialFetch) {
  1202. /**
  1203. * Helper function for doing the data fetch + polling.
  1204. * @private
  1205. */
  1206. function request(url, done, tp) {
  1207. if (!url || url.indexOf('http') !== 0) {
  1208. if (url && options.error) {
  1209. options.error('Invalid URL');
  1210. }
  1211. return false;
  1212. }
  1213. if (initialFetch) {
  1214. clearTimeout(data.liveDataTimeout);
  1215. chart.liveDataURL = url;
  1216. }
  1217. /**
  1218. * @private
  1219. */
  1220. function poll() {
  1221. // Poll
  1222. if (pollingEnabled && chart.liveDataURL === url) {
  1223. // We need to stop doing this if the URL has changed
  1224. data.liveDataTimeout =
  1225. setTimeout(performFetch, updateIntervalMs);
  1226. }
  1227. }
  1228. ajax({
  1229. url: url,
  1230. dataType: tp || 'json',
  1231. success: function (res) {
  1232. if (chart && chart.series) {
  1233. done(res);
  1234. }
  1235. poll();
  1236. },
  1237. error: function (xhr, text) {
  1238. if (++currentRetries < maxRetries) {
  1239. poll();
  1240. }
  1241. return options.error && options.error(text, xhr);
  1242. }
  1243. });
  1244. return true;
  1245. }
  1246. if (!request(originalOptions.csvURL, function (res) {
  1247. chart.update({
  1248. data: {
  1249. csv: res
  1250. }
  1251. });
  1252. }, 'text')) {
  1253. if (!request(originalOptions.rowsURL, function (res) {
  1254. chart.update({
  1255. data: {
  1256. rows: res
  1257. }
  1258. });
  1259. })) {
  1260. request(originalOptions.columnsURL, function (res) {
  1261. chart.update({
  1262. data: {
  1263. columns: res
  1264. }
  1265. });
  1266. });
  1267. }
  1268. }
  1269. }
  1270. performFetch(true);
  1271. return this.hasURLOption(options);
  1272. };
  1273. /**
  1274. * Parse a Google spreadsheet.
  1275. *
  1276. * @function Highcharts.Data#parseGoogleSpreadsheet
  1277. *
  1278. * @return {boolean}
  1279. * Always returns false, because it is an intermediate fetch.
  1280. */
  1281. Data.prototype.parseGoogleSpreadsheet = function () {
  1282. var data = this, options = this.options, googleSpreadsheetKey = options.googleSpreadsheetKey, chart = this.chart,
  1283. // use sheet 1 as the default rather than od6
  1284. // as the latter sometimes cause issues (it looks like it can
  1285. // be renamed in some cases, ref. a fogbugz case).
  1286. 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;
  1287. if (refreshRate < 4000) {
  1288. refreshRate = 4000;
  1289. }
  1290. /**
  1291. * Fetch the actual spreadsheet using XMLHttpRequest.
  1292. * @private
  1293. */
  1294. function fetchSheet(fn) {
  1295. var url = [
  1296. 'https://spreadsheets.google.com/feeds/cells',
  1297. googleSpreadsheetKey,
  1298. worksheet,
  1299. 'public/values?alt=json'
  1300. ].join('/');
  1301. ajax({
  1302. url: url,
  1303. dataType: 'json',
  1304. success: function (json) {
  1305. fn(json);
  1306. if (options.enablePolling) {
  1307. setTimeout(function () {
  1308. fetchSheet(fn);
  1309. }, (options.dataRefreshRate || 2) * 1000);
  1310. }
  1311. },
  1312. error: function (xhr, text) {
  1313. return options.error && options.error(text, xhr);
  1314. }
  1315. });
  1316. }
  1317. if (googleSpreadsheetKey) {
  1318. delete options.googleSpreadsheetKey;
  1319. fetchSheet(function (json) {
  1320. // Prepare the data from the spreadsheat
  1321. var columns = [], cells = json.feed.entry, cell, cellCount = (cells || []).length, colCount = 0, rowCount = 0, val, gr, gc, cellInner, i;
  1322. if (!cells || cells.length === 0) {
  1323. return false;
  1324. }
  1325. // First, find the total number of columns and rows that
  1326. // are actually filled with data
  1327. for (i = 0; i < cellCount; i++) {
  1328. cell = cells[i];
  1329. colCount = Math.max(colCount, cell.gs$cell.col);
  1330. rowCount = Math.max(rowCount, cell.gs$cell.row);
  1331. }
  1332. // Set up arrays containing the column data
  1333. for (i = 0; i < colCount; i++) {
  1334. if (i >= startColumn && i <= endColumn) {
  1335. // Create new columns with the length of either
  1336. // end-start or rowCount
  1337. columns[i - startColumn] = [];
  1338. }
  1339. }
  1340. // Loop over the cells and assign the value to the right
  1341. // place in the column arrays
  1342. for (i = 0; i < cellCount; i++) {
  1343. cell = cells[i];
  1344. gr = cell.gs$cell.row - 1; // rows start at 1
  1345. gc = cell.gs$cell.col - 1; // columns start at 1
  1346. // If both row and col falls inside start and end set the
  1347. // transposed cell value in the newly created columns
  1348. if (gc >= startColumn && gc <= endColumn &&
  1349. gr >= startRow && gr <= endRow) {
  1350. cellInner = cell.gs$cell || cell.content;
  1351. val = null;
  1352. if (cellInner.numericValue) {
  1353. if (cellInner.$t.indexOf('/') >= 0 ||
  1354. cellInner.$t.indexOf('-') >= 0) {
  1355. // This is a date - for future reference.
  1356. val = cellInner.$t;
  1357. }
  1358. else if (cellInner.$t.indexOf('%') > 0) {
  1359. // Percentage
  1360. val = parseFloat(cellInner.numericValue) * 100;
  1361. }
  1362. else {
  1363. val = parseFloat(cellInner.numericValue);
  1364. }
  1365. }
  1366. else if (cellInner.$t && cellInner.$t.length) {
  1367. val = cellInner.$t;
  1368. }
  1369. columns[gc - startColumn][gr - startRow] = val;
  1370. }
  1371. }
  1372. // Insert null for empty spreadsheet cells (#5298)
  1373. columns.forEach(function (column) {
  1374. for (i = 0; i < column.length; i++) {
  1375. if (typeof column[i] === 'undefined') {
  1376. column[i] = null;
  1377. }
  1378. }
  1379. });
  1380. if (chart && chart.series) {
  1381. chart.update({
  1382. data: {
  1383. columns: columns
  1384. }
  1385. });
  1386. }
  1387. else { // #8245
  1388. data.columns = columns;
  1389. data.dataFound();
  1390. }
  1391. });
  1392. }
  1393. // This is an intermediate fetch, so always return false.
  1394. return false;
  1395. };
  1396. /**
  1397. * Trim a string from whitespaces.
  1398. *
  1399. * @function Highcharts.Data#trim
  1400. *
  1401. * @param {string} str
  1402. * String to trim
  1403. *
  1404. * @param {boolean} [inside=false]
  1405. * Remove all spaces between numbers.
  1406. *
  1407. * @return {string}
  1408. * Trimed string
  1409. */
  1410. Data.prototype.trim = function (str, inside) {
  1411. if (typeof str === 'string') {
  1412. str = str.replace(/^\s+|\s+$/g, '');
  1413. // Clear white space insdie the string, like thousands separators
  1414. if (inside && /^[0-9\s]+$/.test(str)) {
  1415. str = str.replace(/\s/g, '');
  1416. }
  1417. if (this.decimalRegex) {
  1418. str = str.replace(this.decimalRegex, '$1.$2');
  1419. }
  1420. }
  1421. return str;
  1422. };
  1423. /**
  1424. * Parse numeric cells in to number types and date types in to true dates.
  1425. *
  1426. * @function Highcharts.Data#parseTypes
  1427. */
  1428. Data.prototype.parseTypes = function () {
  1429. var columns = this.columns, col = columns.length;
  1430. while (col--) {
  1431. this.parseColumn(columns[col], col);
  1432. }
  1433. };
  1434. /**
  1435. * Parse a single column. Set properties like .isDatetime and .isNumeric.
  1436. *
  1437. * @function Highcharts.Data#parseColumn
  1438. *
  1439. * @param {Array<Highcharts.DataValueType>} column
  1440. * Column to parse
  1441. *
  1442. * @param {number} col
  1443. * Column index
  1444. */
  1445. Data.prototype.parseColumn = function (column, col) {
  1446. 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 &&
  1447. chartOptions.xAxis &&
  1448. splat(chartOptions.xAxis)[0].type === 'category') || columnType === 'string');
  1449. if (!rawColumns[col]) {
  1450. rawColumns[col] = [];
  1451. }
  1452. while (row--) {
  1453. val = backup[row] || column[row];
  1454. trimVal = this.trim(val);
  1455. trimInsideVal = this.trim(val, true);
  1456. floatVal = parseFloat(trimInsideVal);
  1457. // Set it the first time
  1458. if (typeof rawColumns[col][row] === 'undefined') {
  1459. rawColumns[col][row] = trimVal;
  1460. }
  1461. // Disable number or date parsing by setting the X axis type to
  1462. // category
  1463. if (forceCategory || (row === 0 && firstRowAsNames)) {
  1464. column[row] = '' + trimVal;
  1465. }
  1466. else if (+trimInsideVal === floatVal) { // is numeric
  1467. column[row] = floatVal;
  1468. // If the number is greater than milliseconds in a year, assume
  1469. // datetime
  1470. if (floatVal > 365 * 24 * 3600 * 1000 &&
  1471. columnType !== 'float') {
  1472. column.isDatetime = true;
  1473. }
  1474. else {
  1475. column.isNumeric = true;
  1476. }
  1477. if (typeof column[row + 1] !== 'undefined') {
  1478. descending = floatVal > column[row + 1];
  1479. }
  1480. // String, continue to determine if it is a date string or really a
  1481. // string
  1482. }
  1483. else {
  1484. if (trimVal && trimVal.length) {
  1485. dateVal = this.parseDate(val);
  1486. }
  1487. // Only allow parsing of dates if this column is an x-column
  1488. if (isXColumn && isNumber(dateVal) && columnType !== 'float') {
  1489. backup[row] = val;
  1490. column[row] = dateVal;
  1491. column.isDatetime = true;
  1492. // Check if the dates are uniformly descending or ascending.
  1493. // If they are not, chances are that they are a different
  1494. // time format, so check for alternative.
  1495. if (typeof column[row + 1] !== 'undefined') {
  1496. diff = dateVal > column[row + 1];
  1497. if (diff !== descending &&
  1498. typeof descending !== 'undefined') {
  1499. if (this.alternativeFormat) {
  1500. this.dateFormat = this.alternativeFormat;
  1501. row = column.length;
  1502. this.alternativeFormat =
  1503. this.dateFormats[this.dateFormat]
  1504. .alternative;
  1505. }
  1506. else {
  1507. column.unsorted = true;
  1508. }
  1509. }
  1510. descending = diff;
  1511. }
  1512. }
  1513. else { // string
  1514. column[row] = trimVal === '' ? null : trimVal;
  1515. if (row !== 0 &&
  1516. (column.isDatetime ||
  1517. column.isNumeric)) {
  1518. column.mixed = true;
  1519. }
  1520. }
  1521. }
  1522. }
  1523. // If strings are intermixed with numbers or dates in a parsed column,
  1524. // it is an indication that parsing went wrong or the data was not
  1525. // intended to display as numbers or dates and parsing is too
  1526. // aggressive. Fall back to categories. Demonstrated in the
  1527. // highcharts/demo/column-drilldown sample.
  1528. if (isXColumn && column.mixed) {
  1529. columns[col] = rawColumns[col];
  1530. }
  1531. // If the 0 column is date or number and descending, reverse all
  1532. // columns.
  1533. if (isXColumn && descending && this.options.sort) {
  1534. for (col = 0; col < columns.length; col++) {
  1535. columns[col].reverse();
  1536. if (firstRowAsNames) {
  1537. columns[col].unshift(columns[col].pop());
  1538. }
  1539. }
  1540. }
  1541. };
  1542. /**
  1543. * Parse a date and return it as a number. Overridable through
  1544. * `options.parseDate`.
  1545. *
  1546. * @function Highcharts.Data#parseDate
  1547. *
  1548. * @param {string} val
  1549. *
  1550. * @return {number}
  1551. */
  1552. Data.prototype.parseDate = function (val) {
  1553. var parseDate = this.options.parseDate, ret, key, format, dateFormat = this.options.dateFormat || this.dateFormat, match;
  1554. if (parseDate) {
  1555. ret = parseDate(val);
  1556. }
  1557. else if (typeof val === 'string') {
  1558. // Auto-detect the date format the first time
  1559. if (!dateFormat) {
  1560. for (key in this.dateFormats) { // eslint-disable-line guard-for-in
  1561. format = this.dateFormats[key];
  1562. match = val.match(format.regex);
  1563. if (match) {
  1564. this.dateFormat = dateFormat = key;
  1565. this.alternativeFormat = format.alternative;
  1566. ret = format.parser(match);
  1567. break;
  1568. }
  1569. }
  1570. // Next time, use the one previously found
  1571. }
  1572. else {
  1573. format = this.dateFormats[dateFormat];
  1574. if (!format) {
  1575. // The selected format is invalid
  1576. format = this.dateFormats['YYYY/mm/dd'];
  1577. }
  1578. match = val.match(format.regex);
  1579. if (match) {
  1580. ret = format.parser(match);
  1581. }
  1582. }
  1583. // Fall back to Date.parse
  1584. if (!match) {
  1585. match = Date.parse(val);
  1586. // External tools like Date.js and MooTools extend Date object
  1587. // and returns a date.
  1588. if (typeof match === 'object' &&
  1589. match !== null &&
  1590. match.getTime) {
  1591. ret = (match.getTime() -
  1592. match.getTimezoneOffset() *
  1593. 60000);
  1594. // Timestamp
  1595. }
  1596. else if (isNumber(match)) {
  1597. ret = match - (new Date(match)).getTimezoneOffset() * 60000;
  1598. }
  1599. }
  1600. }
  1601. return ret;
  1602. };
  1603. /**
  1604. * Reorganize rows into columns.
  1605. *
  1606. * @function Highcharts.Data#rowsToColumns
  1607. *
  1608. * @param {Array<Array<Highcharts.DataValueType>>} rows
  1609. *
  1610. * @return {Array<Array<Highcharts.DataValueType>>|undefined}
  1611. */
  1612. Data.prototype.rowsToColumns = function (rows) {
  1613. var row, rowsLength, col, colsLength, columns;
  1614. if (rows) {
  1615. columns = [];
  1616. rowsLength = rows.length;
  1617. for (row = 0; row < rowsLength; row++) {
  1618. colsLength = rows[row].length;
  1619. for (col = 0; col < colsLength; col++) {
  1620. if (!columns[col]) {
  1621. columns[col] = [];
  1622. }
  1623. columns[col][row] = rows[row][col];
  1624. }
  1625. }
  1626. }
  1627. return columns;
  1628. };
  1629. /**
  1630. * Get the parsed data in a form that we can apply directly to the
  1631. * `series.data` config. Array positions can be mapped using the
  1632. * `series.keys` option.
  1633. *
  1634. * @example
  1635. * const data = Highcharts.data({
  1636. * csv: document.getElementById('data').innerHTML
  1637. * }).getData();
  1638. *
  1639. * @function Highcharts.Data#getData
  1640. *
  1641. * @return {Array<Array<(number|string)>>|undefined} Data rows
  1642. */
  1643. Data.prototype.getData = function () {
  1644. if (this.columns) {
  1645. return this.rowsToColumns(this.columns).slice(1);
  1646. }
  1647. };
  1648. /**
  1649. * A hook for working directly on the parsed columns
  1650. *
  1651. * @function Highcharts.Data#parsed
  1652. *
  1653. * @return {boolean|undefined}
  1654. */
  1655. Data.prototype.parsed = function () {
  1656. if (this.options.parsed) {
  1657. return this.options.parsed.call(this, this.columns);
  1658. }
  1659. };
  1660. /**
  1661. * @private
  1662. * @function Highcharts.Data#getFreeIndexes
  1663. */
  1664. Data.prototype.getFreeIndexes = function (numberOfColumns, seriesBuilders) {
  1665. var s, i, freeIndexes = [], freeIndexValues = [], referencedIndexes;
  1666. // Add all columns as free
  1667. for (i = 0; i < numberOfColumns; i = i + 1) {
  1668. freeIndexes.push(true);
  1669. }
  1670. // Loop all defined builders and remove their referenced columns
  1671. for (s = 0; s < seriesBuilders.length; s = s + 1) {
  1672. referencedIndexes = seriesBuilders[s].getReferencedColumnIndexes();
  1673. for (i = 0; i < referencedIndexes.length; i = i + 1) {
  1674. freeIndexes[referencedIndexes[i]] = false;
  1675. }
  1676. }
  1677. // Collect the values for the free indexes
  1678. for (i = 0; i < freeIndexes.length; i = i + 1) {
  1679. if (freeIndexes[i]) {
  1680. freeIndexValues.push(i);
  1681. }
  1682. }
  1683. return freeIndexValues;
  1684. };
  1685. /**
  1686. * If a complete callback function is provided in the options, interpret the
  1687. * columns into a Highcharts options object.
  1688. *
  1689. * @function Highcharts.Data#complete
  1690. */
  1691. Data.prototype.complete = function () {
  1692. var columns = this.columns, xColumns = [], type, options = this.options, series, data, i, j, r, seriesIndex, chartOptions, allSeriesBuilders = [], builder, freeIndexes, typeCol, index;
  1693. xColumns.length = columns.length;
  1694. if (options.complete || options.afterComplete) {
  1695. // Get the names and shift the top row
  1696. if (this.firstRowAsNames) {
  1697. for (i = 0; i < columns.length; i++) {
  1698. columns[i].name = columns[i].shift();
  1699. }
  1700. }
  1701. // Use the next columns for series
  1702. series = [];
  1703. freeIndexes = this.getFreeIndexes(columns.length, this.valueCount.seriesBuilders);
  1704. // Populate defined series
  1705. for (seriesIndex = 0; seriesIndex < this.valueCount.seriesBuilders.length; seriesIndex++) {
  1706. builder = this.valueCount.seriesBuilders[seriesIndex];
  1707. // If the builder can be populated with remaining columns, then
  1708. // add it to allBuilders
  1709. if (builder.populateColumns(freeIndexes)) {
  1710. allSeriesBuilders.push(builder);
  1711. }
  1712. }
  1713. // Populate dynamic series
  1714. while (freeIndexes.length > 0) {
  1715. builder = new SeriesBuilder();
  1716. builder.addColumnReader(0, 'x');
  1717. // Mark index as used (not free)
  1718. index = freeIndexes.indexOf(0);
  1719. if (index !== -1) {
  1720. freeIndexes.splice(index, 1);
  1721. }
  1722. for (i = 0; i < this.valueCount.global; i++) {
  1723. // Create and add a column reader for the next free column
  1724. // index
  1725. builder.addColumnReader(void 0, this.valueCount.globalPointArrayMap[i]);
  1726. }
  1727. // If the builder can be populated with remaining columns, then
  1728. // add it to allBuilders
  1729. if (builder.populateColumns(freeIndexes)) {
  1730. allSeriesBuilders.push(builder);
  1731. }
  1732. }
  1733. // Get the data-type from the first series x column
  1734. if (allSeriesBuilders.length > 0 &&
  1735. allSeriesBuilders[0].readers.length > 0) {
  1736. typeCol = columns[allSeriesBuilders[0].readers[0].columnIndex];
  1737. if (typeof typeCol !== 'undefined') {
  1738. if (typeCol.isDatetime) {
  1739. type = 'datetime';
  1740. }
  1741. else if (!typeCol.isNumeric) {
  1742. type = 'category';
  1743. }
  1744. }
  1745. }
  1746. // Axis type is category, then the "x" column should be called
  1747. // "name"
  1748. if (type === 'category') {
  1749. for (seriesIndex = 0; seriesIndex < allSeriesBuilders.length; seriesIndex++) {
  1750. builder = allSeriesBuilders[seriesIndex];
  1751. for (r = 0; r < builder.readers.length; r++) {
  1752. if (builder.readers[r].configName === 'x') {
  1753. builder.readers[r].configName = 'name';
  1754. }
  1755. }
  1756. }
  1757. }
  1758. // Read data for all builders
  1759. for (seriesIndex = 0; seriesIndex < allSeriesBuilders.length; seriesIndex++) {
  1760. builder = allSeriesBuilders[seriesIndex];
  1761. // Iterate down the cells of each column and add data to the
  1762. // series
  1763. data = [];
  1764. for (j = 0; j < columns[0].length; j++) {
  1765. data[j] = builder.read(columns, j);
  1766. }
  1767. // Add the series
  1768. series[seriesIndex] = {
  1769. data: data
  1770. };
  1771. if (builder.name) {
  1772. series[seriesIndex].name = builder.name;
  1773. }
  1774. if (type === 'category') {
  1775. series[seriesIndex].turboThreshold = 0;
  1776. }
  1777. }
  1778. // Do the callback
  1779. chartOptions = {
  1780. series: series
  1781. };
  1782. if (type) {
  1783. chartOptions.xAxis = {
  1784. type: type
  1785. };
  1786. if (type === 'category') {
  1787. chartOptions.xAxis.uniqueNames = false;
  1788. }
  1789. }
  1790. if (options.complete) {
  1791. options.complete(chartOptions);
  1792. }
  1793. // The afterComplete hook is used internally to avoid conflict with
  1794. // the externally available complete option.
  1795. if (options.afterComplete) {
  1796. options.afterComplete(chartOptions);
  1797. }
  1798. }
  1799. };
  1800. /**
  1801. * Updates the chart with new data options.
  1802. *
  1803. * @function Highcharts.Data#update
  1804. *
  1805. * @param {Highcharts.DataOptions} options
  1806. *
  1807. * @param {boolean} [redraw=true]
  1808. */
  1809. Data.prototype.update = function (options, redraw) {
  1810. var chart = this.chart;
  1811. if (options) {
  1812. // Set the complete handler
  1813. options.afterComplete = function (dataOptions) {
  1814. // Avoid setting axis options unless the type changes. Running
  1815. // Axis.update will cause the whole structure to be destroyed
  1816. // and rebuilt, and animation is lost.
  1817. if (dataOptions) {
  1818. if (dataOptions.xAxis &&
  1819. chart.xAxis[0] &&
  1820. dataOptions.xAxis.type ===
  1821. chart.xAxis[0].options.type) {
  1822. delete dataOptions.xAxis;
  1823. }
  1824. // @todo looks not right:
  1825. chart.update(dataOptions, redraw, true);
  1826. }
  1827. };
  1828. // Apply it
  1829. merge(true, chart.options.data, options);
  1830. this.init(chart.options.data);
  1831. }
  1832. };
  1833. return Data;
  1834. }());
  1835. // Register the Data prototype and data function on Highcharts
  1836. // Highcharts.Data = Data as any;
  1837. /**
  1838. * Creates a data object to parse data for a chart.
  1839. *
  1840. * @function Highcharts.data
  1841. *
  1842. * @param {Highcharts.DataOptions} dataOptions
  1843. *
  1844. * @param {Highcharts.Options} [chartOptions]
  1845. *
  1846. * @param {Highcharts.Chart} [chart]
  1847. *
  1848. * @return {Highcharts.Data}
  1849. */
  1850. H.data = function (dataOptions, chartOptions, chart) {
  1851. return new H.Data(dataOptions, chartOptions, chart);
  1852. };
  1853. // Extend Chart.init so that the Chart constructor accepts a new configuration
  1854. // option group, data.
  1855. addEvent(Chart, 'init', function (e) {
  1856. var chart = this, // eslint-disable-line no-invalid-this
  1857. userOptions = (e.args[0] || {}), callback = e.args[1];
  1858. if (userOptions && userOptions.data && !chart.hasDataDef) {
  1859. chart.hasDataDef = true;
  1860. /**
  1861. * The data parser for this chart.
  1862. *
  1863. * @name Highcharts.Chart#data
  1864. * @type {Highcharts.Data|undefined}
  1865. */
  1866. chart.data = new H.Data(extend(userOptions.data, {
  1867. afterComplete: function (dataOptions) {
  1868. var i, series;
  1869. // Merge series configs
  1870. if (Object.hasOwnProperty.call(userOptions, 'series')) {
  1871. if (typeof userOptions.series === 'object') {
  1872. i = Math.max(userOptions.series.length, dataOptions && dataOptions.series ?
  1873. dataOptions.series.length :
  1874. 0);
  1875. while (i--) {
  1876. series = userOptions.series[i] || {};
  1877. userOptions.series[i] = merge(series, dataOptions && dataOptions.series ?
  1878. dataOptions.series[i] :
  1879. {});
  1880. }
  1881. }
  1882. else { // Allow merging in dataOptions.series (#2856)
  1883. delete userOptions.series;
  1884. }
  1885. }
  1886. // Do the merge
  1887. userOptions = merge(dataOptions, userOptions);
  1888. // Run chart.init again
  1889. chart.init(userOptions, callback);
  1890. }
  1891. }), userOptions, chart);
  1892. e.preventDefault();
  1893. }
  1894. });
  1895. /**
  1896. * Creates a new SeriesBuilder. A SeriesBuilder consists of a number
  1897. * of ColumnReaders that reads columns and give them a name.
  1898. * Ex: A series builder can be constructed to read column 3 as 'x' and
  1899. * column 7 and 8 as 'y1' and 'y2'.
  1900. * The output would then be points/rows of the form {x: 11, y1: 22, y2: 33}
  1901. *
  1902. * The name of the builder is taken from the second column. In the above
  1903. * example it would be the column with index 7.
  1904. *
  1905. * @private
  1906. * @class
  1907. * @name SeriesBuilder
  1908. */
  1909. var SeriesBuilder = /** @class */ (function () {
  1910. function SeriesBuilder() {
  1911. /* eslint-disable no-invalid-this */
  1912. this.readers = [];
  1913. this.pointIsArray = true;
  1914. /* eslint-enable no-invalid-this */
  1915. this.name = void 0;
  1916. }
  1917. /**
  1918. * Populates readers with column indexes. A reader can be added without
  1919. * a specific index and for those readers the index is taken sequentially
  1920. * from the free columns (this is handled by the ColumnCursor instance).
  1921. *
  1922. * @function SeriesBuilder#populateColumns
  1923. *
  1924. * @param {Array<number>} freeIndexes
  1925. *
  1926. * @returns {boolean}
  1927. */
  1928. SeriesBuilder.prototype.populateColumns = function (freeIndexes) {
  1929. var builder = this, enoughColumns = true;
  1930. // Loop each reader and give it an index if its missing.
  1931. // The freeIndexes.shift() will return undefined if there
  1932. // are no more columns.
  1933. builder.readers.forEach(function (reader) {
  1934. if (typeof reader.columnIndex === 'undefined') {
  1935. reader.columnIndex = freeIndexes.shift();
  1936. }
  1937. });
  1938. // Now, all readers should have columns mapped. If not
  1939. // then return false to signal that this series should
  1940. // not be added.
  1941. builder.readers.forEach(function (reader) {
  1942. if (typeof reader.columnIndex === 'undefined') {
  1943. enoughColumns = false;
  1944. }
  1945. });
  1946. return enoughColumns;
  1947. };
  1948. /**
  1949. * Reads a row from the dataset and returns a point or array depending
  1950. * on the names of the readers.
  1951. *
  1952. * @function SeriesBuilder#read<T>
  1953. *
  1954. * @param {Array<Array<T>>} columns
  1955. *
  1956. * @param {number} rowIndex
  1957. *
  1958. * @returns {Array<T>|Highcharts.Dictionary<T>}
  1959. */
  1960. SeriesBuilder.prototype.read = function (columns, rowIndex) {
  1961. var builder = this, pointIsArray = builder.pointIsArray, point = pointIsArray ? [] : {}, columnIndexes;
  1962. // Loop each reader and ask it to read its value.
  1963. // Then, build an array or point based on the readers names.
  1964. builder.readers.forEach(function (reader) {
  1965. var value = columns[reader.columnIndex][rowIndex];
  1966. if (pointIsArray) {
  1967. point.push(value);
  1968. }
  1969. else {
  1970. if (reader.configName.indexOf('.') > 0) {
  1971. // Handle nested property names
  1972. Point.prototype.setNestedProperty(point, value, reader.configName);
  1973. }
  1974. else {
  1975. point[reader.configName] = value;
  1976. }
  1977. }
  1978. });
  1979. // The name comes from the first column (excluding the x column)
  1980. if (typeof this.name === 'undefined' && builder.readers.length >= 2) {
  1981. columnIndexes = builder.getReferencedColumnIndexes();
  1982. if (columnIndexes.length >= 2) {
  1983. // remove the first one (x col)
  1984. columnIndexes.shift();
  1985. // Sort the remaining
  1986. columnIndexes.sort(function (a, b) {
  1987. return a - b;
  1988. });
  1989. // Now use the lowest index as name column
  1990. this.name = columns[columnIndexes.shift()].name;
  1991. }
  1992. }
  1993. return point;
  1994. };
  1995. /**
  1996. * Creates and adds ColumnReader from the given columnIndex and configName.
  1997. * ColumnIndex can be undefined and in that case the reader will be given
  1998. * an index when columns are populated.
  1999. *
  2000. * @function SeriesBuilder#addColumnReader
  2001. *
  2002. * @param {number} columnIndex
  2003. *
  2004. * @param {string} configName
  2005. */
  2006. SeriesBuilder.prototype.addColumnReader = function (columnIndex, configName) {
  2007. this.readers.push({
  2008. columnIndex: columnIndex,
  2009. configName: configName
  2010. });
  2011. if (!(configName === 'x' ||
  2012. configName === 'y' ||
  2013. typeof configName === 'undefined')) {
  2014. this.pointIsArray = false;
  2015. }
  2016. };
  2017. /**
  2018. * Returns an array of column indexes that the builder will use when
  2019. * reading data.
  2020. *
  2021. * @function SeriesBuilder#getReferencedColumnIndexes
  2022. *
  2023. * @returns {Array<number>}
  2024. */
  2025. SeriesBuilder.prototype.getReferencedColumnIndexes = function () {
  2026. var i, referencedColumnIndexes = [], columnReader;
  2027. for (i = 0; i < this.readers.length; i = i + 1) {
  2028. columnReader = this.readers[i];
  2029. if (typeof columnReader.columnIndex !== 'undefined') {
  2030. referencedColumnIndexes.push(columnReader.columnIndex);
  2031. }
  2032. }
  2033. return referencedColumnIndexes;
  2034. };
  2035. /**
  2036. * Returns true if the builder has a reader for the given configName.
  2037. *
  2038. * @function SeriesBuider#hasReader
  2039. *
  2040. * @param {string} configName
  2041. *
  2042. * @returns {boolean|undefined}
  2043. */
  2044. SeriesBuilder.prototype.hasReader = function (configName) {
  2045. var i, columnReader;
  2046. for (i = 0; i < this.readers.length; i = i + 1) {
  2047. columnReader = this.readers[i];
  2048. if (columnReader.configName === configName) {
  2049. return true;
  2050. }
  2051. }
  2052. // Else return undefined
  2053. };
  2054. return SeriesBuilder;
  2055. }());
  2056. H.Data = Data;
  2057. export default H.Data;