export-data.src.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  1. /* *
  2. *
  3. * Experimental data export module for Highcharts
  4. *
  5. * (c) 2010-2019 Torstein Honsi
  6. *
  7. * License: www.highcharts.com/license
  8. *
  9. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  10. *
  11. * */
  12. // @todo
  13. // - Set up systematic tests for all series types, paired with tests of the data
  14. // module importing the same data.
  15. 'use strict';
  16. import Highcharts from '../parts/Globals.js';
  17. /**
  18. * Function callback to execute while data rows are processed for exporting.
  19. * This allows the modification of data rows before processed into the final
  20. * format.
  21. *
  22. * @callback Highcharts.ExportDataCallbackFunction
  23. * @extends Highcharts.EventCallbackFunction<Highcharts.Chart>
  24. *
  25. * @param {Highcharts.Chart} this
  26. * Chart context where the event occured.
  27. *
  28. * @param {Highcharts.ExportDataEventObject} event
  29. * Event object with data rows that can be modified.
  30. */
  31. /**
  32. * Contains information about the export data event.
  33. *
  34. * @interface Highcharts.ExportDataEventObject
  35. */ /**
  36. * Contains the data rows for the current export task and can be modified.
  37. * @name Highcharts.ExportDataEventObject#dataRows
  38. * @type {Array<Array<string>>}
  39. */
  40. import U from '../parts/Utilities.js';
  41. var defined = U.defined, extend = U.extend, isObject = U.isObject, pick = U.pick;
  42. import '../parts/Chart.js';
  43. import '../mixins/ajax.js';
  44. import '../mixins/download-url.js';
  45. var win = Highcharts.win, doc = win.document, seriesTypes = Highcharts.seriesTypes, downloadURL = Highcharts.downloadURL, fireEvent = Highcharts.fireEvent;
  46. // Can we add this to utils? Also used in screen-reader.js
  47. /**
  48. * HTML encode some characters vulnerable for XSS.
  49. * @private
  50. * @param {string} html The input string
  51. * @return {string} The excaped string
  52. */
  53. function htmlencode(html) {
  54. return html
  55. .replace(/&/g, '&amp;')
  56. .replace(/</g, '&lt;')
  57. .replace(/>/g, '&gt;')
  58. .replace(/"/g, '&quot;')
  59. .replace(/'/g, '&#x27;')
  60. .replace(/\//g, '&#x2F;');
  61. }
  62. Highcharts.setOptions({
  63. /**
  64. * Callback that fires while exporting data. This allows the modification of
  65. * data rows before processed into the final format.
  66. *
  67. * @type {Highcharts.ExportDataCallbackFunction}
  68. * @context Highcharts.Chart
  69. * @requires modules/export-data
  70. * @apioption chart.events.exportData
  71. */
  72. /**
  73. * When set to `false` will prevent the series data from being included in
  74. * any form of data export.
  75. *
  76. * Since version 6.0.0 until 7.1.0 the option was existing undocumented
  77. * as `includeInCSVExport`.
  78. *
  79. * @type {boolean}
  80. * @since 7.1.0
  81. * @requires modules/export-data
  82. * @apioption plotOptions.series.includeInDataExport
  83. */
  84. /**
  85. * @optionparent exporting
  86. * @private
  87. */
  88. exporting: {
  89. /**
  90. * Caption for the data table. Same as chart title by default. Set to
  91. * `false` to disable.
  92. *
  93. * @sample highcharts/export-data/multilevel-table
  94. * Multiple table headers
  95. *
  96. * @type {boolean|string}
  97. * @since 6.0.4
  98. * @requires modules/export-data
  99. * @apioption exporting.tableCaption
  100. */
  101. /**
  102. * Options for exporting data to CSV or ExCel, or displaying the data
  103. * in a HTML table or a JavaScript structure.
  104. *
  105. * This module adds data export options to the export menu and provides
  106. * functions like `Chart.getCSV`, `Chart.getTable`, `Chart.getDataRows`
  107. * and `Chart.viewData`.
  108. *
  109. * The XLS converter is limited and only creates a HTML string that is
  110. * passed for download, which works but creates a warning before
  111. * opening. The workaround for this is to use a third party XLSX
  112. * converter, as demonstrated in the sample below.
  113. *
  114. * @sample highcharts/export-data/categorized/ Categorized data
  115. * @sample highcharts/export-data/stock-timeaxis/ Highstock time axis
  116. * @sample highcharts/export-data/xlsx/
  117. * Using a third party XLSX converter
  118. *
  119. * @since 6.0.0
  120. * @requires modules/export-data
  121. */
  122. csv: {
  123. /**
  124. * Formatter callback for the column headers. Parameters are:
  125. * - `item` - The series or axis object)
  126. * - `key` - The point key, for example y or z
  127. * - `keyLength` - The amount of value keys for this item, for
  128. * example a range series has the keys `low` and `high` so the
  129. * key length is 2.
  130. *
  131. * If [useMultiLevelHeaders](#exporting.useMultiLevelHeaders) is
  132. * true, columnHeaderFormatter by default returns an object with
  133. * columnTitle and topLevelColumnTitle for each key. Columns with
  134. * the same topLevelColumnTitle have their titles merged into a
  135. * single cell with colspan for table/Excel export.
  136. *
  137. * If `useMultiLevelHeaders` is false, or for CSV export, it returns
  138. * the series name, followed by the key if there is more than one
  139. * key.
  140. *
  141. * For the axis it returns the axis title or "Category" or
  142. * "DateTime" by default.
  143. *
  144. * Return `false` to use Highcharts' proposed header.
  145. *
  146. * @sample highcharts/export-data/multilevel-table
  147. * Multiple table headers
  148. *
  149. * @type {Function|null}
  150. */
  151. columnHeaderFormatter: null,
  152. /**
  153. * Which date format to use for exported dates on a datetime X axis.
  154. * See `Highcharts.dateFormat`.
  155. */
  156. dateFormat: '%Y-%m-%d %H:%M:%S',
  157. /**
  158. * Which decimal point to use for exported CSV. Defaults to the same
  159. * as the browser locale, typically `.` (English) or `,` (German,
  160. * French etc).
  161. *
  162. * @type {string|null}
  163. * @since 6.0.4
  164. */
  165. decimalPoint: null,
  166. /**
  167. * The item delimiter in the exported data. Use `;` for direct
  168. * exporting to Excel. Defaults to a best guess based on the browser
  169. * locale. If the locale _decimal point_ is `,`, the `itemDelimiter`
  170. * defaults to `;`, otherwise the `itemDelimiter` defaults to `,`.
  171. *
  172. * @type {string|null}
  173. */
  174. itemDelimiter: null,
  175. /**
  176. * The line delimiter in the exported data, defaults to a newline.
  177. */
  178. lineDelimiter: '\n'
  179. },
  180. /**
  181. * Show a HTML table below the chart with the chart's current data.
  182. *
  183. * @sample highcharts/export-data/showtable/
  184. * Show the table
  185. * @sample highcharts/studies/exporting-table-html
  186. * Experiment with putting the table inside the subtitle to
  187. * allow exporting it.
  188. *
  189. * @since 6.0.0
  190. * @requires modules/export-data
  191. */
  192. showTable: false,
  193. /**
  194. * Use multi level headers in data table. If [csv.columnHeaderFormatter
  195. * ](#exporting.csv.columnHeaderFormatter) is defined, it has to return
  196. * objects in order for multi level headers to work.
  197. *
  198. * @sample highcharts/export-data/multilevel-table
  199. * Multiple table headers
  200. *
  201. * @since 6.0.4
  202. * @requires modules/export-data
  203. */
  204. useMultiLevelHeaders: true,
  205. /**
  206. * If using multi level table headers, use rowspans for headers that
  207. * have only one level.
  208. *
  209. * @sample highcharts/export-data/multilevel-table
  210. * Multiple table headers
  211. *
  212. * @since 6.0.4
  213. * @requires modules/export-data
  214. */
  215. useRowspanHeaders: true
  216. },
  217. /**
  218. * @optionparent lang
  219. *
  220. * @private
  221. */
  222. lang: {
  223. /**
  224. * The text for the menu item.
  225. *
  226. * @since 6.0.0
  227. * @requires modules/export-data
  228. */
  229. downloadCSV: 'Download CSV',
  230. /**
  231. * The text for the menu item.
  232. *
  233. * @since 6.0.0
  234. * @requires modules/export-data
  235. */
  236. downloadXLS: 'Download XLS',
  237. /**
  238. * The text for the menu item.
  239. *
  240. * @since 6.1.0
  241. * @requires modules/export-data
  242. */
  243. openInCloud: 'Open in Highcharts Cloud',
  244. /**
  245. * The text for the menu item.
  246. *
  247. * @since 6.0.0
  248. * @requires modules/export-data
  249. */
  250. viewData: 'View data table'
  251. }
  252. });
  253. /* eslint-disable no-invalid-this */
  254. // Add an event listener to handle the showTable option
  255. Highcharts.addEvent(Highcharts.Chart, 'render', function () {
  256. if (this.options &&
  257. this.options.exporting &&
  258. this.options.exporting.showTable &&
  259. !this.options.chart.forExport) {
  260. this.viewData();
  261. }
  262. });
  263. /* eslint-enable no-invalid-this */
  264. /**
  265. * Set up key-to-axis bindings. This is used when the Y axis is datetime or
  266. * categorized. For example in an arearange series, the low and high values
  267. * should be formatted according to the Y axis type, and in order to link them
  268. * we need this map.
  269. *
  270. * @private
  271. * @function Highcharts.Chart#setUpKeyToAxis
  272. * @return {void}
  273. */
  274. Highcharts.Chart.prototype.setUpKeyToAxis = function () {
  275. if (seriesTypes.arearange) {
  276. seriesTypes.arearange.prototype.keyToAxis = {
  277. low: 'y',
  278. high: 'y'
  279. };
  280. }
  281. if (seriesTypes.gantt) {
  282. seriesTypes.gantt.prototype.keyToAxis = {
  283. start: 'x',
  284. end: 'x'
  285. };
  286. }
  287. };
  288. /**
  289. * Export-data module required. Returns a two-dimensional array containing the
  290. * current chart data.
  291. *
  292. * @function Highcharts.Chart#getDataRows
  293. *
  294. * @param {boolean} [multiLevelHeaders]
  295. * Use multilevel headers for the rows by default. Adds an extra row with
  296. * top level headers. If a custom columnHeaderFormatter is defined, this
  297. * can override the behavior.
  298. *
  299. * @return {Array<Array<(number|string)>>}
  300. * The current chart data
  301. *
  302. * @fires Highcharts.Chart#event:exportData
  303. */
  304. Highcharts.Chart.prototype.getDataRows = function (multiLevelHeaders) {
  305. var hasParallelCoords = this.hasParallelCoordinates, time = this.time, csvOptions = ((this.options.exporting && this.options.exporting.csv) || {}), xAxis, xAxes = this.xAxis, rows = {}, rowArr = [], dataRows, topLevelColumnTitles = [], columnTitles = [], columnTitleObj, i, x, xTitle,
  306. // Options
  307. columnHeaderFormatter = function (item, key, keyLength) {
  308. if (csvOptions.columnHeaderFormatter) {
  309. var s = csvOptions.columnHeaderFormatter(item, key, keyLength);
  310. if (s !== false) {
  311. return s;
  312. }
  313. }
  314. if (!item) {
  315. return 'Category';
  316. }
  317. if (item instanceof Highcharts.Axis) {
  318. return (item.options.title && item.options.title.text) ||
  319. (item.isDatetimeAxis ? 'DateTime' : 'Category');
  320. }
  321. if (multiLevelHeaders) {
  322. return {
  323. columnTitle: keyLength > 1 ?
  324. key :
  325. item.name,
  326. topLevelColumnTitle: item.name
  327. };
  328. }
  329. return item.name + (keyLength > 1 ? ' (' + key + ')' : '');
  330. },
  331. // Map the categories for value axes
  332. getCategoryAndDateTimeMap = function (series, pointArrayMap, pIdx) {
  333. var categoryMap = {}, dateTimeValueAxisMap = {};
  334. pointArrayMap.forEach(function (prop) {
  335. var axisName = ((series.keyToAxis && series.keyToAxis[prop]) ||
  336. prop) + 'Axis',
  337. // Points in parallel coordinates refers to all yAxis
  338. // not only `series.yAxis`
  339. axis = Highcharts.isNumber(pIdx) ?
  340. series.chart[axisName][pIdx] :
  341. series[axisName];
  342. categoryMap[prop] = (axis && axis.categories) || [];
  343. dateTimeValueAxisMap[prop] = (axis && axis.isDatetimeAxis);
  344. });
  345. return {
  346. categoryMap: categoryMap,
  347. dateTimeValueAxisMap: dateTimeValueAxisMap
  348. };
  349. }, xAxisIndices = [];
  350. // Loop the series and index values
  351. i = 0;
  352. this.setUpKeyToAxis();
  353. this.series.forEach(function (series) {
  354. var keys = series.options.keys, pointArrayMap = keys || series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, xTaken = !series.requireSorting && {}, xAxisIndex = xAxes.indexOf(series.xAxis), categoryAndDatetimeMap = getCategoryAndDateTimeMap(series, pointArrayMap), mockSeries, j;
  355. if (series.options.includeInDataExport !== false &&
  356. !series.options.isInternal &&
  357. series.visible !== false // #55
  358. ) {
  359. // Build a lookup for X axis index and the position of the first
  360. // series that belongs to that X axis. Includes -1 for non-axis
  361. // series types like pies.
  362. if (!Highcharts.find(xAxisIndices, function (index) {
  363. return index[0] === xAxisIndex;
  364. })) {
  365. xAxisIndices.push([xAxisIndex, i]);
  366. }
  367. // Compute the column headers and top level headers, usually the
  368. // same as series names
  369. j = 0;
  370. while (j < valueCount) {
  371. columnTitleObj = columnHeaderFormatter(series, pointArrayMap[j], pointArrayMap.length);
  372. columnTitles.push(columnTitleObj.columnTitle || columnTitleObj);
  373. if (multiLevelHeaders) {
  374. topLevelColumnTitles.push(columnTitleObj.topLevelColumnTitle ||
  375. columnTitleObj);
  376. }
  377. j++;
  378. }
  379. mockSeries = {
  380. chart: series.chart,
  381. autoIncrement: series.autoIncrement,
  382. options: series.options,
  383. pointArrayMap: series.pointArrayMap
  384. };
  385. // Export directly from options.data because we need the uncropped
  386. // data (#7913), and we need to support Boost (#7026).
  387. series.options.data.forEach(function eachData(options, pIdx) {
  388. var key, prop, val, name, point;
  389. // In parallel coordinates chart, each data point is connected
  390. // to a separate yAxis, conform this
  391. if (hasParallelCoords) {
  392. categoryAndDatetimeMap = getCategoryAndDateTimeMap(series, pointArrayMap, pIdx);
  393. }
  394. point = { series: mockSeries };
  395. series.pointClass.prototype.applyOptions.apply(point, [options]);
  396. key = point.x;
  397. name = series.data[pIdx] && series.data[pIdx].name;
  398. j = 0;
  399. // Pies, funnels, geo maps etc. use point name in X row
  400. if (!series.xAxis || series.exportKey === 'name') {
  401. key = name;
  402. }
  403. if (xTaken) {
  404. if (xTaken[key]) {
  405. key += '|' + pIdx;
  406. }
  407. xTaken[key] = true;
  408. }
  409. if (!rows[key]) {
  410. // Generate the row
  411. rows[key] = [];
  412. // Contain the X values from one or more X axes
  413. rows[key].xValues = [];
  414. }
  415. rows[key].x = point.x;
  416. rows[key].name = name;
  417. rows[key].xValues[xAxisIndex] = point.x;
  418. while (j < valueCount) {
  419. prop = pointArrayMap[j]; // y, z etc
  420. val = point[prop];
  421. rows[key][i + j] = pick(
  422. // Y axis category if present
  423. categoryAndDatetimeMap.categoryMap[prop][val],
  424. // datetime yAxis
  425. categoryAndDatetimeMap.dateTimeValueAxisMap[prop] ?
  426. time.dateFormat(csvOptions.dateFormat, val) :
  427. null,
  428. // linear/log yAxis
  429. val);
  430. j++;
  431. }
  432. });
  433. i = i + j;
  434. }
  435. });
  436. // Make a sortable array
  437. for (x in rows) {
  438. if (Object.hasOwnProperty.call(rows, x)) {
  439. rowArr.push(rows[x]);
  440. }
  441. }
  442. var xAxisIndex, column;
  443. // Add computed column headers and top level headers to final row set
  444. dataRows = multiLevelHeaders ? [topLevelColumnTitles, columnTitles] :
  445. [columnTitles];
  446. i = xAxisIndices.length;
  447. while (i--) { // Start from end to splice in
  448. xAxisIndex = xAxisIndices[i][0];
  449. column = xAxisIndices[i][1];
  450. xAxis = xAxes[xAxisIndex];
  451. // Sort it by X values
  452. rowArr.sort(function (// eslint-disable-line no-loop-func
  453. a, b) {
  454. return a.xValues[xAxisIndex] - b.xValues[xAxisIndex];
  455. });
  456. // Add header row
  457. xTitle = columnHeaderFormatter(xAxis);
  458. dataRows[0].splice(column, 0, xTitle);
  459. if (multiLevelHeaders && dataRows[1]) {
  460. // If using multi level headers, we just added top level header.
  461. // Also add for sub level
  462. dataRows[1].splice(column, 0, xTitle);
  463. }
  464. // Add the category column
  465. rowArr.forEach(function (// eslint-disable-line no-loop-func
  466. row) {
  467. var category = row.name;
  468. if (xAxis && !defined(category)) {
  469. if (xAxis.isDatetimeAxis) {
  470. if (row.x instanceof Date) {
  471. row.x = row.x.getTime();
  472. }
  473. category = time.dateFormat(csvOptions.dateFormat, row.x);
  474. }
  475. else if (xAxis.categories) {
  476. category = pick(xAxis.names[row.x], xAxis.categories[row.x], row.x);
  477. }
  478. else {
  479. category = row.x;
  480. }
  481. }
  482. // Add the X/date/category
  483. row.splice(column, 0, category);
  484. });
  485. }
  486. dataRows = dataRows.concat(rowArr);
  487. fireEvent(this, 'exportData', { dataRows: dataRows });
  488. return dataRows;
  489. };
  490. /**
  491. * Export-data module required. Returns the current chart data as a CSV string.
  492. *
  493. * @function Highcharts.Chart#getCSV
  494. *
  495. * @param {boolean} [useLocalDecimalPoint]
  496. * Whether to use the local decimal point as detected from the browser.
  497. * This makes it easier to export data to Excel in the same locale as the
  498. * user is.
  499. *
  500. * @return {string}
  501. * CSV representation of the data
  502. */
  503. Highcharts.Chart.prototype.getCSV = function (useLocalDecimalPoint) {
  504. var csv = '', rows = this.getDataRows(), csvOptions = this.options.exporting.csv, decimalPoint = pick(csvOptions.decimalPoint, csvOptions.itemDelimiter !== ',' && useLocalDecimalPoint ?
  505. (1.1).toLocaleString()[1] :
  506. '.'),
  507. // use ';' for direct to Excel
  508. itemDelimiter = pick(csvOptions.itemDelimiter, decimalPoint === ',' ? ';' : ','),
  509. // '\n' isn't working with the js csv data extraction
  510. lineDelimiter = csvOptions.lineDelimiter;
  511. // Transform the rows to CSV
  512. rows.forEach(function (row, i) {
  513. var val = '', j = row.length;
  514. while (j--) {
  515. val = row[j];
  516. if (typeof val === 'string') {
  517. val = '"' + val + '"';
  518. }
  519. if (typeof val === 'number') {
  520. if (decimalPoint !== '.') {
  521. val = val.toString().replace('.', decimalPoint);
  522. }
  523. }
  524. row[j] = val;
  525. }
  526. // Add the values
  527. csv += row.join(itemDelimiter);
  528. // Add the line delimiter
  529. if (i < rows.length - 1) {
  530. csv += lineDelimiter;
  531. }
  532. });
  533. return csv;
  534. };
  535. /**
  536. * Export-data module required. Build a HTML table with the chart's current
  537. * data.
  538. *
  539. * @sample highcharts/export-data/viewdata/
  540. * View the data from the export menu
  541. *
  542. * @function Highcharts.Chart#getTable
  543. *
  544. * @param {boolean} [useLocalDecimalPoint]
  545. * Whether to use the local decimal point as detected from the browser.
  546. * This makes it easier to export data to Excel in the same locale as the
  547. * user is.
  548. *
  549. * @return {string}
  550. * HTML representation of the data.
  551. *
  552. * @fires Highcharts.Chart#event:afterGetTable
  553. */
  554. Highcharts.Chart.prototype.getTable = function (useLocalDecimalPoint) {
  555. var html = '<table id="highcharts-data-table-' + this.index + '">', options = this.options, decimalPoint = useLocalDecimalPoint ? (1.1).toLocaleString()[1] : '.', useMultiLevelHeaders = pick(options.exporting.useMultiLevelHeaders, true), rows = this.getDataRows(useMultiLevelHeaders), rowLength = 0, topHeaders = useMultiLevelHeaders ? rows.shift() : null, subHeaders = rows.shift(),
  556. // Compare two rows for equality
  557. isRowEqual = function (row1, row2) {
  558. var i = row1.length;
  559. if (row2.length === i) {
  560. while (i--) {
  561. if (row1[i] !== row2[i]) {
  562. return false;
  563. }
  564. }
  565. }
  566. else {
  567. return false;
  568. }
  569. return true;
  570. },
  571. // Get table cell HTML from value
  572. getCellHTMLFromValue = function (tag, classes, attrs, value) {
  573. var val = pick(value, ''), className = 'text' + (classes ? ' ' + classes : '');
  574. // Convert to string if number
  575. if (typeof val === 'number') {
  576. val = val.toString();
  577. if (decimalPoint === ',') {
  578. val = val.replace('.', decimalPoint);
  579. }
  580. className = 'number';
  581. }
  582. else if (!value) {
  583. className = 'empty';
  584. }
  585. return '<' + tag + (attrs ? ' ' + attrs : '') +
  586. ' class="' + className + '">' +
  587. val + '</' + tag + '>';
  588. },
  589. // Get table header markup from row data
  590. getTableHeaderHTML = function (topheaders, subheaders, rowLength) {
  591. var html = '<thead>', i = 0, len = rowLength || subheaders && subheaders.length, next, cur, curColspan = 0, rowspan;
  592. // Clean up multiple table headers. Chart.getDataRows() returns two
  593. // levels of headers when using multilevel, not merged. We need to
  594. // merge identical headers, remove redundant headers, and keep it
  595. // all marked up nicely.
  596. if (useMultiLevelHeaders &&
  597. topheaders &&
  598. subheaders &&
  599. !isRowEqual(topheaders, subheaders)) {
  600. html += '<tr>';
  601. for (; i < len; ++i) {
  602. cur = topheaders[i];
  603. next = topheaders[i + 1];
  604. if (cur === next) {
  605. ++curColspan;
  606. }
  607. else if (curColspan) {
  608. // Ended colspan
  609. // Add cur to HTML with colspan.
  610. html += getCellHTMLFromValue('th', 'highcharts-table-topheading', 'scope="col" ' +
  611. 'colspan="' + (curColspan + 1) + '"', cur);
  612. curColspan = 0;
  613. }
  614. else {
  615. // Cur is standalone. If it is same as sublevel,
  616. // remove sublevel and add just toplevel.
  617. if (cur === subheaders[i]) {
  618. if (options.exporting.useRowspanHeaders) {
  619. rowspan = 2;
  620. delete subheaders[i];
  621. }
  622. else {
  623. rowspan = 1;
  624. subheaders[i] = '';
  625. }
  626. }
  627. else {
  628. rowspan = 1;
  629. }
  630. html += getCellHTMLFromValue('th', 'highcharts-table-topheading', 'scope="col"' +
  631. (rowspan > 1 ?
  632. ' valign="top" rowspan="' + rowspan + '"' :
  633. ''), cur);
  634. }
  635. }
  636. html += '</tr>';
  637. }
  638. // Add the subheaders (the only headers if not using multilevels)
  639. if (subheaders) {
  640. html += '<tr>';
  641. for (i = 0, len = subheaders.length; i < len; ++i) {
  642. if (typeof subheaders[i] !== 'undefined') {
  643. html += getCellHTMLFromValue('th', null, 'scope="col"', subheaders[i]);
  644. }
  645. }
  646. html += '</tr>';
  647. }
  648. html += '</thead>';
  649. return html;
  650. };
  651. // Add table caption
  652. if (options.exporting.tableCaption !== false) {
  653. html += '<caption class="highcharts-table-caption">' + pick(options.exporting.tableCaption, (options.title.text ?
  654. htmlencode(options.title.text) :
  655. 'Chart')) + '</caption>';
  656. }
  657. // Find longest row
  658. for (var i = 0, len = rows.length; i < len; ++i) {
  659. if (rows[i].length > rowLength) {
  660. rowLength = rows[i].length;
  661. }
  662. }
  663. // Add header
  664. html += getTableHeaderHTML(topHeaders, subHeaders, Math.max(rowLength, subHeaders.length));
  665. // Transform the rows to HTML
  666. html += '<tbody>';
  667. rows.forEach(function (row) {
  668. html += '<tr>';
  669. for (var j = 0; j < rowLength; j++) {
  670. // Make first column a header too. Especially important for
  671. // category axes, but also might make sense for datetime? Should
  672. // await user feedback on this.
  673. html += getCellHTMLFromValue(j ? 'td' : 'th', null, j ? '' : 'scope="row"', row[j]);
  674. }
  675. html += '</tr>';
  676. });
  677. html += '</tbody></table>';
  678. var e = { html: html };
  679. fireEvent(this, 'afterGetTable', e);
  680. return e.html;
  681. };
  682. /**
  683. * Get a blob object from content, if blob is supported
  684. *
  685. * @private
  686. * @param {string} content
  687. * The content to create the blob from.
  688. * @param {string} type
  689. * The type of the content.
  690. * @return {string|undefined}
  691. * The blob object, or undefined if not supported.
  692. */
  693. function getBlobFromContent(content, type) {
  694. var nav = win.navigator, webKit = (nav.userAgent.indexOf('WebKit') > -1 &&
  695. nav.userAgent.indexOf('Chrome') < 0), domurl = win.URL || win.webkitURL || win;
  696. try {
  697. // MS specific
  698. if (nav.msSaveOrOpenBlob && win.MSBlobBuilder) {
  699. var blob = new win.MSBlobBuilder();
  700. blob.append(content);
  701. return blob.getBlob('image/svg+xml');
  702. }
  703. // Safari requires data URI since it doesn't allow navigation to blob
  704. // URLs.
  705. if (!webKit) {
  706. return domurl.createObjectURL(new win.Blob(['\uFEFF' + content], // #7084
  707. { type: type }));
  708. }
  709. }
  710. catch (e) {
  711. // Ignore
  712. }
  713. }
  714. /**
  715. * Call this on click of 'Download CSV' button
  716. *
  717. * @private
  718. * @function Highcharts.Chart#downloadCSV
  719. * @return {void}
  720. */
  721. Highcharts.Chart.prototype.downloadCSV = function () {
  722. var csv = this.getCSV(true);
  723. downloadURL(getBlobFromContent(csv, 'text/csv') ||
  724. 'data:text/csv,\uFEFF' + encodeURIComponent(csv), this.getFilename() + '.csv');
  725. };
  726. /**
  727. * Call this on click of 'Download XLS' button
  728. *
  729. * @private
  730. * @function Highcharts.Chart#downloadXLS
  731. * @return {void}
  732. */
  733. Highcharts.Chart.prototype.downloadXLS = function () {
  734. var uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' +
  735. 'xmlns:x="urn:schemas-microsoft-com:office:excel" ' +
  736. 'xmlns="http://www.w3.org/TR/REC-html40">' +
  737. '<head><!--[if gte mso 9]><xml><x:ExcelWorkbook>' +
  738. '<x:ExcelWorksheets><x:ExcelWorksheet>' +
  739. '<x:Name>Ark1</x:Name>' +
  740. '<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>' +
  741. '</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>' +
  742. '</xml><![endif]-->' +
  743. '<style>td{border:none;font-family: Calibri, sans-serif;} ' +
  744. '.number{mso-number-format:"0.00";} ' +
  745. '.text{ mso-number-format:"\@";}</style>' +
  746. '<meta name=ProgId content=Excel.Sheet>' +
  747. '<meta charset=UTF-8>' +
  748. '</head><body>' +
  749. this.getTable(true) +
  750. '</body></html>', base64 = function (s) {
  751. return win.btoa(unescape(encodeURIComponent(s))); // #50
  752. };
  753. downloadURL(getBlobFromContent(template, 'application/vnd.ms-excel') ||
  754. uri + base64(template), this.getFilename() + '.xls');
  755. };
  756. /**
  757. * Export-data module required. View the data in a table below the chart.
  758. *
  759. * @function Highcharts.Chart#viewData
  760. * @return {void}
  761. *
  762. * @fires Highcharts.Chart#event:afterViewData
  763. */
  764. Highcharts.Chart.prototype.viewData = function () {
  765. if (!this.dataTableDiv) {
  766. this.dataTableDiv = doc.createElement('div');
  767. this.dataTableDiv.className = 'highcharts-data-table';
  768. // Insert after the chart container
  769. this.renderTo.parentNode.insertBefore(this.dataTableDiv, this.renderTo.nextSibling);
  770. }
  771. this.dataTableDiv.innerHTML = this.getTable();
  772. fireEvent(this, 'afterViewData', this.dataTableDiv);
  773. };
  774. /**
  775. * Experimental function to send a chart's config to the Cloud for editing.
  776. *
  777. * Limitations
  778. * - All functions (formatters and callbacks) are removed since they're not
  779. * JSON.
  780. *
  781. * @function Highcharts.Chart#openInCloud
  782. * @return {void}
  783. *
  784. * @todo
  785. * - Let the Cloud throw a friendly warning about unsupported structures like
  786. * formatters.
  787. * - Dynamically updated charts probably fail, we need a generic
  788. * Chart.getOptions function that returns all non-default options. Should also
  789. * be used by the export module.
  790. */
  791. Highcharts.Chart.prototype.openInCloud = function () {
  792. var options, paramObj, params;
  793. /**
  794. * Recursively remove function callbacks.
  795. * @private
  796. * @param {*} obj
  797. * Container of function callbacks
  798. * @return {void}
  799. */
  800. function removeFunctions(obj) {
  801. Object.keys(obj).forEach(function (key) {
  802. if (typeof obj[key] === 'function') {
  803. delete obj[key];
  804. }
  805. if (isObject(obj[key])) { // object and not an array
  806. removeFunctions(obj[key]);
  807. }
  808. });
  809. }
  810. /**
  811. * @private
  812. * @return {void}
  813. */
  814. function openInCloud() {
  815. var form = doc.createElement('form');
  816. doc.body.appendChild(form);
  817. form.method = 'post';
  818. form.action = 'https://cloud-api.highcharts.com/openincloud';
  819. form.target = '_blank';
  820. var input = doc.createElement('input');
  821. input.type = 'hidden';
  822. input.name = 'chart';
  823. input.value = params;
  824. form.appendChild(input);
  825. form.submit();
  826. doc.body.removeChild(form);
  827. }
  828. options = Highcharts.merge(this.userOptions);
  829. removeFunctions(options);
  830. paramObj = {
  831. name: (options.title && options.title.text) || 'Chart title',
  832. options: options,
  833. settings: {
  834. constructor: 'Chart',
  835. dataProvider: {
  836. csv: this.getCSV()
  837. }
  838. }
  839. };
  840. params = JSON.stringify(paramObj);
  841. openInCloud();
  842. };
  843. // Add "Download CSV" to the exporting menu.
  844. var exportingOptions = Highcharts.getOptions().exporting;
  845. if (exportingOptions) {
  846. extend(exportingOptions.menuItemDefinitions, {
  847. downloadCSV: {
  848. textKey: 'downloadCSV',
  849. onclick: function () {
  850. this.downloadCSV();
  851. }
  852. },
  853. downloadXLS: {
  854. textKey: 'downloadXLS',
  855. onclick: function () {
  856. this.downloadXLS();
  857. }
  858. },
  859. viewData: {
  860. textKey: 'viewData',
  861. onclick: function () {
  862. this.viewData();
  863. }
  864. },
  865. openInCloud: {
  866. textKey: 'openInCloud',
  867. onclick: function () {
  868. this.openInCloud();
  869. }
  870. }
  871. });
  872. if (exportingOptions.buttons) {
  873. exportingOptions.buttons.contextButton.menuItems.push('separator', 'downloadCSV', 'downloadXLS', 'viewData', 'openInCloud');
  874. }
  875. }
  876. // Series specific
  877. if (seriesTypes.map) {
  878. seriesTypes.map.prototype.exportKey = 'name';
  879. }
  880. if (seriesTypes.mapbubble) {
  881. seriesTypes.mapbubble.prototype.exportKey = 'name';
  882. }
  883. if (seriesTypes.treemap) {
  884. seriesTypes.treemap.prototype.exportKey = 'name';
  885. }