data.src.js 101 KB

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