export-data.src.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207
  1. /**
  2. * @license Highcharts JS v9.0.1 (2021-02-16)
  3. *
  4. * Exporting module
  5. *
  6. * (c) 2010-2021 Torstein Honsi
  7. *
  8. * License: www.highcharts.com/license
  9. */
  10. 'use strict';
  11. (function (factory) {
  12. if (typeof module === 'object' && module.exports) {
  13. factory['default'] = factory;
  14. module.exports = factory;
  15. } else if (typeof define === 'function' && define.amd) {
  16. define('highcharts/modules/export-data', ['highcharts', 'highcharts/modules/exporting'], function (Highcharts) {
  17. factory(Highcharts);
  18. factory.Highcharts = Highcharts;
  19. return factory;
  20. });
  21. } else {
  22. factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
  23. }
  24. }(function (Highcharts) {
  25. var _modules = Highcharts ? Highcharts._modules : {};
  26. function _registerModule(obj, path, args, fn) {
  27. if (!obj.hasOwnProperty(path)) {
  28. obj[path] = fn.apply(null, args);
  29. }
  30. }
  31. _registerModule(_modules, 'Extensions/DownloadURL.js', [_modules['Core/Globals.js']], function (Highcharts) {
  32. /* *
  33. *
  34. * (c) 2015-2021 Oystein Moseng
  35. *
  36. * License: www.highcharts.com/license
  37. *
  38. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  39. *
  40. * Mixin for downloading content in the browser
  41. *
  42. * */
  43. var win = Highcharts.win,
  44. doc = win.document,
  45. domurl = win.URL || win.webkitURL || win;
  46. /**
  47. * Convert base64 dataURL to Blob if supported, otherwise returns undefined.
  48. * @private
  49. * @function Highcharts.dataURLtoBlob
  50. * @param {string} dataURL
  51. * URL to convert
  52. * @return {string|undefined}
  53. * Blob
  54. */
  55. var dataURLtoBlob = Highcharts.dataURLtoBlob = function (dataURL) {
  56. var parts = dataURL
  57. .replace(/filename=.*;/, '')
  58. .match(/data:([^;]*)(;base64)?,([0-9A-Za-z+/]+)/);
  59. if (parts &&
  60. parts.length > 3 &&
  61. win.atob &&
  62. win.ArrayBuffer &&
  63. win.Uint8Array &&
  64. win.Blob &&
  65. domurl.createObjectURL) {
  66. // Try to convert data URL to Blob
  67. var binStr = win.atob(parts[3]),
  68. buf = new win.ArrayBuffer(binStr.length),
  69. binary = new win.Uint8Array(buf);
  70. for (var i = 0; i < binary.length; ++i) {
  71. binary[i] = binStr.charCodeAt(i);
  72. }
  73. var blob = new win.Blob([binary], { 'type': parts[1] });
  74. return domurl.createObjectURL(blob);
  75. }
  76. };
  77. /**
  78. * Download a data URL in the browser. Can also take a blob as first param.
  79. *
  80. * @private
  81. * @function Highcharts.downloadURL
  82. * @param {string|global.URL} dataURL
  83. * The dataURL/Blob to download
  84. * @param {string} filename
  85. * The name of the resulting file (w/extension)
  86. * @return {void}
  87. */
  88. var downloadURL = Highcharts.downloadURL = function (dataURL,
  89. filename) {
  90. var nav = win.navigator;
  91. var a = doc.createElement('a'),
  92. windowRef;
  93. // IE specific blob implementation
  94. // Don't use for normal dataURLs
  95. if (typeof dataURL !== 'string' &&
  96. !(dataURL instanceof String) &&
  97. nav.msSaveOrOpenBlob) {
  98. nav.msSaveOrOpenBlob(dataURL, filename);
  99. return;
  100. }
  101. dataURL = "" + dataURL;
  102. // Some browsers have limitations for data URL lengths. Try to convert to
  103. // Blob or fall back. Edge always needs that blob.
  104. var isEdgeBrowser = /Edge\/\d+/.test(nav.userAgent);
  105. if (isEdgeBrowser || dataURL.length > 2000000) {
  106. dataURL = dataURLtoBlob(dataURL) || '';
  107. if (!dataURL) {
  108. throw new Error('Failed to convert to blob');
  109. }
  110. }
  111. // Try HTML5 download attr if supported
  112. if (typeof a.download !== 'undefined') {
  113. a.href = dataURL;
  114. a.download = filename; // HTML5 download attribute
  115. doc.body.appendChild(a);
  116. a.click();
  117. doc.body.removeChild(a);
  118. }
  119. else {
  120. // No download attr, just opening data URI
  121. try {
  122. windowRef = win.open(dataURL, 'chart');
  123. if (typeof windowRef === 'undefined' || windowRef === null) {
  124. throw new Error('Failed to open window');
  125. }
  126. }
  127. catch (e) {
  128. // window.open failed, trying location.href
  129. win.location.href = dataURL;
  130. }
  131. }
  132. };
  133. var exports = {
  134. dataURLtoBlob: dataURLtoBlob,
  135. downloadURL: downloadURL
  136. };
  137. return exports;
  138. });
  139. _registerModule(_modules, 'Extensions/ExportData.js', [_modules['Core/Axis/Axis.js'], _modules['Core/Chart/Chart.js'], _modules['Core/Renderer/HTML/AST.js'], _modules['Core/Globals.js'], _modules['Core/Utilities.js'], _modules['Extensions/DownloadURL.js']], function (Axis, Chart, AST, H, U, DownloadURL) {
  140. /* *
  141. *
  142. * Experimental data export module for Highcharts
  143. *
  144. * (c) 2010-2021 Torstein Honsi
  145. *
  146. * License: www.highcharts.com/license
  147. *
  148. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  149. *
  150. * */
  151. // @todo
  152. // - Set up systematic tests for all series types, paired with tests of the data
  153. // module importing the same data.
  154. var doc = H.doc,
  155. seriesTypes = H.seriesTypes,
  156. win = H.win;
  157. var addEvent = U.addEvent,
  158. defined = U.defined,
  159. extend = U.extend,
  160. find = U.find,
  161. fireEvent = U.fireEvent,
  162. getOptions = U.getOptions,
  163. isNumber = U.isNumber,
  164. pick = U.pick,
  165. setOptions = U.setOptions;
  166. /**
  167. * Function callback to execute while data rows are processed for exporting.
  168. * This allows the modification of data rows before processed into the final
  169. * format.
  170. *
  171. * @callback Highcharts.ExportDataCallbackFunction
  172. * @extends Highcharts.EventCallbackFunction<Highcharts.Chart>
  173. *
  174. * @param {Highcharts.Chart} this
  175. * Chart context where the event occured.
  176. *
  177. * @param {Highcharts.ExportDataEventObject} event
  178. * Event object with data rows that can be modified.
  179. */
  180. /**
  181. * Contains information about the export data event.
  182. *
  183. * @interface Highcharts.ExportDataEventObject
  184. */ /**
  185. * Contains the data rows for the current export task and can be modified.
  186. * @name Highcharts.ExportDataEventObject#dataRows
  187. * @type {Array<Array<string>>}
  188. */
  189. var downloadURL = DownloadURL.downloadURL;
  190. // Can we add this to utils? Also used in screen-reader.js
  191. /**
  192. * HTML encode some characters vulnerable for XSS.
  193. * @private
  194. * @param {string} html The input string
  195. * @return {string} The excaped string
  196. */
  197. function htmlencode(html) {
  198. return html
  199. .replace(/&/g, '&amp;')
  200. .replace(/</g, '&lt;')
  201. .replace(/>/g, '&gt;')
  202. .replace(/"/g, '&quot;')
  203. .replace(/'/g, '&#x27;')
  204. .replace(/\//g, '&#x2F;');
  205. }
  206. setOptions({
  207. /**
  208. * Callback that fires while exporting data. This allows the modification of
  209. * data rows before processed into the final format.
  210. *
  211. * @type {Highcharts.ExportDataCallbackFunction}
  212. * @context Highcharts.Chart
  213. * @requires modules/export-data
  214. * @apioption chart.events.exportData
  215. */
  216. /**
  217. * When set to `false` will prevent the series data from being included in
  218. * any form of data export.
  219. *
  220. * Since version 6.0.0 until 7.1.0 the option was existing undocumented
  221. * as `includeInCSVExport`.
  222. *
  223. * @type {boolean}
  224. * @since 7.1.0
  225. * @requires modules/export-data
  226. * @apioption plotOptions.series.includeInDataExport
  227. */
  228. /**
  229. * @optionparent exporting
  230. * @private
  231. */
  232. exporting: {
  233. /**
  234. * Caption for the data table. Same as chart title by default. Set to
  235. * `false` to disable.
  236. *
  237. * @sample highcharts/export-data/multilevel-table
  238. * Multiple table headers
  239. *
  240. * @type {boolean|string}
  241. * @since 6.0.4
  242. * @requires modules/export-data
  243. * @apioption exporting.tableCaption
  244. */
  245. /**
  246. * Options for exporting data to CSV or ExCel, or displaying the data
  247. * in a HTML table or a JavaScript structure.
  248. *
  249. * This module adds data export options to the export menu and provides
  250. * functions like `Chart.getCSV`, `Chart.getTable`, `Chart.getDataRows`
  251. * and `Chart.viewData`.
  252. *
  253. * The XLS converter is limited and only creates a HTML string that is
  254. * passed for download, which works but creates a warning before
  255. * opening. The workaround for this is to use a third party XLSX
  256. * converter, as demonstrated in the sample below.
  257. *
  258. * @sample highcharts/export-data/categorized/ Categorized data
  259. * @sample highcharts/export-data/stock-timeaxis/ Highstock time axis
  260. * @sample highcharts/export-data/xlsx/
  261. * Using a third party XLSX converter
  262. *
  263. * @since 6.0.0
  264. * @requires modules/export-data
  265. */
  266. csv: {
  267. /**
  268. *
  269. * Options for annotations in the export-data table.
  270. *
  271. * @since 8.2.0
  272. * @requires modules/export-data
  273. * @requires modules/annotations
  274. *
  275. *
  276. */
  277. annotations: {
  278. /**
  279. * The way to mark the separator for annotations
  280. * combined in one export-data table cell.
  281. *
  282. * @since 8.2.0
  283. * @requires modules/annotations
  284. */
  285. itemDelimiter: '; ',
  286. /**
  287. * When several labels are assigned to a specific point,
  288. * they will be displayed in one field in the table.
  289. *
  290. * @sample highcharts/export-data/join-annotations/
  291. * Concatenate point annotations with itemDelimiter set.
  292. *
  293. * @since 8.2.0
  294. * @requires modules/annotations
  295. */
  296. join: false
  297. },
  298. /**
  299. * Formatter callback for the column headers. Parameters are:
  300. * - `item` - The series or axis object)
  301. * - `key` - The point key, for example y or z
  302. * - `keyLength` - The amount of value keys for this item, for
  303. * example a range series has the keys `low` and `high` so the
  304. * key length is 2.
  305. *
  306. * If [useMultiLevelHeaders](#exporting.useMultiLevelHeaders) is
  307. * true, columnHeaderFormatter by default returns an object with
  308. * columnTitle and topLevelColumnTitle for each key. Columns with
  309. * the same topLevelColumnTitle have their titles merged into a
  310. * single cell with colspan for table/Excel export.
  311. *
  312. * If `useMultiLevelHeaders` is false, or for CSV export, it returns
  313. * the series name, followed by the key if there is more than one
  314. * key.
  315. *
  316. * For the axis it returns the axis title or "Category" or
  317. * "DateTime" by default.
  318. *
  319. * Return `false` to use Highcharts' proposed header.
  320. *
  321. * @sample highcharts/export-data/multilevel-table
  322. * Multiple table headers
  323. *
  324. * @type {Function|null}
  325. */
  326. columnHeaderFormatter: null,
  327. /**
  328. * Which date format to use for exported dates on a datetime X axis.
  329. * See `Highcharts.dateFormat`.
  330. */
  331. dateFormat: '%Y-%m-%d %H:%M:%S',
  332. /**
  333. * Which decimal point to use for exported CSV. Defaults to the same
  334. * as the browser locale, typically `.` (English) or `,` (German,
  335. * French etc).
  336. *
  337. * @type {string|null}
  338. * @since 6.0.4
  339. */
  340. decimalPoint: null,
  341. /**
  342. * The item delimiter in the exported data. Use `;` for direct
  343. * exporting to Excel. Defaults to a best guess based on the browser
  344. * locale. If the locale _decimal point_ is `,`, the `itemDelimiter`
  345. * defaults to `;`, otherwise the `itemDelimiter` defaults to `,`.
  346. *
  347. * @type {string|null}
  348. */
  349. itemDelimiter: null,
  350. /**
  351. * The line delimiter in the exported data, defaults to a newline.
  352. */
  353. lineDelimiter: '\n'
  354. },
  355. /**
  356. * Show a HTML table below the chart with the chart's current data.
  357. *
  358. * @sample highcharts/export-data/showtable/
  359. * Show the table
  360. * @sample highcharts/studies/exporting-table-html
  361. * Experiment with putting the table inside the subtitle to
  362. * allow exporting it.
  363. *
  364. * @since 6.0.0
  365. * @requires modules/export-data
  366. */
  367. showTable: false,
  368. /**
  369. * Use multi level headers in data table. If [csv.columnHeaderFormatter
  370. * ](#exporting.csv.columnHeaderFormatter) is defined, it has to return
  371. * objects in order for multi level headers to work.
  372. *
  373. * @sample highcharts/export-data/multilevel-table
  374. * Multiple table headers
  375. *
  376. * @since 6.0.4
  377. * @requires modules/export-data
  378. */
  379. useMultiLevelHeaders: true,
  380. /**
  381. * If using multi level table headers, use rowspans for headers that
  382. * have only one level.
  383. *
  384. * @sample highcharts/export-data/multilevel-table
  385. * Multiple table headers
  386. *
  387. * @since 6.0.4
  388. * @requires modules/export-data
  389. */
  390. useRowspanHeaders: true
  391. },
  392. /**
  393. * @optionparent lang
  394. *
  395. * @private
  396. */
  397. lang: {
  398. /**
  399. * The text for the menu item.
  400. *
  401. * @since 6.0.0
  402. * @requires modules/export-data
  403. */
  404. downloadCSV: 'Download CSV',
  405. /**
  406. * The text for the menu item.
  407. *
  408. * @since 6.0.0
  409. * @requires modules/export-data
  410. */
  411. downloadXLS: 'Download XLS',
  412. /**
  413. * The text for exported table.
  414. *
  415. * @since 8.1.0
  416. * @requires modules/export-data
  417. */
  418. exportData: {
  419. /**
  420. * The annotation column title.
  421. */
  422. annotationHeader: 'Annotations',
  423. /**
  424. * The category column title.
  425. */
  426. categoryHeader: 'Category',
  427. /**
  428. * The category column title when axis type set to "datetime".
  429. */
  430. categoryDatetimeHeader: 'DateTime'
  431. },
  432. /**
  433. * The text for the menu item.
  434. *
  435. * @since 6.0.0
  436. * @requires modules/export-data
  437. */
  438. viewData: 'View data table',
  439. /**
  440. * The text for the menu item.
  441. *
  442. * @since 8.2.0
  443. * @requires modules/export-data
  444. */
  445. hideData: 'Hide data table'
  446. }
  447. });
  448. /* eslint-disable no-invalid-this */
  449. // Add an event listener to handle the showTable option
  450. addEvent(Chart, 'render', function () {
  451. if (this.options &&
  452. this.options.exporting &&
  453. this.options.exporting.showTable &&
  454. !this.options.chart.forExport &&
  455. !this.dataTableDiv) {
  456. this.viewData();
  457. }
  458. });
  459. /* eslint-enable no-invalid-this */
  460. /**
  461. * Set up key-to-axis bindings. This is used when the Y axis is datetime or
  462. * categorized. For example in an arearange series, the low and high values
  463. * should be formatted according to the Y axis type, and in order to link them
  464. * we need this map.
  465. *
  466. * @private
  467. * @function Highcharts.Chart#setUpKeyToAxis
  468. */
  469. Chart.prototype.setUpKeyToAxis = function () {
  470. if (seriesTypes.arearange) {
  471. seriesTypes.arearange.prototype.keyToAxis = {
  472. low: 'y',
  473. high: 'y'
  474. };
  475. }
  476. if (seriesTypes.gantt) {
  477. seriesTypes.gantt.prototype.keyToAxis = {
  478. start: 'x',
  479. end: 'x'
  480. };
  481. }
  482. };
  483. /**
  484. * Export-data module required. Returns a two-dimensional array containing the
  485. * current chart data.
  486. *
  487. * @function Highcharts.Chart#getDataRows
  488. *
  489. * @param {boolean} [multiLevelHeaders]
  490. * Use multilevel headers for the rows by default. Adds an extra row with
  491. * top level headers. If a custom columnHeaderFormatter is defined, this
  492. * can override the behavior.
  493. *
  494. * @return {Array<Array<(number|string)>>}
  495. * The current chart data
  496. *
  497. * @fires Highcharts.Chart#event:exportData
  498. */
  499. Chart.prototype.getDataRows = function (multiLevelHeaders) {
  500. var hasParallelCoords = this.hasParallelCoordinates,
  501. time = this.time,
  502. csvOptions = ((this.options.exporting && this.options.exporting.csv) || {}),
  503. xAxis,
  504. xAxes = this.xAxis,
  505. rows = {},
  506. rowArr = [],
  507. dataRows,
  508. topLevelColumnTitles = [],
  509. columnTitles = [],
  510. columnTitleObj,
  511. i,
  512. x,
  513. xTitle,
  514. langOptions = this.options.lang,
  515. exportDataOptions = langOptions.exportData,
  516. categoryHeader = exportDataOptions.categoryHeader,
  517. categoryDatetimeHeader = exportDataOptions.categoryDatetimeHeader,
  518. // Options
  519. columnHeaderFormatter = function (item,
  520. key,
  521. keyLength) {
  522. if (csvOptions.columnHeaderFormatter) {
  523. var s = csvOptions.columnHeaderFormatter(item,
  524. key,
  525. keyLength);
  526. if (s !== false) {
  527. return s;
  528. }
  529. }
  530. if (!item) {
  531. return categoryHeader;
  532. }
  533. if (item instanceof Axis) {
  534. return (item.options.title && item.options.title.text) ||
  535. (item.dateTime ? categoryDatetimeHeader : categoryHeader);
  536. }
  537. if (multiLevelHeaders) {
  538. return {
  539. columnTitle: keyLength > 1 ?
  540. key :
  541. item.name,
  542. topLevelColumnTitle: item.name
  543. };
  544. }
  545. return item.name + (keyLength > 1 ? ' (' + key + ')' : '');
  546. },
  547. // Map the categories for value axes
  548. getCategoryAndDateTimeMap = function (series, pointArrayMap, pIdx) {
  549. var categoryMap = {},
  550. dateTimeValueAxisMap = {};
  551. pointArrayMap.forEach(function (prop) {
  552. var axisName = ((series.keyToAxis && series.keyToAxis[prop]) ||
  553. prop) + 'Axis',
  554. // Points in parallel coordinates refers to all yAxis
  555. // not only `series.yAxis`
  556. axis = isNumber(pIdx) ?
  557. series.chart[axisName][pIdx] :
  558. series[axisName];
  559. categoryMap[prop] = (axis && axis.categories) || [];
  560. dateTimeValueAxisMap[prop] = (axis && axis.dateTime);
  561. });
  562. return {
  563. categoryMap: categoryMap,
  564. dateTimeValueAxisMap: dateTimeValueAxisMap
  565. };
  566. },
  567. // Create point array depends if xAxis is category
  568. // or point.name is defined #13293
  569. getPointArray = function (series, xAxis) {
  570. var namedPoints = series.data.filter(function (d) {
  571. return (typeof d.y !== 'undefined') && d.name;
  572. });
  573. if (namedPoints.length &&
  574. xAxis &&
  575. !xAxis.categories &&
  576. !series.keyToAxis) {
  577. if (series.pointArrayMap) {
  578. var pointArrayMapCheck = series.pointArrayMap.filter(function (p) { return p === 'x'; });
  579. if (pointArrayMapCheck.length) {
  580. series.pointArrayMap.unshift('x');
  581. return series.pointArrayMap;
  582. }
  583. }
  584. return ['x', 'y'];
  585. }
  586. return series.pointArrayMap || ['y'];
  587. }, xAxisIndices = [];
  588. // Loop the series and index values
  589. i = 0;
  590. this.setUpKeyToAxis();
  591. this.series.forEach(function (series) {
  592. var keys = series.options.keys,
  593. xAxis = series.xAxis,
  594. pointArrayMap = keys || getPointArray(series,
  595. xAxis),
  596. valueCount = pointArrayMap.length,
  597. xTaken = !series.requireSorting && {},
  598. xAxisIndex = xAxes.indexOf(xAxis),
  599. categoryAndDatetimeMap = getCategoryAndDateTimeMap(series,
  600. pointArrayMap),
  601. mockSeries,
  602. j;
  603. if (series.options.includeInDataExport !== false &&
  604. !series.options.isInternal &&
  605. series.visible !== false // #55
  606. ) {
  607. // Build a lookup for X axis index and the position of the first
  608. // series that belongs to that X axis. Includes -1 for non-axis
  609. // series types like pies.
  610. if (!find(xAxisIndices, function (index) {
  611. return index[0] === xAxisIndex;
  612. })) {
  613. xAxisIndices.push([xAxisIndex, i]);
  614. }
  615. // Compute the column headers and top level headers, usually the
  616. // same as series names
  617. j = 0;
  618. while (j < valueCount) {
  619. columnTitleObj = columnHeaderFormatter(series, pointArrayMap[j], pointArrayMap.length);
  620. columnTitles.push(columnTitleObj.columnTitle || columnTitleObj);
  621. if (multiLevelHeaders) {
  622. topLevelColumnTitles.push(columnTitleObj.topLevelColumnTitle ||
  623. columnTitleObj);
  624. }
  625. j++;
  626. }
  627. mockSeries = {
  628. chart: series.chart,
  629. autoIncrement: series.autoIncrement,
  630. options: series.options,
  631. pointArrayMap: series.pointArrayMap
  632. };
  633. // Export directly from options.data because we need the uncropped
  634. // data (#7913), and we need to support Boost (#7026).
  635. series.options.data.forEach(function eachData(options, pIdx) {
  636. var key,
  637. prop,
  638. val,
  639. name,
  640. point;
  641. // In parallel coordinates chart, each data point is connected
  642. // to a separate yAxis, conform this
  643. if (hasParallelCoords) {
  644. categoryAndDatetimeMap = getCategoryAndDateTimeMap(series, pointArrayMap, pIdx);
  645. }
  646. point = { series: mockSeries };
  647. series.pointClass.prototype.applyOptions.apply(point, [options]);
  648. key = point.x;
  649. name = series.data[pIdx] && series.data[pIdx].name;
  650. j = 0;
  651. // Pies, funnels, geo maps etc. use point name in X row
  652. if (!xAxis ||
  653. series.exportKey === 'name' ||
  654. (!hasParallelCoords && xAxis && xAxis.hasNames) && name) {
  655. key = name;
  656. }
  657. if (xTaken) {
  658. if (xTaken[key]) {
  659. key += '|' + pIdx;
  660. }
  661. xTaken[key] = true;
  662. }
  663. if (!rows[key]) {
  664. // Generate the row
  665. rows[key] = [];
  666. // Contain the X values from one or more X axes
  667. rows[key].xValues = [];
  668. }
  669. rows[key].x = point.x;
  670. rows[key].name = name;
  671. rows[key].xValues[xAxisIndex] = point.x;
  672. while (j < valueCount) {
  673. prop = pointArrayMap[j]; // y, z etc
  674. val = point[prop];
  675. rows[key][i + j] = pick(
  676. // Y axis category if present
  677. categoryAndDatetimeMap.categoryMap[prop][val],
  678. // datetime yAxis
  679. categoryAndDatetimeMap.dateTimeValueAxisMap[prop] ?
  680. time.dateFormat(csvOptions.dateFormat, val) :
  681. null,
  682. // linear/log yAxis
  683. val);
  684. j++;
  685. }
  686. });
  687. i = i + j;
  688. }
  689. });
  690. // Make a sortable array
  691. for (x in rows) {
  692. if (Object.hasOwnProperty.call(rows, x)) {
  693. rowArr.push(rows[x]);
  694. }
  695. }
  696. var xAxisIndex,
  697. column;
  698. // Add computed column headers and top level headers to final row set
  699. dataRows = multiLevelHeaders ? [topLevelColumnTitles, columnTitles] :
  700. [columnTitles];
  701. i = xAxisIndices.length;
  702. while (i--) { // Start from end to splice in
  703. xAxisIndex = xAxisIndices[i][0];
  704. column = xAxisIndices[i][1];
  705. xAxis = xAxes[xAxisIndex];
  706. // Sort it by X values
  707. rowArr.sort(function (// eslint-disable-line no-loop-func
  708. a, b) {
  709. return a.xValues[xAxisIndex] - b.xValues[xAxisIndex];
  710. });
  711. // Add header row
  712. xTitle = columnHeaderFormatter(xAxis);
  713. dataRows[0].splice(column, 0, xTitle);
  714. if (multiLevelHeaders && dataRows[1]) {
  715. // If using multi level headers, we just added top level header.
  716. // Also add for sub level
  717. dataRows[1].splice(column, 0, xTitle);
  718. }
  719. // Add the category column
  720. rowArr.forEach(function (// eslint-disable-line no-loop-func
  721. row) {
  722. var category = row.name;
  723. if (xAxis && !defined(category)) {
  724. if (xAxis.dateTime) {
  725. if (row.x instanceof Date) {
  726. row.x = row.x.getTime();
  727. }
  728. category = time.dateFormat(csvOptions.dateFormat, row.x);
  729. }
  730. else if (xAxis.categories) {
  731. category = pick(xAxis.names[row.x], xAxis.categories[row.x], row.x);
  732. }
  733. else {
  734. category = row.x;
  735. }
  736. }
  737. // Add the X/date/category
  738. row.splice(column, 0, category);
  739. });
  740. }
  741. dataRows = dataRows.concat(rowArr);
  742. fireEvent(this, 'exportData', { dataRows: dataRows });
  743. return dataRows;
  744. };
  745. /**
  746. * Export-data module required. Returns the current chart data as a CSV string.
  747. *
  748. * @function Highcharts.Chart#getCSV
  749. *
  750. * @param {boolean} [useLocalDecimalPoint]
  751. * Whether to use the local decimal point as detected from the browser.
  752. * This makes it easier to export data to Excel in the same locale as the
  753. * user is.
  754. *
  755. * @return {string}
  756. * CSV representation of the data
  757. */
  758. Chart.prototype.getCSV = function (useLocalDecimalPoint) {
  759. var csv = '', rows = this.getDataRows(), csvOptions = this.options.exporting.csv, decimalPoint = pick(csvOptions.decimalPoint, csvOptions.itemDelimiter !== ',' && useLocalDecimalPoint ?
  760. (1.1).toLocaleString()[1] :
  761. '.'),
  762. // use ';' for direct to Excel
  763. itemDelimiter = pick(csvOptions.itemDelimiter, decimalPoint === ',' ? ';' : ','),
  764. // '\n' isn't working with the js csv data extraction
  765. lineDelimiter = csvOptions.lineDelimiter;
  766. // Transform the rows to CSV
  767. rows.forEach(function (row, i) {
  768. var val = '',
  769. j = row.length;
  770. while (j--) {
  771. val = row[j];
  772. if (typeof val === 'string') {
  773. val = '"' + val + '"';
  774. }
  775. if (typeof val === 'number') {
  776. if (decimalPoint !== '.') {
  777. val = val.toString().replace('.', decimalPoint);
  778. }
  779. }
  780. row[j] = val;
  781. }
  782. // Add the values
  783. csv += row.join(itemDelimiter);
  784. // Add the line delimiter
  785. if (i < rows.length - 1) {
  786. csv += lineDelimiter;
  787. }
  788. });
  789. return csv;
  790. };
  791. /**
  792. * Export-data module required. Build a HTML table with the chart's current
  793. * data.
  794. *
  795. * @sample highcharts/export-data/viewdata/
  796. * View the data from the export menu
  797. *
  798. * @function Highcharts.Chart#getTable
  799. *
  800. * @param {boolean} [useLocalDecimalPoint]
  801. * Whether to use the local decimal point as detected from the browser.
  802. * This makes it easier to export data to Excel in the same locale as the
  803. * user is.
  804. *
  805. * @return {string}
  806. * HTML representation of the data.
  807. *
  808. * @fires Highcharts.Chart#event:afterGetTable
  809. */
  810. Chart.prototype.getTable = function (useLocalDecimalPoint) {
  811. var serialize = function (node) {
  812. if (!node.tagName || node.tagName === '#text') {
  813. // Text node
  814. return node.textContent || '';
  815. }
  816. var attributes = node.attributes;
  817. var html = "<" + node.tagName;
  818. if (attributes) {
  819. Object.keys(attributes).forEach(function (key) {
  820. html += " " + key + "=\"" + attributes[key] + "\"";
  821. });
  822. }
  823. html += '>';
  824. html += node.textContent || '';
  825. (node.children || []).forEach(function (child) {
  826. html += serialize(child);
  827. });
  828. html += "</" + node.tagName + ">";
  829. return html;
  830. };
  831. var tree = this.getTableAST(useLocalDecimalPoint);
  832. return serialize(tree);
  833. };
  834. /**
  835. * Get the AST of a HTML table representing the chart data.
  836. *
  837. * @private
  838. *
  839. * @function Highcharts.Chart#getTableAST
  840. *
  841. * @param {boolean} [useLocalDecimalPoint]
  842. * Whether to use the local decimal point as detected from the browser.
  843. * This makes it easier to export data to Excel in the same locale as the
  844. * user is.
  845. *
  846. * @return {Highcharts.ASTNode}
  847. * The abstract syntax tree
  848. */
  849. Chart.prototype.getTableAST = function (useLocalDecimalPoint) {
  850. var treeChildren = [];
  851. var options = this.options,
  852. decimalPoint = useLocalDecimalPoint ? (1.1).toLocaleString()[1] : '.',
  853. useMultiLevelHeaders = pick(options.exporting.useMultiLevelHeaders,
  854. true),
  855. rows = this.getDataRows(useMultiLevelHeaders),
  856. rowLength = 0,
  857. topHeaders = useMultiLevelHeaders ? rows.shift() : null,
  858. subHeaders = rows.shift(),
  859. // Compare two rows for equality
  860. isRowEqual = function (row1,
  861. row2) {
  862. var i = row1.length;
  863. if (row2.length === i) {
  864. while (i--) {
  865. if (row1[i] !== row2[i]) {
  866. return false;
  867. }
  868. }
  869. }
  870. else {
  871. return false;
  872. }
  873. return true;
  874. },
  875. // Get table cell HTML from value
  876. getCellHTMLFromValue = function (tagName, classes, attributes, value) {
  877. var textContent = pick(value, ''), className = 'text' + (classes ? ' ' + classes : '');
  878. // Convert to string if number
  879. if (typeof textContent === 'number') {
  880. textContent = textContent.toString();
  881. if (decimalPoint === ',') {
  882. textContent = textContent.replace('.', decimalPoint);
  883. }
  884. className = 'number';
  885. }
  886. else if (!value) {
  887. className = 'empty';
  888. }
  889. attributes = extend({ 'class': className }, attributes);
  890. return {
  891. tagName: tagName,
  892. attributes: attributes,
  893. textContent: textContent
  894. };
  895. },
  896. // Get table header markup from row data
  897. getTableHeaderHTML = function (topheaders, subheaders, rowLength) {
  898. var theadChildren = [];
  899. var i = 0,
  900. len = rowLength || subheaders && subheaders.length,
  901. next,
  902. cur,
  903. curColspan = 0,
  904. rowspan;
  905. // Clean up multiple table headers. Chart.getDataRows() returns two
  906. // levels of headers when using multilevel, not merged. We need to
  907. // merge identical headers, remove redundant headers, and keep it
  908. // all marked up nicely.
  909. if (useMultiLevelHeaders &&
  910. topheaders &&
  911. subheaders &&
  912. !isRowEqual(topheaders, subheaders)) {
  913. var trChildren = [];
  914. for (; i < len; ++i) {
  915. cur = topheaders[i];
  916. next = topheaders[i + 1];
  917. if (cur === next) {
  918. ++curColspan;
  919. }
  920. else if (curColspan) {
  921. // Ended colspan
  922. // Add cur to HTML with colspan.
  923. trChildren.push(getCellHTMLFromValue('th', 'highcharts-table-topheading', {
  924. scope: 'col',
  925. colspan: curColspan + 1
  926. }, cur));
  927. curColspan = 0;
  928. }
  929. else {
  930. // Cur is standalone. If it is same as sublevel,
  931. // remove sublevel and add just toplevel.
  932. if (cur === subheaders[i]) {
  933. if (options.exporting.useRowspanHeaders) {
  934. rowspan = 2;
  935. delete subheaders[i];
  936. }
  937. else {
  938. rowspan = 1;
  939. subheaders[i] = '';
  940. }
  941. }
  942. else {
  943. rowspan = 1;
  944. }
  945. var cell = getCellHTMLFromValue('th', 'highcharts-table-topheading', { scope: 'col' }, cur);
  946. if (rowspan > 1 && cell.attributes) {
  947. cell.attributes.valign = 'top';
  948. cell.attributes.rowspan = rowspan;
  949. }
  950. trChildren.push(cell);
  951. }
  952. }
  953. theadChildren.push({
  954. tagName: 'tr',
  955. children: trChildren
  956. });
  957. }
  958. // Add the subheaders (the only headers if not using multilevels)
  959. if (subheaders) {
  960. var trChildren = [];
  961. for (i = 0, len = subheaders.length; i < len; ++i) {
  962. if (typeof subheaders[i] !== 'undefined') {
  963. trChildren.push(getCellHTMLFromValue('th', null, { scope: 'col' }, subheaders[i]));
  964. }
  965. }
  966. theadChildren.push({
  967. tagName: 'tr',
  968. children: trChildren
  969. });
  970. }
  971. return {
  972. tagName: 'thead',
  973. children: theadChildren
  974. };
  975. };
  976. // Add table caption
  977. if (options.exporting.tableCaption !== false) {
  978. treeChildren.push({
  979. tagName: 'caption',
  980. attributes: {
  981. 'class': 'highcharts-table-caption'
  982. },
  983. textContent: pick(options.exporting.tableCaption, (options.title.text ?
  984. htmlencode(options.title.text) :
  985. 'Chart'))
  986. });
  987. }
  988. // Find longest row
  989. for (var i = 0, len = rows.length; i < len; ++i) {
  990. if (rows[i].length > rowLength) {
  991. rowLength = rows[i].length;
  992. }
  993. }
  994. // Add header
  995. treeChildren.push(getTableHeaderHTML(topHeaders, subHeaders, Math.max(rowLength, subHeaders.length)));
  996. // Transform the rows to HTML
  997. var trs = [];
  998. rows.forEach(function (row) {
  999. var trChildren = [];
  1000. for (var j = 0; j < rowLength; j++) {
  1001. // Make first column a header too. Especially important for
  1002. // category axes, but also might make sense for datetime? Should
  1003. // await user feedback on this.
  1004. trChildren.push(getCellHTMLFromValue(j ? 'td' : 'th', null, j ? {} : { scope: 'row' }, row[j]));
  1005. }
  1006. trs.push({
  1007. tagName: 'tr',
  1008. children: trChildren
  1009. });
  1010. });
  1011. treeChildren.push({
  1012. tagName: 'tbody',
  1013. children: trs
  1014. });
  1015. var e = {
  1016. tree: {
  1017. tagName: 'table',
  1018. id: "highcharts-data-table-" + this.index,
  1019. children: treeChildren
  1020. }
  1021. };
  1022. fireEvent(this, 'aftergetTableAST', e);
  1023. return e.tree;
  1024. };
  1025. /**
  1026. * Get a blob object from content, if blob is supported
  1027. *
  1028. * @private
  1029. * @param {string} content
  1030. * The content to create the blob from.
  1031. * @param {string} type
  1032. * The type of the content.
  1033. * @return {string|undefined}
  1034. * The blob object, or undefined if not supported.
  1035. */
  1036. function getBlobFromContent(content, type) {
  1037. var nav = win.navigator,
  1038. webKit = (nav.userAgent.indexOf('WebKit') > -1 &&
  1039. nav.userAgent.indexOf('Chrome') < 0),
  1040. domurl = win.URL || win.webkitURL || win;
  1041. try {
  1042. // MS specific
  1043. if (nav.msSaveOrOpenBlob && win.MSBlobBuilder) {
  1044. var blob = new win.MSBlobBuilder();
  1045. blob.append(content);
  1046. return blob.getBlob('image/svg+xml');
  1047. }
  1048. // Safari requires data URI since it doesn't allow navigation to blob
  1049. // URLs.
  1050. if (!webKit) {
  1051. return domurl.createObjectURL(new win.Blob(['\uFEFF' + content], // #7084
  1052. { type: type }));
  1053. }
  1054. }
  1055. catch (e) {
  1056. // Ignore
  1057. }
  1058. }
  1059. /**
  1060. * Generates a data URL of CSV for local download in the browser. This is the
  1061. * default action for a click on the 'Download CSV' button.
  1062. *
  1063. * See {@link Highcharts.Chart#getCSV} to get the CSV data itself.
  1064. *
  1065. * @function Highcharts.Chart#downloadCSV
  1066. *
  1067. * @requires modules/exporting
  1068. */
  1069. Chart.prototype.downloadCSV = function () {
  1070. var csv = this.getCSV(true);
  1071. downloadURL(getBlobFromContent(csv, 'text/csv') ||
  1072. 'data:text/csv,\uFEFF' + encodeURIComponent(csv), this.getFilename() + '.csv');
  1073. };
  1074. /**
  1075. * Generates a data URL of an XLS document for local download in the browser.
  1076. * This is the default action for a click on the 'Download XLS' button.
  1077. *
  1078. * See {@link Highcharts.Chart#getTable} to get the table data itself.
  1079. *
  1080. * @function Highcharts.Chart#downloadXLS
  1081. *
  1082. * @requires modules/exporting
  1083. */
  1084. Chart.prototype.downloadXLS = function () {
  1085. var uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' +
  1086. 'xmlns:x="urn:schemas-microsoft-com:office:excel" ' +
  1087. 'xmlns="http://www.w3.org/TR/REC-html40">' +
  1088. '<head><!--[if gte mso 9]><xml><x:ExcelWorkbook>' +
  1089. '<x:ExcelWorksheets><x:ExcelWorksheet>' +
  1090. '<x:Name>Ark1</x:Name>' +
  1091. '<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>' +
  1092. '</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>' +
  1093. '</xml><![endif]-->' +
  1094. '<style>td{border:none;font-family: Calibri, sans-serif;} ' +
  1095. '.number{mso-number-format:"0.00";} ' +
  1096. '.text{ mso-number-format:"\@";}</style>' +
  1097. '<meta name=ProgId content=Excel.Sheet>' +
  1098. '<meta charset=UTF-8>' +
  1099. '</head><body>' +
  1100. this.getTable(true) +
  1101. '</body></html>', base64 = function (s) {
  1102. return win.btoa(unescape(encodeURIComponent(s))); // #50
  1103. };
  1104. downloadURL(getBlobFromContent(template, 'application/vnd.ms-excel') ||
  1105. uri + base64(template), this.getFilename() + '.xls');
  1106. };
  1107. /**
  1108. * Export-data module required. View the data in a table below the chart.
  1109. *
  1110. * @function Highcharts.Chart#viewData
  1111. *
  1112. * @fires Highcharts.Chart#event:afterViewData
  1113. */
  1114. Chart.prototype.viewData = function () {
  1115. this.toggleDataTable(true);
  1116. };
  1117. /**
  1118. * Export-data module required. Hide the data table when visible.
  1119. *
  1120. * @function Highcharts.Chart#hideData
  1121. */
  1122. Chart.prototype.hideData = function () {
  1123. this.toggleDataTable(false);
  1124. };
  1125. Chart.prototype.toggleDataTable = function (show) {
  1126. show = pick(show, !this.isDataTableVisible);
  1127. // Create the div
  1128. if (show && !this.dataTableDiv) {
  1129. this.dataTableDiv = doc.createElement('div');
  1130. this.dataTableDiv.className = 'highcharts-data-table';
  1131. // Insert after the chart container
  1132. this.renderTo.parentNode.insertBefore(this.dataTableDiv, this.renderTo.nextSibling);
  1133. }
  1134. // Toggle the visibility
  1135. if (this.dataTableDiv) {
  1136. this.dataTableDiv.style.display = show ? 'block' : 'none';
  1137. // Generate the data table
  1138. if (show) {
  1139. this.dataTableDiv.innerHTML = '';
  1140. var ast = new AST([this.getTableAST()]);
  1141. ast.addToDOM(this.dataTableDiv);
  1142. fireEvent(this, 'afterViewData', this.dataTableDiv);
  1143. }
  1144. }
  1145. // Set the flag
  1146. this.isDataTableVisible = show;
  1147. // Change the menu item text
  1148. var exportDivElements = this.exportDivElements,
  1149. options = this.options.exporting,
  1150. menuItems = options &&
  1151. options.buttons &&
  1152. options.buttons.contextButton.menuItems,
  1153. lang = this.options.lang;
  1154. if (exportingOptions &&
  1155. exportingOptions.menuItemDefinitions && (lang === null || lang === void 0 ? void 0 : lang.viewData) &&
  1156. lang.hideData &&
  1157. menuItems &&
  1158. exportDivElements &&
  1159. exportDivElements.length) {
  1160. AST.setElementHTML(exportDivElements[menuItems.indexOf('viewData')], this.isDataTableVisible ? lang.hideData : lang.viewData);
  1161. }
  1162. };
  1163. // Add "Download CSV" to the exporting menu.
  1164. var exportingOptions = getOptions().exporting;
  1165. if (exportingOptions) {
  1166. extend(exportingOptions.menuItemDefinitions, {
  1167. downloadCSV: {
  1168. textKey: 'downloadCSV',
  1169. onclick: function () {
  1170. this.downloadCSV();
  1171. }
  1172. },
  1173. downloadXLS: {
  1174. textKey: 'downloadXLS',
  1175. onclick: function () {
  1176. this.downloadXLS();
  1177. }
  1178. },
  1179. viewData: {
  1180. textKey: 'viewData',
  1181. onclick: function () {
  1182. this.toggleDataTable();
  1183. }
  1184. }
  1185. });
  1186. if (exportingOptions.buttons) {
  1187. exportingOptions.buttons.contextButton.menuItems.push('separator', 'downloadCSV', 'downloadXLS', 'viewData');
  1188. }
  1189. }
  1190. // Series specific
  1191. if (seriesTypes.map) {
  1192. seriesTypes.map.prototype.exportKey = 'name';
  1193. }
  1194. if (seriesTypes.mapbubble) {
  1195. seriesTypes.mapbubble.prototype.exportKey = 'name';
  1196. }
  1197. if (seriesTypes.treemap) {
  1198. seriesTypes.treemap.prototype.exportKey = 'name';
  1199. }
  1200. });
  1201. _registerModule(_modules, 'masters/modules/export-data.src.js', [], function () {
  1202. });
  1203. }));