export-data.src.js 48 KB

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