export-data.src.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. /**
  2. * @license Highcharts JS v8.0.0 (2019-12-10)
  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 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 = H.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-2019 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/Globals.js'], _modules['parts/Utilities.js']], function (Highcharts, U) {
  268. /* *
  269. *
  270. * Experimental data export module for Highcharts
  271. *
  272. * (c) 2010-2019 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. /**
  283. * Function callback to execute while data rows are processed for exporting.
  284. * This allows the modification of data rows before processed into the final
  285. * format.
  286. *
  287. * @callback Highcharts.ExportDataCallbackFunction
  288. * @extends Highcharts.EventCallbackFunction<Highcharts.Chart>
  289. *
  290. * @param {Highcharts.Chart} this
  291. * Chart context where the event occured.
  292. *
  293. * @param {Highcharts.ExportDataEventObject} event
  294. * Event object with data rows that can be modified.
  295. */
  296. /**
  297. * Contains information about the export data event.
  298. *
  299. * @interface Highcharts.ExportDataEventObject
  300. */ /**
  301. * Contains the data rows for the current export task and can be modified.
  302. * @name Highcharts.ExportDataEventObject#dataRows
  303. * @type {Array<Array<string>>}
  304. */
  305. var defined = U.defined, extend = U.extend, isObject = U.isObject, pick = U.pick;
  306. var win = Highcharts.win, doc = win.document, seriesTypes = Highcharts.seriesTypes, downloadURL = Highcharts.downloadURL, fireEvent = Highcharts.fireEvent;
  307. // Can we add this to utils? Also used in screen-reader.js
  308. /**
  309. * HTML encode some characters vulnerable for XSS.
  310. * @private
  311. * @param {string} html The input string
  312. * @return {string} The excaped string
  313. */
  314. function htmlencode(html) {
  315. return html
  316. .replace(/&/g, '&amp;')
  317. .replace(/</g, '&lt;')
  318. .replace(/>/g, '&gt;')
  319. .replace(/"/g, '&quot;')
  320. .replace(/'/g, '&#x27;')
  321. .replace(/\//g, '&#x2F;');
  322. }
  323. Highcharts.setOptions({
  324. /**
  325. * Callback that fires while exporting data. This allows the modification of
  326. * data rows before processed into the final format.
  327. *
  328. * @type {Highcharts.ExportDataCallbackFunction}
  329. * @context Highcharts.Chart
  330. * @requires modules/export-data
  331. * @apioption chart.events.exportData
  332. */
  333. /**
  334. * When set to `false` will prevent the series data from being included in
  335. * any form of data export.
  336. *
  337. * Since version 6.0.0 until 7.1.0 the option was existing undocumented
  338. * as `includeInCSVExport`.
  339. *
  340. * @type {boolean}
  341. * @since 7.1.0
  342. * @requires modules/export-data
  343. * @apioption plotOptions.series.includeInDataExport
  344. */
  345. /**
  346. * @optionparent exporting
  347. * @private
  348. */
  349. exporting: {
  350. /**
  351. * Caption for the data table. Same as chart title by default. Set to
  352. * `false` to disable.
  353. *
  354. * @sample highcharts/export-data/multilevel-table
  355. * Multiple table headers
  356. *
  357. * @type {boolean|string}
  358. * @since 6.0.4
  359. * @requires modules/export-data
  360. * @apioption exporting.tableCaption
  361. */
  362. /**
  363. * Options for exporting data to CSV or ExCel, or displaying the data
  364. * in a HTML table or a JavaScript structure.
  365. *
  366. * This module adds data export options to the export menu and provides
  367. * functions like `Chart.getCSV`, `Chart.getTable`, `Chart.getDataRows`
  368. * and `Chart.viewData`.
  369. *
  370. * The XLS converter is limited and only creates a HTML string that is
  371. * passed for download, which works but creates a warning before
  372. * opening. The workaround for this is to use a third party XLSX
  373. * converter, as demonstrated in the sample below.
  374. *
  375. * @sample highcharts/export-data/categorized/ Categorized data
  376. * @sample highcharts/export-data/stock-timeaxis/ Highstock time axis
  377. * @sample highcharts/export-data/xlsx/
  378. * Using a third party XLSX converter
  379. *
  380. * @since 6.0.0
  381. * @requires modules/export-data
  382. */
  383. csv: {
  384. /**
  385. * Formatter callback for the column headers. Parameters are:
  386. * - `item` - The series or axis object)
  387. * - `key` - The point key, for example y or z
  388. * - `keyLength` - The amount of value keys for this item, for
  389. * example a range series has the keys `low` and `high` so the
  390. * key length is 2.
  391. *
  392. * If [useMultiLevelHeaders](#exporting.useMultiLevelHeaders) is
  393. * true, columnHeaderFormatter by default returns an object with
  394. * columnTitle and topLevelColumnTitle for each key. Columns with
  395. * the same topLevelColumnTitle have their titles merged into a
  396. * single cell with colspan for table/Excel export.
  397. *
  398. * If `useMultiLevelHeaders` is false, or for CSV export, it returns
  399. * the series name, followed by the key if there is more than one
  400. * key.
  401. *
  402. * For the axis it returns the axis title or "Category" or
  403. * "DateTime" by default.
  404. *
  405. * Return `false` to use Highcharts' proposed header.
  406. *
  407. * @sample highcharts/export-data/multilevel-table
  408. * Multiple table headers
  409. *
  410. * @type {Function|null}
  411. */
  412. columnHeaderFormatter: null,
  413. /**
  414. * Which date format to use for exported dates on a datetime X axis.
  415. * See `Highcharts.dateFormat`.
  416. */
  417. dateFormat: '%Y-%m-%d %H:%M:%S',
  418. /**
  419. * Which decimal point to use for exported CSV. Defaults to the same
  420. * as the browser locale, typically `.` (English) or `,` (German,
  421. * French etc).
  422. *
  423. * @type {string|null}
  424. * @since 6.0.4
  425. */
  426. decimalPoint: null,
  427. /**
  428. * The item delimiter in the exported data. Use `;` for direct
  429. * exporting to Excel. Defaults to a best guess based on the browser
  430. * locale. If the locale _decimal point_ is `,`, the `itemDelimiter`
  431. * defaults to `;`, otherwise the `itemDelimiter` defaults to `,`.
  432. *
  433. * @type {string|null}
  434. */
  435. itemDelimiter: null,
  436. /**
  437. * The line delimiter in the exported data, defaults to a newline.
  438. */
  439. lineDelimiter: '\n'
  440. },
  441. /**
  442. * Show a HTML table below the chart with the chart's current data.
  443. *
  444. * @sample highcharts/export-data/showtable/
  445. * Show the table
  446. * @sample highcharts/studies/exporting-table-html
  447. * Experiment with putting the table inside the subtitle to
  448. * allow exporting it.
  449. *
  450. * @since 6.0.0
  451. * @requires modules/export-data
  452. */
  453. showTable: false,
  454. /**
  455. * Use multi level headers in data table. If [csv.columnHeaderFormatter
  456. * ](#exporting.csv.columnHeaderFormatter) is defined, it has to return
  457. * objects in order for multi level headers to work.
  458. *
  459. * @sample highcharts/export-data/multilevel-table
  460. * Multiple table headers
  461. *
  462. * @since 6.0.4
  463. * @requires modules/export-data
  464. */
  465. useMultiLevelHeaders: true,
  466. /**
  467. * If using multi level table headers, use rowspans for headers that
  468. * have only one level.
  469. *
  470. * @sample highcharts/export-data/multilevel-table
  471. * Multiple table headers
  472. *
  473. * @since 6.0.4
  474. * @requires modules/export-data
  475. */
  476. useRowspanHeaders: true
  477. },
  478. /**
  479. * @optionparent lang
  480. *
  481. * @private
  482. */
  483. lang: {
  484. /**
  485. * The text for the menu item.
  486. *
  487. * @since 6.0.0
  488. * @requires modules/export-data
  489. */
  490. downloadCSV: 'Download CSV',
  491. /**
  492. * The text for the menu item.
  493. *
  494. * @since 6.0.0
  495. * @requires modules/export-data
  496. */
  497. downloadXLS: 'Download XLS',
  498. /**
  499. * The text for the menu item.
  500. *
  501. * @since 6.1.0
  502. * @requires modules/export-data
  503. */
  504. openInCloud: 'Open in Highcharts Cloud',
  505. /**
  506. * The text for the menu item.
  507. *
  508. * @since 6.0.0
  509. * @requires modules/export-data
  510. */
  511. viewData: 'View data table'
  512. }
  513. });
  514. /* eslint-disable no-invalid-this */
  515. // Add an event listener to handle the showTable option
  516. Highcharts.addEvent(Highcharts.Chart, 'render', function () {
  517. if (this.options &&
  518. this.options.exporting &&
  519. this.options.exporting.showTable &&
  520. !this.options.chart.forExport) {
  521. this.viewData();
  522. }
  523. });
  524. /* eslint-enable no-invalid-this */
  525. /**
  526. * Set up key-to-axis bindings. This is used when the Y axis is datetime or
  527. * categorized. For example in an arearange series, the low and high values
  528. * should be formatted according to the Y axis type, and in order to link them
  529. * we need this map.
  530. *
  531. * @private
  532. * @function Highcharts.Chart#setUpKeyToAxis
  533. * @return {void}
  534. */
  535. Highcharts.Chart.prototype.setUpKeyToAxis = function () {
  536. if (seriesTypes.arearange) {
  537. seriesTypes.arearange.prototype.keyToAxis = {
  538. low: 'y',
  539. high: 'y'
  540. };
  541. }
  542. if (seriesTypes.gantt) {
  543. seriesTypes.gantt.prototype.keyToAxis = {
  544. start: 'x',
  545. end: 'x'
  546. };
  547. }
  548. };
  549. /**
  550. * Export-data module required. Returns a two-dimensional array containing the
  551. * current chart data.
  552. *
  553. * @function Highcharts.Chart#getDataRows
  554. *
  555. * @param {boolean} [multiLevelHeaders]
  556. * Use multilevel headers for the rows by default. Adds an extra row with
  557. * top level headers. If a custom columnHeaderFormatter is defined, this
  558. * can override the behavior.
  559. *
  560. * @return {Array<Array<(number|string)>>}
  561. * The current chart data
  562. *
  563. * @fires Highcharts.Chart#event:exportData
  564. */
  565. Highcharts.Chart.prototype.getDataRows = function (multiLevelHeaders) {
  566. 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,
  567. // Options
  568. columnHeaderFormatter = function (item, key, keyLength) {
  569. if (csvOptions.columnHeaderFormatter) {
  570. var s = csvOptions.columnHeaderFormatter(item, key, keyLength);
  571. if (s !== false) {
  572. return s;
  573. }
  574. }
  575. if (!item) {
  576. return 'Category';
  577. }
  578. if (item instanceof Highcharts.Axis) {
  579. return (item.options.title && item.options.title.text) ||
  580. (item.isDatetimeAxis ? 'DateTime' : 'Category');
  581. }
  582. if (multiLevelHeaders) {
  583. return {
  584. columnTitle: keyLength > 1 ?
  585. key :
  586. item.name,
  587. topLevelColumnTitle: item.name
  588. };
  589. }
  590. return item.name + (keyLength > 1 ? ' (' + key + ')' : '');
  591. },
  592. // Map the categories for value axes
  593. getCategoryAndDateTimeMap = function (series, pointArrayMap, pIdx) {
  594. var categoryMap = {}, dateTimeValueAxisMap = {};
  595. pointArrayMap.forEach(function (prop) {
  596. var axisName = ((series.keyToAxis && series.keyToAxis[prop]) ||
  597. prop) + 'Axis',
  598. // Points in parallel coordinates refers to all yAxis
  599. // not only `series.yAxis`
  600. axis = Highcharts.isNumber(pIdx) ?
  601. series.chart[axisName][pIdx] :
  602. series[axisName];
  603. categoryMap[prop] = (axis && axis.categories) || [];
  604. dateTimeValueAxisMap[prop] = (axis && axis.isDatetimeAxis);
  605. });
  606. return {
  607. categoryMap: categoryMap,
  608. dateTimeValueAxisMap: dateTimeValueAxisMap
  609. };
  610. }, xAxisIndices = [];
  611. // Loop the series and index values
  612. i = 0;
  613. this.setUpKeyToAxis();
  614. this.series.forEach(function (series) {
  615. var keys = series.options.keys, pointArrayMap = keys || series.pointArrayMap || ['y'], valueCount = pointArrayMap.length, xTaken = !series.requireSorting && {}, xAxisIndex = xAxes.indexOf(series.xAxis), categoryAndDatetimeMap = getCategoryAndDateTimeMap(series, pointArrayMap), mockSeries, j;
  616. if (series.options.includeInDataExport !== false &&
  617. !series.options.isInternal &&
  618. series.visible !== false // #55
  619. ) {
  620. // Build a lookup for X axis index and the position of the first
  621. // series that belongs to that X axis. Includes -1 for non-axis
  622. // series types like pies.
  623. if (!Highcharts.find(xAxisIndices, function (index) {
  624. return index[0] === xAxisIndex;
  625. })) {
  626. xAxisIndices.push([xAxisIndex, i]);
  627. }
  628. // Compute the column headers and top level headers, usually the
  629. // same as series names
  630. j = 0;
  631. while (j < valueCount) {
  632. columnTitleObj = columnHeaderFormatter(series, pointArrayMap[j], pointArrayMap.length);
  633. columnTitles.push(columnTitleObj.columnTitle || columnTitleObj);
  634. if (multiLevelHeaders) {
  635. topLevelColumnTitles.push(columnTitleObj.topLevelColumnTitle ||
  636. columnTitleObj);
  637. }
  638. j++;
  639. }
  640. mockSeries = {
  641. chart: series.chart,
  642. autoIncrement: series.autoIncrement,
  643. options: series.options,
  644. pointArrayMap: series.pointArrayMap
  645. };
  646. // Export directly from options.data because we need the uncropped
  647. // data (#7913), and we need to support Boost (#7026).
  648. series.options.data.forEach(function eachData(options, pIdx) {
  649. var key, prop, val, name, point;
  650. // In parallel coordinates chart, each data point is connected
  651. // to a separate yAxis, conform this
  652. if (hasParallelCoords) {
  653. categoryAndDatetimeMap = getCategoryAndDateTimeMap(series, pointArrayMap, pIdx);
  654. }
  655. point = { series: mockSeries };
  656. series.pointClass.prototype.applyOptions.apply(point, [options]);
  657. key = point.x;
  658. name = series.data[pIdx] && series.data[pIdx].name;
  659. j = 0;
  660. // Pies, funnels, geo maps etc. use point name in X row
  661. if (!series.xAxis || series.exportKey === 'name') {
  662. key = name;
  663. }
  664. if (xTaken) {
  665. if (xTaken[key]) {
  666. key += '|' + pIdx;
  667. }
  668. xTaken[key] = true;
  669. }
  670. if (!rows[key]) {
  671. // Generate the row
  672. rows[key] = [];
  673. // Contain the X values from one or more X axes
  674. rows[key].xValues = [];
  675. }
  676. rows[key].x = point.x;
  677. rows[key].name = name;
  678. rows[key].xValues[xAxisIndex] = point.x;
  679. while (j < valueCount) {
  680. prop = pointArrayMap[j]; // y, z etc
  681. val = point[prop];
  682. rows[key][i + j] = pick(
  683. // Y axis category if present
  684. categoryAndDatetimeMap.categoryMap[prop][val],
  685. // datetime yAxis
  686. categoryAndDatetimeMap.dateTimeValueAxisMap[prop] ?
  687. time.dateFormat(csvOptions.dateFormat, val) :
  688. null,
  689. // linear/log yAxis
  690. val);
  691. j++;
  692. }
  693. });
  694. i = i + j;
  695. }
  696. });
  697. // Make a sortable array
  698. for (x in rows) {
  699. if (Object.hasOwnProperty.call(rows, x)) {
  700. rowArr.push(rows[x]);
  701. }
  702. }
  703. var xAxisIndex, column;
  704. // Add computed column headers and top level headers to final row set
  705. dataRows = multiLevelHeaders ? [topLevelColumnTitles, columnTitles] :
  706. [columnTitles];
  707. i = xAxisIndices.length;
  708. while (i--) { // Start from end to splice in
  709. xAxisIndex = xAxisIndices[i][0];
  710. column = xAxisIndices[i][1];
  711. xAxis = xAxes[xAxisIndex];
  712. // Sort it by X values
  713. rowArr.sort(function (// eslint-disable-line no-loop-func
  714. a, b) {
  715. return a.xValues[xAxisIndex] - b.xValues[xAxisIndex];
  716. });
  717. // Add header row
  718. xTitle = columnHeaderFormatter(xAxis);
  719. dataRows[0].splice(column, 0, xTitle);
  720. if (multiLevelHeaders && dataRows[1]) {
  721. // If using multi level headers, we just added top level header.
  722. // Also add for sub level
  723. dataRows[1].splice(column, 0, xTitle);
  724. }
  725. // Add the category column
  726. rowArr.forEach(function (// eslint-disable-line no-loop-func
  727. row) {
  728. var category = row.name;
  729. if (xAxis && !defined(category)) {
  730. if (xAxis.isDatetimeAxis) {
  731. if (row.x instanceof Date) {
  732. row.x = row.x.getTime();
  733. }
  734. category = time.dateFormat(csvOptions.dateFormat, row.x);
  735. }
  736. else if (xAxis.categories) {
  737. category = pick(xAxis.names[row.x], xAxis.categories[row.x], row.x);
  738. }
  739. else {
  740. category = row.x;
  741. }
  742. }
  743. // Add the X/date/category
  744. row.splice(column, 0, category);
  745. });
  746. }
  747. dataRows = dataRows.concat(rowArr);
  748. fireEvent(this, 'exportData', { dataRows: dataRows });
  749. return dataRows;
  750. };
  751. /**
  752. * Export-data module required. Returns the current chart data as a CSV string.
  753. *
  754. * @function Highcharts.Chart#getCSV
  755. *
  756. * @param {boolean} [useLocalDecimalPoint]
  757. * Whether to use the local decimal point as detected from the browser.
  758. * This makes it easier to export data to Excel in the same locale as the
  759. * user is.
  760. *
  761. * @return {string}
  762. * CSV representation of the data
  763. */
  764. Highcharts.Chart.prototype.getCSV = function (useLocalDecimalPoint) {
  765. var csv = '', rows = this.getDataRows(), csvOptions = this.options.exporting.csv, decimalPoint = pick(csvOptions.decimalPoint, csvOptions.itemDelimiter !== ',' && useLocalDecimalPoint ?
  766. (1.1).toLocaleString()[1] :
  767. '.'),
  768. // use ';' for direct to Excel
  769. itemDelimiter = pick(csvOptions.itemDelimiter, decimalPoint === ',' ? ';' : ','),
  770. // '\n' isn't working with the js csv data extraction
  771. lineDelimiter = csvOptions.lineDelimiter;
  772. // Transform the rows to CSV
  773. rows.forEach(function (row, i) {
  774. var val = '', j = row.length;
  775. while (j--) {
  776. val = row[j];
  777. if (typeof val === 'string') {
  778. val = '"' + val + '"';
  779. }
  780. if (typeof val === 'number') {
  781. if (decimalPoint !== '.') {
  782. val = val.toString().replace('.', decimalPoint);
  783. }
  784. }
  785. row[j] = val;
  786. }
  787. // Add the values
  788. csv += row.join(itemDelimiter);
  789. // Add the line delimiter
  790. if (i < rows.length - 1) {
  791. csv += lineDelimiter;
  792. }
  793. });
  794. return csv;
  795. };
  796. /**
  797. * Export-data module required. Build a HTML table with the chart's current
  798. * data.
  799. *
  800. * @sample highcharts/export-data/viewdata/
  801. * View the data from the export menu
  802. *
  803. * @function Highcharts.Chart#getTable
  804. *
  805. * @param {boolean} [useLocalDecimalPoint]
  806. * Whether to use the local decimal point as detected from the browser.
  807. * This makes it easier to export data to Excel in the same locale as the
  808. * user is.
  809. *
  810. * @return {string}
  811. * HTML representation of the data.
  812. *
  813. * @fires Highcharts.Chart#event:afterGetTable
  814. */
  815. Highcharts.Chart.prototype.getTable = function (useLocalDecimalPoint) {
  816. 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(),
  817. // Compare two rows for equality
  818. isRowEqual = function (row1, row2) {
  819. var i = row1.length;
  820. if (row2.length === i) {
  821. while (i--) {
  822. if (row1[i] !== row2[i]) {
  823. return false;
  824. }
  825. }
  826. }
  827. else {
  828. return false;
  829. }
  830. return true;
  831. },
  832. // Get table cell HTML from value
  833. getCellHTMLFromValue = function (tag, classes, attrs, value) {
  834. var val = pick(value, ''), className = 'text' + (classes ? ' ' + classes : '');
  835. // Convert to string if number
  836. if (typeof val === 'number') {
  837. val = val.toString();
  838. if (decimalPoint === ',') {
  839. val = val.replace('.', decimalPoint);
  840. }
  841. className = 'number';
  842. }
  843. else if (!value) {
  844. className = 'empty';
  845. }
  846. return '<' + tag + (attrs ? ' ' + attrs : '') +
  847. ' class="' + className + '">' +
  848. val + '</' + tag + '>';
  849. },
  850. // Get table header markup from row data
  851. getTableHeaderHTML = function (topheaders, subheaders, rowLength) {
  852. var html = '<thead>', i = 0, len = rowLength || subheaders && subheaders.length, next, cur, curColspan = 0, 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, webKit = (nav.userAgent.indexOf('WebKit') > -1 &&
  956. nav.userAgent.indexOf('Chrome') < 0), domurl = win.URL || win.webkitURL || win;
  957. try {
  958. // MS specific
  959. if (nav.msSaveOrOpenBlob && win.MSBlobBuilder) {
  960. var blob = new win.MSBlobBuilder();
  961. blob.append(content);
  962. return blob.getBlob('image/svg+xml');
  963. }
  964. // Safari requires data URI since it doesn't allow navigation to blob
  965. // URLs.
  966. if (!webKit) {
  967. return domurl.createObjectURL(new win.Blob(['\uFEFF' + content], // #7084
  968. { type: type }));
  969. }
  970. }
  971. catch (e) {
  972. // Ignore
  973. }
  974. }
  975. /**
  976. * Call this on click of 'Download CSV' button
  977. *
  978. * @private
  979. * @function Highcharts.Chart#downloadCSV
  980. * @return {void}
  981. */
  982. Highcharts.Chart.prototype.downloadCSV = function () {
  983. var csv = this.getCSV(true);
  984. downloadURL(getBlobFromContent(csv, 'text/csv') ||
  985. 'data:text/csv,\uFEFF' + encodeURIComponent(csv), this.getFilename() + '.csv');
  986. };
  987. /**
  988. * Call this on click of 'Download XLS' button
  989. *
  990. * @private
  991. * @function Highcharts.Chart#downloadXLS
  992. * @return {void}
  993. */
  994. Highcharts.Chart.prototype.downloadXLS = function () {
  995. var uri = 'data:application/vnd.ms-excel;base64,', template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" ' +
  996. 'xmlns:x="urn:schemas-microsoft-com:office:excel" ' +
  997. 'xmlns="http://www.w3.org/TR/REC-html40">' +
  998. '<head><!--[if gte mso 9]><xml><x:ExcelWorkbook>' +
  999. '<x:ExcelWorksheets><x:ExcelWorksheet>' +
  1000. '<x:Name>Ark1</x:Name>' +
  1001. '<x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions>' +
  1002. '</x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook>' +
  1003. '</xml><![endif]-->' +
  1004. '<style>td{border:none;font-family: Calibri, sans-serif;} ' +
  1005. '.number{mso-number-format:"0.00";} ' +
  1006. '.text{ mso-number-format:"\@";}</style>' +
  1007. '<meta name=ProgId content=Excel.Sheet>' +
  1008. '<meta charset=UTF-8>' +
  1009. '</head><body>' +
  1010. this.getTable(true) +
  1011. '</body></html>', base64 = function (s) {
  1012. return win.btoa(unescape(encodeURIComponent(s))); // #50
  1013. };
  1014. downloadURL(getBlobFromContent(template, 'application/vnd.ms-excel') ||
  1015. uri + base64(template), this.getFilename() + '.xls');
  1016. };
  1017. /**
  1018. * Export-data module required. View the data in a table below the chart.
  1019. *
  1020. * @function Highcharts.Chart#viewData
  1021. * @return {void}
  1022. *
  1023. * @fires Highcharts.Chart#event:afterViewData
  1024. */
  1025. Highcharts.Chart.prototype.viewData = function () {
  1026. if (!this.dataTableDiv) {
  1027. this.dataTableDiv = doc.createElement('div');
  1028. this.dataTableDiv.className = 'highcharts-data-table';
  1029. // Insert after the chart container
  1030. this.renderTo.parentNode.insertBefore(this.dataTableDiv, this.renderTo.nextSibling);
  1031. }
  1032. this.dataTableDiv.innerHTML = this.getTable();
  1033. fireEvent(this, 'afterViewData', this.dataTableDiv);
  1034. };
  1035. /**
  1036. * Experimental function to send a chart's config to the Cloud for editing.
  1037. *
  1038. * Limitations
  1039. * - All functions (formatters and callbacks) are removed since they're not
  1040. * JSON.
  1041. *
  1042. * @function Highcharts.Chart#openInCloud
  1043. * @return {void}
  1044. *
  1045. * @todo
  1046. * - Let the Cloud throw a friendly warning about unsupported structures like
  1047. * formatters.
  1048. * - Dynamically updated charts probably fail, we need a generic
  1049. * Chart.getOptions function that returns all non-default options. Should also
  1050. * be used by the export module.
  1051. */
  1052. Highcharts.Chart.prototype.openInCloud = function () {
  1053. var options, paramObj, params;
  1054. /**
  1055. * Recursively remove function callbacks.
  1056. * @private
  1057. * @param {*} obj
  1058. * Container of function callbacks
  1059. * @return {void}
  1060. */
  1061. function removeFunctions(obj) {
  1062. Object.keys(obj).forEach(function (key) {
  1063. if (typeof obj[key] === 'function') {
  1064. delete obj[key];
  1065. }
  1066. if (isObject(obj[key])) { // object and not an array
  1067. removeFunctions(obj[key]);
  1068. }
  1069. });
  1070. }
  1071. /**
  1072. * @private
  1073. * @return {void}
  1074. */
  1075. function openInCloud() {
  1076. var form = doc.createElement('form');
  1077. doc.body.appendChild(form);
  1078. form.method = 'post';
  1079. form.action = 'https://cloud-api.highcharts.com/openincloud';
  1080. form.target = '_blank';
  1081. var input = doc.createElement('input');
  1082. input.type = 'hidden';
  1083. input.name = 'chart';
  1084. input.value = params;
  1085. form.appendChild(input);
  1086. form.submit();
  1087. doc.body.removeChild(form);
  1088. }
  1089. options = Highcharts.merge(this.userOptions);
  1090. removeFunctions(options);
  1091. paramObj = {
  1092. name: (options.title && options.title.text) || 'Chart title',
  1093. options: options,
  1094. settings: {
  1095. constructor: 'Chart',
  1096. dataProvider: {
  1097. csv: this.getCSV()
  1098. }
  1099. }
  1100. };
  1101. params = JSON.stringify(paramObj);
  1102. openInCloud();
  1103. };
  1104. // Add "Download CSV" to the exporting menu.
  1105. var exportingOptions = Highcharts.getOptions().exporting;
  1106. if (exportingOptions) {
  1107. extend(exportingOptions.menuItemDefinitions, {
  1108. downloadCSV: {
  1109. textKey: 'downloadCSV',
  1110. onclick: function () {
  1111. this.downloadCSV();
  1112. }
  1113. },
  1114. downloadXLS: {
  1115. textKey: 'downloadXLS',
  1116. onclick: function () {
  1117. this.downloadXLS();
  1118. }
  1119. },
  1120. viewData: {
  1121. textKey: 'viewData',
  1122. onclick: function () {
  1123. this.viewData();
  1124. }
  1125. },
  1126. openInCloud: {
  1127. textKey: 'openInCloud',
  1128. onclick: function () {
  1129. this.openInCloud();
  1130. }
  1131. }
  1132. });
  1133. if (exportingOptions.buttons) {
  1134. exportingOptions.buttons.contextButton.menuItems.push('separator', 'downloadCSV', 'downloadXLS', 'viewData', 'openInCloud');
  1135. }
  1136. }
  1137. // Series specific
  1138. if (seriesTypes.map) {
  1139. seriesTypes.map.prototype.exportKey = 'name';
  1140. }
  1141. if (seriesTypes.mapbubble) {
  1142. seriesTypes.mapbubble.prototype.exportKey = 'name';
  1143. }
  1144. if (seriesTypes.treemap) {
  1145. seriesTypes.treemap.prototype.exportKey = 'name';
  1146. }
  1147. });
  1148. _registerModule(_modules, 'masters/modules/export-data.src.js', [], function () {
  1149. });
  1150. }));