data.src.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. /**
  2. * @license Highcharts JS v5.0.6 (2016-12-07)
  3. * Data module
  4. *
  5. * (c) 2012-2016 Torstein Honsi
  6. *
  7. * License: www.highcharts.com/license
  8. */
  9. (function(factory) {
  10. if (typeof module === 'object' && module.exports) {
  11. module.exports = factory;
  12. } else {
  13. factory(Highcharts);
  14. }
  15. }(function(Highcharts) {
  16. (function(Highcharts) {
  17. /**
  18. * Data module
  19. *
  20. * (c) 2012-2016 Torstein Honsi
  21. *
  22. * License: www.highcharts.com/license
  23. */
  24. /* global jQuery */
  25. 'use strict';
  26. // Utilities
  27. var win = Highcharts.win,
  28. doc = win.document,
  29. each = Highcharts.each,
  30. pick = Highcharts.pick,
  31. inArray = Highcharts.inArray,
  32. isNumber = Highcharts.isNumber,
  33. splat = Highcharts.splat,
  34. SeriesBuilder;
  35. // The Data constructor
  36. var Data = function(dataOptions, chartOptions) {
  37. this.init(dataOptions, chartOptions);
  38. };
  39. // Set the prototype properties
  40. Highcharts.extend(Data.prototype, {
  41. /**
  42. * Initialize the Data object with the given options
  43. */
  44. init: function(options, chartOptions) {
  45. this.options = options;
  46. this.chartOptions = chartOptions;
  47. this.columns = options.columns || this.rowsToColumns(options.rows) || [];
  48. this.firstRowAsNames = pick(options.firstRowAsNames, true);
  49. this.decimalRegex = options.decimalPoint && new RegExp('^(-?[0-9]+)' + options.decimalPoint + '([0-9]+)$');
  50. // This is a two-dimensional array holding the raw, trimmed string values
  51. // with the same organisation as the columns array. It makes it possible
  52. // for example to revert from interpreted timestamps to string-based
  53. // categories.
  54. this.rawColumns = [];
  55. // No need to parse or interpret anything
  56. if (this.columns.length) {
  57. this.dataFound();
  58. // Parse and interpret
  59. } else {
  60. // Parse a CSV string if options.csv is given
  61. this.parseCSV();
  62. // Parse a HTML table if options.table is given
  63. this.parseTable();
  64. // Parse a Google Spreadsheet
  65. this.parseGoogleSpreadsheet();
  66. }
  67. },
  68. /**
  69. * Get the column distribution. For example, a line series takes a single column for
  70. * Y values. A range series takes two columns for low and high values respectively,
  71. * and an OHLC series takes four columns.
  72. */
  73. getColumnDistribution: function() {
  74. var chartOptions = this.chartOptions,
  75. options = this.options,
  76. xColumns = [],
  77. getValueCount = function(type) {
  78. return (Highcharts.seriesTypes[type || 'line'].prototype.pointArrayMap || [0]).length;
  79. },
  80. getPointArrayMap = function(type) {
  81. return Highcharts.seriesTypes[type || 'line'].prototype.pointArrayMap;
  82. },
  83. globalType = chartOptions && chartOptions.chart && chartOptions.chart.type,
  84. individualCounts = [],
  85. seriesBuilders = [],
  86. seriesIndex = 0,
  87. i;
  88. each((chartOptions && chartOptions.series) || [], function(series) {
  89. individualCounts.push(getValueCount(series.type || globalType));
  90. });
  91. // Collect the x-column indexes from seriesMapping
  92. each((options && options.seriesMapping) || [], function(mapping) {
  93. xColumns.push(mapping.x || 0);
  94. });
  95. // If there are no defined series with x-columns, use the first column as x column
  96. if (xColumns.length === 0) {
  97. xColumns.push(0);
  98. }
  99. // Loop all seriesMappings and constructs SeriesBuilders from
  100. // the mapping options.
  101. each((options && options.seriesMapping) || [], function(mapping) {
  102. var builder = new SeriesBuilder(),
  103. name,
  104. numberOfValueColumnsNeeded = individualCounts[seriesIndex] || getValueCount(globalType),
  105. seriesArr = (chartOptions && chartOptions.series) || [],
  106. series = seriesArr[seriesIndex] || {},
  107. pointArrayMap = getPointArrayMap(series.type || globalType) || ['y'];
  108. // Add an x reader from the x property or from an undefined column
  109. // if the property is not set. It will then be auto populated later.
  110. builder.addColumnReader(mapping.x, 'x');
  111. // Add all column mappings
  112. for (name in mapping) {
  113. if (mapping.hasOwnProperty(name) && name !== 'x') {
  114. builder.addColumnReader(mapping[name], name);
  115. }
  116. }
  117. // Add missing columns
  118. for (i = 0; i < numberOfValueColumnsNeeded; i++) {
  119. if (!builder.hasReader(pointArrayMap[i])) {
  120. //builder.addNextColumnReader(pointArrayMap[i]);
  121. // Create and add a column reader for the next free column index
  122. builder.addColumnReader(undefined, pointArrayMap[i]);
  123. }
  124. }
  125. seriesBuilders.push(builder);
  126. seriesIndex++;
  127. });
  128. var globalPointArrayMap = getPointArrayMap(globalType);
  129. if (globalPointArrayMap === undefined) {
  130. globalPointArrayMap = ['y'];
  131. }
  132. this.valueCount = {
  133. global: getValueCount(globalType),
  134. xColumns: xColumns,
  135. individual: individualCounts,
  136. seriesBuilders: seriesBuilders,
  137. globalPointArrayMap: globalPointArrayMap
  138. };
  139. },
  140. /**
  141. * When the data is parsed into columns, either by CSV, table, GS or direct input,
  142. * continue with other operations.
  143. */
  144. dataFound: function() {
  145. if (this.options.switchRowsAndColumns) {
  146. this.columns = this.rowsToColumns(this.columns);
  147. }
  148. // Interpret the info about series and columns
  149. this.getColumnDistribution();
  150. // Interpret the values into right types
  151. this.parseTypes();
  152. // Handle columns if a handleColumns callback is given
  153. if (this.parsed() !== false) {
  154. // Complete if a complete callback is given
  155. this.complete();
  156. }
  157. },
  158. /**
  159. * Parse a CSV input string
  160. */
  161. parseCSV: function() {
  162. var self = this,
  163. options = this.options,
  164. csv = options.csv,
  165. columns = this.columns,
  166. startRow = options.startRow || 0,
  167. endRow = options.endRow || Number.MAX_VALUE,
  168. startColumn = options.startColumn || 0,
  169. endColumn = options.endColumn || Number.MAX_VALUE,
  170. itemDelimiter,
  171. lines,
  172. activeRowNo = 0;
  173. if (csv) {
  174. lines = csv
  175. .replace(/\r\n/g, '\n') // Unix
  176. .replace(/\r/g, '\n') // Mac
  177. .split(options.lineDelimiter || '\n');
  178. itemDelimiter = options.itemDelimiter || (csv.indexOf('\t') !== -1 ? '\t' : ',');
  179. each(lines, function(line, rowNo) {
  180. var trimmed = self.trim(line),
  181. isComment = trimmed.indexOf('#') === 0,
  182. isBlank = trimmed === '',
  183. items;
  184. if (rowNo >= startRow && rowNo <= endRow && !isComment && !isBlank) {
  185. items = line.split(itemDelimiter);
  186. each(items, function(item, colNo) {
  187. if (colNo >= startColumn && colNo <= endColumn) {
  188. if (!columns[colNo - startColumn]) {
  189. columns[colNo - startColumn] = [];
  190. }
  191. columns[colNo - startColumn][activeRowNo] = item;
  192. }
  193. });
  194. activeRowNo += 1;
  195. }
  196. });
  197. this.dataFound();
  198. }
  199. },
  200. /**
  201. * Parse a HTML table
  202. */
  203. parseTable: function() {
  204. var options = this.options,
  205. table = options.table,
  206. columns = this.columns,
  207. startRow = options.startRow || 0,
  208. endRow = options.endRow || Number.MAX_VALUE,
  209. startColumn = options.startColumn || 0,
  210. endColumn = options.endColumn || Number.MAX_VALUE;
  211. if (table) {
  212. if (typeof table === 'string') {
  213. table = doc.getElementById(table);
  214. }
  215. each(table.getElementsByTagName('tr'), function(tr, rowNo) {
  216. if (rowNo >= startRow && rowNo <= endRow) {
  217. each(tr.children, function(item, colNo) {
  218. if ((item.tagName === 'TD' || item.tagName === 'TH') && colNo >= startColumn && colNo <= endColumn) {
  219. if (!columns[colNo - startColumn]) {
  220. columns[colNo - startColumn] = [];
  221. }
  222. columns[colNo - startColumn][rowNo - startRow] = item.innerHTML;
  223. }
  224. });
  225. }
  226. });
  227. this.dataFound(); // continue
  228. }
  229. },
  230. /**
  231. */
  232. parseGoogleSpreadsheet: function() {
  233. var self = this,
  234. options = this.options,
  235. googleSpreadsheetKey = options.googleSpreadsheetKey,
  236. columns = this.columns,
  237. startRow = options.startRow || 0,
  238. endRow = options.endRow || Number.MAX_VALUE,
  239. startColumn = options.startColumn || 0,
  240. endColumn = options.endColumn || Number.MAX_VALUE,
  241. gr, // google row
  242. gc; // google column
  243. if (googleSpreadsheetKey) {
  244. jQuery.ajax({
  245. dataType: 'json',
  246. url: 'https://spreadsheets.google.com/feeds/cells/' +
  247. googleSpreadsheetKey + '/' + (options.googleSpreadsheetWorksheet || 'od6') +
  248. '/public/values?alt=json-in-script&callback=?',
  249. error: options.error,
  250. success: function(json) {
  251. // Prepare the data from the spreadsheat
  252. var cells = json.feed.entry,
  253. cell,
  254. cellCount = cells.length,
  255. colCount = 0,
  256. rowCount = 0,
  257. i;
  258. // First, find the total number of columns and rows that
  259. // are actually filled with data
  260. for (i = 0; i < cellCount; i++) {
  261. cell = cells[i];
  262. colCount = Math.max(colCount, cell.gs$cell.col);
  263. rowCount = Math.max(rowCount, cell.gs$cell.row);
  264. }
  265. // Set up arrays containing the column data
  266. for (i = 0; i < colCount; i++) {
  267. if (i >= startColumn && i <= endColumn) {
  268. // Create new columns with the length of either end-start or rowCount
  269. columns[i - startColumn] = [];
  270. // Setting the length to avoid jslint warning
  271. columns[i - startColumn].length = Math.min(rowCount, endRow - startRow);
  272. }
  273. }
  274. // Loop over the cells and assign the value to the right
  275. // place in the column arrays
  276. for (i = 0; i < cellCount; i++) {
  277. cell = cells[i];
  278. gr = cell.gs$cell.row - 1; // rows start at 1
  279. gc = cell.gs$cell.col - 1; // columns start at 1
  280. // If both row and col falls inside start and end
  281. // set the transposed cell value in the newly created columns
  282. if (gc >= startColumn && gc <= endColumn &&
  283. gr >= startRow && gr <= endRow) {
  284. columns[gc - startColumn][gr - startRow] = cell.content.$t;
  285. }
  286. }
  287. // Insert null for empty spreadsheet cells (#5298)
  288. each(columns, function(column) {
  289. for (i = 0; i < column.length; i++) {
  290. if (column[i] === undefined) {
  291. column[i] = null;
  292. }
  293. }
  294. });
  295. self.dataFound();
  296. }
  297. });
  298. }
  299. },
  300. /**
  301. * Trim a string from whitespace
  302. */
  303. trim: function(str, inside) {
  304. if (typeof str === 'string') {
  305. str = str.replace(/^\s+|\s+$/g, '');
  306. // Clear white space insdie the string, like thousands separators
  307. if (inside && /^[0-9\s]+$/.test(str)) {
  308. str = str.replace(/\s/g, '');
  309. }
  310. if (this.decimalRegex) {
  311. str = str.replace(this.decimalRegex, '$1.$2');
  312. }
  313. }
  314. return str;
  315. },
  316. /**
  317. * Parse numeric cells in to number types and date types in to true dates.
  318. */
  319. parseTypes: function() {
  320. var columns = this.columns,
  321. col = columns.length;
  322. while (col--) {
  323. this.parseColumn(columns[col], col);
  324. }
  325. },
  326. /**
  327. * Parse a single column. Set properties like .isDatetime and .isNumeric.
  328. */
  329. parseColumn: function(column, col) {
  330. var rawColumns = this.rawColumns,
  331. columns = this.columns,
  332. row = column.length,
  333. val,
  334. floatVal,
  335. trimVal,
  336. trimInsideVal,
  337. firstRowAsNames = this.firstRowAsNames,
  338. isXColumn = inArray(col, this.valueCount.xColumns) !== -1,
  339. dateVal,
  340. backup = [],
  341. diff,
  342. chartOptions = this.chartOptions,
  343. descending,
  344. columnTypes = this.options.columnTypes || [],
  345. columnType = columnTypes[col],
  346. forceCategory = isXColumn && ((chartOptions && chartOptions.xAxis && splat(chartOptions.xAxis)[0].type === 'category') || columnType === 'string');
  347. if (!rawColumns[col]) {
  348. rawColumns[col] = [];
  349. }
  350. while (row--) {
  351. val = backup[row] || column[row];
  352. trimVal = this.trim(val);
  353. trimInsideVal = this.trim(val, true);
  354. floatVal = parseFloat(trimInsideVal);
  355. // Set it the first time
  356. if (rawColumns[col][row] === undefined) {
  357. rawColumns[col][row] = trimVal;
  358. }
  359. // Disable number or date parsing by setting the X axis type to category
  360. if (forceCategory || (row === 0 && firstRowAsNames)) {
  361. column[row] = trimVal;
  362. } else if (+trimInsideVal === floatVal) { // is numeric
  363. column[row] = floatVal;
  364. // If the number is greater than milliseconds in a year, assume datetime
  365. if (floatVal > 365 * 24 * 3600 * 1000 && columnType !== 'float') {
  366. column.isDatetime = true;
  367. } else {
  368. column.isNumeric = true;
  369. }
  370. if (column[row + 1] !== undefined) {
  371. descending = floatVal > column[row + 1];
  372. }
  373. // String, continue to determine if it is a date string or really a string
  374. } else {
  375. dateVal = this.parseDate(val);
  376. // Only allow parsing of dates if this column is an x-column
  377. if (isXColumn && isNumber(dateVal) && columnType !== 'float') { // is date
  378. backup[row] = val;
  379. column[row] = dateVal;
  380. column.isDatetime = true;
  381. // Check if the dates are uniformly descending or ascending. If they
  382. // are not, chances are that they are a different time format, so check
  383. // for alternative.
  384. if (column[row + 1] !== undefined) {
  385. diff = dateVal > column[row + 1];
  386. if (diff !== descending && descending !== undefined) {
  387. if (this.alternativeFormat) {
  388. this.dateFormat = this.alternativeFormat;
  389. row = column.length;
  390. this.alternativeFormat = this.dateFormats[this.dateFormat].alternative;
  391. } else {
  392. column.unsorted = true;
  393. }
  394. }
  395. descending = diff;
  396. }
  397. } else { // string
  398. column[row] = trimVal === '' ? null : trimVal;
  399. if (row !== 0 && (column.isDatetime || column.isNumeric)) {
  400. column.mixed = true;
  401. }
  402. }
  403. }
  404. }
  405. // If strings are intermixed with numbers or dates in a parsed column, it is an indication
  406. // that parsing went wrong or the data was not intended to display as numbers or dates and
  407. // parsing is too aggressive. Fall back to categories. Demonstrated in the
  408. // highcharts/demo/column-drilldown sample.
  409. if (isXColumn && column.mixed) {
  410. columns[col] = rawColumns[col];
  411. }
  412. // If the 0 column is date or number and descending, reverse all columns.
  413. if (isXColumn && descending && this.options.sort) {
  414. for (col = 0; col < columns.length; col++) {
  415. columns[col].reverse();
  416. if (firstRowAsNames) {
  417. columns[col].unshift(columns[col].pop());
  418. }
  419. }
  420. }
  421. },
  422. /**
  423. * A collection of available date formats, extendable from the outside to support
  424. * custom date formats.
  425. */
  426. dateFormats: {
  427. 'YYYY-mm-dd': {
  428. regex: /^([0-9]{4})[\-\/\.]([0-9]{2})[\-\/\.]([0-9]{2})$/,
  429. parser: function(match) {
  430. return Date.UTC(+match[1], match[2] - 1, +match[3]);
  431. }
  432. },
  433. 'dd/mm/YYYY': {
  434. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{4})$/,
  435. parser: function(match) {
  436. return Date.UTC(+match[3], match[2] - 1, +match[1]);
  437. },
  438. alternative: 'mm/dd/YYYY' // different format with the same regex
  439. },
  440. 'mm/dd/YYYY': {
  441. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{4})$/,
  442. parser: function(match) {
  443. return Date.UTC(+match[3], match[1] - 1, +match[2]);
  444. }
  445. },
  446. 'dd/mm/YY': {
  447. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{2})$/,
  448. parser: function(match) {
  449. return Date.UTC(+match[3] + 2000, match[2] - 1, +match[1]);
  450. },
  451. alternative: 'mm/dd/YY' // different format with the same regex
  452. },
  453. 'mm/dd/YY': {
  454. regex: /^([0-9]{1,2})[\-\/\.]([0-9]{1,2})[\-\/\.]([0-9]{2})$/,
  455. parser: function(match) {
  456. return Date.UTC(+match[3] + 2000, match[1] - 1, +match[2]);
  457. }
  458. }
  459. },
  460. /**
  461. * Parse a date and return it as a number. Overridable through options.parseDate.
  462. */
  463. parseDate: function(val) {
  464. var parseDate = this.options.parseDate,
  465. ret,
  466. key,
  467. format,
  468. dateFormat = this.options.dateFormat || this.dateFormat,
  469. match;
  470. if (parseDate) {
  471. ret = parseDate(val);
  472. } else if (typeof val === 'string') {
  473. // Auto-detect the date format the first time
  474. if (!dateFormat) {
  475. for (key in this.dateFormats) {
  476. format = this.dateFormats[key];
  477. match = val.match(format.regex);
  478. if (match) {
  479. this.dateFormat = dateFormat = key;
  480. this.alternativeFormat = format.alternative;
  481. ret = format.parser(match);
  482. break;
  483. }
  484. }
  485. // Next time, use the one previously found
  486. } else {
  487. format = this.dateFormats[dateFormat];
  488. match = val.match(format.regex);
  489. if (match) {
  490. ret = format.parser(match);
  491. }
  492. }
  493. // Fall back to Date.parse
  494. if (!match) {
  495. match = Date.parse(val);
  496. // External tools like Date.js and MooTools extend Date object and
  497. // returns a date.
  498. if (typeof match === 'object' && match !== null && match.getTime) {
  499. ret = match.getTime() - match.getTimezoneOffset() * 60000;
  500. // Timestamp
  501. } else if (isNumber(match)) {
  502. ret = match - (new Date(match)).getTimezoneOffset() * 60000;
  503. }
  504. }
  505. }
  506. return ret;
  507. },
  508. /**
  509. * Reorganize rows into columns
  510. */
  511. rowsToColumns: function(rows) {
  512. var row,
  513. rowsLength,
  514. col,
  515. colsLength,
  516. columns;
  517. if (rows) {
  518. columns = [];
  519. rowsLength = rows.length;
  520. for (row = 0; row < rowsLength; row++) {
  521. colsLength = rows[row].length;
  522. for (col = 0; col < colsLength; col++) {
  523. if (!columns[col]) {
  524. columns[col] = [];
  525. }
  526. columns[col][row] = rows[row][col];
  527. }
  528. }
  529. }
  530. return columns;
  531. },
  532. /**
  533. * A hook for working directly on the parsed columns
  534. */
  535. parsed: function() {
  536. if (this.options.parsed) {
  537. return this.options.parsed.call(this, this.columns);
  538. }
  539. },
  540. getFreeIndexes: function(numberOfColumns, seriesBuilders) {
  541. var s,
  542. i,
  543. freeIndexes = [],
  544. freeIndexValues = [],
  545. referencedIndexes;
  546. // Add all columns as free
  547. for (i = 0; i < numberOfColumns; i = i + 1) {
  548. freeIndexes.push(true);
  549. }
  550. // Loop all defined builders and remove their referenced columns
  551. for (s = 0; s < seriesBuilders.length; s = s + 1) {
  552. referencedIndexes = seriesBuilders[s].getReferencedColumnIndexes();
  553. for (i = 0; i < referencedIndexes.length; i = i + 1) {
  554. freeIndexes[referencedIndexes[i]] = false;
  555. }
  556. }
  557. // Collect the values for the free indexes
  558. for (i = 0; i < freeIndexes.length; i = i + 1) {
  559. if (freeIndexes[i]) {
  560. freeIndexValues.push(i);
  561. }
  562. }
  563. return freeIndexValues;
  564. },
  565. /**
  566. * If a complete callback function is provided in the options, interpret the
  567. * columns into a Highcharts options object.
  568. */
  569. complete: function() {
  570. var columns = this.columns,
  571. xColumns = [],
  572. type,
  573. options = this.options,
  574. series,
  575. data,
  576. i,
  577. j,
  578. r,
  579. seriesIndex,
  580. chartOptions,
  581. allSeriesBuilders = [],
  582. builder,
  583. freeIndexes,
  584. typeCol,
  585. index;
  586. xColumns.length = columns.length;
  587. if (options.complete || options.afterComplete) {
  588. // Get the names and shift the top row
  589. for (i = 0; i < columns.length; i++) {
  590. if (this.firstRowAsNames) {
  591. columns[i].name = columns[i].shift();
  592. }
  593. }
  594. // Use the next columns for series
  595. series = [];
  596. freeIndexes = this.getFreeIndexes(columns.length, this.valueCount.seriesBuilders);
  597. // Populate defined series
  598. for (seriesIndex = 0; seriesIndex < this.valueCount.seriesBuilders.length; seriesIndex++) {
  599. builder = this.valueCount.seriesBuilders[seriesIndex];
  600. // If the builder can be populated with remaining columns, then add it to allBuilders
  601. if (builder.populateColumns(freeIndexes)) {
  602. allSeriesBuilders.push(builder);
  603. }
  604. }
  605. // Populate dynamic series
  606. while (freeIndexes.length > 0) {
  607. builder = new SeriesBuilder();
  608. builder.addColumnReader(0, 'x');
  609. // Mark index as used (not free)
  610. index = inArray(0, freeIndexes);
  611. if (index !== -1) {
  612. freeIndexes.splice(index, 1);
  613. }
  614. for (i = 0; i < this.valueCount.global; i++) {
  615. // Create and add a column reader for the next free column index
  616. builder.addColumnReader(undefined, this.valueCount.globalPointArrayMap[i]);
  617. }
  618. // If the builder can be populated with remaining columns, then add it to allBuilders
  619. if (builder.populateColumns(freeIndexes)) {
  620. allSeriesBuilders.push(builder);
  621. }
  622. }
  623. // Get the data-type from the first series x column
  624. if (allSeriesBuilders.length > 0 && allSeriesBuilders[0].readers.length > 0) {
  625. typeCol = columns[allSeriesBuilders[0].readers[0].columnIndex];
  626. if (typeCol !== undefined) {
  627. if (typeCol.isDatetime) {
  628. type = 'datetime';
  629. } else if (!typeCol.isNumeric) {
  630. type = 'category';
  631. }
  632. }
  633. }
  634. // Axis type is category, then the "x" column should be called "name"
  635. if (type === 'category') {
  636. for (seriesIndex = 0; seriesIndex < allSeriesBuilders.length; seriesIndex++) {
  637. builder = allSeriesBuilders[seriesIndex];
  638. for (r = 0; r < builder.readers.length; r++) {
  639. if (builder.readers[r].configName === 'x') {
  640. builder.readers[r].configName = 'name';
  641. }
  642. }
  643. }
  644. }
  645. // Read data for all builders
  646. for (seriesIndex = 0; seriesIndex < allSeriesBuilders.length; seriesIndex++) {
  647. builder = allSeriesBuilders[seriesIndex];
  648. // Iterate down the cells of each column and add data to the series
  649. data = [];
  650. for (j = 0; j < columns[0].length; j++) {
  651. data[j] = builder.read(columns, j);
  652. }
  653. // Add the series
  654. series[seriesIndex] = {
  655. data: data
  656. };
  657. if (builder.name) {
  658. series[seriesIndex].name = builder.name;
  659. }
  660. if (type === 'category') {
  661. series[seriesIndex].turboThreshold = 0;
  662. }
  663. }
  664. // Do the callback
  665. chartOptions = {
  666. series: series
  667. };
  668. if (type) {
  669. chartOptions.xAxis = {
  670. type: type
  671. };
  672. if (type === 'category') {
  673. chartOptions.xAxis.uniqueNames = false;
  674. }
  675. }
  676. if (options.complete) {
  677. options.complete(chartOptions);
  678. }
  679. // The afterComplete hook is used internally to avoid conflict with the externally
  680. // available complete option.
  681. if (options.afterComplete) {
  682. options.afterComplete(chartOptions);
  683. }
  684. }
  685. }
  686. });
  687. // Register the Data prototype and data function on Highcharts
  688. Highcharts.Data = Data;
  689. Highcharts.data = function(options, chartOptions) {
  690. return new Data(options, chartOptions);
  691. };
  692. // Extend Chart.init so that the Chart constructor accepts a new configuration
  693. // option group, data.
  694. Highcharts.wrap(Highcharts.Chart.prototype, 'init', function(proceed, userOptions, callback) {
  695. var chart = this;
  696. if (userOptions && userOptions.data) {
  697. Highcharts.data(Highcharts.extend(userOptions.data, {
  698. afterComplete: function(dataOptions) {
  699. var i, series;
  700. // Merge series configs
  701. if (userOptions.hasOwnProperty('series')) {
  702. if (typeof userOptions.series === 'object') {
  703. i = Math.max(userOptions.series.length, dataOptions.series.length);
  704. while (i--) {
  705. series = userOptions.series[i] || {};
  706. userOptions.series[i] = Highcharts.merge(series, dataOptions.series[i]);
  707. }
  708. } else { // Allow merging in dataOptions.series (#2856)
  709. delete userOptions.series;
  710. }
  711. }
  712. // Do the merge
  713. userOptions = Highcharts.merge(dataOptions, userOptions);
  714. proceed.call(chart, userOptions, callback);
  715. }
  716. }), userOptions);
  717. } else {
  718. proceed.call(chart, userOptions, callback);
  719. }
  720. });
  721. /**
  722. * Creates a new SeriesBuilder. A SeriesBuilder consists of a number
  723. * of ColumnReaders that reads columns and give them a name.
  724. * Ex: A series builder can be constructed to read column 3 as 'x' and
  725. * column 7 and 8 as 'y1' and 'y2'.
  726. * The output would then be points/rows of the form {x: 11, y1: 22, y2: 33}
  727. *
  728. * The name of the builder is taken from the second column. In the above
  729. * example it would be the column with index 7.
  730. * @constructor
  731. */
  732. SeriesBuilder = function() {
  733. this.readers = [];
  734. this.pointIsArray = true;
  735. };
  736. /**
  737. * Populates readers with column indexes. A reader can be added without
  738. * a specific index and for those readers the index is taken sequentially
  739. * from the free columns (this is handled by the ColumnCursor instance).
  740. * @returns {boolean}
  741. */
  742. SeriesBuilder.prototype.populateColumns = function(freeIndexes) {
  743. var builder = this,
  744. enoughColumns = true;
  745. // Loop each reader and give it an index if its missing.
  746. // The freeIndexes.shift() will return undefined if there
  747. // are no more columns.
  748. each(builder.readers, function(reader) {
  749. if (reader.columnIndex === undefined) {
  750. reader.columnIndex = freeIndexes.shift();
  751. }
  752. });
  753. // Now, all readers should have columns mapped. If not
  754. // then return false to signal that this series should
  755. // not be added.
  756. each(builder.readers, function(reader) {
  757. if (reader.columnIndex === undefined) {
  758. enoughColumns = false;
  759. }
  760. });
  761. return enoughColumns;
  762. };
  763. /**
  764. * Reads a row from the dataset and returns a point or array depending
  765. * on the names of the readers.
  766. * @param columns
  767. * @param rowIndex
  768. * @returns {Array | Object}
  769. */
  770. SeriesBuilder.prototype.read = function(columns, rowIndex) {
  771. var builder = this,
  772. pointIsArray = builder.pointIsArray,
  773. point = pointIsArray ? [] : {},
  774. columnIndexes;
  775. // Loop each reader and ask it to read its value.
  776. // Then, build an array or point based on the readers names.
  777. each(builder.readers, function(reader) {
  778. var value = columns[reader.columnIndex][rowIndex];
  779. if (pointIsArray) {
  780. point.push(value);
  781. } else {
  782. point[reader.configName] = value;
  783. }
  784. });
  785. // The name comes from the first column (excluding the x column)
  786. if (this.name === undefined && builder.readers.length >= 2) {
  787. columnIndexes = builder.getReferencedColumnIndexes();
  788. if (columnIndexes.length >= 2) {
  789. // remove the first one (x col)
  790. columnIndexes.shift();
  791. // Sort the remaining
  792. columnIndexes.sort();
  793. // Now use the lowest index as name column
  794. this.name = columns[columnIndexes.shift()].name;
  795. }
  796. }
  797. return point;
  798. };
  799. /**
  800. * Creates and adds ColumnReader from the given columnIndex and configName.
  801. * ColumnIndex can be undefined and in that case the reader will be given
  802. * an index when columns are populated.
  803. * @param columnIndex {Number | undefined}
  804. * @param configName
  805. */
  806. SeriesBuilder.prototype.addColumnReader = function(columnIndex, configName) {
  807. this.readers.push({
  808. columnIndex: columnIndex,
  809. configName: configName
  810. });
  811. if (!(configName === 'x' || configName === 'y' || configName === undefined)) {
  812. this.pointIsArray = false;
  813. }
  814. };
  815. /**
  816. * Returns an array of column indexes that the builder will use when
  817. * reading data.
  818. * @returns {Array}
  819. */
  820. SeriesBuilder.prototype.getReferencedColumnIndexes = function() {
  821. var i,
  822. referencedColumnIndexes = [],
  823. columnReader;
  824. for (i = 0; i < this.readers.length; i = i + 1) {
  825. columnReader = this.readers[i];
  826. if (columnReader.columnIndex !== undefined) {
  827. referencedColumnIndexes.push(columnReader.columnIndex);
  828. }
  829. }
  830. return referencedColumnIndexes;
  831. };
  832. /**
  833. * Returns true if the builder has a reader for the given configName.
  834. * @param configName
  835. * @returns {boolean}
  836. */
  837. SeriesBuilder.prototype.hasReader = function(configName) {
  838. var i, columnReader;
  839. for (i = 0; i < this.readers.length; i = i + 1) {
  840. columnReader = this.readers[i];
  841. if (columnReader.configName === configName) {
  842. return true;
  843. }
  844. }
  845. // Else return undefined
  846. };
  847. }(Highcharts));
  848. }));