define(["require", "exports", "tslib", "d3-axis", "d3-array", "d3-scale", "d3-selection", "d3-format", "d3-time-format", "d3-time", "d3-format", "@fluentui/react"], function (require, exports, tslib_1, d3_axis_1, d3_array_1, d3_scale_1, d3_selection_1, d3_format_1, d3_time_format_1, d3_time_1, d3_format_2, react_1) {
    "use strict";
    var _a;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.createMeasurementSpan = exports.copyStyle = exports.resolveCSSVariables = exports.areArraysEqual = exports.getSecureProps = exports.formatDate = exports.isScalePaddingDefined = exports.getScalePadding = exports.getBarWidth = exports.formatValueWithSIPrefix = exports.wrapTextInsideDonut = exports.rotateXAxisLabels = exports.convertToLocaleString = exports.getAccessibleDataObject = exports.pointTypes = exports.CustomPoints = exports.Points = exports.getTypeOfAxis = exports.findHBCWANumericMinMaxOfY = exports.findVerticalNumericMinMaxOfY = exports.findVSBCNumericMinMaxOfY = exports.findNumericMinMaxOfY = exports.domainRageOfVerticalNumeric = exports.domainRangeOfDateForAreaLineVerticalBarChart = exports.domainRangeOfVSBCNumeric = exports.domainRangeOfXStringAxis = exports.domainRangeOfNumericForHorizontalBarChartWithAxis = exports.domainRangeOfNumericForAreaChart = exports.getXAxisType = exports.tooltipOfXAxislabels = exports.calculateLongestLabelWidth = exports.wrapContent = exports.createYAxisLabels = exports.createWrapOfXLabels = exports.silceOrAppendToArray = exports.getUnique = exports.calloutData = exports.createStringYAxis = exports.createStringYAxisForHorizontalBarChartWithAxis = exports.createNumericYAxis = exports.createYAxisForHorizontalBarChartWithAxis = exports.prepareDatapoints = exports.createStringXAxis = exports.createDateXAxis = exports.createNumericXAxis = exports.YAxisType = exports.XAxisTypes = exports.ChartTypes = void 0;
    var ChartTypes;
    (function (ChartTypes) {
        ChartTypes[ChartTypes["AreaChart"] = 0] = "AreaChart";
        ChartTypes[ChartTypes["LineChart"] = 1] = "LineChart";
        ChartTypes[ChartTypes["VerticalBarChart"] = 2] = "VerticalBarChart";
        ChartTypes[ChartTypes["VerticalStackedBarChart"] = 3] = "VerticalStackedBarChart";
        ChartTypes[ChartTypes["GroupedVerticalBarChart"] = 4] = "GroupedVerticalBarChart";
        ChartTypes[ChartTypes["HeatMapChart"] = 5] = "HeatMapChart";
        ChartTypes[ChartTypes["HorizontalBarChartWithAxis"] = 6] = "HorizontalBarChartWithAxis";
    })(ChartTypes || (exports.ChartTypes = ChartTypes = {}));
    var XAxisTypes;
    (function (XAxisTypes) {
        XAxisTypes[XAxisTypes["NumericAxis"] = 0] = "NumericAxis";
        XAxisTypes[XAxisTypes["DateAxis"] = 1] = "DateAxis";
        XAxisTypes[XAxisTypes["StringAxis"] = 2] = "StringAxis";
    })(XAxisTypes || (exports.XAxisTypes = XAxisTypes = {}));
    var YAxisType;
    (function (YAxisType) {
        YAxisType[YAxisType["NumericAxis"] = 0] = "NumericAxis";
        YAxisType[YAxisType["DateAxis"] = 1] = "DateAxis";
        YAxisType[YAxisType["StringAxis"] = 2] = "StringAxis";
    })(YAxisType || (exports.YAxisType = YAxisType = {}));
    /**
     * Create Numeric X axis
     * @export
     * @param {IXAxisParams} xAxisParams
     */
    function createNumericXAxis(xAxisParams, tickParams, chartType, culture) {
        var _a;
        var domainNRangeValues = xAxisParams.domainNRangeValues, _b = xAxisParams.showRoundOffXTickValues, showRoundOffXTickValues = _b === void 0 ? false : _b, _c = xAxisParams.xAxistickSize, xAxistickSize = _c === void 0 ? 6 : _c, _d = xAxisParams.tickPadding, tickPadding = _d === void 0 ? 10 : _d, xAxisCount = xAxisParams.xAxisCount, xAxisElement = xAxisParams.xAxisElement, hideTickOverlap = xAxisParams.hideTickOverlap;
        var xAxisScale = (0, d3_scale_1.scaleLinear)()
            .domain([domainNRangeValues.dStartValue, domainNRangeValues.dEndValue])
            .range([domainNRangeValues.rStartValue, domainNRangeValues.rEndValue]);
        showRoundOffXTickValues && xAxisScale.nice();
        var tickCount = xAxisCount !== null && xAxisCount !== void 0 ? xAxisCount : 6;
        var tickFormat = function (domainValue, _index) {
            if (tickParams.tickFormat) {
                return (0, d3_format_1.format)(tickParams.tickFormat)(domainValue);
            }
            var xAxisValue = typeof domainValue === 'number' ? domainValue : domainValue.valueOf();
            return (0, exports.convertToLocaleString)(xAxisValue, culture);
        };
        if (hideTickOverlap && typeof xAxisCount === 'undefined') {
            var longestLabelWidth = (0, exports.calculateLongestLabelWidth)(xAxisScale.ticks().map(tickFormat), '[class^="xAxis-"] text') + 20;
            var _e = xAxisScale.range(), start = _e[0], end = _e[1];
            tickCount = Math.min(Math.max(1, Math.floor(Math.abs(end - start) / longestLabelWidth)), 10);
        }
        var xAxis = (0, d3_axis_1.axisBottom)(xAxisScale)
            .tickSize(xAxistickSize)
            .tickPadding(tickPadding)
            .ticks(tickCount)
            .tickFormat(tickFormat);
        if (chartType === ChartTypes.HorizontalBarChartWithAxis) {
            xAxis.tickSizeInner(-(xAxisParams.containerHeight - xAxisParams.margins.top));
        }
        if (tickParams.tickValues) {
            xAxis.tickValues(tickParams.tickValues);
        }
        if (xAxisElement) {
            (0, d3_selection_1.select)(xAxisElement).call(xAxis).selectAll('text').attr('aria-hidden', 'true');
        }
        var tickValues = ((_a = tickParams.tickValues) !== null && _a !== void 0 ? _a : xAxisScale.ticks(tickCount)).map(xAxis.tickFormat());
        return { xScale: xAxisScale, tickValues: tickValues };
    }
    exports.createNumericXAxis = createNumericXAxis;
    function multiFormat(date, locale, useUTC) {
        var timeFormat = locale ? (useUTC ? locale.utcFormat : locale.format) : useUTC ? d3_time_format_1.utcFormat : d3_time_format_1.timeFormat;
        var formatMillisecond = timeFormat('.%L');
        var formatSecond = timeFormat(':%S');
        var formatMinute = timeFormat('%I:%M');
        var formatHour = timeFormat('%I %p');
        var formatDay = timeFormat('%a %d');
        var formatWeek = timeFormat('%b %d');
        var formatMonth = timeFormat('%B');
        var formatYear = timeFormat('%Y');
        var timeSecond = useUTC ? d3_time_1.utcSecond : d3_time_1.timeSecond;
        var timeMinute = useUTC ? d3_time_1.utcMinute : d3_time_1.timeMinute;
        var timeHour = useUTC ? d3_time_1.utcHour : d3_time_1.timeHour;
        var timeDay = useUTC ? d3_time_1.utcDay : d3_time_1.timeDay;
        var timeMonth = useUTC ? d3_time_1.utcMonth : d3_time_1.timeMonth;
        var timeWeek = useUTC ? d3_time_1.utcWeek : d3_time_1.timeWeek;
        var timeYear = useUTC ? d3_time_1.utcYear : d3_time_1.timeYear;
        return (timeSecond(date) < date
            ? formatMillisecond
            : timeMinute(date) < date
                ? formatSecond
                : timeHour(date) < date
                    ? formatMinute
                    : timeDay(date) < date
                        ? formatHour
                        : timeMonth(date) < date
                            ? timeWeek(date) < date
                                ? formatDay
                                : formatWeek
                            : timeYear(date) < date
                                ? formatMonth
                                : formatYear)(date);
    }
    function isPowerOf10(num) {
        var roundedfinalYMax = handleFloatingPointPrecisionError(num);
        return Math.log10(roundedfinalYMax) % 1 === 0;
    }
    //for reference, go through this 'https://docs.python.org/release/2.5.1/tut/node16.html'
    function handleFloatingPointPrecisionError(num) {
        var rounded = Math.round(num);
        return Math.abs(num - rounded) < 1e-6 ? rounded : num;
    }
    /**
     * Creating Date x axis of the Chart
     * @export
     * @param {IXAxisParams} xAxisParams
     * @param {ITickParams} tickParams
     */
    function createDateXAxis(xAxisParams, tickParams, culture, options, timeFormatLocale, customDateTimeFormatter, useUTC) {
        var _a;
        var domainNRangeValues = xAxisParams.domainNRangeValues, xAxisElement = xAxisParams.xAxisElement, _b = xAxisParams.tickPadding, tickPadding = _b === void 0 ? 6 : _b, _c = xAxisParams.xAxistickSize, xAxistickSize = _c === void 0 ? 6 : _c, xAxisCount = xAxisParams.xAxisCount, hideTickOverlap = xAxisParams.hideTickOverlap;
        var xAxisScale = useUTC ? (0, d3_scale_1.scaleUtc)() : (0, d3_scale_1.scaleTime)();
        xAxisScale
            .domain([domainNRangeValues.dStartValue, domainNRangeValues.dEndValue])
            .range([domainNRangeValues.rStartValue, domainNRangeValues.rEndValue]);
        var tickCount = xAxisCount !== null && xAxisCount !== void 0 ? xAxisCount : 6;
        var tickFormat = function (domainValue, _index) {
            if (customDateTimeFormatter) {
                return customDateTimeFormatter(domainValue);
            }
            if (culture && options) {
                return domainValue.toLocaleString(culture, options);
            }
            if (timeFormatLocale) {
                var locale = (0, d3_time_format_1.timeFormatLocale)(timeFormatLocale);
                return multiFormat(domainValue, locale, useUTC);
            }
            if (culture === undefined && tickParams.tickFormat) {
                if (useUTC) {
                    return (0, d3_time_format_1.utcFormat)(tickParams.tickFormat)(domainValue);
                }
                else {
                    return (0, d3_time_format_1.timeFormat)(tickParams.tickFormat)(domainValue);
                }
            }
            return multiFormat(domainValue, undefined, useUTC);
        };
        if (hideTickOverlap && typeof xAxisCount === 'undefined') {
            var longestLabelWidth = (0, exports.calculateLongestLabelWidth)(xAxisScale.ticks().map(tickFormat), '[class^="xAxis-"] text') + 40;
            var _d = xAxisScale.range(), start = _d[0], end = _d[1];
            tickCount = Math.min(Math.max(1, Math.floor(Math.abs(end - start) / longestLabelWidth)), 10);
        }
        var xAxis = (0, d3_axis_1.axisBottom)(xAxisScale)
            .tickSize(xAxistickSize)
            .tickPadding(tickPadding)
            .ticks(tickCount)
            .tickFormat(tickFormat);
        tickParams.tickValues ? xAxis.tickValues(tickParams.tickValues) : '';
        if (xAxisElement) {
            (0, d3_selection_1.select)(xAxisElement).call(xAxis).selectAll('text').attr('aria-hidden', 'true');
        }
        var tickValues = ((_a = tickParams.tickValues) !== null && _a !== void 0 ? _a : xAxisScale.ticks(tickCount)).map(xAxis.tickFormat());
        return { xScale: xAxisScale, tickValues: tickValues };
    }
    exports.createDateXAxis = createDateXAxis;
    /**
     * Create String X axis
     * Currently using for only Vetical stacked bar chart and grouped vertical bar chart
     * @export
     * @param {IXAxisParams} xAxisParams
     * @param {ITickParams} tickParams
     * @param {string[]} dataset
     * @returns
     */
    function createStringXAxis(xAxisParams, tickParams, dataset, culture) {
        var _a;
        var domainNRangeValues = xAxisParams.domainNRangeValues, _b = xAxisParams.xAxistickSize, xAxistickSize = _b === void 0 ? 6 : _b, _c = xAxisParams.tickPadding, tickPadding = _c === void 0 ? 10 : _c, _d = xAxisParams.xAxisPadding, xAxisPadding = _d === void 0 ? 0.1 : _d, xAxisInnerPadding = xAxisParams.xAxisInnerPadding, xAxisOuterPadding = xAxisParams.xAxisOuterPadding, containerWidth = xAxisParams.containerWidth, hideTickOverlap = xAxisParams.hideTickOverlap;
        var xAxisScale = (0, d3_scale_1.scaleBand)()
            .domain(dataset)
            .range([domainNRangeValues.rStartValue, domainNRangeValues.rEndValue])
            .paddingInner(typeof xAxisInnerPadding !== 'undefined' ? xAxisInnerPadding : xAxisPadding)
            .paddingOuter(typeof xAxisOuterPadding !== 'undefined' ? xAxisOuterPadding : xAxisPadding);
        var tickValues = (_a = tickParams.tickValues) !== null && _a !== void 0 ? _a : dataset;
        if (hideTickOverlap) {
            var nonOverlappingTickValues = [];
            // Here, we need the width of each individual label to detect overlaps,
            // but calculateLongestLabelWidth returns the maximum pixel width from an array of labels.
            // So call this function separately for each label, instead of the entire array.
            var tickSizes = tickValues.map(function (value) { return (0, exports.calculateLongestLabelWidth)([value], '[class^="xAxis-"] text'); });
            // for LTR
            var start = 0;
            var end = containerWidth;
            var sign = 1;
            var range = xAxisScale.range();
            if (range[1] - range[0] < 0) {
                // for RTL
                start = containerWidth;
                end = 0;
                sign = -1;
            }
            for (var i = tickValues.length - 1; i >= 0; i--) {
                var tickPosition = xAxisScale(tickValues[i]);
                if (sign * (tickPosition - (sign * tickSizes[i]) / 2 - start) >= 0 &&
                    sign * (tickPosition + (sign * tickSizes[i]) / 2 - end) <= 0) {
                    nonOverlappingTickValues.push(tickValues[i]);
                    end = tickPosition - sign * (tickSizes[i] / 2 + 10);
                }
            }
            nonOverlappingTickValues = nonOverlappingTickValues.reverse();
            tickValues = nonOverlappingTickValues;
        }
        var xAxis = (0, d3_axis_1.axisBottom)(xAxisScale).tickSize(xAxistickSize).tickPadding(tickPadding).tickValues(tickValues);
        if (xAxisParams.xAxisElement) {
            (0, d3_selection_1.select)(xAxisParams.xAxisElement).call(xAxis).selectAll('text').attr('aria-hidden', 'true');
        }
        return { xScale: xAxisScale, tickValues: tickValues };
    }
    exports.createStringXAxis = createStringXAxis;
    /**
     * This method is used to calculate the rounded tick values for the y-axis
     * @param {number} minVal
     * @param {number} maxVal
     * @param {number} splitInto
     * @returns {number[]}
     */
    function calculateRoundedTicks(minVal, maxVal, splitInto) {
        var finalYmin = minVal >= 0 && minVal === maxVal ? 0 : minVal;
        var finalYmax = minVal < 0 && minVal === maxVal ? 0 : maxVal;
        var ticksInterval = (0, d3_array_1.nice)(finalYmin, finalYmax, splitInto);
        var ticks = (0, d3_array_1.ticks)(ticksInterval[0], ticksInterval[ticksInterval.length - 1], splitInto);
        if (ticks[ticks.length - 1] > finalYmax && isPowerOf10(finalYmax)) {
            ticks.pop();
        }
        return ticks;
    }
    /**
     * This method used for creating data points for the y axis.
     * @export
     * @param {number} maxVal
     * @param {number} minVal
     * @param {number} splitInto
     * @param {boolean} isIntegralDataset
     * @returns {number[]}
     */
    function prepareDatapoints(maxVal, minVal, splitInto, isIntegralDataset, roundedTicks) {
        if (roundedTicks) {
            return calculateRoundedTicks(minVal, maxVal, splitInto);
        }
        var val = isIntegralDataset
            ? Math.ceil((maxVal - minVal) / splitInto)
            : (maxVal - minVal) / splitInto >= 1
                ? Math.ceil((maxVal - minVal) / splitInto)
                : (maxVal - minVal) / splitInto;
        /*
          For cases where we have negative and positive values
          The dataPointsArray is filled from 0 to minVal by val difference
          Then the array is reversed and values from 0(excluding 0) to maxVal are appended
          This ensures presence of 0 to act as an anchor reference.
          For simple cases where the scale may not encounter such a need for 0,
          We simply fill from minVal to maxVal
        */
        var dataPointsArray = [minVal < 0 && maxVal >= 0 ? 0 : minVal];
        /*For the case of all positive or all negative, we need to add another value
         in array for atleast one interval, but in case of mix of positive and negative,
         there will always be one more entry that will be added by the logic we have*/
        if (dataPointsArray[0] === minVal) {
            dataPointsArray.push(minVal + val);
        }
        if (minVal < 0 && maxVal >= 0) {
            while (dataPointsArray[dataPointsArray.length - 1] > minVal) {
                dataPointsArray.push(dataPointsArray[dataPointsArray.length - 1] - val);
            }
            dataPointsArray.reverse();
        }
        while (dataPointsArray[dataPointsArray.length - 1] < maxVal) {
            dataPointsArray.push(dataPointsArray[dataPointsArray.length - 1] + val);
        }
        return dataPointsArray;
    }
    exports.prepareDatapoints = prepareDatapoints;
    function createYAxisForHorizontalBarChartWithAxis(yAxisParams, isRtl) {
        var _a = yAxisParams.yMinMaxValues, yMinMaxValues = _a === void 0 ? { startValue: 0, endValue: 0 } : _a, _b = yAxisParams.yAxisElement, yAxisElement = _b === void 0 ? null : _b, _c = yAxisParams.yMaxValue, yMaxValue = _c === void 0 ? 0 : _c, _d = yAxisParams.yMinValue, yMinValue = _d === void 0 ? 0 : _d, containerHeight = yAxisParams.containerHeight, margins = yAxisParams.margins, _e = yAxisParams.tickPadding, tickPadding = _e === void 0 ? 12 : _e, _f = yAxisParams.maxOfYVal, maxOfYVal = _f === void 0 ? 0 : _f, yAxisTickFormat = yAxisParams.yAxisTickFormat, _g = yAxisParams.yAxisTickCount, yAxisTickCount = _g === void 0 ? 4 : _g;
        // maxOfYVal coming from only area chart and Grouped vertical bar chart(Calculation done at base file)
        var tempVal = maxOfYVal || yMinMaxValues.endValue;
        var finalYmax = tempVal > yMaxValue ? tempVal : yMaxValue;
        var finalYmin = yMinMaxValues.startValue < yMinValue ? 0 : yMinValue;
        var yAxisScale = (0, d3_scale_1.scaleLinear)()
            .domain([finalYmin, finalYmax])
            .range([containerHeight - margins.bottom, margins.top]);
        var axis = isRtl ? (0, d3_axis_1.axisRight)(yAxisScale) : (0, d3_axis_1.axisLeft)(yAxisScale);
        var yAxis = axis.tickPadding(tickPadding).ticks(yAxisTickCount);
        yAxisTickFormat ? yAxis.tickFormat(yAxisTickFormat) : yAxis.tickFormat((0, d3_format_1.format)('.2~s'));
        yAxisElement ? (0, d3_selection_1.select)(yAxisElement).call(yAxis).selectAll('text').attr('aria-hidden', 'true') : '';
        return yAxisScale;
    }
    exports.createYAxisForHorizontalBarChartWithAxis = createYAxisForHorizontalBarChartWithAxis;
    function createNumericYAxis(yAxisParams, isRtl, axisData, isIntegralDataset, useSecondaryYScale, supportNegativeData, roundedTicks) {
        if (useSecondaryYScale === void 0) { useSecondaryYScale = false; }
        if (supportNegativeData === void 0) { supportNegativeData = false; }
        if (roundedTicks === void 0) { roundedTicks = false; }
        var _a = yAxisParams.yMinMaxValues, yMinMaxValues = _a === void 0 ? { startValue: 0, endValue: 0 } : _a, _b = yAxisParams.yAxisElement, yAxisElement = _b === void 0 ? null : _b, _c = yAxisParams.yMaxValue, yMaxValue = _c === void 0 ? 0 : _c, _d = yAxisParams.yMinValue, yMinValue = _d === void 0 ? 0 : _d, containerHeight = yAxisParams.containerHeight, containerWidth = yAxisParams.containerWidth, margins = yAxisParams.margins, _e = yAxisParams.tickPadding, tickPadding = _e === void 0 ? 12 : _e, _f = yAxisParams.maxOfYVal, maxOfYVal = _f === void 0 ? 0 : _f, yAxisTickFormat = yAxisParams.yAxisTickFormat, _g = yAxisParams.yAxisTickCount, yAxisTickCount = _g === void 0 ? 4 : _g, eventAnnotationProps = yAxisParams.eventAnnotationProps, eventLabelHeight = yAxisParams.eventLabelHeight;
        // maxOfYVal coming from only area chart and Grouped vertical bar chart(Calculation done at base file)
        var tempVal = maxOfYVal || yMinMaxValues.endValue;
        var finalYmax = tempVal > yMaxValue ? tempVal : yMaxValue;
        var finalYmin = supportNegativeData
            ? Math.min(yMinMaxValues.startValue, yMinValue || 0)
            : yMinMaxValues.startValue < yMinValue
                ? 0
                : yMinValue;
        var domainValues = prepareDatapoints(finalYmax, finalYmin, yAxisTickCount, isIntegralDataset, roundedTicks);
        var yAxisScale = (0, d3_scale_1.scaleLinear)()
            .domain([supportNegativeData ? domainValues[0] : finalYmin, domainValues[domainValues.length - 1]])
            .range([containerHeight - margins.bottom, margins.top + (eventAnnotationProps ? eventLabelHeight : 0)]);
        var axis = (!isRtl && useSecondaryYScale) || (isRtl && !useSecondaryYScale) ? (0, d3_axis_1.axisRight)(yAxisScale) : (0, d3_axis_1.axisLeft)(yAxisScale);
        var yAxis = axis
            .tickPadding(tickPadding)
            .tickValues(domainValues)
            .tickSizeInner(-(containerWidth - margins.left - margins.right));
        yAxisTickFormat ? yAxis.tickFormat(yAxisTickFormat) : yAxis.tickFormat((0, d3_format_1.format)('.2~s'));
        yAxisElement ? (0, d3_selection_1.select)(yAxisElement).call(yAxis).selectAll('text').attr('aria-hidden', 'true') : '';
        axisData.yAxisDomainValues = domainValues;
        return yAxisScale;
    }
    exports.createNumericYAxis = createNumericYAxis;
    /**
     * Creating String Y axis of the chart for Horizontal Bar Chart With Axis
     * @param yAxisParams
     * @param dataPoints
     * @param isRtl
     */
    var createStringYAxisForHorizontalBarChartWithAxis = function (yAxisParams, dataPoints, isRtl, barWidth) {
        var containerHeight = yAxisParams.containerHeight, _a = yAxisParams.tickPadding, tickPadding = _a === void 0 ? 12 : _a, margins = yAxisParams.margins, yAxisTickFormat = yAxisParams.yAxisTickFormat, yAxisElement = yAxisParams.yAxisElement;
        var yAxisScale = (0, d3_scale_1.scaleBand)()
            .domain(dataPoints)
            .range([containerHeight - margins.bottom - barWidth / 2, margins.top + barWidth / 2]);
        var axis = isRtl ? (0, d3_axis_1.axisRight)(yAxisScale) : (0, d3_axis_1.axisLeft)(yAxisScale);
        var yAxis = axis.tickPadding(tickPadding).ticks(dataPoints);
        if (yAxisTickFormat) {
            yAxis.tickFormat(yAxisTickFormat);
        }
        yAxisElement ? (0, d3_selection_1.select)(yAxisElement).call(yAxis).selectAll('text') : '';
        return yAxisScale;
    };
    exports.createStringYAxisForHorizontalBarChartWithAxis = createStringYAxisForHorizontalBarChartWithAxis;
    /**
     * Creating String Y axis of the chart for other chart except Horizontal Bar Chart With Axis
     * @param yAxisParams
     * @param dataPoints
     * @param isRtl
     */
    var createStringYAxis = function (yAxisParams, dataPoints, isRtl) {
        var containerHeight = yAxisParams.containerHeight, _a = yAxisParams.tickPadding, tickPadding = _a === void 0 ? 12 : _a, margins = yAxisParams.margins, yAxisTickFormat = yAxisParams.yAxisTickFormat, yAxisElement = yAxisParams.yAxisElement, _b = yAxisParams.yAxisPadding, yAxisPadding = _b === void 0 ? 0 : _b;
        var yAxisScale = (0, d3_scale_1.scaleBand)()
            .domain(dataPoints)
            .range([containerHeight - margins.bottom, margins.top])
            .padding(yAxisPadding);
        var axis = isRtl ? (0, d3_axis_1.axisRight)(yAxisScale) : (0, d3_axis_1.axisLeft)(yAxisScale);
        var yAxis = axis.tickPadding(tickPadding).tickValues(dataPoints).tickSize(0);
        if (yAxisTickFormat) {
            yAxis.tickFormat(yAxisTickFormat);
        }
        yAxisElement ? (0, d3_selection_1.select)(yAxisElement).call(yAxis).selectAll('text') : '';
        return yAxisScale;
    };
    exports.createStringYAxis = createStringYAxis;
    /**
     * For area chart and line chart, while displaying stackCallout, Need to form a callout data object.
     * This methos creates an object for those 2 charts.
     * @param values
     */
    function calloutData(values) {
        var combinedResult = [];
        values.forEach(function (line) {
            var elements = line.data
                .filter(function (point) { return !point.hideCallout; })
                .map(function (point) {
                return tslib_1.__assign(tslib_1.__assign({}, point), { legend: line.legend, color: line.color, index: line.index });
            });
            combinedResult = combinedResult.concat(elements);
        });
        var xValToDataPoints = {};
        combinedResult.forEach(function (ele) {
            var xValue = ele.x instanceof Date ? ele.x.getTime() : ele.x;
            if (xValue in xValToDataPoints) {
                xValToDataPoints[xValue].push({
                    legend: ele.legend,
                    y: ele.y,
                    color: ele.color,
                    xAxisCalloutData: ele.xAxisCalloutData,
                    yAxisCalloutData: ele.yAxisCalloutData,
                    callOutAccessibilityData: ele.callOutAccessibilityData,
                    index: ele.index,
                });
            }
            else {
                xValToDataPoints[xValue] = [
                    {
                        legend: ele.legend,
                        y: ele.y,
                        color: ele.color,
                        xAxisCalloutData: ele.xAxisCalloutData,
                        yAxisCalloutData: ele.yAxisCalloutData,
                        callOutAccessibilityData: ele.callOutAccessibilityData,
                        index: ele.index,
                    },
                ];
            }
        });
        var result = Object.keys(xValToDataPoints).map(function (xValue) {
            return { x: Number(xValue), values: xValToDataPoints[xValue] };
        });
        return result;
    }
    exports.calloutData = calloutData;
    function getUnique(arr, comp) {
        var unique = arr
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            .map(function (e) { return e[comp]; })
            // store the keys of the unique objects
            .map(function (e, i, final) { return final.indexOf(e) === i && i; })
            // eliminate the dead keys & store unique objects
            .filter(function (e) { return arr[e]; })
            .map(function (e) { return arr[e]; });
        return unique;
    }
    exports.getUnique = getUnique;
    /**
     * This function takes two paramerter
     * 1. an array of strings
     * 2. a string value
     * if the value is not present in the given array then it will return the new
     * array by appending the value to the present arrray.
     *
     * if the value is already present in  the given array then it will return the new
     * array by deleteing the value from the the array
     * @param array
     * @param value
     */
    function silceOrAppendToArray(array, value) {
        var pos = array.indexOf(value);
        if (pos === -1) {
            return tslib_1.__spreadArray(tslib_1.__spreadArray([], array, true), [value], false);
        }
        else {
            return array.slice(0, pos).concat(array.slice(pos + 1));
        }
    }
    exports.silceOrAppendToArray = silceOrAppendToArray;
    /**
     * This method used for wrapping of x axis labels (tick values).
     * It breaks down given text value by space separated and calculates the total height needed to display all the words.
     * That value = removal value. This value needs to be remove from total svg height, svg will shrink and
     * total text will be displayed.
     * @export
     * @param {IWrapLabelProps} wrapLabelProps
     * @returns
     */
    function createWrapOfXLabels(wrapLabelProps) {
        var node = wrapLabelProps.node, xAxis = wrapLabelProps.xAxis, noOfCharsToTruncate = wrapLabelProps.noOfCharsToTruncate, showXAxisLablesTooltip = wrapLabelProps.showXAxisLablesTooltip;
        if (node === null) {
            return;
        }
        var axisNode = (0, d3_selection_1.select)(node).call(xAxis);
        var removeVal = 0;
        var width = 10;
        var arr = [];
        axisNode.selectAll('.tick text').each(function () {
            var text = (0, d3_selection_1.select)(this);
            var totalWord = text.text();
            var truncatedWord = "".concat(text.text().slice(0, noOfCharsToTruncate), "...");
            var totalWordLength = text.text().length;
            var words = text.text().split(/\s+/).reverse();
            arr.push(words.length);
            var word = '';
            var line = [];
            var lineNumber = 0;
            var lineHeight = 1.1; // ems
            var y = text.attr('y');
            var dy = parseFloat(text.attr('dy'));
            var tspan = text
                .text(null)
                .append('tspan')
                .attr('x', 0)
                .attr('y', y)
                .attr('id', 'BaseSpan')
                .attr('dy', dy + 'em')
                .attr('data-', totalWord);
            if (showXAxisLablesTooltip && totalWordLength > noOfCharsToTruncate) {
                tspan = text
                    .append('tspan')
                    .attr('id', 'showDots')
                    .attr('x', 0)
                    .attr('y', y)
                    .attr('dy', ++lineNumber * lineHeight + dy + 'em')
                    .text(truncatedWord);
            }
            else if (showXAxisLablesTooltip && totalWordLength <= noOfCharsToTruncate) {
                tspan = text
                    .append('tspan')
                    .attr('id', 'LessLength')
                    .attr('x', 0)
                    .attr('y', y)
                    .attr('dy', ++lineNumber * lineHeight + dy + 'em')
                    .text(totalWord);
            }
            else {
                while ((word = words.pop())) {
                    line.push(word);
                    tspan.text(line.join(' '));
                    if (tspan.node().getComputedTextLength() > width && line.length > 1) {
                        line.pop();
                        tspan.text(line.join(' '));
                        line = [word];
                        tspan = text
                            .append('tspan')
                            .attr('id', 'WordBreakId')
                            .attr('x', 0)
                            .attr('y', y)
                            .attr('dy', ++lineNumber * lineHeight + dy + 'em')
                            .text(word);
                    }
                }
                var maxDigit = Math.max.apply(Math, arr);
                var maxHeight_1 = 12; // intial value to render corretly first time
                axisNode.selectAll('text').each(function () {
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    var outerHTMLElement = document.getElementById('WordBreakId');
                    var BoxCordinates = outerHTMLElement && outerHTMLElement.getBoundingClientRect();
                    var boxHeight = BoxCordinates && BoxCordinates.height;
                    if (boxHeight > maxHeight_1) {
                        maxHeight_1 = boxHeight;
                    }
                });
                // If we take directly maxDigit * maxheight, then it will show more height between x axis tick values and bottom.
                // To avoid this, reducing maxDigit value by removing some digit based on legth of word.
                var removeDigit = 4;
                if (maxDigit <= 2) {
                    removeDigit = 1;
                }
                else if (maxDigit > 2 && maxDigit <= 6) {
                    removeDigit = 2;
                }
                else if (maxDigit > 6 && maxDigit <= 9) {
                    removeDigit = 3;
                }
                removeVal = (maxDigit - removeDigit) * maxHeight_1;
            }
        });
        return removeVal > 0 ? removeVal : 0;
    }
    exports.createWrapOfXLabels = createWrapOfXLabels;
    /**
     * This method used for wrapping of y axis labels (tick values).
     */
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function createYAxisLabels(node, 
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    yAxis, noOfCharsToTruncate, truncateLabel, isRtl) {
        if (node === null) {
            return;
        }
        var axisNode = (0, d3_selection_1.select)(node).call(yAxis);
        axisNode.selectAll('.tick text').each(function () {
            var text = (0, d3_selection_1.select)(this);
            var totalWord = text.text();
            var truncatedWord = isRtl
                ? "...".concat(text.text().slice(0, noOfCharsToTruncate))
                : "".concat(text.text().slice(0, noOfCharsToTruncate), "...");
            var totalWordLength = text.text().length;
            var padding = truncateLabel ? 1.5 : 1; // ems
            var y = text.attr('y');
            var x = text.attr('x');
            var dy = parseFloat(text.attr('dy'));
            var dx = 0;
            text
                .text(null)
                .append('tspan')
                .attr('x', x)
                .attr('y', y)
                .attr('id', 'BaseSpan')
                .attr('dy', dy + 'em')
                .attr('data-', totalWord);
            if (truncateLabel && totalWordLength > noOfCharsToTruncate) {
                text
                    .append('tspan')
                    .attr('id', 'showDots')
                    .attr('x', isRtl ? 0 : x)
                    .attr('y', y)
                    .attr('dy', dy)
                    .attr('dx', padding + dx + 'em')
                    .text(truncatedWord);
            }
            else {
                text
                    .attr('text-align', 'start')
                    .append('tspan')
                    .attr('id', 'LessLength')
                    .attr('x', isRtl ? 0 : x)
                    .attr('y', y)
                    .attr('dx', padding + dx + 'em')
                    .text(totalWord);
            }
        });
    }
    exports.createYAxisLabels = createYAxisLabels;
    var wrapContent = function (content, id, maxWidth) {
        var textElement = (0, d3_selection_1.select)("#".concat(id));
        textElement.text(content);
        if (!textElement.node()) {
            return false;
        }
        var isOverflowing = false;
        var textLength = textElement.node().getComputedTextLength();
        while (textLength > maxWidth && content.length > 0) {
            content = content.slice(0, -1);
            textElement.text(content + '...');
            isOverflowing = true;
            textLength = textElement.node().getComputedTextLength();
        }
        return isOverflowing;
    };
    exports.wrapContent = wrapContent;
    /**
     * Calculates the width of the longest axis label in pixels
     */
    var calculateLongestLabelWidth = function (labels, query) {
        if (query === void 0) { query = 'none'; }
        var maxLabelWidth = 0;
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        if (ctx) {
            var axisText = document.querySelector(query);
            if (axisText) {
                var styles = window.getComputedStyle(axisText, null);
                var fontWeight = styles.getPropertyValue('font-weight');
                var fontSize = styles.getPropertyValue('font-size');
                var fontFamily = styles.getPropertyValue('font-family');
                ctx.font = "".concat(fontWeight, " ").concat(fontSize, " ").concat(fontFamily);
            }
            else {
                ctx.font = '600 10px "Segoe UI"';
            }
            labels.forEach(function (label) {
                maxLabelWidth = Math.max(ctx.measureText(label.toString()).width, maxLabelWidth);
            });
        }
        return maxLabelWidth;
    };
    exports.calculateLongestLabelWidth = calculateLongestLabelWidth;
    /**
     * This method displays a tooltip to the x axis lables(tick values)
     * when prop 'showXAxisLablesTooltip' enables to the respected chart.
     * On hover of the truncated word(at x axis labels tick), a tooltip will be appeared.
     */
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function tooltipOfXAxislabels(xAxistooltipProps) {
        var tooltipCls = xAxistooltipProps.tooltipCls, xAxis = xAxistooltipProps.xAxis, id = xAxistooltipProps.id;
        if (xAxis === null) {
            return null;
        }
        var div = (0, d3_selection_1.select)('body').append('div').attr('id', id).attr('class', tooltipCls).style('opacity', 0);
        var aa = xAxis.selectAll('#BaseSpan')._groups[0];
        var baseSpanLength = aa && Object.keys(aa).length;
        var originalDataArray = [];
        for (var i = 0; i < baseSpanLength; i++) {
            var originalData = aa[i].dataset && Object.values(aa[i].dataset)[0];
            originalDataArray.push(originalData);
        }
        var tickObject = xAxis.selectAll('.tick')._groups[0];
        var tickObjectLength = tickObject && Object.keys(tickObject).length;
        var _loop_1 = function (i) {
            var d1 = tickObject[i];
            (0, d3_selection_1.select)(d1)
                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                .on('mouseover', function (event, d) {
                div.style('opacity', 0.9);
                div
                    .text(originalDataArray[i])
                    .style('left', event.pageX + 'px')
                    .style('top', event.pageY - 28 + 'px');
            })
                .on('mouseout', function (d) {
                div.style('opacity', 0);
            });
        };
        for (var i = 0; i < tickObjectLength; i++) {
            _loop_1(i);
        }
    }
    exports.tooltipOfXAxislabels = tooltipOfXAxislabels;
    /**
     * Find the axis type of line chart and area chart from given data
     * @param points
     */
    function getXAxisType(points) {
        var isXAxisDateType = false;
        if (points && points.length > 0) {
            points.forEach(function (chartData) {
                if (chartData.data.length > 0) {
                    isXAxisDateType = chartData.data[0].x instanceof Date;
                    return;
                }
            });
        }
        return isXAxisDateType;
    }
    exports.getXAxisType = getXAxisType;
    /**
     * Calculates Domain and range values for Numeric X axis.
     * This method calculates Area cart and line chart.
     * @export
     * @param {ILineChartPoints[]} points
     * @param {IMargins} margins
     * @param {number} width
     * @param {boolean} isRTL
     * @returns {IDomainNRange}
     */
    function domainRangeOfNumericForAreaChart(points, margins, width, isRTL) {
        var xMin = (0, d3_array_1.min)(points, function (point) {
            return (0, d3_array_1.min)(point.data, function (item) { return item.x; });
        });
        var xMax = (0, d3_array_1.max)(points, function (point) {
            return (0, d3_array_1.max)(point.data, function (item) {
                return item.x;
            });
        });
        var rStartValue = margins.left;
        var rEndValue = width - margins.right;
        return isRTL
            ? { dStartValue: xMax, dEndValue: xMin, rStartValue: rStartValue, rEndValue: rEndValue }
            : { dStartValue: xMin, dEndValue: xMax, rStartValue: rStartValue, rEndValue: rEndValue };
    }
    exports.domainRangeOfNumericForAreaChart = domainRangeOfNumericForAreaChart;
    /**
     * Calculates Domain and range values for Numeric X axis.
     * This method calculates Horizontal Chart with Axis
     * @export
     * @param {ILineChartPoints[]} points
     * @param {IMargins} margins
     * @param {number} width
     * @param {boolean} isRTL
     * @returns {IDomainNRange}
     */
    function domainRangeOfNumericForHorizontalBarChartWithAxis(points, margins, containerWidth, isRTL, shiftX) {
        var xMax = (0, d3_array_1.max)(points, function (point) { return point.x; });
        var rMin = isRTL ? margins.left : margins.left + shiftX;
        var rMax = isRTL ? containerWidth - margins.right - shiftX : containerWidth - margins.right;
        return isRTL
            ? { dStartValue: xMax, dEndValue: 0, rStartValue: rMin, rEndValue: rMax }
            : { dStartValue: 0, dEndValue: xMax, rStartValue: rMin, rEndValue: rMax };
    }
    exports.domainRangeOfNumericForHorizontalBarChartWithAxis = domainRangeOfNumericForHorizontalBarChartWithAxis;
    /**
     * Calculates Range values of x Axis string axis
     * For String axis, we need to give domain values (Not start and end array values)
     * So sending 0 as domain values. Domain will be handled at creation of string axis
     * For charts stacked bar chart, grouped vertical bar chart, HeatMapChart and Vertical bar chart
     * @export
     * @param {IMargins} margins
     * @param {number} width
     * @param {boolean} isRTL
     * @returns {IDomainNRange}
     */
    function domainRangeOfXStringAxis(margins, width, isRTL) {
        var rMin = margins.left;
        var rMax = width - margins.right;
        return isRTL
            ? { dStartValue: 0, dEndValue: 0, rStartValue: rMax, rEndValue: rMin }
            : { dStartValue: 0, dEndValue: 0, rStartValue: rMin, rEndValue: rMax };
    }
    exports.domainRangeOfXStringAxis = domainRangeOfXStringAxis;
    /**
     * Calculate domain and range values to the Vertical stacked bar chart - For Numeric axis
     * @export
     * @param {IDataPoint[]} points
     * @param {IMargins} margins
     * @param {number} width
     * @param {boolean} isRTL
     * @param {number} barWidth
     * @returns {IDomainNRange}
     */
    function domainRangeOfVSBCNumeric(points, margins, width, isRTL, barWidth) {
        var xMin = (0, d3_array_1.min)(points, function (point) { return point.x; });
        var xMax = (0, d3_array_1.max)(points, function (point) { return point.x; });
        var rMax = margins.left;
        var rMin = width - margins.right;
        return isRTL
            ? { dStartValue: xMax, dEndValue: xMin, rStartValue: rMax, rEndValue: rMin }
            : { dStartValue: xMin, dEndValue: xMax, rStartValue: rMax, rEndValue: rMin };
    }
    exports.domainRangeOfVSBCNumeric = domainRangeOfVSBCNumeric;
    /**
     * Calculates Domain and range values for Date X axis.
     * This method calculates Bar chart.
     * @export
     * @param {IVerticalBarChartDataPoint[]} points
     * @param {IMargins} margins
     * @param {number} width
     * @param {boolean} isRTL
     * @param {Date[] | number[]} tickValues
     * @returns {IDomainNRange}
     */
    function domainRangeOfDateForAreaLineVerticalBarChart(points, margins, width, isRTL, tickValues, chartType, barWidth) {
        if (tickValues === void 0) { tickValues = []; }
        var sDate;
        var lDate;
        if (chartType === ChartTypes.AreaChart || chartType === ChartTypes.LineChart) {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            sDate = (0, d3_array_1.min)(points, function (point) {
                return (0, d3_array_1.min)(point.data, function (item) {
                    return item.x;
                });
            });
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            lDate = (0, d3_array_1.max)(points, function (point) {
                return (0, d3_array_1.max)(point.data, function (item) {
                    return item.x;
                });
            });
            // Need to draw graph with given small and large date
            // (Which Involves customization of date axis tick values)
            // That may be Either from given graph data or from prop 'tickValues' date values.
            // So, Finding smallest and largest dates
            sDate = (0, d3_array_1.min)(tslib_1.__spreadArray(tslib_1.__spreadArray([], tickValues, true), [sDate], false));
            lDate = (0, d3_array_1.max)(tslib_1.__spreadArray(tslib_1.__spreadArray([], tickValues, true), [lDate], false));
        }
        else {
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            sDate = (0, d3_array_1.min)(points, function (point) { return point.x; });
            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            lDate = (0, d3_array_1.max)(points, function (point) { return point.x; });
        }
        var rStartValue = margins.left;
        var rEndValue = width - margins.right;
        return isRTL
            ? { dStartValue: lDate, dEndValue: sDate, rStartValue: rStartValue, rEndValue: rEndValue }
            : { dStartValue: sDate, dEndValue: lDate, rStartValue: rStartValue, rEndValue: rEndValue };
    }
    exports.domainRangeOfDateForAreaLineVerticalBarChart = domainRangeOfDateForAreaLineVerticalBarChart;
    /**
     * Calculate domain and range values to the Vertical bar chart - For Numeric axis
     * @export
     * @param {IDataPoint[]} points
     * @param {IMargins} margins
     * @param {number} containerWidth
     * @param {boolean} isRTL
     * @param {number} barWidth
     * @returns {IDomainNRange}
     */
    function domainRageOfVerticalNumeric(points, margins, containerWidth, isRTL, barWidth) {
        var xMax = (0, d3_array_1.max)(points, function (point) { return point.x; });
        var xMin = (0, d3_array_1.min)(points, function (point) { return point.x; });
        var rMin = margins.left;
        var rMax = containerWidth - margins.right;
        return isRTL
            ? { dStartValue: xMax, dEndValue: xMin, rStartValue: rMin, rEndValue: rMax }
            : { dStartValue: xMin, dEndValue: xMax, rStartValue: rMin, rEndValue: rMax };
    }
    exports.domainRageOfVerticalNumeric = domainRageOfVerticalNumeric;
    /**
     * Calculating start and ending values of the Area chart and LineChart
     * @export
     * @param {ILineChartPoints[]} points
     * @returns {{ startValue: number; endValue: number }}
     */
    function findNumericMinMaxOfY(points) {
        var yMax = (0, d3_array_1.max)(points, function (point) {
            return (0, d3_array_1.max)(point.data, function (item) { return item.y; });
        });
        var yMin = (0, d3_array_1.min)(points, function (point) {
            return (0, d3_array_1.min)(point.data, function (item) { return item.y; });
        });
        return {
            startValue: yMin,
            endValue: yMax,
        };
    }
    exports.findNumericMinMaxOfY = findNumericMinMaxOfY;
    /**
     * Find the minimum and maximum values of the vertical stacked bar chart y axis data point. Used for create y axis.
     * @export
     * @param {IDataPoint[]} dataset
     * @returns {{ startValue: number; endValue: number }}
     */
    function findVSBCNumericMinMaxOfY(dataset) {
        var yMax = (0, d3_array_1.max)(dataset, function (point) { return point.y; });
        var yMin = (0, d3_array_1.min)(dataset, function (point) { return point.y; });
        return { startValue: yMin, endValue: yMax };
    }
    exports.findVSBCNumericMinMaxOfY = findVSBCNumericMinMaxOfY;
    /**
     * Fins the min and max values of the vertical bar chart y axis data point.
     * @export
     * @param {IVerticalBarChartDataPoint[]} points
     * @returns {{ startValue: number; endValue: number }}
     */
    function findVerticalNumericMinMaxOfY(points) {
        var yMax = (0, d3_array_1.max)(points, function (point) {
            if (point.lineData !== undefined) {
                if (point.y > point.lineData.y) {
                    return point.y;
                }
                else {
                    return point.lineData.y;
                }
            }
            else {
                return point.y;
            }
        });
        var yMin = (0, d3_array_1.min)(points, function (point) {
            if (point.lineData !== undefined) {
                if (point.y < point.lineData.y) {
                    return point.y;
                }
                else {
                    return point.lineData.y;
                }
            }
            else {
                return point.y;
            }
        });
        return { startValue: yMin, endValue: yMax };
    }
    exports.findVerticalNumericMinMaxOfY = findVerticalNumericMinMaxOfY;
    /**
     * Fins the min and max values of the vertical bar chart y axis data point.
     * @export
     * @param {IVerticalBarChartDataPoint[]} points
     * @returns {{ startValue: number; endValue: number }}
     */
    function findHBCWANumericMinMaxOfY(points, yAxisType) {
        if (yAxisType !== undefined && yAxisType === YAxisType.NumericAxis) {
            var yMax = (0, d3_array_1.max)(points, function (point) { return point.y; });
            var yMin = (0, d3_array_1.min)(points, function (point) { return point.y; });
            return { startValue: yMin, endValue: yMax };
        }
        return { startValue: 0, endValue: 0 };
    }
    exports.findHBCWANumericMinMaxOfY = findHBCWANumericMinMaxOfY;
    /**
     * @param p string or number or Date
     *
     * This function takes the single data point of the x-aixs
     * and decides what is the x-axis
     */
    var getTypeOfAxis = function (p, isXAxis) {
        if (isXAxis) {
            switch (typeof p) {
                case 'string':
                    return XAxisTypes.StringAxis;
                case 'number':
                    return XAxisTypes.NumericAxis;
                default:
                    return XAxisTypes.DateAxis;
            }
        }
        else {
            switch (typeof p) {
                case 'string':
                    return YAxisType.StringAxis;
                case 'number':
                    return YAxisType.NumericAxis;
                default:
                    return YAxisType.DateAxis;
            }
        }
    };
    exports.getTypeOfAxis = getTypeOfAxis;
    /**
     * we need to make sure that if we add any property to this, then
     * we need to also add that in  pointTypes below and vise-versa
     */
    var Points;
    (function (Points) {
        Points[Points["circle"] = 0] = "circle";
        Points[Points["square"] = 1] = "square";
        Points[Points["triangle"] = 2] = "triangle";
        Points[Points["diamond"] = 3] = "diamond";
        Points[Points["pyramid"] = 4] = "pyramid";
        Points[Points["hexagon"] = 5] = "hexagon";
        Points[Points["pentagon"] = 6] = "pentagon";
        Points[Points["octagon"] = 7] = "octagon";
    })(Points || (exports.Points = Points = {}));
    var CustomPoints;
    (function (CustomPoints) {
        CustomPoints[CustomPoints["dottedLine"] = 0] = "dottedLine";
    })(CustomPoints || (exports.CustomPoints = CustomPoints = {}));
    /**
     * we need to make sure that if we add any property to this, then
     * we need to also add that in enum Point and vise-versa
     */
    exports.pointTypes = (_a = {},
        _a[Points.circle] = {
            widthRatio: 1,
        },
        _a[Points.square] = {
            widthRatio: 1,
        },
        _a[Points.triangle] = {
            widthRatio: 1,
        },
        _a[Points.diamond] = {
            widthRatio: 1,
        },
        _a[Points.pyramid] = {
            widthRatio: 1,
        },
        _a[Points.hexagon] = {
            widthRatio: 2,
        },
        _a[Points.pentagon] = {
            widthRatio: 1.168,
        },
        _a[Points.octagon] = {
            widthRatio: 2.414,
        },
        _a);
    /**
     * @param accessibleData accessible data
     * @param role string to define role of tag
     * @param isDataFocusable boolean
     * function returns the accessibility data object
     */
    var getAccessibleDataObject = function (accessibleData, role, isDataFocusable) {
        if (role === void 0) { role = 'text'; }
        if (isDataFocusable === void 0) { isDataFocusable = true; }
        accessibleData = accessibleData !== null && accessibleData !== void 0 ? accessibleData : {};
        return {
            role: role,
            'data-is-focusable': isDataFocusable,
            'aria-label': accessibleData.ariaLabel,
            'aria-labelledby': accessibleData.ariaLabelledBy,
            'aria-describedby': accessibleData.ariaDescribedBy,
        };
    };
    exports.getAccessibleDataObject = getAccessibleDataObject;
    var convertToLocaleString = function (data, culture) {
        if (data === undefined || data === null || Number.isNaN(data)) {
            return data;
        }
        culture = culture || undefined;
        if (typeof data === 'number') {
            return data.toLocaleString(culture);
        }
        else if (typeof data === 'string' && !window.isNaN(Number(data))) {
            var num = Number(data);
            return num.toLocaleString(culture);
        }
        else if (data instanceof Date) {
            return data.toLocaleDateString(culture);
        }
        return data;
    };
    exports.convertToLocaleString = convertToLocaleString;
    function rotateXAxisLabels(rotateLabelProps) {
        var node = rotateLabelProps.node, xAxis = rotateLabelProps.xAxis;
        if (node === null || xAxis === null) {
            return;
        }
        var maxHeight = 0;
        var xAxisTranslations = [];
        (0, d3_selection_1.select)(node)
            .call(xAxis)
            .selectAll('.tick')
            .each(function () {
            var translateValue = this.getAttribute('transform');
            if ((translateValue === null || translateValue === void 0 ? void 0 : translateValue.indexOf('rotate')) === -1) {
                var translatePair = translateValue
                    .substring(translateValue.indexOf('(') + 1, translateValue.indexOf(')'))
                    .split(',');
                if (translatePair.length === 2) {
                    xAxisTranslations.push(translatePair[0]);
                    this.setAttribute('transform', "translate(".concat(translatePair[0], ",0)rotate(-45)"));
                }
            }
            var BoxCordinates = this.getBoundingClientRect();
            var boxHeight = BoxCordinates && BoxCordinates.height;
            if (boxHeight > maxHeight) {
                maxHeight = boxHeight;
            }
        });
        var idx = 0;
        (0, d3_selection_1.select)(node)
            .call(xAxis)
            .selectAll('.tick')
            .each(function () {
            if (xAxisTranslations.length > idx) {
                this.setAttribute('transform', "translate(".concat(xAxisTranslations[idx], ",").concat(maxHeight / 2, ")rotate(-45)")); // Translate y by max height/2
                idx += 1;
            }
        });
        return Math.floor(maxHeight / 1.414); // Compute maxHeight/tanInverse(45) to get the vertical height of labels.
    }
    exports.rotateXAxisLabels = rotateXAxisLabels;
    function wrapTextInsideDonut(selectorClass, maxWidth) {
        var idx = 0;
        (0, d3_selection_1.selectAll)(".".concat(selectorClass)).each(function () {
            var text = (0, d3_selection_1.select)(this);
            var words = text.text().split(/\s+/).reverse();
            var word = '';
            var line = [];
            var lineNumber = 0;
            var lineHeight = 1.1; // ems
            var y = text.attr('y');
            var tspan = text
                .text(null)
                .append('tspan')
                .attr('id', "WordBreakId-".concat(idx, "-").concat(lineNumber))
                .attr('x', 0)
                .attr('y', y)
                .attr('dy', lineNumber++ * lineHeight + 'em');
            while ((word = words.pop())) {
                line.push(word);
                tspan.text(line.join(' ') + ' ');
                if (tspan.node().getComputedTextLength() > maxWidth && line.length > 1) {
                    line.pop();
                    tspan.text(line.join(' ') + ' ');
                    line = [word];
                    tspan = text
                        .append('tspan')
                        .attr('id', "WordBreakId-".concat(idx, "-").concat(lineNumber))
                        .attr('x', 0)
                        .attr('y', y)
                        .attr('dy', lineNumber++ * lineHeight + 'em')
                        .text(word);
                }
            }
            idx += 1;
        });
    }
    exports.wrapTextInsideDonut = wrapTextInsideDonut;
    function formatValueWithSIPrefix(value) {
        var specifier;
        if (value < 1000) {
            specifier = '.2~'; // upto 2 decimal places without insignificant trailing zeros
        }
        else {
            specifier = '.1'; // upto 1 decimal place
        }
        return (0, d3_format_2.formatPrefix)(specifier, value)(value);
    }
    exports.formatValueWithSIPrefix = formatValueWithSIPrefix;
    var DEFAULT_BAR_WIDTH = 16;
    var MIN_BAR_WIDTH = 1;
    var getBarWidth = function (barWidthProp, maxBarWidthProp, adjustedValue) {
        if (adjustedValue === void 0) { adjustedValue = DEFAULT_BAR_WIDTH; }
        var barWidth;
        if (typeof barWidthProp === 'number') {
            barWidth = barWidthProp;
        }
        else if (barWidthProp === 'default' || typeof barWidthProp === 'undefined') {
            barWidth = Math.min(adjustedValue, DEFAULT_BAR_WIDTH);
        }
        else {
            barWidth = adjustedValue;
        }
        if (typeof maxBarWidthProp === 'number') {
            barWidth = Math.min(barWidth, maxBarWidthProp);
        }
        barWidth = Math.max(barWidth, MIN_BAR_WIDTH);
        return barWidth;
    };
    exports.getBarWidth = getBarWidth;
    var getScalePadding = function (prop, shorthandProp, defaultValue) {
        if (defaultValue === void 0) { defaultValue = 0; }
        var padding = typeof prop === 'number' ? prop : typeof shorthandProp === 'number' ? shorthandProp : defaultValue;
        padding = Math.max(0, Math.min(padding, 1));
        return padding;
    };
    exports.getScalePadding = getScalePadding;
    var isScalePaddingDefined = function (prop, shorthandProp) {
        return typeof prop === 'number' || typeof shorthandProp === 'number';
    };
    exports.isScalePaddingDefined = isScalePaddingDefined;
    var formatDate = function (date, useUTC) {
        var timeFormat = useUTC ? d3_time_format_1.utcFormat : d3_time_format_1.timeFormat;
        return timeFormat('%-e %b %Y, %H:%M')(date) + (useUTC ? ' GMT' : '');
    };
    exports.formatDate = formatDate;
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    function getSecureProps(props) {
        if (props === void 0) { props = {}; }
        var dangerouslySetInnerHTML = props.dangerouslySetInnerHTML, result = tslib_1.__rest(props, ["dangerouslySetInnerHTML"]);
        return result;
    }
    exports.getSecureProps = getSecureProps;
    function areArraysEqual(arr1, arr2) {
        if (arr1 === arr2) {
            return true;
        }
        if (!arr1 && !arr2) {
            return true;
        }
        if (!arr1 || !arr2 || arr1.length !== arr2.length) {
            return false;
        }
        for (var i = 0; i < arr1.length; i++) {
            if (arr1[i] !== arr2[i]) {
                return false;
            }
        }
        return true;
    }
    exports.areArraysEqual = areArraysEqual;
    var cssVarRegExp = /var\((--[a-zA-Z0-9\-]+)\)/g;
    function resolveCSSVariables(chartContainer, styleRules) {
        var containerStyles = getComputedStyle(chartContainer);
        return styleRules.replace(cssVarRegExp, function (match, group1) {
            return containerStyles.getPropertyValue(group1);
        });
    }
    exports.resolveCSSVariables = resolveCSSVariables;
    function copyStyle(properties, fromEl, toEl) {
        var styles = getComputedStyle(fromEl);
        if (Array.isArray(properties)) {
            properties.forEach(function (prop) {
                (0, d3_selection_1.select)(toEl).style(prop, styles.getPropertyValue(prop));
            });
        }
        else {
            Object.entries(properties).forEach(function (_a) {
                var fromProp = _a[0], toProp = _a[1];
                (0, d3_selection_1.select)(toEl).style(toProp, styles.getPropertyValue(fromProp));
            });
        }
    }
    exports.copyStyle = copyStyle;
    var MEASUREMENT_SPAN_STYLE = {
        position: 'absolute',
        visibility: 'hidden',
        top: '-20000px',
        left: 0,
        padding: 0,
        margin: 0,
        border: 'none',
        whiteSpace: 'pre',
    };
    var MEASUREMENT_SPAN_ID = (0, react_1.getId)('measurement_span_');
    var createMeasurementSpan = function (text, className, parentElement) {
        var measurementSpan = document.getElementById(MEASUREMENT_SPAN_ID);
        if (!measurementSpan) {
            measurementSpan = document.createElement('span');
            measurementSpan.setAttribute('id', MEASUREMENT_SPAN_ID);
            measurementSpan.setAttribute('aria-hidden', 'true');
            if (parentElement) {
                parentElement.appendChild(measurementSpan);
            }
            else {
                document.body.appendChild(measurementSpan);
            }
        }
        measurementSpan.setAttribute('class', className);
        Object.assign(measurementSpan.style, MEASUREMENT_SPAN_STYLE);
        measurementSpan.textContent = "".concat(text);
        return measurementSpan;
    };
    exports.createMeasurementSpan = createMeasurementSpan;
});
//# sourceMappingURL=utilities.js.map