44acf9945fa88e3d80c2bc7201d55b236aaa6124.svn-base 27 KB

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