data.src.js 96 KB

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