export-data.src.js 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. /**
  2. * @license Highcharts JS v8.2.2 (2020-10-22)
  3. *
  4. * Exporting module
  5. *
  6. * (c) 2010-2019 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-2020 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. nav = win.navigator,
  45. doc = win.document,
  46. domurl = win.URL || win.webkitURL || win,
  47. isEdgeBrowser = /Edge\/\d+/.test(nav.userAgent);
  48. /**
  49. * Convert base64 dataURL to Blob if supported, otherwise returns undefined.
  50. * @private
  51. * @function Highcharts.dataURLtoBlob
  52. * @param {string} dataURL
  53. * URL to convert
  54. * @return {string|undefined}
  55. * Blob
  56. */
  57. var dataURLtoBlob = Highcharts.dataURLtoBlob = function (dataURL) {
  58. var parts = dataURL
  59. .replace(/filename=.*;/, '')
  60. .match(/data:([^;]*)(;base64)?,([0-9A-Za-z+/]+)/);
  61. if (parts &&
  62. parts.length > 3 &&
  63. win.atob &&
  64. win.ArrayBuffer &&
  65. win.Uint8Array &&
  66. win.Blob &&
  67. domurl.createObjectURL) {
  68. // Try to convert data URL to Blob
  69. var binStr = win.atob(parts[3]),
  70. buf = new win.ArrayBuffer(binStr.length),
  71. binary = new win.Uint8Array(buf);
  72. for (var i = 0; i < binary.length; ++i) {
  73. binary[i] = binStr.charCodeAt(i);
  74. }
  75. var blob = new win.Blob([binary], { 'type': parts[1] });
  76. return domurl.createObjectURL(blob);
  77. }
  78. };
  79. /**
  80. * Download a data URL in the browser. Can also take a blob as first param.
  81. *
  82. * @private
  83. * @function Highcharts.downloadURL
  84. * @param {string|global.URL} dataURL
  85. * The dataURL/Blob to download
  86. * @param {string} filename
  87. * The name of the resulting file (w/extension)
  88. * @return {void}
  89. */
  90. var downloadURL = Highcharts.downloadURL = function (dataURL,
  91. filename) {
  92. var a = doc.createElement('a'),
  93. windowRef;
  94. // IE specific blob implementation
  95. // Don't use for normal dataURLs
  96. if (typeof dataURL !== 'string' &&
  97. !(dataURL instanceof String) &&
  98. nav.msSaveOrOpenBlob) {
  99. nav.msSaveOrOpenBlob(dataURL, filename);
  100. return;
  101. }
  102. dataURL = "" + dataURL;
  103. // Some browsers have limitations for data URL lengths. Try to convert to
  104. // Blob or fall back. Edge always needs that blob.
  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/Globals.js'], _modules['Core/Utilities.js'], _modules['Extensions/DownloadURL.js']], function (Axis, Chart, H, U, DownloadURL) {
  140. /* *
  141. *
  142. * Experimental data export module for Highcharts
  143. *
  144. * (c) 2010-2020 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 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(),
  812. // Compare two rows for equality
  813. isRowEqual = function (row1, row2) {
  814. var i = row1.length;
  815. if (row2.length === i) {
  816. while (i--) {
  817. if (row1[i] !== row2[i]) {
  818. return false;
  819. }
  820. }
  821. }
  822. else {
  823. return false;
  824. }
  825. return true;
  826. },
  827. // Get table cell HTML from value
  828. getCellHTMLFromValue = function (tag, classes, attrs, value) {
  829. var val = pick(value, ''), className = 'text' + (classes ? ' ' + classes : '');
  830. // Convert to string if number
  831. if (typeof val === 'number') {
  832. val = val.toString();
  833. if (decimalPoint === ',') {
  834. val = val.replace('.', decimalPoint);
  835. }
  836. className = 'number';
  837. }
  838. else if (!value) {
  839. className = 'empty';
  840. }
  841. return '<' + tag + (attrs ? ' ' + attrs : '') +
  842. ' class="' + className + '">' +
  843. val + '</' + tag + '>';
  844. },
  845. // Get table header markup from row data
  846. getTableHeaderHTML = function (topheaders, subheaders, rowLength) {
  847. var html = '<thead>',
  848. i = 0,
  849. len = rowLength || subheaders && subheaders.length,
  850. next,
  851. cur,
  852. curColspan = 0,
  853. rowspan;
  854. // Clean up multiple table headers. Chart.getDataRows() returns two
  855. // levels of headers when using multilevel, not merged. We need to
  856. // merge identical headers, remove redundant headers, and keep it
  857. // all marked up nicely.
  858. if (useMultiLevelHeaders &&
  859. topheaders &&
  860. subheaders &&
  861. !isRowEqual(topheaders, subheaders)) {
  862. html += '<tr>';
  863. for (; i < len; ++i) {
  864. cur = topheaders[i];
  865. next = topheaders[i + 1];
  866. if (cur === next) {
  867. ++curColspan;
  868. }
  869. else if (curColspan) {
  870. // Ended colspan
  871. // Add cur to HTML with colspan.
  872. html += getCellHTMLFromValue('th', 'highcharts-table-topheading', 'scope="col" ' +
  873. 'colspan="' + (curColspan + 1) + '"', cur);
  874. curColspan = 0;
  875. }
  876. else {
  877. // Cur is standalone. If it is same as sublevel,
  878. // remove sublevel and add just toplevel.
  879. if (cur === subheaders[i]) {
  880. if (options.exporting.useRowspanHeaders) {
  881. rowspan = 2;
  882. delete subheaders[i];
  883. }
  884. else {
  885. rowspan = 1;
  886. subheaders[i] = '';
  887. }
  888. }
  889. else {
  890. rowspan = 1;
  891. }
  892. html += getCellHTMLFromValue('th', 'highcharts-table-topheading', 'scope="col"' +
  893. (rowspan > 1 ?
  894. ' valign="top" rowspan="' + rowspan + '"' :
  895. ''), cur);
  896. }
  897. }
  898. html += '</tr>';
  899. }
  900. // Add the subheaders (the only headers if not using multilevels)
  901. if (subheaders) {
  902. html += '<tr>';
  903. for (i = 0, len = subheaders.length; i < len; ++i) {
  904. if (typeof subheaders[i] !== 'undefined') {
  905. html += getCellHTMLFromValue('th', null, 'scope="col"', subheaders[i]);
  906. }
  907. }
  908. html += '</tr>';
  909. }
  910. html += '</thead>';
  911. return html;
  912. };
  913. // Add table caption
  914. if (options.exporting.tableCaption !== false) {
  915. html += '<caption class="highcharts-table-caption">' + pick(options.exporting.tableCaption, (options.title.text ?
  916. htmlencode(options.title.text) :
  917. 'Chart')) + '</caption>';
  918. }
  919. // Find longest row
  920. for (var i = 0, len = rows.length; i < len; ++i) {
  921. if (rows[i].length > rowLength) {
  922. rowLength = rows[i].length;
  923. }
  924. }
  925. // Add header
  926. html += getTableHeaderHTML(topHeaders, subHeaders, Math.max(rowLength, subHeaders.length));
  927. // Transform the rows to HTML
  928. html += '<tbody>';
  929. rows.forEach(function (row) {
  930. html += '<tr>';
  931. for (var j = 0; j < rowLength; j++) {
  932. // Make first column a header too. Especially important for
  933. // category axes, but also might make sense for datetime? Should
  934. // await user feedback on this.
  935. html += getCellHTMLFromValue(j ? 'td' : 'th', null, j ? '' : 'scope="row"', row[j]);
  936. }
  937. html += '</tr>';
  938. });
  939. html += '</tbody></table>';
  940. var e = { html: html };
  941. fireEvent(this, 'afterGetTable', e);
  942. return e.html;
  943. };
  944. /**
  945. * Get a blob object from content, if blob is supported
  946. *
  947. * @private
  948. * @param {string} content
  949. * The content to create the blob from.
  950. * @param {string} type
  951. * The type of the content.
  952. * @return {string|undefined}
  953. * The blob object, or undefined if not supported.
  954. */
  955. function getBlobFromContent(content, type) {
  956. var nav = win.navigator,
  957. webKit = (nav.userAgent.indexOf('WebKit') > -1 &&
  958. nav.userAgent.indexOf('Chrome') < 0),
  959. domurl = win.URL || win.webkitURL || win;
  960. try {
  961. // MS specific
  962. if (nav.msSaveOrOpenBlob && win.MSBlobBuilder) {
  963. var blob = new win.MSBlobBuilder();
  964. blob.append(content);
  965. return blob.getBlob('image/svg+xml');
  966. }
  967. // Safari requires data URI since it doesn't allow navigation to blob
  968. // URLs.
  969. if (!webKit) {
  970. return domurl.createObjectURL(new win.Blob(['\uFEFF' + content], // #7084
  971. { type: type }));
  972. }
  973. }
  974. catch (e) {
  975. // Ignore
  976. }
  977. }
  978. /**
  979. * Generates a data URL of CSV for local download in the browser. This is the
  980. * default action for a click on the 'Download CSV' button.
  981. *
  982. * See {@link Highcharts.Chart#getCSV} to get the CSV data itself.
  983. *
  984. * @function Highcharts.Chart#downloadCSV
  985. *
  986. * @requires modules/exporting
  987. */
  988. Chart.prototype.downloadCSV = function () {
  989. var csv = this.getCSV(true);
  990. downloadURL(getBlobFromContent(csv, 'text/csv') ||
  991. 'data:text/csv,\uFEFF' + encodeURIComponent(csv), this.getFilename() + '.csv');
  992. };
  993. /**
  994. * Generates a data URL of an XLS document for local download in the browser.
  995. * This is the default action for a click on the 'Download XLS' button.
  996. *
  997. * See {@link Highcharts.Chart#getTable} to get the table data itself.
  998. *
  999. * @function Highcharts.Chart#downloadXLS
  1000. *
  1001. * @requires modules/exporting
  1002. */
  1003. Chart.prototype.downloadXLS = function () {
  1004. var uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' +
  1005. 'xmlns:x="urn:schemas-microsoft-com:office:excel" ' +
  1006. 'xmlns="http://www.w3.org/TR/REC-html40">' +
  1007. '<head><!--[if gte mso 9]><xml><x:ExcelWorkbook>' +
  1008. '<x:ExcelWorksheets><x:ExcelWorksheet>' +
  1009. '<x:Name>Ark1</x:Name>' +
  1010. '<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>' +
  1011. '</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>' +
  1012. '</xml><![endif]-->' +
  1013. '<style>td{border:none;font-family: Calibri, sans-serif;} ' +
  1014. '.number{mso-number-format:"0.00";} ' +
  1015. '.text{ mso-number-format:"\@";}</style>' +
  1016. '<meta name=ProgId content=Excel.Sheet>' +
  1017. '<meta charset=UTF-8>' +
  1018. '</head><body>' +
  1019. this.getTable(true) +
  1020. '</body></html>', base64 = function (s) {
  1021. return win.btoa(unescape(encodeURIComponent(s))); // #50
  1022. };
  1023. downloadURL(getBlobFromContent(template, 'application/vnd.ms-excel') ||
  1024. uri + base64(template), this.getFilename() + '.xls');
  1025. };
  1026. /**
  1027. * Export-data module required. View the data in a table below the chart.
  1028. *
  1029. * @function Highcharts.Chart#viewData
  1030. *
  1031. * @fires Highcharts.Chart#event:afterViewData
  1032. */
  1033. Chart.prototype.viewData = function () {
  1034. // Create div and generate the data table.
  1035. if (!this.dataTableDiv) {
  1036. this.dataTableDiv = doc.createElement('div');
  1037. this.dataTableDiv.className = 'highcharts-data-table';
  1038. // Insert after the chart container
  1039. this.renderTo.parentNode.insertBefore(this.dataTableDiv, this.renderTo.nextSibling);
  1040. this.dataTableDiv.innerHTML = this.getTable();
  1041. }
  1042. // Show the data table again.
  1043. if (this.dataTableDiv.style.display === '' || this.dataTableDiv.style.display === 'none') {
  1044. this.dataTableDiv.style.display = 'block';
  1045. }
  1046. this.isDataTableVisible = true;
  1047. fireEvent(this, 'afterViewData', this.dataTableDiv);
  1048. };
  1049. /**
  1050. * Export-data module required. Hide the data table when visible.
  1051. *
  1052. * @function Highcharts.Chart#hideData
  1053. */
  1054. Chart.prototype.hideData = function () {
  1055. if (this.dataTableDiv && this.dataTableDiv.style.display === 'block') {
  1056. this.dataTableDiv.style.display = 'none';
  1057. }
  1058. this.isDataTableVisible = false;
  1059. };
  1060. Chart.prototype.toggleDataTable = function () {
  1061. var exportDivElements = this.exportDivElements,
  1062. options = this.options.exporting,
  1063. menuItems = options && options.buttons && options.buttons.contextButton.menuItems,
  1064. lang = this.options.lang;
  1065. if (this.isDataTableVisible) {
  1066. this.hideData();
  1067. }
  1068. else {
  1069. this.viewData();
  1070. }
  1071. // Change the button text based on table visibility.
  1072. if ((exportingOptions === null || exportingOptions === void 0 ? void 0 : exportingOptions.menuItemDefinitions) && (lang === null || lang === void 0 ? void 0 : lang.viewData) &&
  1073. lang.hideData &&
  1074. menuItems &&
  1075. exportDivElements &&
  1076. exportDivElements.length) {
  1077. exportDivElements[menuItems.indexOf('viewData')]
  1078. .innerHTML = this.isDataTableVisible ? lang.hideData : lang.viewData;
  1079. }
  1080. };
  1081. // Add "Download CSV" to the exporting menu.
  1082. var exportingOptions = getOptions().exporting;
  1083. if (exportingOptions) {
  1084. extend(exportingOptions.menuItemDefinitions, {
  1085. downloadCSV: {
  1086. textKey: 'downloadCSV',
  1087. onclick: function () {
  1088. this.downloadCSV();
  1089. }
  1090. },
  1091. downloadXLS: {
  1092. textKey: 'downloadXLS',
  1093. onclick: function () {
  1094. this.downloadXLS();
  1095. }
  1096. },
  1097. viewData: {
  1098. textKey: 'viewData',
  1099. onclick: function () {
  1100. this.toggleDataTable();
  1101. }
  1102. }
  1103. });
  1104. if (exportingOptions.buttons) {
  1105. exportingOptions.buttons.contextButton.menuItems.push('separator', 'downloadCSV', 'downloadXLS', 'viewData');
  1106. }
  1107. }
  1108. // Series specific
  1109. if (seriesTypes.map) {
  1110. seriesTypes.map.prototype.exportKey = 'name';
  1111. }
  1112. if (seriesTypes.mapbubble) {
  1113. seriesTypes.mapbubble.prototype.exportKey = 'name';
  1114. }
  1115. if (seriesTypes.treemap) {
  1116. seriesTypes.treemap.prototype.exportKey = 'name';
  1117. }
  1118. });
  1119. _registerModule(_modules, 'masters/modules/export-data.src.js', [], function () {
  1120. });
  1121. }));