UNPKG

highcharts

Version:
1,439 lines (1,410 loc) 108 kB
// SPDX-License-Identifier: LicenseRef-Highcharts /** * @license Highcharts JS v13.0.1 (2026-08-17) * @module highcharts/modules/data * @requires highcharts * * Data module * * (c) 2012-2026 Highsoft AS * Author: Torstein Hønsi * * A commercial license may be required depending on use, * see www.highcharts.com/license */ import * as __WEBPACK_EXTERNAL_MODULE__highcharts_src_js_8202131d__ from "../highcharts.src.js"; /******/ // The require scope /******/ const __webpack_require__ = {}; /******/ /************************************************************************/ /******/ /* webpack/runtime/compat get default export */ /******/ (() => { /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = (module) => { /******/ const getter = module && module.__esModule ? /******/ () => (module['default']) : /******/ () => (module); /******/ __webpack_require__.d(getter, { a: getter }); /******/ return getter; /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter/value functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ if(Array.isArray(definition)) { /******/ var i = 0; /******/ while(i < definition.length) { /******/ var key = definition[i++]; /******/ var binding = definition[i++]; /******/ if(!__webpack_require__.o(exports, key)) { /******/ if(binding === 0) { /******/ Object.defineProperty(exports, key, { enumerable: true, value: definition[i++] }); /******/ } else { /******/ Object.defineProperty(exports, key, { enumerable: true, get: binding }); /******/ } /******/ } else if(binding === 0) { i++; } /******/ } /******/ } else { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) /******/ })(); /******/ /************************************************************************/ ;// external ["../highcharts.src.js","default"] const external_highcharts_src_js_default_namespaceObject = __WEBPACK_EXTERNAL_MODULE__highcharts_src_js_8202131d__["default"]; var external_highcharts_src_js_default_default = /*#__PURE__*/__webpack_require__.n(external_highcharts_src_js_default_namespaceObject); ;// ./code/es-modules/Core/HttpUtilities.js /* * * * (c) 2010-2026 Highsoft AS * Author: Christer Vasseng, Torstein Hønsi * * Integration of this software requires a license. * - For commercial use, see www.highcharts.com/license * - For non-commercial, see www.highcharts.com/license-eula * * * */ const { win } = (external_highcharts_src_js_default_default()); /* * * * Functions * * */ /** * Perform an Ajax call. * * @function Highcharts.ajax * * @param {Highcharts.AjaxSettingsObject} settings * The Ajax settings to use. * * @return {false | undefined} * Returns false, if error occurred. */ function ajax(settings) { const headers = { json: 'application/json', xml: 'application/xml', text: 'text/plain', octet: 'application/octet-stream' }, r = new XMLHttpRequest(); /** * Private error handler. * @internal * @param {XMLHttpRequest} xhr * Internal request object. * @param {string | Error} err * Occurred error. */ function handleError(xhr, err) { if (settings.error) { settings.error(xhr, err); } else { // @todo Maybe emit a highcharts error event here } } if (!settings.url) { return false; } r.open((settings.type || 'get').toUpperCase(), settings.url, true); if (!settings.headers?.['Content-Type']) { r.setRequestHeader('Content-Type', headers[settings.dataType || 'json'] || headers.text); } (0,external_highcharts_src_js_default_namespaceObject.objectEach)(settings.headers, function (val, key) { r.setRequestHeader(key, val); }); if (settings.responseType) { r.responseType = settings.responseType; } // @todo lacking timeout handling r.onreadystatechange = function () { let res; if (r.readyState === 4) { if (r.status === 200) { if (settings.responseType !== 'blob') { res = r.responseText; if (settings.dataType === 'json') { try { res = JSON.parse(res); } catch (e) { if (e instanceof Error) { return handleError(r, e); } } } } return settings.success?.(res, r); } handleError(r, r.responseText); } }; if (settings.data && typeof settings.data !== 'string') { settings.data = JSON.stringify(settings.data); } r.send(settings.data); } /** * Get a JSON resource over XHR, also supporting CORS without preflight. * * @function Highcharts.getJSON * * @param {string} url * The URL to load. * @param {Function} success * The success callback. For error handling, use the `Highcharts.ajax` function * instead. */ function getJSON(url, success) { HttpUtilities.ajax({ url: url, success: success, dataType: 'json', headers: { // Override the Content-Type to avoid preflight problems with CORS // in the Highcharts demos 'Content-Type': 'text/plain' } }); } /** * The post utility. * * @internal * @function Highcharts.post * * @param {string} url * Post URL. * * @param {Object} data * Post data. * * @param {RequestInit} [fetchOptions] * Additional attributes for the post request. */ async function post(url, data, fetchOptions) { // Prepare a form to send the data const formData = new win.FormData(); // Add the data to the form (0,external_highcharts_src_js_default_namespaceObject.objectEach)(data, function (value, name) { formData.append(name, value); }); formData.append('b64', 'true'); // Send the POST const response = await win.fetch(url, { method: 'POST', body: formData, ...fetchOptions }); // Check the response if (response.ok) { // Get the text from the response const text = await response.text(); // Prepare self-click link with the Base64 representation const link = document.createElement('a'); link.href = `data:${data.type};base64,${text}`; link.download = data.filename; link.click(); // Remove the link (0,external_highcharts_src_js_default_namespaceObject.discardElement)(link); } } /** * Utility functions for Ajax. * @class * @name Highcharts.HttpUtilities */ const HttpUtilities = { ajax, getJSON }; HttpUtilities.post = post; /* harmony default export */ const Core_HttpUtilities = (HttpUtilities); /* * * * API Declarations * * */ /** * @interface Highcharts.AjaxSettingsObject */ /** * The payload to send. * * @name Highcharts.AjaxSettingsObject#data * @type {string | Highcharts.Dictionary<any> | undefined} */ /** * The data type expected. * * @name Highcharts.AjaxSettingsObject#dataType * @type {"json" | "xml" | "text" | "octet" | undefined} */ /** * Function to call on error. * * @name Highcharts.AjaxSettingsObject#error * @type {Function | undefined} */ /** * The headers; keyed on header name. * * @name Highcharts.AjaxSettingsObject#headers * @type {Highcharts.Dictionary<string> | undefined} */ /** * Function to call on success. * * @name Highcharts.AjaxSettingsObject#success * @type {Function | undefined} */ /** * The HTTP method to use. For example GET or POST. * * @name Highcharts.AjaxSettingsObject#type * @type {string | undefined} */ /** * The URL to call. * * @name Highcharts.AjaxSettingsObject#url * @type {string} */ (''); // Keeps doclets above in JS file ;// external ["../highcharts.src.js","default","Axis"] const external_highcharts_src_js_default_Axis_namespaceObject = __WEBPACK_EXTERNAL_MODULE__highcharts_src_js_8202131d__["default"].Axis; var external_highcharts_src_js_default_Axis_default = /*#__PURE__*/__webpack_require__.n(external_highcharts_src_js_default_Axis_namespaceObject); ;// external ["../highcharts.src.js","default","Chart"] const external_highcharts_src_js_default_Chart_namespaceObject = __WEBPACK_EXTERNAL_MODULE__highcharts_src_js_8202131d__["default"].Chart; var external_highcharts_src_js_default_Chart_default = /*#__PURE__*/__webpack_require__.n(external_highcharts_src_js_default_Chart_namespaceObject); ;// ./code/es-modules/Data/ColumnUtils.js /* * * * (c) 2020-2026 Highsoft AS * * Integration of this software requires a license. * - For commercial use, see www.highcharts.com/license * - For non-commercial, see www.highcharts.com/license-eula * * * Authors: * - Dawid Draguła * * */ /* * * * Functions * * */ /** * Sets the length of the column array. * * @param {DataTableColumn} column * Column to be modified. * * @param {number} length * New length of the column. * * @param {boolean} asSubarray * If column is a typed array, return a subarray instead of a new array. It * is faster `O(1)`, but the entire buffer will be kept in memory until all * views of it are destroyed. Default is `false`. * * @return {DataTableColumn} * Modified column. * * @private */ function setLength(column, length, asSubarray) { if (Array.isArray(column)) { column.length = length; return column; } return column[asSubarray ? 'subarray' : 'slice'](0, length); } /** * Splices a column array. * * @param {DataTableColumn} column * Column to be modified. * * @param {number} start * Index at which to start changing the array. * * @param {number} deleteCount * An integer indicating the number of old array elements to remove. * * @param {boolean} removedAsSubarray * If column is a typed array, return a subarray instead of a new array. It * is faster `O(1)`, but the entire buffer will be kept in memory until all * views to it are destroyed. Default is `true`. * * @param {Array<number>|TypedArray} items * The elements to add to the array, beginning at the start index. If you * don't specify any elements, `splice()` will only remove elements from the * array. * * @return {SpliceResult} * Object containing removed elements and the modified column. * * @private */ function splice(column, start, deleteCount, removedAsSubarray, items = []) { if (Array.isArray(column)) { if (!Array.isArray(items)) { items = Array.from(items); } return { removed: column.splice(start, deleteCount, ...items), array: column }; } const Constructor = Object.getPrototypeOf(column) .constructor; const removed = column[removedAsSubarray ? 'subarray' : 'slice'](start, start + deleteCount); const newLength = column.length - deleteCount + items.length; const result = new Constructor(newLength); result.set(column.subarray(0, start), 0); result.set(items, start); result.set(column.subarray(start + deleteCount), start + items.length); return { removed: removed, array: result }; } /** * Converts a cell value to a number. * * @param {DataTableCellType} value * Cell value to convert to a number. * * @param {boolean} useNaN * If `true`, returns `NaN` for non-numeric values; if `false`, * returns `null` instead. * * @return {number | null} * Number or `null` if the value is not a number. * * @private */ function convertToNumber(value, useNaN) { switch (typeof value) { case 'boolean': return (value ? 1 : 0); case 'number': return (isNaN(value) && !useNaN ? null : value); default: value = parseFloat(`${value ?? ''}`); return (isNaN(value) && !useNaN ? null : value); } } /* * * * Default Export * * */ const ColumnUtils = { convertToNumber, setLength, splice }; /* harmony default export */ const Data_ColumnUtils = (ColumnUtils); ;// ./code/es-modules/Data/DataTableCore.js /* * * * (c) 2009-2026 Highsoft AS * * Integration of this software requires a license. * - For commercial use, see www.highcharts.com/license * - For non-commercial, see www.highcharts.com/license-eula * * * Authors: * - Sophie Bremer * - Gøran Slettemark * - Torstein Hønsi * * */ const { setLength: DataTableCore_setLength, splice: DataTableCore_splice } = Data_ColumnUtils; /* * * * Class * * */ /** * Class to manage columns and rows in a table structure. It provides methods * to add, remove, and manipulate columns and rows, as well as to retrieve data * from specific cells. * * Highcharts allows passing a `DataTable` or a configuration object for a data * table in the `dataTable` property, either chart-level * [dataTable](https://api.highcharts.com/highcharts/dataTable) or as * [series.dataTable](https://api.highcharts.com/highcharts/series.dataTable). * The `DataTable` is then used as a source for the series data points, mapped * by the `series.dataMapping` option. * * After chart instantiation, the data table can be accessed from the series as * `series.dataTable`. CRUD operations on the data table will be reflected in * the chart. * * @example * const dataTable = new Highcharts.DataTable({ * columns: { * year: [2020, 2021, 2022, 2023], * cost: [11, 13, 12, 14], * revenue: [12, 15, 14, 18] * } * }); * * @class * @name Highcharts.DataTable * * @param {Highcharts.DataTableOptionsObject} [options] * Options to initialize the new DataTable instance. */ class DataTableCore { constructor(options = {}) { this.isDataTable = true; this.autoId = !options.id; this.columns = {}; this.id = (options.id || (0,external_highcharts_src_js_default_namespaceObject.uniqueKey)()); this.rowCount = 0; this.versionTag = (0,external_highcharts_src_js_default_namespaceObject.uniqueKey)(); let rowCount = 0; (0,external_highcharts_src_js_default_namespaceObject.objectEach)(options.columns || {}, (column, columnId) => { this.columns[columnId] = column.slice(); rowCount = Math.max(rowCount, column.length); }); this.applyRowCount(rowCount); } /* * * * Functions * * */ /** * Applies a row count to the table by setting the `rowCount` property and * adjusting the length of all columns. * * @private * @param {number} rowCount The new row count. */ applyRowCount(rowCount) { this.rowCount = rowCount; (0,external_highcharts_src_js_default_namespaceObject.objectEach)(this.columns, (column, columnId) => { if (column.length !== rowCount) { this.columns[columnId] = DataTableCore_setLength(column, rowCount); } }); } /** * Delete rows. Simplified version of the full * `DataTable.deleteRows` method. * * @sample highcharts/datatable/live-chart/ * Add and delete rows in a live chart * @sample highcharts/datatable/shared-with-grid/ * Chart with data table CRUD operations * * @function Highcharts.DataTable#deleteRows * * @param {number} rowIndex * The start row index * * @param {number} [rowCount=1] * The number of rows to delete * * @return {void} * * @emits #afterDeleteRows */ deleteRows(rowIndex, rowCount = 1) { if (rowCount > 0 && rowIndex < this.rowCount) { let length = 0; (0,external_highcharts_src_js_default_namespaceObject.objectEach)(this.columns, (column, columnId) => { this.columns[columnId] = DataTableCore_splice(column, rowIndex, rowCount).array; length = column.length; }); this.rowCount = length; } (0,external_highcharts_src_js_default_namespaceObject.fireEvent)(this, 'afterDeleteRows', { rowIndex, rowCount }); this.versionTag = (0,external_highcharts_src_js_default_namespaceObject.uniqueKey)(); } /** * Fetches the given column by the canonical column ID. Simplified version * of the full `DataTable.getRow` method, always returning by reference. * * @function Highcharts.DataTable#getColumn * * @param {string} columnId * ID of the column to get. * * @return {Highcharts.DataTableColumn|undefined} * A copy of the column, or `undefined` if not found. */ getColumn(columnId, // eslint-disable-next-line @typescript-eslint/no-unused-vars asReference) { return this.columns[columnId]; } /** * Retrieves all or the given columns. Simplified version of the full * `DataTable.getColumns` method, always returning by reference. * * @function Highcharts.DataTable#getColumns * * @param {Array<string>} [columnIds] * Column ids to retrieve. * * @return {Highcharts.DataTableColumnCollection} * Collection of columns. If a requested column was not found, it is * `undefined`. */ getColumns(columnIds, // eslint-disable-next-line @typescript-eslint/no-unused-vars asReference) { return (columnIds || Object.keys(this.columns)).reduce((columns, columnId) => { columns[columnId] = this.columns[columnId]; return columns; }, {}); } /** * Retrieves the row at a given index. * * @function Highcharts.DataTable#getRowObject * * @param {number} rowIndex * Row index to retrieve. First row has index 0. * * @param {Array<string>} [columnNames] * Column names to retrieve. * * @return {Record<string, number|string|undefined>|undefined} * Returns the row values, or `undefined` if not found. */ getRowObject(rowIndex, columnNames) { const row = {}, columns = this.columns; columnNames ?? (columnNames = Object.keys(this.columns)); for (const columnName of columnNames) { row[columnName] = columns[columnName]?.[rowIndex]; } return row; } /** * Sets cell values for a column. Will insert a new column, if not found. * * @function Highcharts.DataTable#setColumn * * @param {string} columnId * Column name to set. * * @param {Highcharts.DataTableColumn} [column] * Values to set in the column. * * @param {number} [rowIndex] * Index of the first row to change. (Default: 0) * * @param {Record<string, (boolean|number|string|null|undefined)>} [eventDetail] * Custom information for pending events. * * @emits #setColumns * @emits #afterSetColumns */ setColumn(columnId, column = [], rowIndex = 0, eventDetail) { this.setColumns({ [columnId]: column }, rowIndex, eventDetail); } /** * Sets cell values for multiple columns. Will insert new columns, if not * found. Simplified version of the full `DataTable.setColumns`, limited * to full replacement of the columns (undefined `rowIndex`). * * @sample highcharts/datatable/shared-with-grid/ * Chart with data table CRUD operations * * @function Highcharts.DataTable#setColumns * * @param {Highcharts.DataTableColumnCollection} columns * Columns as a collection, where the keys are the column names. * * @param {number} [rowIndex] * Index of the first row to change. Ignored in the simplified `DataTable`, * as it always replaces the full column. * * @param {Record<string, (boolean|number|string|null|undefined)>} [eventDetail] * Custom information for pending events. * * @emits #setColumns * @emits #afterSetColumns */ setColumns(columns, rowIndex, eventDetail) { let rowCount = this.rowCount; (0,external_highcharts_src_js_default_namespaceObject.objectEach)(columns, (column, columnId) => { this.columns[columnId] = column.slice(); rowCount = column.length; }); this.applyRowCount(rowCount); if (!eventDetail?.silent) { (0,external_highcharts_src_js_default_namespaceObject.fireEvent)(this, 'afterSetColumns'); this.versionTag = (0,external_highcharts_src_js_default_namespaceObject.uniqueKey)(); } } /** * Sets cell values of a row. Will insert a new row if no index was * provided, or if the index is higher than the total number of table rows. * A simplified version of the full `DateTable.setRow`, limited to objects. * * @sample highcharts/datatable/live-chart/ * Add and delete rows in a live chart * @sample stock/datatable/live-candlestick/ * Live candlestick * @sample highcharts/datatable/shared-with-grid/ * Chart with data table CRUD operations * * @function Highcharts.DataTable#setRow * * @param {Record<string, number|string|undefined>} row * Cell values to set. * * @param {number} [rowIndex] * Index of the row to set. Leave `undefined` to add as a new row. * * @param {boolean} [insert] * Whether to insert the row at the given index, or to overwrite the row. * * @param {Record<string, (boolean|number|string|null|undefined)>} [eventDetail] * Custom information for pending events. * * @emits #afterSetRows */ setRow(row, rowIndex = this.rowCount, insert, eventDetail) { var _a; const { columns } = this, indexRowCount = insert ? this.rowCount + 1 : rowIndex + 1, rowKeys = Object.keys(row); if (eventDetail?.addColumns !== false) { for (let i = 0, iEnd = rowKeys.length; i < iEnd; i++) { columns[_a = rowKeys[i]] || (columns[_a] = new Array(this.rowCount)); } } (0,external_highcharts_src_js_default_namespaceObject.objectEach)(columns, (column, columnId) => { if (column) { if (insert) { column = DataTableCore_splice(column, rowIndex, 0, true, [row[columnId]]).array; } else { column[rowIndex] = // Preserve explicit null and undefined but fall back // to existing value if the new row does not have the // key columnId in row ? row[columnId] : column[rowIndex]; } columns[columnId] = column; } }); this.applyRowCount(Math.max(indexRowCount, this.rowCount)); if (!eventDetail?.silent) { (0,external_highcharts_src_js_default_namespaceObject.fireEvent)(this, 'afterSetRows', { rowIndex }); this.versionTag = (0,external_highcharts_src_js_default_namespaceObject.uniqueKey)(); } } /** * Returns the modified (clone) or the original data table if the modified * one does not exist. * * @return {Highcharts.DataTable} * The modified (clone) or the original data table. */ getModified() { return this.modified || this; } } /* * * * Default Export * * */ /* harmony default export */ const Data_DataTableCore = (DataTableCore); /* * * * API Declarations * * */ /** * A collection of data table columns defined by a object where the key is the * column ID and the value is an array of the column values. Typed arrays are * supported. * * @type {Highcharts.DataTableColumnCollection|undefined} * @apioption dataTable.columns */ /** * Custom ID to identify the new DataTable instance. * * @type {string|undefined} * @apioption dataTable.id */ /** * A typed array. * @typedef {Int8Array|Uint8Array|Uint8ClampedArray|Int16Array|Uint16Array|Int32Array|Uint32Array|Float32Array|Float64Array} Highcharts.TypedArray */ /** * A column of values in a data table. * @typedef {Array<boolean|null|number|string|undefined>|Highcharts.TypedArray} Highcharts.DataTableColumn */ /** * A collection of data table columns defined by a object where the key is the * column ID and the value is an array of the column values. Typed arrays are * supported. * @typedef {Record<string, Highcharts.DataTableColumn>} Highcharts.DataTableColumnCollection */ /** * Options for the `DataTable` or `DataTableCore` classes. * @interface Highcharts.DataTableOptionsObject */ /** * The column options for the data table. The columns are defined by an object * where the key is the column ID and the value is an array of the column * values. * * @name Highcharts.DataTableOptionsObject.columns * @type {Highcharts.DataTableColumnCollection|undefined} */ /** * Custom ID to identify the new DataTable instance. * * @name Highcharts.DataTableOptionsObject.id * @type {string|undefined} */ (''); // Keeps doclets above in JS file ;// external ["../highcharts.src.js","default","Point"] const external_highcharts_src_js_default_Point_namespaceObject = __WEBPACK_EXTERNAL_MODULE__highcharts_src_js_8202131d__["default"].Point; var external_highcharts_src_js_default_Point_default = /*#__PURE__*/__webpack_require__.n(external_highcharts_src_js_default_Point_namespaceObject); ;// external ["../highcharts.src.js","default","SeriesRegistry"] const external_highcharts_src_js_default_SeriesRegistry_namespaceObject = __WEBPACK_EXTERNAL_MODULE__highcharts_src_js_8202131d__["default"].SeriesRegistry; var external_highcharts_src_js_default_SeriesRegistry_default = /*#__PURE__*/__webpack_require__.n(external_highcharts_src_js_default_SeriesRegistry_namespaceObject); ;// external ["../highcharts.src.js","default","Time"] const external_highcharts_src_js_default_Time_namespaceObject = __WEBPACK_EXTERNAL_MODULE__highcharts_src_js_8202131d__["default"].Time; var external_highcharts_src_js_default_Time_default = /*#__PURE__*/__webpack_require__.n(external_highcharts_src_js_default_Time_namespaceObject); ;// ./code/es-modules/Extensions/Data.js /* * * * Data module * * (c) 2012-2026 Highsoft AS * Author: Torstein Hønsi * * Integration of this software requires a license. * - For commercial use, see www.highcharts.com/license * - For non-commercial, see www.highcharts.com/license-eula * * * */ const { doc } = (external_highcharts_src_js_default_default()); const { seriesTypes } = (external_highcharts_src_js_default_SeriesRegistry_default()); /* * * * Functions * * */ /** * Get the free column indexes. * * @param {number} numberOfColumns * The number of columns. * * @param {Array<SeriesBuilder>} seriesBuilders * The seriesBuilders. * * @return {Array<number>} * The free indexes. * * @internal */ function getFreeIndexes(numberOfColumns, seriesBuilders) { // Add all columns as free const freeIndexes = new Array(numberOfColumns).fill(true), freeIndexValues = []; // Loop all defined builders and remove their referenced columns seriesBuilders.forEach((seriesBuilder) => { seriesBuilder.getReferencedColumnIndexes().forEach((index) => { freeIndexes[index] = false; }); }); // Collect the values for the free indexes freeIndexes.forEach((isFree, i) => { if (isFree) { freeIndexValues.push(i); } }); return freeIndexValues; } /** * Checks if the data options has URL options. * * @internal * * @param {Highcharts.DataOptions} options * The data options to check. * * @return {boolean} * Returns true if any of the URL options is set. */ function hasURLOption(options) { return !!(options.rowsURL || options.csvURL || options.columnsURL); } /* * * * Class * * */ /** * The Data class * * @requires modules/data * * @class * @name Highcharts.Data * * @param {Highcharts.DataOptions} dataOptions * * @param {Highcharts.Options} [chartOptions] * * @param {Highcharts.Chart} [chart] */ class Data { /* * * * Static Properties * * */ /** * Creates a data object to parse data for a chart. * * @function Highcharts.data */ static data(dataOptions, chartOptions = {}, chart) { return new Data(dataOptions, chartOptions, chart); } /** * Reorganize rows into columns. * * @function Highcharts.Data.rowsToColumns */ static rowsToColumns(rows) { let row, rowsLength, col, colsLength, columns; if (rows) { columns = []; rowsLength = rows.length; for (row = 0; row < rowsLength; row++) { colsLength = rows[row].length; for (col = 0; col < colsLength; col++) { if (!columns[col]) { columns[col] = []; } columns[col][row] = rows[row][col]; } } } return columns; } /* * * * Constructors * * */ constructor(dataOptions, chartOptions = {}, chart) { /** * A collection of two-dimensional arrays. * @internal */ this.rowsToColumns = Data.rowsToColumns; // Backwards compatibility /** * A collection of available date formats, extendable from the outside to * support custom date formats. * * @name Highcharts.Data#dateFormats * @type {Highcharts.Dictionary<Highcharts.DataDateFormatObject>} */ this.dateFormats = { 'YYYY/mm/dd': { regex: /^(\d{4})[\-\/\.](\d{1,2})[\-\/\.](\d{1,2})$/, parser: function (match) { return (match ? Date.UTC(+match[1], +match[2] - 1, +match[3]) : NaN); } }, 'dd/mm/YYYY': { regex: /^(\d{1,2})[\-\/\.](\d{1,2})[\-\/\.](\d{4})$/, parser: function (match) { return (match ? Date.UTC(+match[3], +match[2] - 1, +match[1]) : NaN); }, alternative: 'mm/dd/YYYY' // Different format with the same regex }, 'mm/dd/YYYY': { regex: /^(\d{1,2})[\-\/\.](\d{1,2})[\-\/\.](\d{4})$/, parser: function (match) { return (match ? Date.UTC(+match[3], +match[1] - 1, +match[2]) : NaN); } }, 'dd/mm/YY': { regex: /^(\d{1,2})[\-\/\.](\d{1,2})[\-\/\.](\d{2})$/, parser: function (match) { if (!match) { return NaN; } const d = new Date(); let year = +match[3]; if (year > (d.getFullYear() - 2000)) { year += 1900; } else { year += 2000; } return Date.UTC(year, +match[2] - 1, +match[1]); }, alternative: 'mm/dd/YY' // Different format with the same regex }, 'mm/dd/YY': { regex: /^(\d{1,2})[\-\/\.](\d{1,2})[\-\/\.](\d{2})$/, parser: function (match) { return (match ? Date.UTC(+match[3] + 2000, +match[1] - 1, +match[2]) : NaN); } } }; this.chart = chart; this.chartOptions = chartOptions; this.options = dataOptions; this.rawColumns = []; this.init(dataOptions, chartOptions, chart); } /* * * * Functions * * */ /** * Initialize the Data object with the given options * * @internal * @function Highcharts.Data#init */ init(dataOptions, chartOptions, chart) { let decimalPoint = dataOptions.decimalPoint, hasData; if (chartOptions) { this.chartOptions = chartOptions; } if (chart) { this.chart = chart; } if (decimalPoint !== '.' && decimalPoint !== ',') { decimalPoint = void 0; } this.options = dataOptions; this.columns = (dataOptions.columns || this.rowsToColumns(dataOptions.rows) || []); this.firstRowAsNames = dataOptions.firstRowAsNames ?? this.firstRowAsNames ?? true; this.decimalRegex = (decimalPoint && new RegExp('^(-?[0-9]+)' + decimalPoint + '([0-9]+)$')); // Always stop old polling when we have new options if (this.liveDataTimeout !== void 0) { (0,external_highcharts_src_js_default_namespaceObject.internalClearTimeout)(this.liveDataTimeout); } // This is a two-dimensional array holding the raw, trimmed string // values with the same organization as the columns array. It makes it // possible for example to revert from interpreted timestamps to // string-based categories. this.rawColumns = []; // No need to parse or interpret anything if (this.columns.length) { this.dataFound(); hasData = !hasURLOption(dataOptions); } if (!hasData) { // Fetch live data hasData = this.fetchLiveData(); } if (!hasData) { // Parse a CSV string if options.csv is given. The parseCSV function // returns a columns array, if it has no length, we have no data hasData = Boolean(this.parseCSV().length); } if (!hasData) { // Parse a HTML table if options.table is given hasData = Boolean(this.parseTable().length); } if (!hasData) { // Parse a Google Spreadsheet hasData = this.parseGoogleSpreadsheet(); } if (!hasData && dataOptions.afterComplete) { dataOptions.afterComplete(this); } } /** * Get the column distribution. For example, a line series takes a single * column for Y values. A range series takes two columns for low and high * values respectively, and an OHLC series takes four columns. * * @function Highcharts.Data#getColumnDistribution * @internal */ getColumnDistribution() { const chartOptions = this.chartOptions, options = this.options, xColumns = [], getValueCount = function (type = 'line') { return (seriesTypes[type].prototype.pointArrayMap || [0]).length; }, getPointArrayMap = function (type = 'line') { return seriesTypes[type].prototype.pointArrayMap; }, globalType = chartOptions?.chart?.type, individualCounts = [], seriesBuilders = [], // If no series mapping is defined, check if the series array is // defined with types. seriesMapping = (options?.seriesMapping || chartOptions?.series?.map(function () { return { x: 0 }; }) || []); let seriesIndex = 0; (chartOptions?.series || []).forEach((series) => { individualCounts.push(getValueCount(series.type || globalType)); }); // Collect the x-column indexes from seriesMapping seriesMapping.forEach((mapping) => { xColumns.push(mapping.x || 0); }); // If there are no defined series with x-columns, use the first column // as x column if (xColumns.length === 0) { xColumns.push(0); } // Loop all seriesMappings and constructs SeriesBuilders from // the mapping options. seriesMapping.forEach((mapping) => { const builder = new SeriesBuilder(), numberOfValueColumnsNeeded = individualCounts[seriesIndex] || getValueCount(globalType), seriesArr = chartOptions?.series ?? [], series = seriesArr[seriesIndex] ?? {}, defaultPointArrayMap = getPointArrayMap(series.type || globalType), pointArrayMap = defaultPointArrayMap ?? ['y']; if ( // User-defined x.mapping (0,external_highcharts_src_js_default_namespaceObject.defined)(mapping.x) || // All non cartesian don't need 'x' series.isCartesian || // Except pie series: !defaultPointArrayMap) { // Add an x reader from the x property or from an undefined // column if the property is not set. It will then be auto // populated later. builder.addColumnReader(mapping.x, 'x'); } // Add all column mappings (0,external_highcharts_src_js_default_namespaceObject.objectEach)(mapping, function (val, name) { if (name !== 'x') { builder.addColumnReader(val, name); } }); // Add missing columns for (let i = 0; i < numberOfValueColumnsNeeded; i++) { if (!builder.hasReader(pointArrayMap[i])) { // Create and add a column reader for the next free column // index builder.addColumnReader(void 0, pointArrayMap[i]); } } seriesBuilders.push(builder); seriesIndex++; }); let globalPointArrayMap = getPointArrayMap(globalType); if (typeof globalPointArrayMap === 'undefined') { globalPointArrayMap = ['y']; } this.valueCount = { global: getValueCount(globalType), xColumns: xColumns, individual: individualCounts, seriesBuilders: seriesBuilders, globalPointArrayMap: globalPointArrayMap }; } /** * When the data is parsed into columns, either by CSV, table, GS or direct * input, continue with other operations. * * @internal * @function Highcharts.Data#dataFound */ dataFound() { if (this.options.switchRowsAndColumns) { this.columns = this.rowsToColumns(this.columns); } // Interpret the info about series and columns this.getColumnDistribution(); // Interpret the values into right types this.parseTypes(); // Handle columns if a handleColumns callback is given if (this.parsed() !== false) { // Complete if a complete callback is given this.complete(); } } /** * Parse a CSV input string * * @function Highcharts.Data#parseCSV */ parseCSV(inOptions) { const self = this, columns = this.columns = [], options = inOptions || this.options, startColumn = options.startColumn || 0, endColumn = options.endColumn || Number.MAX_VALUE, dataTypes = [], // We count potential delimiters in the prepass, and use the // result as the basis of half-intelligent guesses. potDelimiters = { ',': 0, ';': 0, '\t': 0 }; let csv = options.csv, startRow = options.startRow || 0, endRow = options.endRow || Number.MAX_VALUE, itemDelimiter, lines, rowIt = 0; /* This implementation is quite verbose. It will be shortened once it's stable and passes all the test. It's also not written with speed in mind, instead everything is very segregated, and there a several redundant loops. This is to make it easier to stabilize the code initially. We do a pre-pass on the first 4 rows to make some intelligent guesses on the set. Guessed delimiters are in this pass counted. Auto detecting delimiters - If we meet a quoted string, the next symbol afterwards (that's not \s, \t) is the delimiter - If we meet a date, the next symbol afterwards is the delimiter Date formats - If we meet a column with date formats, check all of them to see if one of the potential months crossing 12. If it does, we now know the format It would make things easier to guess the delimiter before doing the actual parsing. General rules: - Quoting is allowed, e.g: "Col 1",123,321 - Quoting is optional, e.g.: Col1,123,321 - Double quoting is escaping, e.g. "Col ""Hello world""",123 - Spaces are considered part of the data: Col1 ,123 - New line is always the row delimiter - Potential column delimiters are , ; \t - First row may optionally contain headers - The last row may or may not have a row delimiter - Comments are optionally supported, in which case the comment must start at the first column, and the rest of the line will be ignored */ /** * Parse a single row. * @internal */ function parseRow(columnStr, rowNumber, noAdd, callbacks) { let i = 0, c = '', cl = '', cn = '', token = '', actualColumn = 0, column = 0; /** * Read a single character from the column string. * * @internal */ function read(j) { c = columnStr[j]; cl = columnStr[j - 1]; cn = columnStr[j + 1]; } /** * Push a type to the dataTypes array. * * @internal */ function pushType(type) { if (dataTypes.length < column + 1) { dataTypes.push([type]); } if (dataTypes[column][dataTypes[column].length - 1] !== type) { dataTypes[column].push(type); } } /** * Push a token to the columns array. * * @internal */ function push() { if (startColumn > actualColumn || actualColumn > endColumn) { // Skip this column, but increment the column count (#7272) ++actualColumn; token = ''; return; } if (!options.columnTypes) { if (!isNaN(parseFloat(token)) && isFinite(token)) { token = parseFloat(token); pushType('number'); } else if (!isNaN(Date.parse(token))) { token = token.replace(/\//g, '-'); pushType('date'); } else { pushType('string'); } } if (columns.length < column + 1) { columns.push([]); } if (!noAdd) { // Don't push - if there's a varying amount of columns // for each row, pushing will skew everything down n slots columns[column][rowNumber] = token; } token = ''; ++column; ++actualColumn; } if (!columnStr.trim().length) { return; } if (columnStr.trim()[0] === '#') { return; } for (; i < columnStr.length; i++) { read(i); if (c === '"') { read(++i); while (i < columnStr.length) { if (c === '"' && cl !== '"' && cn !== '"') { break; } if (c !== '"' || (c === '"' && cl !== '"')) { token += c; } read(++i); } // Perform "plugin" handling } else if (callbacks?.[c]) { if (callbacks[c](c, token)) { push(); } // Delimiter - push current token } else if (c === itemDelimiter) { push(); // Actual column data } else { token += c; } } push(); } /** * Attempt to guess the delimiter. We do a separate parse pass here * because we need to count potential delimiters softly without making * any assumptions. * @internal */ function guessDelimiter(lines) { let points = 0, commas = 0, guessed = false; lines.some(function (columnStr, i) { let inStr = false, c, cn, cl, token = ''; // We should be able to detect dateFormats within 13 rows if (i > 13) { return true; } for (let j = 0; j < columnStr.length; j++) { c = columnStr[j]; cn = columnStr[j + 1]; cl = columnStr[j - 1]; if (c === '#') { // Skip the rest of the line - it's a comment return; } if (c === '"') { if (inStr) { if (cl !== '"' && cn !== '"') { while (cn === ' ' && j < columnStr.length) { cn = columnStr[++j]; } // After parsing a string, the next non-blank // should be a delimiter if the CSV is properly // formed. if (typeof potDelimiters[cn] !== 'undefined') { potDelimiters[cn]++; } inStr = false; } } else { inStr = true; } } else if (typeof potDelimiters[c] !== 'undefined') { token = token.trim(); if (!isNaN(Date.parse(token))) { potDelimiters[c]++; } else if (isNaN(token) || !isFinite(token)) { potDelimiters[c]++; } token = ''; } else { token += c; } if (c === ',') { commas++; } if (c === '.') { points++; } } }); // Count the potential delimiters. // This could be improved by checking if the number of delimiters // equals the number of columns - 1 if (potDelimiters[';'] > potDelimiters[',']) { guessed = ';'; } else if (potDelimiters[','] > potDelimiters[';']) { guessed = ','; } else { // No good guess could be made.. guessed = ','; } // Try to deduce the decimal point if it's not explicitly set. // If both commas or points is > 0 there is likely an issue if (!options.decimalPoint) { if (points > commas) { options.decimalPoint = '.'; } else { options.decimalPoint = ','; } // Apply a new decimal regex based on the presumed decimal sep. self.decimalRegex = new RegExp('^(-?[0-9]+)' + options.decimalPoint + '([0-9]+)$'); } return guessed; } /** * Tries to guess the date format * - Check if either month candidate exceeds 12 * - Check if year is missing (use current year) * - Check if a shortened year format is used (e.g. 1/1/99) * - If no guess can be made, the user must be prompted * data is the data to deduce a format based on * @internal */ function deduceDateFormat(data, limit) { const format = 'YYYY/mm/dd', stable = [], max = []; let thing, guessedFormat = [], calculatedFormat, i = 0, madeDeduction = false, j; if (!limit || limit > data.length) { limi