data.src.js 26 KB

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