data.src.js 74 KB

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