data.src.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. /**
  2. * @license Data plugin for Highcharts
  3. *
  4. * (c) 2012-2014 Torstein Honsi
  5. *
  6. * License: www.highcharts.com/license
  7. */
  8. /*
  9. * The Highcharts Data plugin is a utility to ease parsing of input sources like
  10. * CSV, HTML tables or grid views into basic configuration options for use
  11. * directly in the Highcharts constructor.
  12. *
  13. * Demo: http://jsfiddle.net/highcharts/SnLFj/
  14. *
  15. * --- OPTIONS ---
  16. *
  17. * - columns : Array<Array<Mixed>>
  18. * A two-dimensional array representing the input data on tabular form. This input can
  19. * be used when the data is already parsed, for example from a grid view component.
  20. * Each cell can be a string or number. If not switchRowsAndColumns is set, the columns
  21. * are interpreted as series. See also the rows option.
  22. *
  23. * - complete : Function(chartOptions)
  24. * The callback that is evaluated when the data is finished loading, optionally from an
  25. * external source, and parsed. The first argument passed is a finished chart options
  26. * object, containing the series. Thise options
  27. * can be extended with additional options and passed directly to the chart constructor. This is
  28. * related to the parsed callback, that goes in at an earlier stage.
  29. *
  30. * - csv : String
  31. * A comma delimited string to be parsed. Related options are startRow, endRow, startColumn
  32. * and endColumn to delimit what part of the table is used. The lineDelimiter and
  33. * itemDelimiter options define the CSV delimiter formats.
  34. *
  35. * - endColumn : Integer
  36. * In tabular input data, the first row (indexed by 0) to use. Defaults to the last
  37. * column containing data.
  38. *
  39. * - endRow : Integer
  40. * In tabular input data, the last row (indexed by 0) to use. Defaults to the last row
  41. * containing data.
  42. *
  43. * - googleSpreadsheetKey : String
  44. * A Google Spreadsheet key. See https://developers.google.com/gdata/samples/spreadsheet_sample
  45. * for general information on GS.
  46. *
  47. * - googleSpreadsheetWorksheet : String
  48. * The Google Spreadsheet worksheet. The available id's can be read from
  49. * https://spreadsheets.google.com/feeds/worksheets/{key}/public/basic
  50. *
  51. * - itemDelimiter : String
  52. * Item or cell delimiter for parsing CSV. Defaults to the tab character "\t" if a tab character
  53. * is found in the CSV string, if not it defaults to ",".
  54. *
  55. * - lineDelimiter : String
  56. * Line delimiter for parsing CSV. Defaults to "\n".
  57. *
  58. * - parsed : Function
  59. * A callback function to access the parsed columns, the two-dimentional input data
  60. * array directly, before they are interpreted into series data and categories. See also
  61. * the complete callback, that goes in on a later stage where the raw columns are interpreted
  62. * into a Highcharts option structure.
  63. *
  64. * - parseDate : Function
  65. * A callback function to parse string representations of dates into JavaScript timestamps.
  66. * Return an integer on success.
  67. *
  68. * - rows : Array<Array<Mixed>>
  69. * The same as the columns input option, but defining rows intead of columns.
  70. *
  71. * - startColumn : Integer
  72. * In tabular input data, the first column (indexed by 0) to use.
  73. *
  74. * - startRow : Integer
  75. * In tabular input data, the first row (indexed by 0) to use.
  76. *
  77. * - switchRowsAndColumns : Boolean
  78. * Switch rows and columns of the input data, so that this.columns effectively becomes the
  79. * rows of the data set, and the rows are interpreted as series.
  80. *
  81. * - table : String|HTMLElement
  82. * A HTML table or the id of such to be parsed as input data. Related options ara startRow,
  83. * endRow, startColumn and endColumn to delimit what part of the table is used.
  84. */
  85. // JSLint options:
  86. /*global jQuery */
  87. (function (Highcharts) { // docs
  88. // Utilities
  89. var each = Highcharts.each;
  90. // The Data constructor
  91. var Data = function (dataOptions, chartOptions) {
  92. this.init(dataOptions, chartOptions);
  93. };
  94. // Set the prototype properties
  95. Highcharts.extend(Data.prototype, {
  96. /**
  97. * Initialize the Data object with the given options
  98. */
  99. init: function (options, chartOptions) {
  100. this.options = options;
  101. this.chartOptions = chartOptions;
  102. this.columns = options.columns || this.rowsToColumns(options.rows) || [];
  103. // No need to parse or interpret anything
  104. if (this.columns.length) {
  105. this.dataFound();
  106. // Parse and interpret
  107. } else {
  108. // Parse a CSV string if options.csv is given
  109. this.parseCSV();
  110. // Parse a HTML table if options.table is given
  111. this.parseTable();
  112. // Parse a Google Spreadsheet
  113. this.parseGoogleSpreadsheet();
  114. }
  115. },
  116. /**
  117. * Get the column distribution. For example, a line series takes a single column for
  118. * Y values. A range series takes two columns for low and high values respectively,
  119. * and an OHLC series takes four columns.
  120. */
  121. getColumnDistribution: function () {
  122. var chartOptions = this.chartOptions,
  123. getValueCount = function (type) {
  124. return (Highcharts.seriesTypes[type || 'line'].prototype.pointArrayMap || [0]).length;
  125. },
  126. globalType = chartOptions && chartOptions.chart && chartOptions.chart.type,
  127. individualCounts = [];
  128. each((chartOptions && chartOptions.series) || [], function (series) {
  129. individualCounts.push(getValueCount(series.type || globalType));
  130. });
  131. this.valueCount = {
  132. global: getValueCount(globalType),
  133. individual: individualCounts
  134. };
  135. },
  136. /**
  137. * When the data is parsed into columns, either by CSV, table, GS or direct input,
  138. * continue with other operations.
  139. */
  140. dataFound: function () {
  141. if (this.options.switchRowsAndColumns) {
  142. this.columns = this.rowsToColumns(this.columns);
  143. }
  144. // Interpret the values into right types
  145. this.parseTypes();
  146. // Use first row for series names?
  147. this.findHeaderRow();
  148. // Handle columns if a handleColumns callback is given
  149. this.parsed();
  150. // Complete if a complete callback is given
  151. this.complete();
  152. },
  153. /**
  154. * Parse a CSV input string
  155. */
  156. parseCSV: function () {
  157. var self = this,
  158. options = this.options,
  159. csv = options.csv,
  160. columns = this.columns,
  161. startRow = options.startRow || 0,
  162. endRow = options.endRow || Number.MAX_VALUE,
  163. startColumn = options.startColumn || 0,
  164. endColumn = options.endColumn || Number.MAX_VALUE,
  165. itemDelimiter,
  166. lines,
  167. activeRowNo = 0;
  168. if (csv) {
  169. lines = csv
  170. .replace(/\r\n/g, "\n") // Unix
  171. .replace(/\r/g, "\n") // Mac
  172. .split(options.lineDelimiter || "\n");
  173. itemDelimiter = options.itemDelimiter || (csv.indexOf('\t') !== -1 ? '\t' : ',');
  174. each(lines, function (line, rowNo) {
  175. var trimmed = self.trim(line),
  176. isComment = trimmed.indexOf('#') === 0,
  177. isBlank = trimmed === '',
  178. items;
  179. if (rowNo >= startRow && rowNo <= endRow && !isComment && !isBlank) {
  180. items = line.split(itemDelimiter);
  181. each(items, function (item, colNo) {
  182. if (colNo >= startColumn && colNo <= endColumn) {
  183. if (!columns[colNo - startColumn]) {
  184. columns[colNo - startColumn] = [];
  185. }
  186. columns[colNo - startColumn][activeRowNo] = item;
  187. }
  188. });
  189. activeRowNo += 1;
  190. }
  191. });
  192. this.dataFound();
  193. }
  194. },
  195. /**
  196. * Parse a HTML table
  197. */
  198. parseTable: function () {
  199. var options = this.options,
  200. table = options.table,
  201. columns = this.columns,
  202. startRow = options.startRow || 0,
  203. endRow = options.endRow || Number.MAX_VALUE,
  204. startColumn = options.startColumn || 0,
  205. endColumn = options.endColumn || Number.MAX_VALUE;
  206. if (table) {
  207. if (typeof table === 'string') {
  208. table = document.getElementById(table);
  209. }
  210. each(table.getElementsByTagName('tr'), function (tr, rowNo) {
  211. if (rowNo >= startRow && rowNo <= endRow) {
  212. each(tr.children, function (item, colNo) {
  213. if ((item.tagName === 'TD' || item.tagName === 'TH') && colNo >= startColumn && colNo <= endColumn) {
  214. if (!columns[colNo - startColumn]) {
  215. columns[colNo - startColumn] = [];
  216. }
  217. columns[colNo - startColumn][rowNo - startRow] = item.innerHTML;
  218. }
  219. });
  220. }
  221. });
  222. this.dataFound(); // continue
  223. }
  224. },
  225. /**
  226. */
  227. parseGoogleSpreadsheet: function () {
  228. var self = this,
  229. options = this.options,
  230. googleSpreadsheetKey = options.googleSpreadsheetKey,
  231. columns = this.columns,
  232. startRow = options.startRow || 0,
  233. endRow = options.endRow || Number.MAX_VALUE,
  234. startColumn = options.startColumn || 0,
  235. endColumn = options.endColumn || Number.MAX_VALUE,
  236. gr, // google row
  237. gc; // google column
  238. if (googleSpreadsheetKey) {
  239. jQuery.ajax({
  240. dataType: 'json',
  241. url: 'https://spreadsheets.google.com/feeds/cells/' +
  242. googleSpreadsheetKey + '/' + (options.googleSpreadsheetWorksheet || 'od6') +
  243. '/public/values?alt=json-in-script&callback=?',
  244. error: options.error,
  245. success: function (json) {
  246. // Prepare the data from the spreadsheat
  247. var cells = json.feed.entry,
  248. cell,
  249. cellCount = cells.length,
  250. colCount = 0,
  251. rowCount = 0,
  252. i;
  253. // First, find the total number of columns and rows that
  254. // are actually filled with data
  255. for (i = 0; i < cellCount; i++) {
  256. cell = cells[i];
  257. colCount = Math.max(colCount, cell.gs$cell.col);
  258. rowCount = Math.max(rowCount, cell.gs$cell.row);
  259. }
  260. // Set up arrays containing the column data
  261. for (i = 0; i < colCount; i++) {
  262. if (i >= startColumn && i <= endColumn) {
  263. // Create new columns with the length of either end-start or rowCount
  264. columns[i - startColumn] = [];
  265. // Setting the length to avoid jslint warning
  266. columns[i - startColumn].length = Math.min(rowCount, endRow - startRow);
  267. }
  268. }
  269. // Loop over the cells and assign the value to the right
  270. // place in the column arrays
  271. for (i = 0; i < cellCount; i++) {
  272. cell = cells[i];
  273. gr = cell.gs$cell.row - 1; // rows start at 1
  274. gc = cell.gs$cell.col - 1; // columns start at 1
  275. // If both row and col falls inside start and end
  276. // set the transposed cell value in the newly created columns
  277. if (gc >= startColumn && gc <= endColumn &&
  278. gr >= startRow && gr <= endRow) {
  279. columns[gc - startColumn][gr - startRow] = cell.content.$t;
  280. }
  281. }
  282. self.dataFound();
  283. }
  284. });
  285. }
  286. },
  287. /**
  288. * Find the header row. For now, we just check whether the first row contains
  289. * numbers or strings. Later we could loop down and find the first row with
  290. * numbers.
  291. */
  292. findHeaderRow: function () {
  293. var headerRow = 0;
  294. each(this.columns, function (column) {
  295. if (typeof column[0] !== 'string') {
  296. headerRow = null;
  297. }
  298. });
  299. this.headerRow = 0;
  300. },
  301. /**
  302. * Trim a string from whitespace
  303. */
  304. trim: function (str) {
  305. return typeof str === 'string' ? str.replace(/^\s+|\s+$/g, '') : str;
  306. },
  307. /**
  308. * Parse numeric cells in to number types and date types in to true dates.
  309. */
  310. parseTypes: function () {
  311. var columns = this.columns,
  312. col = columns.length,
  313. row,
  314. val,
  315. floatVal,
  316. trimVal,
  317. dateVal;
  318. while (col--) {
  319. row = columns[col].length;
  320. while (row--) {
  321. val = columns[col][row];
  322. floatVal = parseFloat(val);
  323. trimVal = this.trim(val);
  324. /*jslint eqeq: true*/
  325. if (trimVal == floatVal) { // is numeric
  326. /*jslint eqeq: false*/
  327. columns[col][row] = floatVal;
  328. // If the number is greater than milliseconds in a year, assume datetime
  329. if (floatVal > 365 * 24 * 3600 * 1000) {
  330. columns[col].isDatetime = true;
  331. } else {
  332. columns[col].isNumeric = true;
  333. }
  334. } else { // string, continue to determine if it is a date string or really a string
  335. dateVal = this.parseDate(val);
  336. if (col === 0 && typeof dateVal === 'number' && !isNaN(dateVal)) { // is date
  337. columns[col][row] = dateVal;
  338. columns[col].isDatetime = true;
  339. } else { // string
  340. columns[col][row] = trimVal === '' ? null : trimVal;
  341. }
  342. }
  343. }
  344. }
  345. },
  346. /**
  347. * A collection of available date formats, extendable from the outside to support
  348. * custom date formats.
  349. */
  350. dateFormats: {
  351. 'YYYY-mm-dd': {
  352. regex: '^([0-9]{4})-([0-9]{2})-([0-9]{2})$',
  353. parser: function (match) {
  354. return Date.UTC(+match[1], match[2] - 1, +match[3]);
  355. }
  356. }
  357. },
  358. /**
  359. * Parse a date and return it as a number. Overridable through options.parseDate.
  360. */
  361. parseDate: function (val) {
  362. var parseDate = this.options.parseDate,
  363. ret,
  364. key,
  365. format,
  366. match;
  367. if (parseDate) {
  368. ret = parseDate(val);
  369. }
  370. if (typeof val === 'string') {
  371. for (key in this.dateFormats) {
  372. format = this.dateFormats[key];
  373. match = val.match(format.regex);
  374. if (match) {
  375. ret = format.parser(match);
  376. }
  377. }
  378. }
  379. return ret;
  380. },
  381. /**
  382. * Reorganize rows into columns
  383. */
  384. rowsToColumns: function (rows) {
  385. var row,
  386. rowsLength,
  387. col,
  388. colsLength,
  389. columns;
  390. if (rows) {
  391. columns = [];
  392. rowsLength = rows.length;
  393. for (row = 0; row < rowsLength; row++) {
  394. colsLength = rows[row].length;
  395. for (col = 0; col < colsLength; col++) {
  396. if (!columns[col]) {
  397. columns[col] = [];
  398. }
  399. columns[col][row] = rows[row][col];
  400. }
  401. }
  402. }
  403. return columns;
  404. },
  405. /**
  406. * A hook for working directly on the parsed columns
  407. */
  408. parsed: function () {
  409. if (this.options.parsed) {
  410. this.options.parsed.call(this, this.columns);
  411. }
  412. },
  413. /**
  414. * If a complete callback function is provided in the options, interpret the
  415. * columns into a Highcharts options object.
  416. */
  417. complete: function () {
  418. var columns = this.columns,
  419. firstCol,
  420. type,
  421. options = this.options,
  422. valueCount,
  423. series,
  424. data,
  425. i,
  426. j,
  427. seriesIndex,
  428. chartOptions;
  429. if (options.complete || options.afterComplete) {
  430. this.getColumnDistribution();
  431. // Use first column for X data or categories?
  432. if (columns.length > 1) {
  433. firstCol = columns.shift();
  434. if (this.headerRow === 0) {
  435. firstCol.shift(); // remove the first cell
  436. }
  437. if (firstCol.isDatetime) {
  438. type = 'datetime';
  439. } else if (!firstCol.isNumeric) {
  440. type = 'category';
  441. }
  442. }
  443. // Get the names and shift the top row
  444. for (i = 0; i < columns.length; i++) {
  445. if (this.headerRow === 0) {
  446. columns[i].name = columns[i].shift();
  447. }
  448. }
  449. // Use the next columns for series
  450. series = [];
  451. for (i = 0, seriesIndex = 0; i < columns.length; seriesIndex++) {
  452. // This series' value count
  453. valueCount = Highcharts.pick(this.valueCount.individual[seriesIndex], this.valueCount.global);
  454. // Iterate down the cells of each column and add data to the series
  455. data = [];
  456. // Only loop and fill the data series if there are columns available.
  457. // We need this check to avoid reading outside the array bounds.
  458. if (i + valueCount <= columns.length) {
  459. for (j = 0; j < columns[i].length; j++) {
  460. data[j] = [
  461. firstCol[j],
  462. columns[i][j] !== undefined ? columns[i][j] : null
  463. ];
  464. if (valueCount > 1) {
  465. data[j].push(columns[i + 1][j] !== undefined ? columns[i + 1][j] : null);
  466. }
  467. if (valueCount > 2) {
  468. data[j].push(columns[i + 2][j] !== undefined ? columns[i + 2][j] : null);
  469. }
  470. if (valueCount > 3) {
  471. data[j].push(columns[i + 3][j] !== undefined ? columns[i + 3][j] : null);
  472. }
  473. if (valueCount > 4) {
  474. data[j].push(columns[i + 4][j] !== undefined ? columns[i + 4][j] : null);
  475. }
  476. }
  477. }
  478. // Add the series
  479. series[seriesIndex] = {
  480. name: columns[i].name,
  481. data: data
  482. };
  483. i += valueCount;
  484. }
  485. // Do the callback
  486. chartOptions = {
  487. xAxis: {
  488. type: type
  489. },
  490. series: series
  491. };
  492. if (options.complete) {
  493. options.complete(chartOptions);
  494. }
  495. // The afterComplete hook is used internally to avoid conflict with the externally
  496. // available complete option.
  497. if (options.afterComplete) {
  498. options.afterComplete(chartOptions);
  499. }
  500. }
  501. }
  502. });
  503. // Register the Data prototype and data function on Highcharts
  504. Highcharts.Data = Data;
  505. Highcharts.data = function (options, chartOptions) {
  506. return new Data(options, chartOptions);
  507. };
  508. // Extend Chart.init so that the Chart constructor accepts a new configuration
  509. // option group, data.
  510. Highcharts.wrap(Highcharts.Chart.prototype, 'init', function (proceed, userOptions, callback) {
  511. var chart = this;
  512. if (userOptions && userOptions.data) {
  513. Highcharts.data(Highcharts.extend(userOptions.data, {
  514. afterComplete: function (dataOptions) {
  515. var i, series;
  516. // Merge series configs
  517. if (userOptions.hasOwnProperty('series')) {
  518. if (typeof userOptions.series === 'object') {
  519. i = Math.max(userOptions.series.length, dataOptions.series.length);
  520. while (i--) {
  521. series = userOptions.series[i] || {};
  522. userOptions.series[i] = Highcharts.merge(series, dataOptions.series[i]);
  523. }
  524. } else { // Allow merging in dataOptions.series (#2856)
  525. delete userOptions.series;
  526. }
  527. }
  528. // Do the merge
  529. userOptions = Highcharts.merge(dataOptions, userOptions);
  530. proceed.call(chart, userOptions, callback);
  531. }
  532. }), userOptions);
  533. } else {
  534. proceed.call(chart, userOptions, callback);
  535. }
  536. });
  537. }(Highcharts));