// packages/components/src/unit-control/index.tsx
import clsx from "clsx";
import deprecated from "@wordpress/deprecated";
import { forwardRef, useMemo, useRef, useEffect } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import { ValueInput } from "./styles/unit-control-styles.js";
import UnitSelectControl from "./unit-select-control.js";
import { CSS_UNITS, getParsedQuantityAndUnit, getUnitsWithCurrentUnit, getValidParsedQuantityAndUnit } from "./utils.js";
import { useControlledState } from "../utils/hooks/index.js";
import { escapeRegExp } from "../utils/strings.js";
import { useDeprecated36pxDefaultSizeProp } from "../utils/use-deprecated-props.js";
import { maybeWarnDeprecated36pxSize } from "../utils/deprecated-36px-size.js";
import { jsx as _jsx } from "react/jsx-runtime";
import { parseQuantityAndUnitFromRawValue, useCustomUnits } from "./utils.js";
function UnforwardedUnitControl(unitControlProps, forwardedRef) {
  const {
    __unstableStateReducer,
    autoComplete = "off",
    // @ts-expect-error Ensure that children is omitted from restProps
    children,
    className,
    disabled = false,
    disableUnits = false,
    isPressEnterToChange = false,
    isResetValueOnUnitChange = false,
    isUnitSelectTabbable = true,
    label,
    onChange: onChangeProp,
    onUnitChange,
    size = "default",
    unit: unitProp,
    units: unitsProp = CSS_UNITS,
    value: valueProp,
    onFocus: onFocusProp,
    __shouldNotWarnDeprecated36pxSize,
    ...props
  } = useDeprecated36pxDefaultSizeProp(unitControlProps);
  maybeWarnDeprecated36pxSize({
    componentName: "UnitControl",
    __next40pxDefaultSize: props.__next40pxDefaultSize,
    size,
    __shouldNotWarnDeprecated36pxSize
  });
  if ("unit" in unitControlProps) {
    deprecated("UnitControl unit prop", {
      since: "5.6",
      hint: "The unit should be provided within the `value` prop.",
      version: "6.2"
    });
  }
  const nonNullValueProp = valueProp !== null && valueProp !== void 0 ? valueProp : void 0;
  const [units, reFirstCharacterOfUnits] = useMemo(() => {
    const list = getUnitsWithCurrentUnit(nonNullValueProp, unitProp, unitsProp);
    const [{
      value: firstUnitValue = ""
    } = {}, ...rest] = list;
    const firstCharacters = rest.reduce((carry, {
      value
    }) => {
      const first = escapeRegExp(value?.substring(0, 1) || "");
      return carry.includes(first) ? carry : `${carry}|${first}`;
    }, escapeRegExp(firstUnitValue.substring(0, 1)));
    return [list, new RegExp(`^(?:${firstCharacters})$`, "i")];
  }, [nonNullValueProp, unitProp, unitsProp]);
  const [parsedQuantity, parsedUnit] = getParsedQuantityAndUnit(nonNullValueProp, unitProp, units);
  const [unit, setUnit] = useControlledState(units.length === 1 ? units[0].value : unitProp, {
    initial: parsedUnit,
    fallback: ""
  });
  useEffect(() => {
    if (parsedUnit !== void 0) {
      setUnit(parsedUnit);
    }
  }, [parsedUnit, setUnit]);
  const classes = clsx(
    "components-unit-control",
    // This class is added for legacy purposes to maintain it on the outer
    // wrapper. See: https://github.com/WordPress/gutenberg/pull/45139
    "components-unit-control-wrapper",
    className
  );
  const handleOnQuantityChange = (nextQuantityValue, changeProps) => {
    if (nextQuantityValue === "" || typeof nextQuantityValue === "undefined" || nextQuantityValue === null) {
      onChangeProp?.("", changeProps);
      return;
    }
    const onChangeValue = getValidParsedQuantityAndUnit(nextQuantityValue, units, parsedQuantity, unit).join("");
    onChangeProp?.(onChangeValue, changeProps);
  };
  const handleOnUnitChange = (nextUnitValue, changeProps) => {
    const {
      data
    } = changeProps;
    let nextValue = `${parsedQuantity !== null && parsedQuantity !== void 0 ? parsedQuantity : ""}${nextUnitValue}`;
    if (isResetValueOnUnitChange && data?.default !== void 0) {
      nextValue = `${data.default}${nextUnitValue}`;
    }
    onChangeProp?.(nextValue, changeProps);
    onUnitChange?.(nextUnitValue, changeProps);
    setUnit(nextUnitValue);
  };
  let handleOnKeyDown;
  if (!disableUnits && isUnitSelectTabbable && units.length) {
    handleOnKeyDown = (event) => {
      props.onKeyDown?.(event);
      if (!event.metaKey && !event.ctrlKey && reFirstCharacterOfUnits.test(event.key)) {
        refInputSuffix.current?.focus();
      }
    };
  }
  const refInputSuffix = useRef(null);
  const inputSuffix = !disableUnits ? /* @__PURE__ */ _jsx(UnitSelectControl, {
    ref: refInputSuffix,
    "aria-label": __("Select unit"),
    disabled,
    isUnitSelectTabbable,
    onChange: handleOnUnitChange,
    size: ["small", "compact"].includes(size) || size === "default" && !props.__next40pxDefaultSize ? "small" : "default",
    unit,
    units,
    onFocus: onFocusProp,
    onBlur: unitControlProps.onBlur
  }) : null;
  let step = props.step;
  if (!step && units) {
    var _activeUnit$step;
    const activeUnit = units.find((option) => option.value === unit);
    step = (_activeUnit$step = activeUnit?.step) !== null && _activeUnit$step !== void 0 ? _activeUnit$step : 1;
  }
  return /* @__PURE__ */ _jsx(ValueInput, {
    ...props,
    __shouldNotWarnDeprecated36pxSize: true,
    autoComplete,
    className: classes,
    disabled,
    spinControls: "none",
    isPressEnterToChange,
    label,
    onKeyDown: handleOnKeyDown,
    onChange: handleOnQuantityChange,
    ref: forwardedRef,
    size,
    suffix: inputSuffix,
    type: isPressEnterToChange ? "text" : "number",
    value: parsedQuantity !== null && parsedQuantity !== void 0 ? parsedQuantity : "",
    step,
    onFocus: onFocusProp,
    __unstableStateReducer
  });
}
var UnitControl = forwardRef(UnforwardedUnitControl);
var unit_control_default = UnitControl;
export {
  UnitControl,
  unit_control_default as default,
  parseQuantityAndUnitFromRawValue,
  useCustomUnits
};
//# sourceMappingURL=index.js.map
