define(["require", "exports", "tslib", "d3-array", "d3-scale", "d3-format", "../../utilities/colors", "../GaugeChart/index", "../../utilities/utilities", "@fluentui/chart-utilities", "d3-shape", "./PlotlyColorAdapter", "d3-color"], function (require, exports, tslib_1, d3_array_1, d3_scale_1, d3_format_1, colors_1, index_1, utilities_1, chart_utilities_1, d3_shape_1, PlotlyColorAdapter_1, d3_color_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getGridProperties = exports.isNonPlotType = exports.getValidXYRanges = exports.getNumberAtIndexOrDefault = exports.getAllupLegendsProps = exports.findArrayAttributes = exports.projectPolarToCartesian = exports.transformPlotlyJsonToChartTableProps = exports.transformPlotlyJsonToGaugeProps = exports.transformPlotlyJsonToSankeyProps = exports.transformPlotlyJsonToHeatmapProps = exports.transformPlotlyJsonToHorizontalBarWithAxisProps = exports.transformPlotlyJsonToScatterChartProps = exports.transformPlotlyJsonToLineChartProps = exports.transformPlotlyJsonToAreaChartProps = exports.transformPlotlyJsonToVBCProps = exports.transformPlotlyJsonToGVBCProps = exports.transformPlotlyJsonToVSBCProps = exports.transformPlotlyJsonToDonutProps = exports.resolveXAxisPoint = exports._getGaugeAxisColor = exports.correctYearMonth = exports.SINGLE_REPEAT = exports.NON_PLOT_KEY_PREFIX = void 0;
    exports.NON_PLOT_KEY_PREFIX = 'nonplot_';
    exports.SINGLE_REPEAT = 'repeat(1, 1fr)';
    var dashOptions = {
        dot: {
            strokeDasharray: '1, 5',
            strokeLinecap: 'round',
            strokeWidth: '2',
            lineBorderWidth: '4',
        },
        dash: {
            strokeDasharray: '5, 5',
            strokeLinecap: 'butt',
            strokeWidth: '2',
            lineBorderWidth: '4',
        },
        longdash: {
            strokeDasharray: '10, 5',
            strokeLinecap: 'butt',
            strokeWidth: '2',
            lineBorderWidth: '4',
        },
        dashdot: {
            strokeDasharray: '5, 5, 1, 5',
            strokeLinecap: 'butt',
            strokeWidth: '2',
            lineBorderWidth: '4',
        },
        longdashdot: {
            strokeDasharray: '10, 5, 1, 5',
            strokeLinecap: 'butt',
            strokeWidth: '2',
            lineBorderWidth: '4',
        },
        solid: {
            strokeDasharray: '0',
            strokeLinecap: 'butt',
            strokeWidth: '2',
            lineBorderWidth: '4',
        },
    };
    function getTitles(layout) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
        var titles = {
            chartTitle: typeof (layout === null || layout === void 0 ? void 0 : layout.title) === 'string' ? layout.title : (_b = (_a = layout === null || layout === void 0 ? void 0 : layout.title) === null || _a === void 0 ? void 0 : _a.text) !== null && _b !== void 0 ? _b : '',
            xAxisTitle: typeof ((_c = layout === null || layout === void 0 ? void 0 : layout.xaxis) === null || _c === void 0 ? void 0 : _c.title) === 'string' ? (_d = layout === null || layout === void 0 ? void 0 : layout.xaxis) === null || _d === void 0 ? void 0 : _d.title : (_g = (_f = (_e = layout === null || layout === void 0 ? void 0 : layout.xaxis) === null || _e === void 0 ? void 0 : _e.title) === null || _f === void 0 ? void 0 : _f.text) !== null && _g !== void 0 ? _g : '',
            yAxisTitle: typeof ((_h = layout === null || layout === void 0 ? void 0 : layout.yaxis) === null || _h === void 0 ? void 0 : _h.title) === 'string' ? (_j = layout === null || layout === void 0 ? void 0 : layout.yaxis) === null || _j === void 0 ? void 0 : _j.title : (_m = (_l = (_k = layout === null || layout === void 0 ? void 0 : layout.yaxis) === null || _k === void 0 ? void 0 : _k.title) === null || _l === void 0 ? void 0 : _l.text) !== null && _m !== void 0 ? _m : '',
        };
        return titles;
    }
    var getXAxisTickFormat = function (series, layout) {
        var xAxis = getXAxisProperties(series, layout);
        if (xAxis === null || xAxis === void 0 ? void 0 : xAxis.tickformat) {
            return {
                tickFormat: xAxis === null || xAxis === void 0 ? void 0 : xAxis.tickformat,
            };
        }
        return {};
    };
    var getYAxisTickFormat = function (series, layout) {
        var yAxis = getYAxisProperties(series, layout);
        if (yAxis === null || yAxis === void 0 ? void 0 : yAxis.tickformat) {
            return {
                yAxisTickFormat: (0, d3_format_1.format)(yAxis === null || yAxis === void 0 ? void 0 : yAxis.tickformat),
            };
        }
        return {};
    };
    var getYMinMaxValues = function (series, layout) {
        var _a;
        var range = (_a = getYAxisProperties(series, layout)) === null || _a === void 0 ? void 0 : _a.range;
        if (range && range.length === 2) {
            return {
                yMinValue: range[0],
                yMaxValue: range[1],
            };
        }
        return {};
    };
    var getYAxisProperties = function (series, layout) {
        return layout === null || layout === void 0 ? void 0 : layout.yaxis;
    };
    var getXAxisProperties = function (series, layout) {
        return layout === null || layout === void 0 ? void 0 : layout.xaxis;
    };
    var getFormattedCalloutYData = function (yVal, yAxisFormat) {
        if (typeof (yAxisFormat === null || yAxisFormat === void 0 ? void 0 : yAxisFormat.yAxisTickFormat) === 'function' && typeof yVal === 'number') {
            return yAxisFormat.yAxisTickFormat(yVal);
        }
        return (0, chart_utilities_1.formatToLocaleString)(yVal);
    };
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    var correctYearMonth = function (xValues) {
        var presentYear = new Date().getFullYear();
        if (xValues.length > 0 && Array.isArray(xValues[0])) {
            throw new Error('updateXValues:: 2D array not supported');
        }
        var dates = xValues.map(function (possiblyMonthValue) {
            var parsedDate = "".concat(possiblyMonthValue, " 01, ").concat(presentYear);
            return (0, chart_utilities_1.isDate)(parsedDate) ? new Date(parsedDate) : null;
        });
        var filteredDateIndexPairs = dates.map(function (date, index) { return [date, index]; }).filter(function (_a) {
            var date = _a[0];
            return date !== null;
        });
        for (var i = filteredDateIndexPairs.length - 1; i > 0; i--) {
            var currentDate = filteredDateIndexPairs[i][0];
            var previousDate = filteredDateIndexPairs[i - 1][0];
            var currentMonth = currentDate.getMonth();
            var previousMonth = previousDate.getMonth();
            var currentYear = currentDate.getFullYear();
            var previousYear = previousDate.getFullYear();
            if (previousMonth >= currentMonth) {
                filteredDateIndexPairs[i - 1][0].setFullYear(currentYear - 1);
            }
            else if (previousYear > currentYear) {
                filteredDateIndexPairs[i - 1][0].setFullYear(currentYear);
            }
            dates[filteredDateIndexPairs[i - 1][1]] = filteredDateIndexPairs[i - 1][0];
        }
        xValues = xValues.map(function (month, index) {
            if (dates[index] === null) {
                return null;
            }
            return "".concat(month, " 01, ").concat(dates[index].getFullYear());
        });
        return xValues;
    };
    exports.correctYearMonth = correctYearMonth;
    var usesSecondaryYScale = function (series, layout) {
        var _a, _b;
        return series.yaxis === 'y2' && (((_a = layout === null || layout === void 0 ? void 0 : layout.yaxis2) === null || _a === void 0 ? void 0 : _a.anchor) === 'x' || ((_b = layout === null || layout === void 0 ? void 0 : layout.yaxis2) === null || _b === void 0 ? void 0 : _b.side) === 'right');
    };
    var getSecondaryYAxisValues = function (data, layout, maxAllowedMinY, minAllowedMaxY) {
        var _a, _b, _c, _d;
        var containsSecondaryYAxis = false;
        var yMinValue;
        var yMaxValue;
        data.forEach(function (series) {
            if (usesSecondaryYScale(series, layout)) {
                containsSecondaryYAxis = true;
                var yValues = series.y;
                if (yValues) {
                    yMinValue = Math.min.apply(Math, yValues);
                    yMaxValue = Math.max.apply(Math, yValues);
                }
            }
        });
        if (!containsSecondaryYAxis) {
            return {};
        }
        if (typeof yMinValue === 'number' && typeof maxAllowedMinY === 'number') {
            yMinValue = Math.min(yMinValue, maxAllowedMinY);
        }
        if (typeof yMaxValue === 'number' && typeof minAllowedMaxY === 'number') {
            yMaxValue = Math.max(yMaxValue, minAllowedMaxY);
        }
        if ((_a = layout === null || layout === void 0 ? void 0 : layout.yaxis2) === null || _a === void 0 ? void 0 : _a.range) {
            yMinValue = layout.yaxis2.range[0];
            yMaxValue = layout.yaxis2.range[1];
        }
        return {
            secondaryYAxistitle: typeof ((_b = layout === null || layout === void 0 ? void 0 : layout.yaxis2) === null || _b === void 0 ? void 0 : _b.title) === 'string'
                ? layout.yaxis2.title
                : typeof ((_d = (_c = layout === null || layout === void 0 ? void 0 : layout.yaxis2) === null || _c === void 0 ? void 0 : _c.title) === null || _d === void 0 ? void 0 : _d.text) === 'string'
                    ? layout.yaxis2.title.text
                    : undefined,
            secondaryYScaleOptions: {
                yMinValue: yMinValue,
                yMaxValue: yMaxValue,
            },
        };
    };
    var _getGaugeAxisColor = function (colorway, colorwayType, color, colorMap, isDarkTheme) {
        var extractedColors = (0, PlotlyColorAdapter_1.extractColor)(colorway, colorwayType, color, colorMap, isDarkTheme);
        return (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, 0, '', colorMap, isDarkTheme);
    };
    exports._getGaugeAxisColor = _getGaugeAxisColor;
    var resolveXAxisPoint = function (x, isXYearCategory, isXString, isXDate, isXNumber) {
        if (x === null || x === undefined) {
            return '';
        }
        if (isXYearCategory) {
            return x.toString();
        }
        if (isXString) {
            if (isXDate) {
                var date = new Date(x);
                return date;
            }
            if (isXNumber) {
                return parseFloat(x);
            }
            return x;
        }
        return x;
    };
    exports.resolveXAxisPoint = resolveXAxisPoint;
    var transformPlotlyJsonToDonutProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
        var firstData = input.data[0];
        // extract colors for each series only once
        // use piecolorway if available
        // otherwise, default to colorway from template
        var colors = (0, PlotlyColorAdapter_1.extractColor)((_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.piecolorway) !== null && _b !== void 0 ? _b : (_e = (_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.template) === null || _d === void 0 ? void 0 : _d.layout) === null || _e === void 0 ? void 0 : _e.colorway, colorwayType, (_g = (_f = input.layout) === null || _f === void 0 ? void 0 : _f.piecolorway) !== null && _g !== void 0 ? _g : (_h = firstData === null || firstData === void 0 ? void 0 : firstData.marker) === null || _h === void 0 ? void 0 : _h.colors, colorMap, isDarkTheme);
        var mapLegendToDataPoint = {};
        (_j = firstData.labels) === null || _j === void 0 ? void 0 : _j.forEach(function (label, index) {
            var value = (0, exports.getNumberAtIndexOrDefault)(firstData.values, index);
            if ((0, chart_utilities_1.isInvalidValue)(value) || value < 0) {
                return;
            }
            var legend = "".concat(label);
            // resolve color for each legend from the extracted colors
            var color = (0, PlotlyColorAdapter_1.resolveColor)(colors, index, legend, colorMap, isDarkTheme);
            if (!mapLegendToDataPoint[legend]) {
                mapLegendToDataPoint[legend] = {
                    legend: legend,
                    data: value,
                    color: color,
                };
            }
            else {
                mapLegendToDataPoint[legend].data += value;
            }
        });
        var width = (_l = (_k = input.layout) === null || _k === void 0 ? void 0 : _k.width) !== null && _l !== void 0 ? _l : 440;
        var height = (_o = (_m = input.layout) === null || _m === void 0 ? void 0 : _m.height) !== null && _o !== void 0 ? _o : 220;
        var hideLabels = firstData.textinfo
            ? !['value', 'percent', 'label+percent'].includes(firstData.textinfo)
            : false;
        var donutMarginHorizontal = hideLabels ? 0 : 80;
        var donutMarginVertical = 40 + (hideLabels ? 0 : 40);
        var innerRadius = firstData.hole
            ? firstData.hole * (Math.min(width - donutMarginHorizontal, height - donutMarginVertical) / 2)
            : utilities_1.MIN_DONUT_RADIUS;
        var chartTitle = getTitles(input.layout).chartTitle;
        return {
            data: {
                chartTitle: chartTitle,
                chartData: Object.values(mapLegendToDataPoint),
            },
            hideLegend: isMultiPlot || ((_p = input.layout) === null || _p === void 0 ? void 0 : _p.showlegend) === false,
            width: (_q = input.layout) === null || _q === void 0 ? void 0 : _q.width,
            height: height,
            innerRadius: innerRadius,
            hideLabels: hideLabels,
            showLabelsInPercent: firstData.textinfo ? ['percent', 'label+percent'].includes(firstData.textinfo) : true,
            roundCorners: true,
        };
    };
    exports.transformPlotlyJsonToDonutProps = transformPlotlyJsonToDonutProps;
    var transformPlotlyJsonToVSBCProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme, fallbackVSBC) {
        var _a, _b, _c;
        var mapXToDataPoints = {};
        var yMaxValue = 0;
        var yMinValue = 0;
        var secondaryYAxisValues = getSecondaryYAxisValues(input.data, input.layout);
        var _d = getLegendProps(input.data, input.layout, isMultiPlot), legends = _d.legends, hideLegend = _d.hideLegend;
        var colorScale = undefined;
        var yAxisTickFormat = getYAxisTickFormat(input.data[0], input.layout);
        input.data.forEach(function (series, index1) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
            if (((_c = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.coloraxis) === null || _b === void 0 ? void 0 : _b.colorscale) === null || _c === void 0 ? void 0 : _c.length) &&
                (0, chart_utilities_1.isArrayOrTypedArray)((_d = series.marker) === null || _d === void 0 ? void 0 : _d.color) &&
                ((_e = series.marker) === null || _e === void 0 ? void 0 : _e.color).length > 0 &&
                typeof ((_g = (_f = series.marker) === null || _f === void 0 ? void 0 : _f.color) === null || _g === void 0 ? void 0 : _g[0]) === 'number') {
                colorScale = createColorScale(input.layout, series);
            }
            var isXYearCategory = (0, chart_utilities_1.isYearArray)(series.x); // Consider year as categorical not numeric continuous axis
            // extract bar colors for each series only once
            var extractedBarColors = (0, PlotlyColorAdapter_1.extractColor)((_k = (_j = (_h = input.layout) === null || _h === void 0 ? void 0 : _h.template) === null || _j === void 0 ? void 0 : _j.layout) === null || _k === void 0 ? void 0 : _k.colorway, colorwayType, (_l = series.marker) === null || _l === void 0 ? void 0 : _l.color, colorMap, isDarkTheme);
            // extract line colors for each series only once
            var extractedLineColors = (0, PlotlyColorAdapter_1.extractColor)((_p = (_o = (_m = input.layout) === null || _m === void 0 ? void 0 : _m.template) === null || _o === void 0 ? void 0 : _o.layout) === null || _p === void 0 ? void 0 : _p.colorway, colorwayType, (_q = series.line) === null || _q === void 0 ? void 0 : _q.color, colorMap, isDarkTheme);
            var xValues = series.x;
            var isXDate = (0, chart_utilities_1.isDateArray)(xValues);
            var isXString = (0, chart_utilities_1.isStringArray)(xValues);
            var isXNumber = (0, chart_utilities_1.isNumberArray)(xValues);
            var validXYRanges = (0, exports.getValidXYRanges)(series);
            validXYRanges.forEach(function (_a, rangeIdx) {
                var rangeStart = _a[0], rangeEnd = _a[1];
                var rangeXValues = series.x.slice(rangeStart, rangeEnd);
                var rangeYValues = series.y.slice(rangeStart, rangeEnd);
                rangeXValues.forEach(function (x, index2) {
                    var _a, _b, _c, _d, _e, _f;
                    if (!mapXToDataPoints[x]) {
                        mapXToDataPoints[x] = {
                            xAxisPoint: (0, exports.resolveXAxisPoint)(x, isXYearCategory, isXString, isXDate, isXNumber),
                            chartData: [],
                            lineData: [],
                        };
                    }
                    var legend = legends[index1];
                    // resolve color for each legend's bars from the colorscale or extracted colors
                    var color = colorScale
                        ? colorScale((0, chart_utilities_1.isArrayOrTypedArray)((_a = series.marker) === null || _a === void 0 ? void 0 : _a.color)
                            ? (_c = (_b = series.marker) === null || _b === void 0 ? void 0 : _b.color) === null || _c === void 0 ? void 0 : _c[index2 % ((_d = series.marker) === null || _d === void 0 ? void 0 : _d.color).length]
                            : 0)
                        : (0, PlotlyColorAdapter_1.resolveColor)(extractedBarColors, index2, legend, colorMap, isDarkTheme);
                    var opacity = (0, PlotlyColorAdapter_1.getOpacity)(series, index2);
                    var yVal = rangeYValues[index2];
                    var yAxisCalloutData = getFormattedCalloutYData(yVal, yAxisTickFormat);
                    if (series.type === 'bar') {
                        mapXToDataPoints[x].chartData.push({
                            legend: legend,
                            data: yVal,
                            color: (_e = (0, d3_color_1.rgb)(color).copy({ opacity: opacity }).formatHex8()) !== null && _e !== void 0 ? _e : color,
                            yAxisCalloutData: yAxisCalloutData,
                        });
                        if (typeof yVal === 'number') {
                            yMaxValue = Math.max(yMaxValue, yVal);
                        }
                    }
                    else if (series.type === 'scatter' || !!fallbackVSBC) {
                        var lineColor = (0, PlotlyColorAdapter_1.resolveColor)(extractedLineColors, index1, legend, colorMap, isDarkTheme);
                        var lineOptions = getLineOptions(series.line);
                        var legendShape = getLegendShape(series);
                        mapXToDataPoints[x].lineData.push({
                            legend: legend + (validXYRanges.length > 1 ? ".".concat(rangeIdx + 1) : ''),
                            legendShape: legendShape,
                            y: yVal,
                            color: (_f = (0, d3_color_1.rgb)(lineColor).copy({ opacity: opacity }).formatHex8()) !== null && _f !== void 0 ? _f : color,
                            lineOptions: tslib_1.__assign(tslib_1.__assign({}, (lineOptions !== null && lineOptions !== void 0 ? lineOptions : {})), { mode: series.mode }),
                            useSecondaryYScale: usesSecondaryYScale(series, input.layout),
                            yAxisCalloutData: yAxisCalloutData,
                        });
                        if (!usesSecondaryYScale(series, input.layout) && typeof yVal === 'number') {
                            yMaxValue = Math.max(yMaxValue, yVal);
                            yMinValue = Math.min(yMinValue, yVal);
                        }
                    }
                });
            });
        });
        return tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({ data: Object.values(mapXToDataPoints), width: (_a = input.layout) === null || _a === void 0 ? void 0 : _a.width, height: (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.height) !== null && _c !== void 0 ? _c : 350, barWidth: 'auto', yMaxValue: yMaxValue, yMinValue: yMinValue, mode: 'plotly' }, secondaryYAxisValues), { hideTickOverlap: true, hideLegend: hideLegend, roundCorners: true, supportNegativeData: true, barGapMax: 2, showYAxisLables: true, noOfCharsToTruncate: 20, showYAxisLablesTooltip: true }), getTitles(input.layout)), getAxisCategoryOrderProps(input.data, input.layout)), getXAxisTickFormat(input.data[0], input.layout)), yAxisTickFormat);
    };
    exports.transformPlotlyJsonToVSBCProps = transformPlotlyJsonToVSBCProps;
    var createColorScale = function (layout, series) {
        var _a, _b, _c, _d, _e, _f;
        var scale = (_a = layout === null || layout === void 0 ? void 0 : layout.coloraxis) === null || _a === void 0 ? void 0 : _a.colorscale;
        var colorValues = (_b = series.marker) === null || _b === void 0 ? void 0 : _b.color;
        var _g = [
            (_d = (_c = layout === null || layout === void 0 ? void 0 : layout.coloraxis) === null || _c === void 0 ? void 0 : _c.cmin) !== null && _d !== void 0 ? _d : Math.min.apply(Math, colorValues),
            (_f = (_e = layout === null || layout === void 0 ? void 0 : layout.coloraxis) === null || _e === void 0 ? void 0 : _e.cmax) !== null && _f !== void 0 ? _f : Math.max.apply(Math, colorValues),
        ], dMin = _g[0], dMax = _g[1];
        // Normalize colorscale domain to actual data domain
        var scaleDomain = scale.map(function (_a) {
            var pos = _a[0];
            return dMin + pos * (dMax - dMin);
        });
        var scaleColors = scale.map(function (item) { return item[1]; });
        return (0, d3_scale_1.scaleLinear)().domain(scaleDomain).range(scaleColors);
    };
    var transformPlotlyJsonToGVBCProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        var _a, _b, _c;
        var mapXToDataPoints = {};
        var secondaryYAxisValues = getSecondaryYAxisValues(input.data, input.layout, 0, 0);
        var _d = getLegendProps(input.data, input.layout, isMultiPlot), legends = _d.legends, hideLegend = _d.hideLegend;
        var colorScale = undefined;
        var yAxisTickFormat = getYAxisTickFormat(input.data[0], input.layout);
        input.data.forEach(function (series, index1) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
            if (((_c = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.coloraxis) === null || _b === void 0 ? void 0 : _b.colorscale) === null || _c === void 0 ? void 0 : _c.length) &&
                (0, chart_utilities_1.isArrayOrTypedArray)((_d = series.marker) === null || _d === void 0 ? void 0 : _d.color) &&
                ((_e = series.marker) === null || _e === void 0 ? void 0 : _e.color).length > 0 &&
                typeof ((_g = (_f = series.marker) === null || _f === void 0 ? void 0 : _f.color) === null || _g === void 0 ? void 0 : _g[0]) === 'number') {
                colorScale = createColorScale(input.layout, series);
            }
            // extract colors for each series only once
            var extractedColors = (0, PlotlyColorAdapter_1.extractColor)((_k = (_j = (_h = input.layout) === null || _h === void 0 ? void 0 : _h.template) === null || _j === void 0 ? void 0 : _j.layout) === null || _k === void 0 ? void 0 : _k.colorway, colorwayType, (_l = series.marker) === null || _l === void 0 ? void 0 : _l.color, colorMap, isDarkTheme);
            (_m = series.x) === null || _m === void 0 ? void 0 : _m.forEach(function (x, xIndex) {
                var _a, _b, _c, _d, _e, _f;
                if ((0, chart_utilities_1.isInvalidValue)(x) || (0, chart_utilities_1.isInvalidValue)((_a = series.y) === null || _a === void 0 ? void 0 : _a[xIndex])) {
                    return;
                }
                if (!mapXToDataPoints[x]) {
                    mapXToDataPoints[x] = { name: x.toString(), series: [] };
                }
                if (series.type === 'bar') {
                    var legend = legends[index1];
                    // resolve color for each legend's bars from the colorscale or extracted colors
                    var color = colorScale
                        ? colorScale((0, chart_utilities_1.isArrayOrTypedArray)((_b = series.marker) === null || _b === void 0 ? void 0 : _b.color)
                            ? (_d = (_c = series.marker) === null || _c === void 0 ? void 0 : _c.color) === null || _d === void 0 ? void 0 : _d[xIndex % ((_e = series.marker) === null || _e === void 0 ? void 0 : _e.color).length]
                            : 0)
                        : (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, xIndex, legend, colorMap, isDarkTheme);
                    var opacity = (0, PlotlyColorAdapter_1.getOpacity)(series, xIndex);
                    var yVal = series.y[xIndex];
                    mapXToDataPoints[x].series.push({
                        key: legend,
                        data: yVal,
                        xAxisCalloutData: x,
                        color: (_f = (0, d3_color_1.rgb)(color).copy({ opacity: opacity }).formatHex8()) !== null && _f !== void 0 ? _f : color,
                        legend: legend,
                        useSecondaryYScale: usesSecondaryYScale(series, input.layout),
                        yAxisCalloutData: getFormattedCalloutYData(yVal, yAxisTickFormat),
                    });
                }
            });
        });
        return tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({ data: Object.values(mapXToDataPoints), width: (_a = input.layout) === null || _a === void 0 ? void 0 : _a.width, height: (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.height) !== null && _c !== void 0 ? _c : 350, barwidth: 'auto', mode: 'plotly' }, secondaryYAxisValues), { hideTickOverlap: true, hideLegend: hideLegend, roundCorners: true }), getTitles(input.layout)), getAxisCategoryOrderProps(input.data, input.layout)), getYMinMaxValues(input.data[0], input.layout)), getXAxisTickFormat(input.data[0], input.layout)), yAxisTickFormat);
    };
    exports.transformPlotlyJsonToGVBCProps = transformPlotlyJsonToGVBCProps;
    var transformPlotlyJsonToVBCProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        var _a, _b, _c;
        var vbcData = [];
        var _d = getLegendProps(input.data, input.layout, isMultiPlot), legends = _d.legends, hideLegend = _d.hideLegend;
        var colorScale = undefined;
        input.data.forEach(function (series, seriesIdx) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
            if (!series.x) {
                return;
            }
            if (((_c = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.coloraxis) === null || _b === void 0 ? void 0 : _b.colorscale) === null || _c === void 0 ? void 0 : _c.length) &&
                (0, chart_utilities_1.isArrayOrTypedArray)((_d = series.marker) === null || _d === void 0 ? void 0 : _d.color) &&
                ((_e = series.marker) === null || _e === void 0 ? void 0 : _e.color).length > 0 &&
                typeof ((_g = (_f = series.marker) === null || _f === void 0 ? void 0 : _f.color) === null || _g === void 0 ? void 0 : _g[0]) === 'number') {
                colorScale = createColorScale(input.layout, series);
            }
            // extract colors for each series only once
            var extractedColors = (0, PlotlyColorAdapter_1.extractColor)((_k = (_j = (_h = input.layout) === null || _h === void 0 ? void 0 : _h.template) === null || _j === void 0 ? void 0 : _j.layout) === null || _k === void 0 ? void 0 : _k.colorway, colorwayType, (_l = series.marker) === null || _l === void 0 ? void 0 : _l.color, colorMap, isDarkTheme);
            var xValues = [];
            var yValues = [];
            series.x.forEach(function (xVal, index) {
                var yVal = (0, exports.getNumberAtIndexOrDefault)(series.y, index);
                if ((0, chart_utilities_1.isInvalidValue)(xVal) || (0, chart_utilities_1.isInvalidValue)(yVal)) {
                    return;
                }
                xValues.push(xVal);
                yValues.push(yVal);
            });
            var isXString = (0, chart_utilities_1.isStringArray)(xValues);
            // TODO: In case of a single bin, add an empty bin of the same size to prevent the
            // default bar width from being used and ensure the bar spans the full intended range.
            var xBins = createBins(xValues, (_m = series.xbins) === null || _m === void 0 ? void 0 : _m.start, (_o = series.xbins) === null || _o === void 0 ? void 0 : _o.end, (_p = series.xbins) === null || _p === void 0 ? void 0 : _p.size);
            var yBins = xBins.map(function () { return []; });
            var total = 0;
            xValues.forEach(function (xVal, index) {
                var binIdx = findBinIndex(xBins, xVal, isXString);
                if (binIdx !== -1) {
                    yBins[binIdx].push(yValues[index]);
                }
            });
            var y = yBins.map(function (bin) {
                var yVal = calculateHistFunc(series.histfunc, bin);
                total += yVal;
                return yVal;
            });
            xBins.forEach(function (bin, index) {
                var _a, _b, _c, _d, _e;
                var legend = legends[seriesIdx];
                // resolve color for each legend's bars from the colorscale or extracted colors
                var color = colorScale
                    ? colorScale((0, chart_utilities_1.isArrayOrTypedArray)((_a = series.marker) === null || _a === void 0 ? void 0 : _a.color)
                        ? (_c = (_b = series.marker) === null || _b === void 0 ? void 0 : _b.color) === null || _c === void 0 ? void 0 : _c[index % ((_d = series.marker) === null || _d === void 0 ? void 0 : _d.color).length]
                        : 0)
                    : (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, index, legend, colorMap, isDarkTheme);
                var opacity = (0, PlotlyColorAdapter_1.getOpacity)(series, index);
                var yVal = calculateHistNorm(series.histnorm, y[index], total, isXString ? bin.length : getBinSize(bin));
                vbcData.push(tslib_1.__assign({ x: isXString ? bin.join(', ') : getBinCenter(bin), y: yVal, legend: legend, color: (_e = (0, d3_color_1.rgb)(color).copy({ opacity: opacity }).formatHex8()) !== null && _e !== void 0 ? _e : color }, (isXString
                    ? {}
                    : { xAxisCalloutData: "[".concat(bin.x0, " - ").concat(bin.x1, ")") })));
            });
        });
        return tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({ data: vbcData, width: (_a = input.layout) === null || _a === void 0 ? void 0 : _a.width, height: (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.height) !== null && _c !== void 0 ? _c : 350, supportNegativeData: true, mode: 'histogram', hideTickOverlap: true, maxBarWidth: 50, hideLegend: hideLegend, roundCorners: true }, getTitles(input.layout)), getAxisCategoryOrderProps(input.data, input.layout)), getYMinMaxValues(input.data[0], input.layout));
    };
    exports.transformPlotlyJsonToVBCProps = transformPlotlyJsonToVBCProps;
    var transformPlotlyJsonToAreaChartProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        return transformPlotlyJsonToScatterTraceProps(input, isMultiPlot, 'area', colorMap, colorwayType, isDarkTheme);
    };
    exports.transformPlotlyJsonToAreaChartProps = transformPlotlyJsonToAreaChartProps;
    var transformPlotlyJsonToLineChartProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        return transformPlotlyJsonToScatterTraceProps(input, isMultiPlot, 'line', colorMap, colorwayType, isDarkTheme);
    };
    exports.transformPlotlyJsonToLineChartProps = transformPlotlyJsonToLineChartProps;
    var transformPlotlyJsonToScatterChartProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        return transformPlotlyJsonToScatterTraceProps(input, isMultiPlot, 'scatter', colorMap, colorwayType, isDarkTheme);
    };
    exports.transformPlotlyJsonToScatterChartProps = transformPlotlyJsonToScatterChartProps;
    var transformPlotlyJsonToScatterTraceProps = function (input, isMultiPlot, chartType, colorMap, colorwayType, isDarkTheme) {
        var _a, _b, _c, _d;
        var isScatterMarkers = [
            'markers',
            'text+markers',
            'markers+text',
            'lines+markers',
            'markers+line',
            'text+lines+markers',
        ].includes((_a = input.data[0]) === null || _a === void 0 ? void 0 : _a.mode);
        var isAreaChart = chartType === 'area';
        var isScatterChart = chartType === 'scatter';
        var secondaryYAxisValues = getSecondaryYAxisValues(input.data, input.layout, isAreaChart ? 0 : undefined, isAreaChart ? 0 : undefined);
        var mode = 'tonexty';
        var _e = getLegendProps(input.data, input.layout, isMultiPlot), legends = _e.legends, hideLegend = _e.hideLegend;
        var yAxisTickFormat = getYAxisTickFormat(input.data[0], input.layout);
        var chartData = input.data
            .map(function (series, index) {
            var _a, _b, _c, _d, _e, _f, _g;
            var colors = isScatterMarkers
                ? ((_a = series === null || series === void 0 ? void 0 : series.mode) === null || _a === void 0 ? void 0 : _a.includes('line'))
                    ? (_b = series.line) === null || _b === void 0 ? void 0 : _b.color
                    : (_c = series.marker) === null || _c === void 0 ? void 0 : _c.color
                : (_d = series.line) === null || _d === void 0 ? void 0 : _d.color;
            // extract colors for each series only once
            var extractedColors = (0, PlotlyColorAdapter_1.extractColor)((_g = (_f = (_e = input.layout) === null || _e === void 0 ? void 0 : _e.template) === null || _f === void 0 ? void 0 : _f.layout) === null || _g === void 0 ? void 0 : _g.colorway, colorwayType, colors, colorMap, isDarkTheme);
            var xValues = series.x;
            var isXString = (0, chart_utilities_1.isStringArray)(xValues);
            var isXDate = (0, chart_utilities_1.isDateArray)(xValues);
            var isXNumber = (0, chart_utilities_1.isNumberArray)(xValues);
            var isXYearCategory = (0, chart_utilities_1.isYearArray)(series.x); // Consider year as categorical not numeric continuous axis
            var legend = legends[index];
            // resolve color for each legend's lines from the extracted colors
            var seriesColor = (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, index, legend, colorMap, isDarkTheme);
            var seriesOpacity = (0, PlotlyColorAdapter_1.getOpacity)(series, index);
            mode = series.fill === 'tozeroy' ? 'tozeroy' : 'tonexty';
            var lineOptions = getLineOptions(series.line);
            var legendShape = getLegendShape(series);
            var validXYRanges = (0, exports.getValidXYRanges)(series);
            return validXYRanges.map(function (_a, rangeIdx) {
                var _b, _c;
                var rangeStart = _a[0], rangeEnd = _a[1];
                var rangeXValues = xValues.slice(rangeStart, rangeEnd);
                var rangeYValues = series.y.slice(rangeStart, rangeEnd);
                var markerSizes = (0, chart_utilities_1.isArrayOrTypedArray)((_b = series.marker) === null || _b === void 0 ? void 0 : _b.size)
                    ? series.marker.size.slice(rangeStart, rangeEnd)
                    : [];
                var textValues = Array.isArray(series.text) ? series.text.slice(rangeStart, rangeEnd) : undefined;
                return {
                    legend: legend,
                    legendShape: legendShape,
                    data: rangeXValues.map(function (x, i) {
                        var _a, _b;
                        return (tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({ x: (0, exports.resolveXAxisPoint)(x, isXYearCategory, isXString, isXDate, isXNumber), y: rangeYValues[i] }, (Array.isArray((_a = series.marker) === null || _a === void 0 ? void 0 : _a.size)
                            ? { markerSize: markerSizes[i] }
                            : typeof ((_b = series.marker) === null || _b === void 0 ? void 0 : _b.size) === 'number'
                                ? { markerSize: series.marker.size }
                                : {})), (textValues ? { text: textValues[i] } : {})), { yAxisCalloutData: getFormattedCalloutYData(rangeYValues[i], yAxisTickFormat) }));
                    }),
                    color: (_c = (0, d3_color_1.rgb)(seriesColor).copy({ opacity: seriesOpacity }).formatHex8()) !== null && _c !== void 0 ? _c : seriesColor,
                    lineOptions: tslib_1.__assign(tslib_1.__assign({}, (lineOptions !== null && lineOptions !== void 0 ? lineOptions : {})), { mode: series.mode }),
                    useSecondaryYScale: usesSecondaryYScale(series, input.layout),
                };
            });
        })
            .flat();
        var yMinMax = getYMinMaxValues(input.data[0], input.layout);
        if (yMinMax.yMinValue === undefined && yMinMax.yMaxValue === undefined) {
            var yMinMaxValues = (0, utilities_1.findNumericMinMaxOfY)(chartData);
            yMinMax.yMinValue = yMinMaxValues.startValue;
            yMinMax.yMaxValue = yMinMaxValues.endValue;
        }
        var numDataPoints = chartData.reduce(function (total, lineChartPoints) { return total + lineChartPoints.data.length; }, 0);
        var chartProps = {
            lineChartData: chartData,
        };
        var scatterChartProps = {
            scatterChartData: chartData,
        };
        var commonProps = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({ supportNegativeData: true }, secondaryYAxisValues), { width: (_b = input.layout) === null || _b === void 0 ? void 0 : _b.width, height: (_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.height) !== null && _d !== void 0 ? _d : 350, hideTickOverlap: true, hideLegend: hideLegend, useUTC: false, optimizeLargeData: numDataPoints > 1000 }), getTitles(input.layout)), getXAxisTickFormat(input.data[0], input.layout)), yAxisTickFormat);
        if (isAreaChart) {
            return tslib_1.__assign({ data: chartProps, mode: mode }, commonProps);
        }
        else {
            return tslib_1.__assign(tslib_1.__assign({ data: isScatterChart ? scatterChartProps : chartProps, roundedTicks: true, enableReflow: false }, commonProps), yMinMax);
        }
    };
    var transformPlotlyJsonToHorizontalBarWithAxisProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
        var _s = getLegendProps(input.data, input.layout, isMultiPlot), legends = _s.legends, hideLegend = _s.hideLegend;
        var colorScale = undefined;
        var chartData = input.data
            .map(function (series, index) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
            if (((_c = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.coloraxis) === null || _b === void 0 ? void 0 : _b.colorscale) === null || _c === void 0 ? void 0 : _c.length) &&
                (0, chart_utilities_1.isArrayOrTypedArray)((_d = series.marker) === null || _d === void 0 ? void 0 : _d.color) &&
                ((_e = series.marker) === null || _e === void 0 ? void 0 : _e.color).length > 0 &&
                typeof ((_g = (_f = series.marker) === null || _f === void 0 ? void 0 : _f.color) === null || _g === void 0 ? void 0 : _g[0]) === 'number') {
                colorScale = createColorScale(input.layout, series);
            }
            // extract colors for each series only once
            var extractedColors = (0, PlotlyColorAdapter_1.extractColor)((_k = (_j = (_h = input.layout) === null || _h === void 0 ? void 0 : _h.template) === null || _j === void 0 ? void 0 : _j.layout) === null || _k === void 0 ? void 0 : _k.colorway, colorwayType, (_l = series.marker) === null || _l === void 0 ? void 0 : _l.color, colorMap, isDarkTheme);
            var legend = legends[index];
            return series.y
                .map(function (yValue, i) {
                var _a, _b, _c, _d, _e, _f;
                if ((0, chart_utilities_1.isInvalidValue)((_a = series.x) === null || _a === void 0 ? void 0 : _a[i]) || (0, chart_utilities_1.isInvalidValue)(yValue)) {
                    return null;
                }
                // resolve color for each legend's bars from the colorscale or extracted colors
                var color = colorScale
                    ? colorScale((0, chart_utilities_1.isArrayOrTypedArray)((_b = series.marker) === null || _b === void 0 ? void 0 : _b.color)
                        ? (_d = (_c = series.marker) === null || _c === void 0 ? void 0 : _c.color) === null || _d === void 0 ? void 0 : _d[i % ((_e = series.marker) === null || _e === void 0 ? void 0 : _e.color).length]
                        : 0)
                    : (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, i, legend, colorMap, isDarkTheme);
                var opacity = (0, PlotlyColorAdapter_1.getOpacity)(series, i);
                return {
                    x: series.x[i],
                    y: yValue,
                    legend: legend,
                    color: (_f = (0, d3_color_1.rgb)(color).copy({ opacity: opacity }).formatHex8()) !== null && _f !== void 0 ? _f : color,
                };
            })
                .filter(function (point) { return point !== null; });
        })
            .flat();
        var chartHeight = (_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.height) !== null && _b !== void 0 ? _b : 450;
        var margin = (_e = (_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.margin) === null || _d === void 0 ? void 0 : _d.l) !== null && _e !== void 0 ? _e : 0;
        var padding = (_h = (_g = (_f = input.layout) === null || _f === void 0 ? void 0 : _f.margin) === null || _g === void 0 ? void 0 : _g.pad) !== null && _h !== void 0 ? _h : 0;
        var availableHeight = chartHeight - margin - padding;
        var numberOfRows = new Set(chartData.map(function (d) { return d.y; })).size || 1;
        var scalingFactor = 0.01;
        var gapFactor = 1 / (1 + scalingFactor * numberOfRows);
        var barHeight = availableHeight / (numberOfRows * (1 + gapFactor));
        return tslib_1.__assign(tslib_1.__assign({ data: chartData, secondaryYAxistitle: typeof ((_k = (_j = input.layout) === null || _j === void 0 ? void 0 : _j.yaxis2) === null || _k === void 0 ? void 0 : _k.title) === 'string'
                ? (_m = (_l = input.layout) === null || _l === void 0 ? void 0 : _l.yaxis2) === null || _m === void 0 ? void 0 : _m.title
                : ((_q = (_p = (_o = input.layout) === null || _o === void 0 ? void 0 : _o.yaxis2) === null || _p === void 0 ? void 0 : _p.title) === null || _q === void 0 ? void 0 : _q.text) || '', barHeight: barHeight, showYAxisLables: true, height: chartHeight, width: (_r = input.layout) === null || _r === void 0 ? void 0 : _r.width, hideTickOverlap: true, hideLegend: hideLegend, noOfCharsToTruncate: 20, showYAxisLablesTooltip: true, roundCorners: true }, getTitles(input.layout)), getAxisCategoryOrderProps(input.data, input.layout));
    };
    exports.transformPlotlyJsonToHorizontalBarWithAxisProps = transformPlotlyJsonToHorizontalBarWithAxisProps;
    var transformPlotlyJsonToHeatmapProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8;
        var firstData = input.data[0];
        var heatmapDataPoints = [];
        var zMin = Number.POSITIVE_INFINITY;
        var zMax = Number.NEGATIVE_INFINITY;
        if (firstData.type === 'histogram2d') {
            var xValues_1 = [];
            var yValues_1 = [];
            var zValues_1 = [];
            (_a = firstData.x) === null || _a === void 0 ? void 0 : _a.forEach(function (xVal, index) {
                var _a;
                var zVal = (0, exports.getNumberAtIndexOrDefault)(firstData.z, index);
                if ((0, chart_utilities_1.isInvalidValue)(xVal) || (0, chart_utilities_1.isInvalidValue)((_a = firstData.y) === null || _a === void 0 ? void 0 : _a[index]) || (0, chart_utilities_1.isInvalidValue)(zVal)) {
                    return;
                }
                xValues_1.push(xVal);
                yValues_1.push(firstData.y[index]);
                zValues_1.push(zVal);
            });
            var isXString_1 = (0, chart_utilities_1.isStringArray)(xValues_1);
            var isYString_1 = (0, chart_utilities_1.isStringArray)(yValues_1);
            var xBins_1 = createBins(xValues_1, (_b = firstData.xbins) === null || _b === void 0 ? void 0 : _b.start, (_c = firstData.xbins) === null || _c === void 0 ? void 0 : _c.end, (_d = firstData.xbins) === null || _d === void 0 ? void 0 : _d.size);
            var yBins_1 = createBins(yValues_1, (_e = firstData.ybins) === null || _e === void 0 ? void 0 : _e.start, (_f = firstData.ybins) === null || _f === void 0 ? void 0 : _f.end, (_g = firstData.ybins) === null || _g === void 0 ? void 0 : _g.size);
            var zBins_1 = yBins_1.map(function () { return xBins_1.map(function () { return []; }); });
            var total_1 = 0;
            xValues_1.forEach(function (xVal, index) {
                var xBinIdx = findBinIndex(xBins_1, xVal, isXString_1);
                var yBinIdx = findBinIndex(yBins_1, yValues_1[index], isYString_1);
                if (xBinIdx !== -1 && yBinIdx !== -1) {
                    zBins_1[yBinIdx][xBinIdx].push(zValues_1[index]);
                }
            });
            var z_1 = zBins_1.map(function (row) {
                return row.map(function (bin) {
                    var zVal = calculateHistFunc(firstData.histfunc, bin);
                    total_1 += zVal;
                    return zVal;
                });
            });
            xBins_1.forEach(function (xBin, xIdx) {
                yBins_1.forEach(function (yBin, yIdx) {
                    var zVal = calculateHistNorm(firstData.histnorm, z_1[yIdx][xIdx], total_1, isXString_1 ? xBin.length : getBinSize(xBin), isYString_1 ? yBin.length : getBinSize(yBin));
                    heatmapDataPoints.push({
                        x: isXString_1 ? xBin.join(', ') : getBinCenter(xBin),
                        y: isYString_1 ? yBin.join(', ') : getBinCenter(yBin),
                        value: zVal,
                        rectText: zVal,
                    });
                    if (typeof zVal === 'number') {
                        zMin = Math.min(zMin, zVal);
                        zMax = Math.max(zMax, zVal);
                    }
                });
            });
        }
        else {
            (_h = firstData.x) === null || _h === void 0 ? void 0 : _h.forEach(function (xVal, xIdx) {
                var _a;
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                (_a = firstData.y) === null || _a === void 0 ? void 0 : _a.forEach(function (yVal, yIdx) {
                    var _a, _b, _c, _d, _e, _f;
                    var zVal = (_b = (_a = firstData.z) === null || _a === void 0 ? void 0 : _a[yIdx]) === null || _b === void 0 ? void 0 : _b[xIdx];
                    heatmapDataPoints.push({
                        x: ((_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.xaxis) === null || _d === void 0 ? void 0 : _d.type) === 'date' ? xVal : xVal !== null && xVal !== void 0 ? xVal : 0,
                        y: ((_f = (_e = input.layout) === null || _e === void 0 ? void 0 : _e.yaxis) === null || _f === void 0 ? void 0 : _f.type) === 'date' ? yVal : yVal,
                        value: zVal,
                        rectText: zVal,
                    });
                    if (typeof zVal === 'number') {
                        zMin = Math.min(zMin, zVal);
                        zMax = Math.max(zMax, zVal);
                    }
                });
            });
        }
        var heatmapData = {
            legend: (_j = firstData.name) !== null && _j !== void 0 ? _j : '',
            data: heatmapDataPoints,
            value: 0,
        };
        // Initialize domain and range to default values
        var defaultDomain = [zMin, (zMax + zMin) / 2, zMax];
        var defaultRange = [
            (0, colors_1.getColorFromToken)(colors_1.DataVizPalette.color1),
            (0, colors_1.getColorFromToken)(colors_1.DataVizPalette.color2),
            (0, colors_1.getColorFromToken)(colors_1.DataVizPalette.color3),
        ];
        var colorscale = (_0 = (_u = (_q = (_m = (_k = firstData === null || firstData === void 0 ? void 0 : firstData.colorscale) !== null && _k !== void 0 ? _k : (_l = input.layout) === null || _l === void 0 ? void 0 : _l.colorscale) !== null && _m !== void 0 ? _m : (_p = (_o = input.layout) === null || _o === void 0 ? void 0 : _o.coloraxis) === null || _p === void 0 ? void 0 : _p.colorscale) !== null && _q !== void 0 ? _q : (_t = (_s = (_r = input.layout) === null || _r === void 0 ? void 0 : _r.template) === null || _s === void 0 ? void 0 : _s.layout) === null || _t === void 0 ? void 0 : _t.colorscale) !== null && _u !== void 0 ? _u : (firstData.type === 'histogram2d' && ((_z = (_y = (_x = (_w = (_v = input.layout) === null || _v === void 0 ? void 0 : _v.template) === null || _w === void 0 ? void 0 : _w.data) === null || _x === void 0 ? void 0 : _x.histogram2d) === null || _y === void 0 ? void 0 : _y[0]) === null || _z === void 0 ? void 0 : _z.colorscale))) !== null && _0 !== void 0 ? _0 : (_5 = (_4 = (_3 = (_2 = (_1 = input.layout) === null || _1 === void 0 ? void 0 : _1.template) === null || _2 === void 0 ? void 0 : _2.data) === null || _3 === void 0 ? void 0 : _3.heatmap) === null || _4 === void 0 ? void 0 : _4[0]) === null || _5 === void 0 ? void 0 : _5.colorscale;
        // determine if the types diverging, sequential or sequentialminus are present in colorscale
        if (colorscale &&
            typeof colorscale === 'object' &&
            ('diverging' in colorscale || 'sequential' in colorscale || 'sequentialminus' in colorscale)) {
            var isDivergent = zMin < 0 && zMax > 0; // Data spans both positive and negative values
            var isSequential = zMin >= 0; // Data is entirely positive
            var isSequentialMinus = zMax <= 0; // Data is entirely negative
            if (isDivergent) {
                colorscale = colorscale === null || colorscale === void 0 ? void 0 : colorscale.diverging;
            }
            else if (isSequential) {
                colorscale = colorscale === null || colorscale === void 0 ? void 0 : colorscale.sequential;
            }
            else if (isSequentialMinus) {
                colorscale = colorscale === null || colorscale === void 0 ? void 0 : colorscale.sequentialminus;
            }
        }
        var domainValuesForColorScale = Array.isArray(colorscale)
            ? colorscale.map(function (arr) { return arr[0] * (zMax - zMin) + zMin; })
            : defaultDomain;
        var rangeValuesForColorScale = Array.isArray(colorscale)
            ? colorscale.map(function (arr) { return arr[1]; })
            : defaultRange;
        return tslib_1.__assign(tslib_1.__assign({ data: [heatmapData], domainValuesForColorScale: domainValuesForColorScale, rangeValuesForColorScale: rangeValuesForColorScale, hideLegend: true, showYAxisLables: true, sortOrder: 'none', width: (_6 = input.layout) === null || _6 === void 0 ? void 0 : _6.width, height: (_8 = (_7 = input.layout) === null || _7 === void 0 ? void 0 : _7.height) !== null && _8 !== void 0 ? _8 : 350, hideTickOverlap: true, noOfCharsToTruncate: 20, showYAxisLablesTooltip: true }, getTitles(input.layout)), getAxisCategoryOrderProps([firstData], input.layout));
    };
    exports.transformPlotlyJsonToHeatmapProps = transformPlotlyJsonToHeatmapProps;
    var transformPlotlyJsonToSankeyProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
        var _m = input.data[0], link = _m.link, node = _m.node;
        var validLinks = ((_a = link === null || link === void 0 ? void 0 : link.value) !== null && _a !== void 0 ? _a : [])
            .map(function (val, index) {
            var _a, _b;
            if ((0, chart_utilities_1.isInvalidValue)(val) || (0, chart_utilities_1.isInvalidValue)((_a = link === null || link === void 0 ? void 0 : link.source) === null || _a === void 0 ? void 0 : _a[index]) || (0, chart_utilities_1.isInvalidValue)((_b = link === null || link === void 0 ? void 0 : link.target) === null || _b === void 0 ? void 0 : _b[index])) {
                return null;
            }
            return {
                value: val,
                source: link === null || link === void 0 ? void 0 : link.source[index],
                target: link === null || link === void 0 ? void 0 : link.target[index],
            };
        })
            // Filter out negative nodes, unequal nodes and self-references (circular links)
            .filter(function (x) { return x !== null && x.source >= 0 && x.target >= 0 && x.source !== x.target; });
        var extractedNodeColors = (0, PlotlyColorAdapter_1.extractColor)((_d = (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.template) === null || _c === void 0 ? void 0 : _c.layout) === null || _d === void 0 ? void 0 : _d.colorway, colorwayType, node === null || node === void 0 ? void 0 : node.color, colorMap, isDarkTheme);
        var sankeyChartData = {
            nodes: (_e = node.label) === null || _e === void 0 ? void 0 : _e.map(function (label, index) {
                var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedNodeColors, index, label, colorMap, isDarkTheme);
                return {
                    nodeId: index,
                    name: label,
                    color: color,
                };
            }),
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            links: validLinks.map(function (validLink, index) {
                return tslib_1.__assign({}, validLink);
            }),
        };
        var styles = {
            root: tslib_1.__assign({}, (((_g = (_f = input.layout) === null || _f === void 0 ? void 0 : _f.font) === null || _g === void 0 ? void 0 : _g.size) ? { fontSize: (_h = input.layout.font) === null || _h === void 0 ? void 0 : _h.size } : {})),
        };
        var chartTitle = getTitles(input.layout).chartTitle;
        return {
            data: {
                chartTitle: chartTitle,
                SankeyChartData: sankeyChartData,
            },
            width: (_j = input.layout) === null || _j === void 0 ? void 0 : _j.width,
            height: (_l = (_k = input.layout) === null || _k === void 0 ? void 0 : _k.height) !== null && _l !== void 0 ? _l : 468,
            styles: styles,
            enableReflow: true,
        };
    };
    exports.transformPlotlyJsonToSankeyProps = transformPlotlyJsonToSankeyProps;
    var transformPlotlyJsonToGaugeProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25;
        var firstData = input.data[0];
        var stepsColors = ((_a = firstData.gauge) === null || _a === void 0 ? void 0 : _a.steps) ? firstData.gauge.steps.map(function (step) { return step.color; }) : undefined;
        var extractedColors = (0, PlotlyColorAdapter_1.extractColor)((_d = (_c = (_b = input.layout) === null || _b === void 0 ? void 0 : _b.template) === null || _c === void 0 ? void 0 : _c.layout) === null || _d === void 0 ? void 0 : _d.colorway, colorwayType, stepsColors, colorMap, isDarkTheme);
        var segments = ((_f = (_e = firstData.gauge) === null || _e === void 0 ? void 0 : _e.steps) === null || _f === void 0 ? void 0 : _f.length)
            ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
                firstData.gauge.steps.map(function (step, index) {
                    var _a, _b;
                    var legend = step.name || "Segment ".concat(index + 1);
                    var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedColors, index, legend, colorMap, isDarkTheme);
                    return {
                        legend: legend,
                        size: ((_a = step.range) === null || _a === void 0 ? void 0 : _a[1]) - ((_b = step.range) === null || _b === void 0 ? void 0 : _b[0]),
                        color: color,
                    };
                })
            : [
                {
                    legend: 'Current',
                    size: (_g = firstData.value) !== null && _g !== void 0 ? _g : 0 - ((_l = (_k = (_j = (_h = firstData.gauge) === null || _h === void 0 ? void 0 : _h.axis) === null || _j === void 0 ? void 0 : _j.range) === null || _k === void 0 ? void 0 : _k[0]) !== null && _l !== void 0 ? _l : 0),
                    color: (0, exports._getGaugeAxisColor)((_p = (_o = (_m = input.layout) === null || _m === void 0 ? void 0 : _m.template) === null || _o === void 0 ? void 0 : _o.layout) === null || _p === void 0 ? void 0 : _p.colorway, colorwayType, (_r = (_q = firstData.gauge) === null || _q === void 0 ? void 0 : _q.axis) === null || _r === void 0 ? void 0 : _r.color, colorMap, isDarkTheme),
                },
                {
                    legend: 'Target',
                    size: ((_v = (_u = (_t = (_s = firstData.gauge) === null || _s === void 0 ? void 0 : _s.axis) === null || _t === void 0 ? void 0 : _t.range) === null || _u === void 0 ? void 0 : _u[1]) !== null && _v !== void 0 ? _v : 100) - ((_w = firstData.value) !== null && _w !== void 0 ? _w : 0),
                    color: colors_1.DataVizPalette.disabled,
                },
            ];
        var sublabel;
        var sublabelColor;
        if ((_x = firstData.delta) === null || _x === void 0 ? void 0 : _x.reference) {
            var diff = firstData.value - firstData.delta.reference;
            if (diff >= 0) {
                sublabel = "\u25B2 ".concat(diff);
                var extractedIncreasingDeltaColors = (0, PlotlyColorAdapter_1.extractColor)((_0 = (_z = (_y = input.layout) === null || _y === void 0 ? void 0 : _y.template) === null || _z === void 0 ? void 0 : _z.layout) === null || _0 === void 0 ? void 0 : _0.colorway, colorwayType, (_2 = (_1 = firstData.delta) === null || _1 === void 0 ? void 0 : _1.increasing) === null || _2 === void 0 ? void 0 : _2.color, colorMap, isDarkTheme);
                var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedIncreasingDeltaColors, 0, '', colorMap, isDarkTheme);
                sublabelColor = color;
            }
            else {
                sublabel = "\u25BC ".concat(Math.abs(diff));
                var extractedDecreasingDeltaColors = (0, PlotlyColorAdapter_1.extractColor)((_5 = (_4 = (_3 = input.layout) === null || _3 === void 0 ? void 0 : _3.template) === null || _4 === void 0 ? void 0 : _4.layout) === null || _5 === void 0 ? void 0 : _5.colorway, colorwayType, (_7 = (_6 = firstData.delta) === null || _6 === void 0 ? void 0 : _6.decreasing) === null || _7 === void 0 ? void 0 : _7.color, colorMap, isDarkTheme);
                var color = (0, PlotlyColorAdapter_1.resolveColor)(extractedDecreasingDeltaColors, 0, '', colorMap, isDarkTheme);
                sublabelColor = color;
            }
        }
        var styles = {
            sublabel: {
                fill: sublabelColor,
            },
        };
        var chartTitle = getTitles(input.layout).chartTitle;
        return {
            segments: segments,
            chartValue: (_8 = firstData.value) !== null && _8 !== void 0 ? _8 : 0,
            chartTitle: chartTitle,
            sublabel: sublabel,
            // range values can be null
            minValue: typeof ((_11 = (_10 = (_9 = firstData.gauge) === null || _9 === void 0 ? void 0 : _9.axis) === null || _10 === void 0 ? void 0 : _10.range) === null || _11 === void 0 ? void 0 : _11[0]) === 'number' ? (_14 = (_13 = (_12 = firstData.gauge) === null || _12 === void 0 ? void 0 : _12.axis) === null || _13 === void 0 ? void 0 : _13.range) === null || _14 === void 0 ? void 0 : _14[0] : undefined,
            maxValue: typeof ((_17 = (_16 = (_15 = firstData.gauge) === null || _15 === void 0 ? void 0 : _15.axis) === null || _16 === void 0 ? void 0 : _16.range) === null || _17 === void 0 ? void 0 : _17[1]) === 'number' ? (_20 = (_19 = (_18 = firstData.gauge) === null || _18 === void 0 ? void 0 : _18.axis) === null || _19 === void 0 ? void 0 : _19.range) === null || _20 === void 0 ? void 0 : _20[1] : undefined,
            chartValueFormat: function () { var _a, _b; return (_b = (_a = firstData.value) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''; },
            width: (_21 = input.layout) === null || _21 === void 0 ? void 0 : _21.width,
            height: (_23 = (_22 = input.layout) === null || _22 === void 0 ? void 0 : _22.height) !== null && _23 !== void 0 ? _23 : 220,
            styles: styles,
            variant: ((_25 = (_24 = firstData.gauge) === null || _24 === void 0 ? void 0 : _24.steps) === null || _25 === void 0 ? void 0 : _25.length) ? index_1.GaugeChartVariant.MultipleSegments : index_1.GaugeChartVariant.SingleSegment,
            roundCorners: true,
        };
    };
    exports.transformPlotlyJsonToGaugeProps = transformPlotlyJsonToGaugeProps;
    var cleanText = function (text) {
        return text
            .replace(/&lt;[^&]*?&gt;/g, '')
            .replace(/<[^>]*>/g, '')
            .replace(/&lt;br&gt;|\\u003cbr\\u003e|<br>/gi, '')
            .replace(/\$[^$]*\$/g, '$')
            .trim();
    };
    var formatValue = function (value, colIndex, cells) {
        if (value === null || typeof value === 'boolean') {
            return value;
        }
        var formatStr = Array.isArray(cells.format) ? cells.format[colIndex] : cells.format;
        var prefix = Array.isArray(cells.prefix) ? cells.prefix[colIndex] : cells.prefix;
        var suffix = Array.isArray(cells.suffix) ? cells.suffix[colIndex] : cells.suffix;
        var formatted = value;
        if (typeof value === 'number') {
            if (typeof formatStr === 'string') {
                try {
                    formatted = (0, d3_format_1.format)(formatStr)(value);
                }
                catch (_a) {
                    formatted = (0, utilities_1.formatScientificLimitWidth)(value);
                }
            }
            else {
                formatted = (0, utilities_1.formatScientificLimitWidth)(value);
            }
        }
        return "".concat(prefix !== null && prefix !== void 0 ? prefix : '').concat(formatted).concat(suffix !== null && suffix !== void 0 ? suffix : '');
    };
    var transformPlotlyJsonToChartTableProps = function (input, isMultiPlot, colorMap, colorwayType, isDarkTheme) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
        var tableData = input.data[0];
        var normalizeHeaders = function (values, header) {
            var cleanedValues = Array.isArray(values[0])
                ? values.map(function (row) {
                    return row
                        .map(function (cell) { return cleanText(cell); })
                        .filter(Boolean)
                        .join(' ');
                })
                : values.map(function (cell) { return cleanText(cell); });
            return cleanedValues.map(function (value, colIndex) {
                var _a, _b, _c;
                var fontColorRaw = (_a = header === null || header === void 0 ? void 0 : header.font) === null || _a === void 0 ? void 0 : _a.color;
                var fontColor;
                if (Array.isArray(fontColorRaw)) {
                    var colorEntry = fontColorRaw[colIndex];
                    if (Array.isArray(colorEntry)) {
                        fontColor = typeof colorEntry[0] === 'string' ? colorEntry[0] : undefined;
                    }
                    else if (typeof colorEntry === 'string') {
                        fontColor = colorEntry;
                    }
                }
                else if (typeof fontColorRaw === 'string') {
                    fontColor = fontColorRaw;
                }
                var fontSizeRaw = (_b = header === null || header === void 0 ? void 0 : header.font) === null || _b === void 0 ? void 0 : _b.size;
                var fontSize;
                if (Array.isArray(fontSizeRaw)) {
                    fontSize = Array.isArray(fontSizeRaw[0]) ? fontSizeRaw[0][colIndex] : fontSizeRaw[colIndex];
                }
                else if (typeof fontSizeRaw === 'number') {
                    fontSize = fontSizeRaw;
                }
                var updatedColIndex = colIndex >= 1 ? 1 : 0;
                var fillColorRaw = (_c = header === null || header === void 0 ? void 0 : header.fill) === null || _c === void 0 ? void 0 : _c.color;
                var backgroundColor = Array.isArray(fillColorRaw) ? fillColorRaw[updatedColIndex] : fillColorRaw;
                var textAlignRaw = header === null || header === void 0 ? void 0 : header.align;
                var textAlign = Array.isArray(textAlignRaw) ? textAlignRaw[colIndex] : textAlignRaw;
                var style = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, (typeof fontColor === 'string' ? { color: fontColor } : {})), (typeof fontSize === 'number' ? { fontSize: fontSize } : {})), (typeof backgroundColor === 'string' ? { backgroundColor: backgroundColor } : {})), (textAlign ? { textAlign: textAlign } : {}));
                return { value: value, style: style };
            });
        };
        var columns = (_b = (_a = tableData.cells) === null || _a === void 0 ? void 0 : _a.values) !== null && _b !== void 0 ? _b : [];
        var cells = tableData.cells.font ? tableData.cells : (_e = (_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.template) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.table[0].cells;
        var rows = columns[0].map(function (_, rowIndex) {
            return columns.map(function (col, colIndex) {
                var _a, _b, _c;
                var cellValue = col[rowIndex];
                var cleanValue = typeof cellValue === 'string' ? cleanText(cellValue) : cellValue;
                var formattedValue = typeof cleanValue === 'string' || typeof cleanValue === 'number'
                    ? formatValue(cleanValue, colIndex, cells)
                    : cleanValue;
                var rawFontColor = (_a = cells === null || cells === void 0 ? void 0 : cells.font) === null || _a === void 0 ? void 0 : _a.color;
                var fontColor;
                if (Array.isArray(rawFontColor)) {
                    var entry = rawFontColor[colIndex];
                    var colorValue = Array.isArray(entry) ? entry[rowIndex] : entry;
                    fontColor = typeof colorValue === 'string' ? colorValue : undefined;
                }
                else if (typeof rawFontColor === 'string') {
                    fontColor = rawFontColor;
                }
                var rawFontSize = (_b = cells === null || cells === void 0 ? void 0 : cells.font) === null || _b === void 0 ? void 0 : _b.size;
                var fontSize;
                if (Array.isArray(rawFontSize)) {
                    var entry = rawFontSize[colIndex];
                    var fontSizeValue = Array.isArray(entry) ? entry[rowIndex] : entry;
                    fontSize = typeof fontSizeValue === 'number' ? fontSizeValue : undefined;
                }
                else if (typeof rawFontSize === 'number') {
                    fontSize = rawFontSize;
                }
                var updatedColIndex = colIndex >= 1 ? 1 : 0;
                var rawBackgroundColor = (_c = cells === null || cells === void 0 ? void 0 : cells.fill) === null || _c === void 0 ? void 0 : _c.color;
                var backgroundColor;
                if (Array.isArray(rawBackgroundColor)) {
                    var entry = rawBackgroundColor[updatedColIndex];
                    var colorValue = Array.isArray(entry) ? entry[rowIndex] : entry;
                    backgroundColor = typeof colorValue === 'string' ? colorValue : undefined;
                }
                else if (typeof rawBackgroundColor === 'string') {
                    backgroundColor = rawBackgroundColor;
                }
                var rawTextAlign = Array.isArray(cells === null || cells === void 0 ? void 0 : cells.align) ? cells.align[colIndex] : cells === null || cells === void 0 ? void 0 : cells.align;
                var textAlign = rawTextAlign;
                var style = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, (fontColor ? { color: fontColor } : {})), (typeof fontSize === 'number' ? { fontSize: fontSize } : {})), (backgroundColor ? { backgroundColor: backgroundColor } : {})), (textAlign ? { textAlign: textAlign } : {}));
                return {
                    value: formattedValue,
                    style: style,
                };
            });
        });
        var styles = {
            root: tslib_1.__assign({}, (((_g = (_f = input.layout) === null || _f === void 0 ? void 0 : _f.font) === null || _g === void 0 ? void 0 : _g.size) ? { fontSize: input.layout.font.size } : {})),
        };
        return {
            headers: normalizeHeaders((_j = (_h = tableData.header) === null || _h === void 0 ? void 0 : _h.values) !== null && _j !== void 0 ? _j : [], ((_k = tableData.header) === null || _k === void 0 ? void 0 : _k.font) ? tableData.header : (_o = (_m = (_l = input.layout) === null || _l === void 0 ? void 0 : _l.template) === null || _m === void 0 ? void 0 : _m.data) === null || _o === void 0 ? void 0 : _o.table[0].header),
            rows: rows,
            width: (_p = input.layout) === null || _p === void 0 ? void 0 : _p.width,
            height: (_q = input.layout) === null || _q === void 0 ? void 0 : _q.height,
            styles: styles,
        };
    };
    exports.transformPlotlyJsonToChartTableProps = transformPlotlyJsonToChartTableProps;
    var projectPolarToCartesian = function (input) {
        var _a, _b, _c, _d;
        var projection = tslib_1.__assign({}, input);
        for (var sindex = 0; sindex < input.data.length; sindex++) {
            var series = input.data[sindex];
            series.x = [];
            series.y = [];
            for (var ptindex = 0; ptindex < ((_b = (_a = series.r) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0); ptindex++) {
                if ((0, chart_utilities_1.isInvalidValue)((_c = series.theta) === null || _c === void 0 ? void 0 : _c[ptindex]) || (0, chart_utilities_1.isInvalidValue)((_d = series.r) === null || _d === void 0 ? void 0 : _d[ptindex])) {
                    continue;
                }
                var thetaRad = (series.theta[ptindex] * Math.PI) / 180;
                var radius = series.r[ptindex];
                series.x.push(radius * Math.cos(thetaRad));
                series.y.push(radius * Math.sin(thetaRad));
            }
            projection.data[sindex] = series;
        }
        return projection;
    };
    exports.projectPolarToCartesian = projectPolarToCartesian;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function isPlainObject(obj) {
        if (window && window.process && window.process.versions) {
            return Object.prototype.toString.call(obj) === '[object Object]';
        }
        return (Object.prototype.toString.call(obj) === '[object Object]' &&
            Object.getPrototypeOf(obj).hasOwnProperty('hasOwnProperty'));
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    var arrayAttributes = [];
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    var stack = [];
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    var isArrayStack = [];
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    var baseContainer, baseAttrName;
    /**
     * Interate iteratively through the trace object and find all the array attributes.
     * 1 trace record = 1 series of data
     * @param trace
     */
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function findArrayAttributes(trace) {
        // Init basecontainer and baseAttrName
        crawlIntoTrace(baseContainer, 0, '');
    }
    exports.findArrayAttributes = findArrayAttributes;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function crawlIntoTrace(container, i, astrPartial) {
        var item = container[stack[i]];
        var newAstrPartial = astrPartial + stack[i];
        if (i === stack.length - 1) {
            if ((0, chart_utilities_1.isArrayOrTypedArray)(item)) {
                arrayAttributes.push(baseAttrName + newAstrPartial);
            }
        }
        else {
            if (isArrayStack[i]) {
                if (Array.isArray(item)) {
                    for (var j = 0; j < item.length; j++) {
                        if (isPlainObject(item[j])) {
                            crawlIntoTrace(item[j], i + 1, newAstrPartial + '[' + j + '].');
                        }
                    }
                }
            }
            else if (isPlainObject(item)) {
                crawlIntoTrace(item, i + 1, newAstrPartial + '.');
            }
        }
    }
    function getLineOptions(line) {
        if (!line) {
            return;
        }
        var lineOptions = {};
        if (line.dash) {
            lineOptions = tslib_1.__assign(tslib_1.__assign({}, lineOptions), dashOptions[line.dash]);
        }
        switch (line.shape) {
            case 'spline':
                var smoothing = typeof line.smoothing === 'number' ? line.smoothing : 1;
                lineOptions.curve = d3_shape_1.curveCardinal.tension(1 - smoothing / 1.3);
                break;
            case 'hv':
                lineOptions.curve = 'stepAfter';
                break;
            case 'vh':
                lineOptions.curve = 'stepBefore';
                break;
            case 'hvh':
                lineOptions.curve = 'step';
                break;
            default:
                lineOptions.curve = 'linear';
        }
        return Object.keys(lineOptions).length > 0 ? lineOptions : undefined;
    }
    // TODO: Use binary search to find the appropriate bin for numeric value.
    var findBinIndex = function (bins, value, isString) {
        if (typeof value === 'undefined' || value === null) {
            return -1;
        }
        return isString
            ? bins.findIndex(function (bin) { return bin.includes(value); })
            : bins.findIndex(function (bin, index) {
                return value >= bin.x0 &&
                    (index === bins.length - 1 ? value <= bin.x1 : value < bin.x1);
            });
    };
    var getBinSize = function (bin) {
        return bin.x1 - bin.x0;
    };
    var getBinCenter = function (bin) {
        return (bin.x1 + bin.x0) / 2;
    };
    // TODO: Add support for date axes
    var createBins = function (data, binStart, binEnd, binSize) {
        if (!data || data.length === 0) {
            return [];
        }
        if ((0, chart_utilities_1.isStringArray)(data)) {
            var categories_1 = Array.from(new Set(data));
            var start = typeof binStart === 'number' ? Math.ceil(binStart) : 0;
            var stop_1 = typeof binEnd === 'number' ? Math.floor(binEnd) + 1 : categories_1.length;
            var step_1 = typeof binSize === 'number' ? binSize : 1;
            return (0, d3_array_1.range)(start, stop_1, step_1).map(function (i) { return categories_1.slice(i, i + step_1); });
        }
        var scale = (0, d3_scale_1.scaleLinear)()
            .domain((0, d3_array_1.extent)(data))
            .nice();
        var _a = scale.domain(), minVal = _a[0], maxVal = _a[1];
        minVal = typeof binStart === 'number' ? binStart : minVal;
        maxVal = typeof binEnd === 'number' ? binEnd : maxVal;
        var binGenerator = (0, d3_array_1.bin)().domain([minVal, maxVal]);
        if (typeof binSize === 'number' && binSize > 0) {
            var thresholds = [];
            var precision = Math.max(getPrecision(minVal), getPrecision(binSize));
            var th = precisionRound(minVal, precision);
            while (th < precisionRound(maxVal + binSize, precision)) {
                thresholds.push(th);
                th = precisionRound(th + binSize, precision);
            }
            minVal = thresholds[0];
            maxVal = thresholds[thresholds.length - 1];
            binGenerator.domain([minVal, maxVal]).thresholds(thresholds);
            // When the domain ends at the last threshold (maxVal), d3Bin creates an extra final bin where
            // both x0 and x1 are equal to maxVal and inclusive. The previous bin also has x1 equal to maxVal,
            // but it is exclusive. To maintain consistent bin widths, remove the final bin,
            // making the previous bin the last one, with both x0 and x1 inclusive.
            return binGenerator(data).slice(0, -1);
        }
        return binGenerator(data);
    };
    var calculateHistFunc = function (histfunc, bin) {
        var _a, _b;
        switch (histfunc) {
            case 'sum':
                return (0, d3_array_1.sum)(bin);
            case 'avg':
                return bin.length === 0 ? 0 : (0, d3_array_1.sum)(bin) / bin.length;
            case 'min':
                return (_a = (0, d3_array_1.min)(bin)) !== null && _a !== void 0 ? _a : 0;
            case 'max':
                return (_b = (0, d3_array_1.max)(bin)) !== null && _b !== void 0 ? _b : 0;
            default:
                return bin.length;
        }
    };
    var calculateHistNorm = function (histnorm, value, total, dx, dy) {
        if (dy === void 0) { dy = 1; }
        switch (histnorm) {
            case 'percent':
                return total === 0 ? 0 : (value / total) * 100;
            case 'probability':
                return total === 0 ? 0 : value / total;
            case 'density':
                return dx * dy === 0 ? 0 : value / (dx * dy);
            case 'probability density':
                return total * dx * dy === 0 ? 0 : value / (total * dx * dy);
            default:
                return value;
        }
    };
    var getPrecision = function (value) {
        var _a, _b;
        return (_b = (_a = value.toString().split('.')[1]) === null || _a === void 0 ? void 0 : _a.length) !== null && _b !== void 0 ? _b : 0;
    };
    var precisionRound = function (value, precision) {
        var factor = Math.pow(10, precision);
        return Math.round(value * factor) / factor;
    };
    var getLegendShape = function (series) {
        var _a, _b;
        var dashType = ((_a = series.line) === null || _a === void 0 ? void 0 : _a.dash) || 'solid';
        if (dashType === 'dot' || dashType === 'dash' || dashType === 'dashdot') {
            return 'dottedLine';
        }
        else if ((_b = series.mode) === null || _b === void 0 ? void 0 : _b.includes('markers')) {
            return 'circle';
        }
        return 'default';
    };
    var getAllupLegendsProps = function (input, colorMap, colorwayType, traceInfo, isDarkTheme) {
        var allupLegends = [];
        // reduce on showlegend boolean propperty. reduce should return true if at least one series has showlegend true
        var toShowLegend = input.data.reduce(function (acc, series) {
            return (acc || series.showlegend === true || series.showlegend === undefined);
        }, false);
        if (toShowLegend) {
            input.data.forEach(function (series, index) {
                var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
                if (traceInfo[index].type === 'donut') {
                    var pieSeries = series;
                    var colors_2 = (0, PlotlyColorAdapter_1.extractColor)((_b = (_a = input.layout) === null || _a === void 0 ? void 0 : _a.piecolorway) !== null && _b !== void 0 ? _b : (_e = (_d = (_c = input.layout) === null || _c === void 0 ? void 0 : _c.template) === null || _d === void 0 ? void 0 : _d.layout) === null || _e === void 0 ? void 0 : _e.colorway, colorwayType, (_g = (_f = input.layout) === null || _f === void 0 ? void 0 : _f.piecolorway) !== null && _g !== void 0 ? _g : (_h = pieSeries === null || pieSeries === void 0 ? void 0 : pieSeries.marker) === null || _h === void 0 ? void 0 : _h.colors, colorMap, isDarkTheme);
                    (_j = pieSeries.labels) === null || _j === void 0 ? void 0 : _j.forEach(function (label, labelIndex) {
                        var legend = "".concat(label);
                        // resolve color for each legend from the extracted colors
                        var color = (0, PlotlyColorAdapter_1.resolveColor)(colors_2, labelIndex, legend, colorMap, isDarkTheme);
                        if (legend !== '' && allupLegends.some(function (group) { return group.title === legend; }) === false) {
                            allupLegends.push({
                                title: legend,
                                color: color,
                            });
                        }
                    });
                }
                else if ((0, exports.isNonPlotType)(traceInfo[index].type) === false) {
                    var plotSeries = series;
                    var name_1 = plotSeries.legendgroup;
                    var color = ((_k = plotSeries.line) === null || _k === void 0 ? void 0 : _k.color) || ((_l = plotSeries.marker) === null || _l === void 0 ? void 0 : _l.color);
                    var legendShape = getLegendShape(plotSeries);
                    var resolvedColor = (0, PlotlyColorAdapter_1.extractColor)((_p = (_o = (_m = input.layout) === null || _m === void 0 ? void 0 : _m.template) === null || _o === void 0 ? void 0 : _o.layout) === null || _p === void 0 ? void 0 : _p.colorway, colorwayType, color, colorMap, isDarkTheme);
                    if (name_1 !== undefined && name_1 !== '' && allupLegends.some(function (group) { return group.title === name_1; }) === false) {
                        allupLegends.push({
                            title: name_1,
                            color: resolvedColor,
                            shape: legendShape,
                        });
                    }
                }
            });
        }
        return {
            legends: allupLegends,
            centerLegends: true,
            enabledWrapLines: true,
            canSelectMultipleLegends: true,
        };
    };
    exports.getAllupLegendsProps = getAllupLegendsProps;
    var getLegendProps = function (data, layout, isMultiPlot) {
        var legends = [];
        if (data.length === 1) {
            legends.push(data[0].name || '');
        }
        else {
            data.forEach(function (series, index) {
                legends.push(series.name || "Series ".concat(index + 1));
            });
        }
        var hideLegendsData = data.every(function (series) { return series.showlegend === false; });
        var hideLegendsInferred = (layout === null || layout === void 0 ? void 0 : layout.showlegend) === false || ((layout === null || layout === void 0 ? void 0 : layout.showlegend) !== true && legends.length < 2);
        return {
            legends: legends,
            hideLegend: isMultiPlot || hideLegendsInferred || hideLegendsData,
        };
    };
    var getNumberAtIndexOrDefault = function (data, index) {
        if ((0, chart_utilities_1.isArrayOrTypedArray)(data)) {
            if (typeof data[index] !== 'number' || !isFinite(data[index])) {
                return;
            }
            return data[index];
        }
        return 1;
    };
    exports.getNumberAtIndexOrDefault = getNumberAtIndexOrDefault;
    var getValidXYRanges = function (series) {
        if (!(0, chart_utilities_1.isArrayOrTypedArray)(series.x) || !(0, chart_utilities_1.isArrayOrTypedArray)(series.y)) {
            return [];
        }
        var ranges = [];
        var start = 0;
        var end = 0;
        for (; end < series.x.length; end++) {
            if ((0, chart_utilities_1.isInvalidValue)(series.x[end]) || (0, chart_utilities_1.isInvalidValue)(series.y[end])) {
                if (end - start > 0) {
                    ranges.push([start, end]);
                }
                start = end + 1;
            }
        }
        if (end - start > 0) {
            ranges.push([start, end]);
        }
        return ranges;
    };
    exports.getValidXYRanges = getValidXYRanges;
    var getIndexFromKey = function (key, pattern) {
        var normalizedKey = key.replace(pattern, '') === '' ? '1' : key.replace(pattern, '');
        return parseInt(normalizedKey, 10) - 1;
    };
    var isNonPlotType = function (chartType) {
        return ['donut', 'sankey', 'pie'].includes(chartType);
    };
    exports.isNonPlotType = isNonPlotType;
    var getGridProperties = function (schema, isMultiPlot, validTracesInfo) {
        var _a;
        var domainX = [];
        var domainY = [];
        var cartesianDomains = 0;
        var annotations = {};
        var templateRows = '1fr';
        var templateColumns = '1fr';
        var gridLayout = {};
        if (!isMultiPlot) {
            return { templateRows: templateRows, templateColumns: templateColumns, layout: gridLayout };
        }
        var layout = schema === null || schema === void 0 ? void 0 : schema.layout;
        if (layout !== undefined && layout !== null && Object.keys(layout).length > 0) {
            Object.keys(layout !== null && layout !== void 0 ? layout : {}).forEach(function (key) {
                var _a, _b, _c, _d, _e;
                if (key.startsWith('xaxis')) {
                    var index = getIndexFromKey(key, 'xaxis');
                    var anchor = (_b = (_a = layout[key]) === null || _a === void 0 ? void 0 : _a.anchor) !== null && _b !== void 0 ? _b : 'y';
                    var anchorIndex = getIndexFromKey(anchor, 'y');
                    if (index !== anchorIndex) {
                        throw new Error("Invalid layout: xaxis ".concat(index + 1, " anchor should be y").concat(anchorIndex + 1));
                    }
                    var xAxisLayout = layout[key];
                    var domainXInfo = {
                        start: (xAxisLayout === null || xAxisLayout === void 0 ? void 0 : xAxisLayout.domain) ? xAxisLayout.domain[0] : 0,
                        end: (xAxisLayout === null || xAxisLayout === void 0 ? void 0 : xAxisLayout.domain) ? xAxisLayout.domain[1] : 1,
                    };
                    domainX.push(domainXInfo);
                }
                else if (key.startsWith('yaxis')) {
                    var index = getIndexFromKey(key, 'yaxis');
                    var anchor = (_d = (_c = layout[key]) === null || _c === void 0 ? void 0 : _c.anchor) !== null && _d !== void 0 ? _d : 'x';
                    var anchorIndex = getIndexFromKey(anchor, 'x');
                    if (index !== anchorIndex) {
                        if ((index === 1 && anchorIndex === 0) || ((_e = layout.yaxis2) === null || _e === void 0 ? void 0 : _e.side) === 'right') {
                            // Special case for secondary y axis where yaxis2 can anchor to x1
                            return { templateRows: templateRows, templateColumns: templateColumns };
                        }
                        throw new Error("Invalid layout: yaxis ".concat(index + 1, " anchor should be x").concat(anchorIndex + 1));
                    }
                    var yAxisLayout = layout[key];
                    var domainYInfo = {
                        start: (yAxisLayout === null || yAxisLayout === void 0 ? void 0 : yAxisLayout.domain) ? yAxisLayout.domain[0] : 0,
                        end: (yAxisLayout === null || yAxisLayout === void 0 ? void 0 : yAxisLayout.domain) ? yAxisLayout.domain[1] : 1,
                    };
                    domainY.push(domainYInfo);
                }
            });
        }
        cartesianDomains = domainX.length; // Assuming that the number of x and y axes is the same
        validTracesInfo.forEach(function (trace, index) {
            var _a, _b, _c, _d, _e;
            if ((0, exports.isNonPlotType)(trace.type)) {
                var series = (_a = schema === null || schema === void 0 ? void 0 : schema.data) === null || _a === void 0 ? void 0 : _a[index];
                var domainXInfo = {
                    start: ((_b = series.domain) === null || _b === void 0 ? void 0 : _b.x) ? series.domain.x[0] : 0,
                    end: ((_c = series.domain) === null || _c === void 0 ? void 0 : _c.x) ? series.domain.x[1] : 1,
                };
                var domainYInfo = {
                    start: ((_d = series.domain) === null || _d === void 0 ? void 0 : _d.y) ? series.domain.y[0] : 0,
                    end: ((_e = series.domain) === null || _e === void 0 ? void 0 : _e.y) ? series.domain.y[1] : 1,
                };
                domainX.push(domainXInfo);
                domainY.push(domainYInfo);
            }
        });
        if (layout !== undefined && layout !== null && Object.keys(layout).length > 0) {
            (_a = layout.annotations) === null || _a === void 0 ? void 0 : _a.forEach(function (annotation) {
                var xMatches = domainX.flatMap(function (interval, idx) {
                    return (annotation === null || annotation === void 0 ? void 0 : annotation.x) >= interval.start && (annotation === null || annotation === void 0 ? void 0 : annotation.x) <= interval.end ? [idx] : [];
                });
                var yMatch = domainY.findIndex(function (interval, yIndex) {
                    return xMatches.includes(yIndex) &&
                        (annotation === null || annotation === void 0 ? void 0 : annotation.y) >= interval.start &&
                        (annotation === null || annotation === void 0 ? void 0 : annotation.y) <= interval.end;
                });
                if (yMatch !== -1) {
                    if (annotations[yMatch] === undefined) {
                        annotations[yMatch] = {};
                    }
                    if ((annotation === null || annotation === void 0 ? void 0 : annotation.textangle) === 90) {
                        annotations[yMatch].yAnnotation = annotation.text;
                    }
                    else {
                        annotations[yMatch].xAnnotation = annotation.text;
                    }
                }
            });
        }
        if (domainX.length > 0) {
            var uniqueXIntervals_1 = new Map();
            domainX.forEach(function (interval) {
                var key = "".concat(interval.start, "-").concat(interval.end);
                if (!uniqueXIntervals_1.has(key)) {
                    uniqueXIntervals_1.set(key, interval);
                }
            });
            var sortedXStart_1 = Array.from(uniqueXIntervals_1.values())
                .map(function (interval) { return interval.start; })
                .sort();
            templateColumns = "repeat(".concat(sortedXStart_1.length, ", 1fr)");
            domainX.forEach(function (interval, index) {
                var cellName = index >= cartesianDomains
                    ? "".concat(exports.NON_PLOT_KEY_PREFIX).concat(index - cartesianDomains + 1)
                    : "x".concat(index === 0 ? '' : index + 1);
                var columnIndex = sortedXStart_1.findIndex(function (start) { return start === interval.start; });
                var columnNumber = columnIndex + 1; // Column numbers are 1-based
                var annotationProps = annotations[index];
                var xAnnotation = annotationProps === null || annotationProps === void 0 ? void 0 : annotationProps.xAnnotation;
                var row = {
                    row: -1,
                    column: columnNumber,
                    xAnnotation: xAnnotation,
                    xDomain: interval,
                    yDomain: { start: 0, end: 1 }, // Default yDomain for x-axis
                };
                gridLayout[cellName] = row;
            });
        }
        if (domainY.length > 0) {
            var uniqueYIntervals_1 = new Map();
            domainY.forEach(function (interval) {
                var key = "".concat(interval.start, "-").concat(interval.end);
                if (!uniqueYIntervals_1.has(key)) {
                    uniqueYIntervals_1.set(key, interval);
                }
            });
            var sortedYStart_1 = Array.from(uniqueYIntervals_1.values())
                .map(function (interval) { return interval.start; })
                .sort();
            var numberOfRows_1 = sortedYStart_1.length;
            templateRows = "repeat(".concat(numberOfRows_1, ", 1fr)");
            domainY.forEach(function (interval, index) {
                var cellName = index >= cartesianDomains
                    ? "".concat(exports.NON_PLOT_KEY_PREFIX).concat(index - cartesianDomains + 1)
                    : "x".concat(index === 0 ? '' : index + 1);
                var rowIndex = sortedYStart_1.findIndex(function (start) { return start === interval.start; });
                var rowNumber = numberOfRows_1 - rowIndex; // Rows are 1-based and we need to reverse the order for CSS grid
                var annotationProps = annotations[index];
                var yAnnotation = annotationProps === null || annotationProps === void 0 ? void 0 : annotationProps.yAnnotation;
                var cell = gridLayout[cellName];
                if (cell !== undefined) {
                    cell.row = rowNumber;
                    cell.yAnnotation = yAnnotation;
                    cell.yDomain = interval;
                }
            });
        }
        return {
            templateRows: templateRows,
            templateColumns: templateColumns,
            layout: gridLayout,
        };
    };
    exports.getGridProperties = getGridProperties;
    /**
     * @see {@link https://github.com/plotly/plotly.js/blob/master/src/plots/cartesian/category_order_defaults.js#L50}
     */
    var getAxisCategoryOrderProps = function (data, layout) {
        var result = {};
        var axesById = {
            x: layout === null || layout === void 0 ? void 0 : layout.xaxis,
            y: layout === null || layout === void 0 ? void 0 : layout.yaxis,
        };
        Object.keys(axesById).forEach(function (axId) {
            var ax = axesById[axId];
            var axLetter = axId[0];
            var propName = "".concat(axLetter, "AxisCategoryOrder");
            var values = [];
            data.forEach(function (series) {
                var _a;
                (_a = series[axLetter]) === null || _a === void 0 ? void 0 : _a.forEach(function (val) {
                    if (!(0, chart_utilities_1.isInvalidValue)(val)) {
                        values.push(val);
                    }
                });
            });
            var isAxisTypeCategory = (ax === null || ax === void 0 ? void 0 : ax.type) === 'category' || ((0, chart_utilities_1.isStringArray)(values) && !(0, chart_utilities_1.isNumberArray)(values) && !(0, chart_utilities_1.isDateArray)(values));
            if (!isAxisTypeCategory) {
                return;
            }
            var isValidArray = (0, chart_utilities_1.isArrayOrTypedArray)(ax === null || ax === void 0 ? void 0 : ax.categoryarray) && ax.categoryarray.length > 0;
            if (isValidArray && (!(ax === null || ax === void 0 ? void 0 : ax.categoryorder) || ax.categoryorder === 'array')) {
                result[propName] = ax.categoryarray;
                return;
            }
            if (!(ax === null || ax === void 0 ? void 0 : ax.categoryorder) || ax.categoryorder === 'trace' || ax.categoryorder === 'array') {
                var categoriesInTraceOrder = Array.from(new Set(values));
                result[propName] = categoriesInTraceOrder;
                return;
            }
            result[propName] = ax.categoryorder;
        });
        return result;
    };
});
//# sourceMappingURL=PlotlySchemaAdapter.js.map