/* @oracle/oraclejet-preact: undefined */
'use strict';

var jsxRuntime = require('preact/jsx-runtime');
var TrackResizeContainer = require('./TrackResizeContainer-96619aba.js');
var classNames = require('./classNames-c14c6ef3.js');
var mergeProps = require('./mergeProps-e3da7237.js');
var hooks = require('preact/hooks');
var useUser = require('./useUser-c85f9587.js');
var useMeterDatatip = require('./useMeterDatatip-cd934c90.js');
var useKeyboardEvents = require('./useKeyboardEvents-01439376.js');
var meterUtils = require('./meterUtils-efa93410.js');
var utils = require('./utils-606327d1.js');
var UNSAFE_MeterBar_themes_MeterBarContract_css = require('./UNSAFE_MeterBar/themes/MeterBarContract.css.js');
var size = require('./size-0056ef1a.js');
var UNSAFE_MeterBar_themes_MeterBarStyles_css = require('./UNSAFE_MeterBar/themes/MeterBarStyles.css.js');
var utils$1 = require('./utils-194c450f.js');
require('./TabbableModeContext-e99d527e.js');
var useTabbableMode = require('./useTabbableMode-5c8fd9e5.js');
var useComponentTheme = require('./useComponentTheme-082fc8e4.js');
var UNSAFE_MeterBar_themes_redwood_MeterBarTheme = require('./UNSAFE_MeterBar/themes/redwood/MeterBarTheme.js');
var useTestId = require('./useTestId-32c35bff.js');
var useTextDimensions = require('./useTextDimensions-b94e8899.js');
var useCssVars = require('./useCssVars-99ce6e96.js');
var Common_themes_themeContract_css = require('./Common/themes/themeContract.css.js');
var LinearMeter = require('./LinearMeter-01730327.js');

/**
 * @license
 * Copyright (c) %FIRST_YEAR% %CURRENT_YEAR%, Oracle and/or its affiliates.
 * The Universal Permissive License (UPL), Version 1.0
 * as shown at https://oss.oracle.com/licenses/upl/
 * @ignore
 */
const FIT_REF_BAR_PROTRUSION = 16;
const MAX_VERTICAL_LABEL_WIDTH_IN_XUNITS = 15;
const REF_LINE_LENGTH_IN_XUNITS = 5;
const LABEL_GAP = 4;
/**
 * Returns the metric value of the clicked point.
 * @param event The PointerEvent
 * @param dimensionsRef RefObject to stored dimensions of the meter bar.
 * @param min The minimum value of the meter bar.
 * @param max The maximum value of the meter bar.
 * @param step The step value of the meter bar.
 * @param orientation The orientation of the meter bar.
 * @param isRtl Whether the reading mode is 'rtl'
 * @returns The metric value of the clicked point.
 */
function getValue(event, dimensionsRef, min, max, step, orientation, isRtl) {
    const dims = dimensionsRef.current;
    if (!dims || dims.width === 0) {
        return undefined;
    }
    let val;
    if (orientation === 'horizontal') {
        const width = event.offsetX;
        val = min + ((max - min) * (isRtl ? dims.width - width : width)) / dims.width;
    }
    else {
        const height = dims.height - event.offsetY;
        val = min + ((max - min) * height) / dims.height;
    }
    val = Math.round(val / step) * step;
    return Math.max(min, Math.min(max, val));
}
/**
 * Returns the true dimension of the meter bar after first render. All dimensions are 0 for initial render.
 * @param element The meter bar track HTML element
 * @returns The dimension of the meter bar.
 */
function getDimensions(element) {
    if (!element) {
        return {
            width: 0,
            height: 0
        };
    }
    const trackDims = element.getBoundingClientRect();
    return {
        width: trackDims.width,
        height: trackDims.height
    };
}
/**
 * Returns object with 'start' and 'end' keys. Value for each key will be true if at least one ref line with correposnding position is present in meter bar.
 * @param lines The array of reference lines.
 * @returns Returns object with start and end keys.
 */
function getRefLinesInfo(lines) {
    let refLineInfo = { start: false, end: false };
    if (lines) {
        refLineInfo = lines.reduce((acc, cur) => {
            acc.start = acc.start || cur.position === 'start';
            acc.end = acc.end || cur.position === 'end' || cur.position == null;
            return acc;
        }, refLineInfo);
    }
    return refLineInfo;
}
const getFitMarginClass = function (info, isHoriz, barTrackMarginTopFitStyle, barTrackMarginStartFitStyle, barTrackMarginBottomFitStyle, barTrackMarginEndFitStyle) {
    const className = [];
    if (info.start) {
        className.push(isHoriz ? barTrackMarginTopFitStyle : barTrackMarginStartFitStyle);
    }
    if (info.end) {
        className.push(isHoriz ? barTrackMarginBottomFitStyle : barTrackMarginEndFitStyle);
    }
    return className;
};
const getFitTrackWidth = function (info, maxLabelWidth, width, isHoriz) {
    if (width) {
        if (info.start && !isHoriz) {
            width = width - FIT_REF_BAR_PROTRUSION;
        }
        if (info.end && !isHoriz) {
            width = width - FIT_REF_BAR_PROTRUSION;
        }
    }
    if (maxLabelWidth && width) {
        width -= 2 * maxLabelWidth + 2 * LABEL_GAP;
    }
    return width;
};
const getFitTrackHeight = function (info, maxLabelHeight, height, isHoriz) {
    if (height) {
        if (info.start && isHoriz) {
            height = height - FIT_REF_BAR_PROTRUSION;
        }
        if (info.end && isHoriz) {
            height = height - FIT_REF_BAR_PROTRUSION;
        }
    }
    if (maxLabelHeight && height) {
        height -= 2 * maxLabelHeight + 2 * LABEL_GAP;
    }
    return height;
};
const getFitMarginStyle = function (maxLabelWidth, maxLabelHeight, isHoriz) {
    const refMargin = `${utils.xUnits(4)} + ${LABEL_GAP}px`;
    if (isHoriz) {
        return `calc(${refMargin} + ${maxLabelHeight}px) 0 calc(${refMargin} + ${maxLabelHeight}px) 0`;
    }
    return `0 calc(${refMargin} + ${maxLabelWidth}px) 0 calc(${refMargin} + ${maxLabelWidth}px)`;
};
/**
 * Returns the translation offset for the reference line label
 */
function getReferenceLineLabelTranslationOffset(isLeft, isBottom, isHoriz, isRtl, isStartPos, length, size) {
    const refLineLength = length || utils.xUnits(REF_LINE_LENGTH_IN_XUNITS);
    const barSize = size || UNSAFE_MeterBar_themes_MeterBarContract_css.meterBarVars.size;
    const overHang = `calc(${refLineLength} - ${barSize})`;
    if (isHoriz) {
        if (isStartPos) {
            return `${isLeft ? '-50%' : '50%'} calc(-100% - ${overHang} - ${LABEL_GAP}px)`;
        }
        else {
            return `${isLeft ? '-50%' : '50%'} calc(${refLineLength} + ${LABEL_GAP}px)`;
        }
    }
    else {
        if (isRtl) {
            return isStartPos
                ? `calc(100% + ${overHang} + ${LABEL_GAP}px) ${isBottom ? '50%' : '-50%'}`
                : `calc(0px - ${refLineLength} - ${LABEL_GAP}px) ${isBottom ? '50%' : '-50%'}`;
        }
        else {
            return isStartPos
                ? `calc(-100% - ${overHang} - ${LABEL_GAP}px) ${isBottom ? '50%' : '-50%'}`
                : `calc(${refLineLength} + ${LABEL_GAP}px) ${isBottom ? '50%' : '-50%'}`;
        }
    }
}
/**
 * Returns the margin needed to accomodate reference line and label in a sized meter circle.
 */
function getSizedMargin(info, isHoriz, hasReferenceLine, hasReferenceLineLabel, maxRefLabelDims) {
    const marginValue = `calc(${utils.xUnits(REF_LINE_LENGTH_IN_XUNITS)} - ${UNSAFE_MeterBar_themes_MeterBarContract_css.meterBarVars.size})`;
    const gap = LABEL_GAP;
    const hasBothPosition = info.start && info.end;
    if (hasReferenceLineLabel) {
        return isHoriz
            ? `calc(${maxRefLabelDims.height + gap}px + ${marginValue}) 0 calc(${maxRefLabelDims.height + gap}px + ${marginValue}) 0`
            : `0 calc(${maxRefLabelDims.width + gap}px + ${marginValue}) 0 calc(${maxRefLabelDims.width + gap}px + ${marginValue})`;
    }
    else if (hasReferenceLine) {
        if (hasBothPosition) {
            return isHoriz ? `${marginValue} 0 ${marginValue}` : `0 ${marginValue} 0 ${marginValue}`;
        }
        else if (info.start && !info.end) {
            return isHoriz ? `${marginValue} 0 0 0` : `0 ${marginValue} 0 0`;
        }
        else if (!info.start && info.end) {
            return isHoriz ? `0 0 ${marginValue} 0` : `0 0 0 ${marginValue}`;
        }
    }
    return undefined;
}
function getComponentStyle(isFit, isHoriz, length, maxRefLabelDims, fitTrackHeight, fitTrackWidth) {
    return {
        width: isFit ? fitTrackWidth : isHoriz ? size.sizeToCSS(length) : undefined,
        height: isFit ? fitTrackHeight : isHoriz ? undefined : size.sizeToCSS(length),
        margin: isFit
            ? getFitMarginStyle(maxRefLabelDims.width, maxRefLabelDims.height, isHoriz)
            : undefined
    };
}
function getReferenceLineAlignmentStyle(isLeft, isRtl, maxLabelWidth, percentage) {
    return {
        left: isLeft ? `max(${maxLabelWidth}px, ${isRtl ? 100 - percentage : percentage}%)` : undefined,
        right: !isLeft
            ? `max(${maxLabelWidth}px, ${isRtl ? percentage : 100 - percentage}%)`
            : undefined
    };
}
function getReferenceLineTranslation(isHoriz, isRtl, percent) {
    if (percent === 0 && !isRtl) {
        return;
    }
    if (percent === 100) {
        if (isRtl)
            return isHoriz ? '3px' : '0 3px';
        return isHoriz ? '-2px' : '0 2px';
    }
    return isHoriz ? (isRtl ? '1px 0' : '-1px 0') : isRtl ? '0 -1px' : '0 1px';
}
function getReferenceLinePosition(isHoriz, isLeft, isBottom, isRtl, percent, maxLabelWidth, maxLabelHeight) {
    return {
        ...(isHoriz ? getReferenceLineAlignmentStyle(isLeft, isRtl, maxLabelWidth / 2, percent) : {}),
        bottom: isHoriz
            ? undefined
            : isBottom
                ? `max(${maxLabelHeight / 2 - LABEL_GAP}px, ${percent}%)`
                : undefined,
        top: isHoriz
            ? undefined
            : !isBottom
                ? `max(${maxLabelHeight / 2 - LABEL_GAP}px, ${100 - percent}%)`
                : undefined,
        maxWidth: !isHoriz ? utils.xUnits(MAX_VERTICAL_LABEL_WIDTH_IN_XUNITS) : undefined
    };
}

function ReferenceLineBar({ orientation, percent, color, position, length, label, maxLabelWidth, maxLabelHeight, trackSize, labelStyle }) {
    const isHoriz = orientation === 'horizontal';
    const { direction } = useUser.useUser();
    const isRtl = direction === 'rtl';
    const isStartPos = position === 'start';
    const percentage = `${percent}%`;
    const width = isHoriz ? undefined : length;
    const height = isHoriz ? length : undefined;
    const isLeft = (percent < 50 && !isRtl) || (percent > 50 && isRtl);
    const isBottom = percent < 50;
    return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { class: classNames.classNames([
                    UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.referenceLinesBaseStyle,
                    isHoriz ? UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.referenceLinesHorizontalStyle : UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.referenceLinesVerticalStyle,
                    isStartPos
                        ? isHoriz
                            ? UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.referenceLinesHoriontalStartStyle
                            : isRtl
                                ? UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.referenceLinesVerticalStartRtlStyle
                                : UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.referenceLinesVerticalStartLtrStyle
                        : ''
                ]), style: {
                    left: isHoriz && !isRtl ? percentage : undefined,
                    right: isHoriz && isRtl ? percentage : undefined,
                    bottom: isHoriz ? undefined : percentage,
                    backgroundColor: utils$1.getVisThresholdColor(color),
                    width,
                    height,
                    translate: getReferenceLineTranslation(isHoriz, isRtl, percent)
                } }), label && (jsxRuntime.jsx("div", { className: UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.labelDivStyle, style: {
                    ...getReferenceLinePosition(isHoriz, isLeft, isBottom, isRtl, percent, maxLabelWidth, maxLabelHeight),
                    translate: getReferenceLineLabelTranslationOffset(isLeft, isBottom, isHoriz, isRtl, isStartPos, length, trackSize),
                    ...labelStyle
                }, children: label }))] }));
}

function ThresholdBar({ color, length, orientation, ...otherProps }) {
    const { direction } = useUser.useUser();
    const isHoriz = orientation === 'horizontal';
    const isRtl = direction === 'rtl';
    return (jsxRuntime.jsx("div", { class: classNames.classNames([
            UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.thresholdBarBaseStyle,
            isHoriz
                ? isRtl
                    ? UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.thresholdBarHorizontalBarTrackSectionRtlStyle
                    : UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.thresholdBarHorizontalBarTrackSectionLtrStyle
                : UNSAFE_MeterBar_themes_MeterBarStyles_css.styles.thresholdBarVerticalBarTrackSectionStyle,
            otherProps.class
        ]), style: {
            width: isHoriz ? length : '100%',
            height: isHoriz ? '100%' : length,
            backgroundColor: utils$1.getVisThresholdColor(color)
        } }));
}

function MeterBarWithDimensions({ max = 100, min = 0, value = 0, step = 1, length = '100%', width, height, size, orientation = 'horizontal', isTrackRendered = true, thresholdDisplay = 'all', indicatorSize = 1, testId, baseline, isReadonly, ...props }) {
    const testIdProps = useTestId.useTestId(testId);
    meterUtils.validateRange(min, max, value, step, isReadonly, baseline);
    const currentInputRef = hooks.useRef();
    const isHoriz = orientation === 'horizontal';
    const barTrackRef = hooks.useRef(null);
    const dimensionsRef = hooks.useRef(getDimensions(null));
    const { direction, forcedColors } = useUser.useUser();
    const isRtl = direction === 'rtl';
    hooks.useEffect(() => {
        if (props.onCommit || props.onInput) {
            dimensionsRef.current = getDimensions(barTrackRef.current);
        }
    }, [size, length, orientation, props.onCommit, props.onInput]);
    const { textMeasureContent, getTextDimensions } = useTextDimensions.useTextDimensions();
    const getValueFromEvent = (event) => {
        // only evaluate value from bar track
        if (event.target == barTrackRef.current) {
            return getValue(event, dimensionsRef, min, max, step, orientation, isRtl);
        }
        return;
    };
    const isPointerActiveRef = hooks.useRef(false);
    const pointerEventsProps = useMeterDatatip.usePointerEvents(value, getValueFromEvent, barTrackRef, currentInputRef, isPointerActiveRef, props.onCommit, props.onInput);
    const keyboardEventsProps = useKeyboardEvents.useKeyboardEvents(value, min, max, step, currentInputRef, props.onCommit, props.onInput);
    const { datatipContent, datatipProps } = useMeterDatatip.useMeterDatatip(value, isPointerActiveRef, props.datatip, props['aria-describedby']);
    const ariaLabelProps = meterUtils.getMeterAriaProps(value, min, max, props['aria-label'], props['aria-labelledby'], props.thresholds);
    const mergedProps = mergeProps.mergeProps(pointerEventsProps, keyboardEventsProps, datatipProps, ariaLabelProps);
    const resolvedBaseline = baseline !== undefined ? Math.max(min, Math.min(baseline, max)) : min;
    const baselineOffsetPercent = ((resolvedBaseline - min) * 100) / (max - min);
    const valueBarOffsetPercent = ((value - min) * 100) / (max - min);
    const valueBarStartOffset = Math.min(baselineOffsetPercent, valueBarOffsetPercent);
    const valueBarLength = `${Math.abs(baselineOffsetPercent - valueBarOffsetPercent)}%`;
    const valueBarSize = `${Math.max(0, Math.min(1, indicatorSize)) * 100}%`;
    const { trackColor, indicatorColor } = meterUtils.getTrackAndIndicatorColor(value, thresholdDisplay, props.trackColor, props.indicatorColor, props.thresholds);
    const refLineInfo = getRefLinesInfo(props.referenceLines);
    const isInteractive = props.onCommit || props.onInput;
    const { isTabbable } = useTabbableMode.useTabbableMode();
    const { classes, styles: { interactiveStyle, barValueBaseStyle, barValueVerticalStyle, barValueHorizontalStyle, barValueHighContrastStyle, barTrackBaseStyle, barTrackHorizontalSizeStyle, barTrackVerticalSizeStyle, barTrackBorderStyle, barTrackMarginTopFitStyle, barTrackMarginStartFitStyle, barTrackMarginBottomFitStyle, barTrackMarginEndFitStyle, trackSectionHorizontalFirstStyle, trackSectionHorizontalLastStyle, trackSectionVerticalFirstStyle, trackSectionVerticalLastStyle, trackSectionRoundedCornersStyle } } = useComponentTheme.useComponentTheme(UNSAFE_MeterBar_themes_redwood_MeterBarTheme.MeterBarRedwoodTheme, {
        size,
        orientation
    });
    const isFit = size === 'fit';
    const hasReferenceLabel = meterUtils.hasLabelledReferenceLine(props.referenceLines);
    const fontSize = meterUtils.getDefaultReferenceLineLabelFontSize('sm');
    const meterBarCssVars = hooks.useMemo(() => [
        {
            tokenVar: fontSize,
            key: 'labelFontSize',
            cssProp: 'font-size'
        },
        {
            tokenVar: Common_themes_themeContract_css.typographyVars.body.md.lineHeight,
            key: 'lineHeight',
            cssProp: 'line-height'
        }
    ], [fontSize]);
    const { resolvedVars, cssContent } = useCssVars.useCssVars(meterBarCssVars);
    const { dims, maxRefLabelDims } = meterUtils.getMaxRefLabelDims(resolvedVars['fontSize'], resolvedVars['lineHeight'], props.referenceLines, getTextDimensions);
    const fitTrackWidth = getFitTrackWidth(refLineInfo, maxRefLabelDims.width, width, isHoriz);
    const fitTrackHeight = getFitTrackHeight(refLineInfo, maxRefLabelDims.height, height, isHoriz);
    const fitTrackSize = isHoriz ? fitTrackHeight : fitTrackWidth;
    return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx("div", { tabIndex: !isTabbable ? -1 : 0, ...testIdProps, ...mergedProps, style: getComponentStyle(isFit, isHoriz, length, maxRefLabelDims, fitTrackHeight, fitTrackWidth), class: classNames.classNames([
                    classes,
                    ...(isFit
                        ? getFitMarginClass(refLineInfo, isHoriz, barTrackMarginTopFitStyle, barTrackMarginStartFitStyle, barTrackMarginBottomFitStyle, barTrackMarginEndFitStyle)
                        : [])
                ]), children: jsxRuntime.jsxs(LinearMeter.BarTrack, { ref: barTrackRef, orientation: orientation, color: !isTrackRendered || (thresholdDisplay === 'all' && props.thresholds)
                        ? 'transparent'
                        : trackColor, class: classNames.classNames([
                        barTrackBaseStyle,
                        isInteractive ? interactiveStyle : '',
                        isHoriz ? barTrackHorizontalSizeStyle : barTrackVerticalSizeStyle,
                        !isTrackRendered || (thresholdDisplay === 'all' && props.thresholds)
                            ? undefined
                            : barTrackBorderStyle
                    ]), style: {
                        margin: !isFit
                            ? getSizedMargin(refLineInfo, isHoriz, !!props.referenceLines?.length, hasReferenceLabel, maxRefLabelDims)
                            : undefined
                    }, children: [thresholdDisplay === 'all' &&
                            props.thresholds
                                ?.filter((threshold) => threshold.max > min && threshold.max <= max)
                                .sort((a, b) => a.max - b.max)
                                .map((threshold, index, thresholds) => {
                                const diff = index === 0 ? threshold.max - min : threshold.max - thresholds[index - 1].max;
                                const trackSectionLastStyle = isHoriz
                                    ? trackSectionHorizontalLastStyle
                                    : trackSectionVerticalLastStyle;
                                let trackSectionStyleClass = index === 0
                                    ? isHoriz
                                        ? trackSectionHorizontalFirstStyle
                                        : trackSectionVerticalFirstStyle
                                    : '';
                                if (threshold.max === max)
                                    trackSectionStyleClass =
                                        index === 0
                                            ? trackSectionRoundedCornersStyle // Single threshold from min to max
                                            : trackSectionLastStyle;
                                return (jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [jsxRuntime.jsx(ThresholdBar, { class: trackSectionStyleClass, orientation: orientation, length: `${(diff * 100) / (max - min)}%`, color: threshold.color }), isTrackRendered && index === thresholds.length - 1 && threshold.max < max ? (jsxRuntime.jsx(ThresholdBar, { class: trackSectionLastStyle, color: trackColor, orientation: orientation, length: `${((max - thresholds[index].max) * 100) / (max - min)}%` })) : ('')] }));
                            }), jsxRuntime.jsx(LinearMeter.BarValue, { left: isHoriz && !isRtl ? `${valueBarStartOffset}%` : undefined, bottom: !isHoriz ? `${valueBarStartOffset}%` : undefined, right: isHoriz && isRtl ? `${valueBarStartOffset}%` : undefined, width: isHoriz ? valueBarLength : '100%', height: isHoriz ? '100%' : valueBarLength, length: valueBarLength, size: valueBarSize, orientation: orientation, class: classNames.classNames([
                                barValueBaseStyle,
                                isHoriz ? barValueHorizontalStyle : barValueVerticalStyle,
                                forcedColors === 'active' ? barValueHighContrastStyle : ''
                            ]), color: indicatorColor }), props.referenceLines?.map((refLine, index) => (jsxRuntime.jsx(ReferenceLineBar, { label: refLine.label, labelStyle: {
                                fontSize: resolvedVars['labelFontSize'],
                                ...refLine.labelStyle
                            }, color: refLine.color, maxLabelWidth: dims[index]?.width, maxLabelHeight: dims[index]?.height, orientation: orientation, percent: ((refLine.value - min) * 100) / (max - min), position: refLine.position, trackSize: isFit ? `${fitTrackSize}px` : UNSAFE_MeterBar_themes_MeterBarContract_css.meterBarVars.size, length: isFit ? `calc(${utils.xUnits(4)} + ${fitTrackSize}px)` : undefined })))] }) }), cssContent, datatipContent, textMeasureContent] }));
}

/**
 * A Meter bar displays information graphically in a rectangular bar, highlighting a specific metric value's progress in relation to its min, max, or thresholds.
 */
function MeterBar({ orientation, length, size, ...props }) {
    return (jsxRuntime.jsx(jsxRuntime.Fragment, { children: size === 'fit' ? (jsxRuntime.jsx(TrackResizeContainer.TrackResizeContainer, { width: "100%", height: "100%", children: (width, height) => (jsxRuntime.jsx(MeterBarWithDimensions, { width: width, height: height, orientation: orientation, size: size, ...props })) })) : (jsxRuntime.jsx(MeterBarWithDimensions, { size: size, length: length, orientation: orientation, ...props })) }));
}

exports.MeterBar = MeterBar;
//# sourceMappingURL=MeterBar-1ae1adde.js.map
