export-data.src.js 48 KB

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