@wordpress/components
Version:
UI components for WordPress.
235 lines (234 loc) • 13.1 kB
JavaScript
import clsx from "clsx";
import deprecated from "@wordpress/deprecated";
import { forwardRef, useEffect, useMemo, useRef } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import NumberControl from "../number-control/index.mjs";
import UnitSelectControl from "./unit-select-control.mjs";
import { CSS_UNITS, getParsedQuantityAndUnit, getUnitsWithCurrentUnit, getValidParsedQuantityAndUnit, parseQuantityAndUnitFromRawValue, useCustomUnits } from "./utils.mjs";
import { useControlledState } from "../utils/hooks/index.mjs";
import { multiply } from "../utils/math.mjs";
import { escapeRegExp } from "../utils/strings.mjs";
import { jsx } from "react/jsx-runtime";
// packages/style-runtime/src/index.ts
const STYLE_HASH_ATTRIBUTE = "data-wp-hash";
/**
* Returns the shared style runtime registry.
*
* The registry is stored on `globalThis` so separately bundled copies of this
* package can coordinate through the same document and style maps.
*
* @return The shared runtime registry.
*/
function getRuntime() {
const globalScope = globalThis;
if (globalScope.__wpStyleRuntime) return globalScope.__wpStyleRuntime;
globalScope.__wpStyleRuntime = {
documents: /* @__PURE__ */ new Map(),
styles: /* @__PURE__ */ new Map(),
injectedStyles: /* @__PURE__ */ new WeakMap()
};
if (typeof document !== "undefined") registerDocument(document);
return globalScope.__wpStyleRuntime;
}
/**
* Checks whether a document already contains a style tag for a hash.
*
* @param targetDocument Document to inspect.
* @param hash Stable hash for the transformed CSS.
*
* @return Whether the style hash already exists in the document.
*/
function documentContainsStyleHash(targetDocument, hash) {
if (!targetDocument.head) return false;
for (const style of targetDocument.head.querySelectorAll(`style[${STYLE_HASH_ATTRIBUTE}]`)) if (style.getAttribute(STYLE_HASH_ATTRIBUTE) === hash) return true;
return false;
}
/**
* Injects a registered style into a document, unless that document already
* contains a style tag for the same hash.
*
* @param targetDocument Document to inject the style into.
* @param hash Stable hash for the transformed CSS.
* @param css CSS text to inject.
*/
function injectStyle(targetDocument, hash, css) {
if (!targetDocument.head) return;
const runtime = getRuntime();
let injectedStyles = runtime.injectedStyles.get(targetDocument);
if (!injectedStyles) {
injectedStyles = /* @__PURE__ */ new Set();
runtime.injectedStyles.set(targetDocument, injectedStyles);
}
if (injectedStyles.has(hash)) return;
if (documentContainsStyleHash(targetDocument, hash)) {
injectedStyles.add(hash);
return;
}
const style = targetDocument.createElement("style");
style.setAttribute(STYLE_HASH_ATTRIBUTE, hash);
style.appendChild(targetDocument.createTextNode(css));
targetDocument.head.appendChild(style);
injectedStyles.add(hash);
}
/**
* Registers a document as a style injection target.
*
* Existing registered styles are replayed into the document immediately.
* Documents are reference-counted so multiple providers can safely register the
* same document without one cleanup removing it while another registration is
* still active.
*
* @param targetDocument Document to receive registered styles.
* @return Cleanup function that unregisters this document registration.
*/
function registerDocument(targetDocument) {
const runtime = getRuntime();
runtime.documents.set(targetDocument, (runtime.documents.get(targetDocument) ?? 0) + 1);
for (const [hash, css] of runtime.styles) injectStyle(targetDocument, hash, css);
return () => {
const count = runtime.documents.get(targetDocument);
if (count === void 0) return;
if (count <= 1) {
runtime.documents.delete(targetDocument);
return;
}
runtime.documents.set(targetDocument, count - 1);
};
}
/**
* Registers a style and injects it into all registered documents.
*
* The hash is used as the deduplication key, so calling this repeatedly with
* the same hash will not add duplicate style tags to a document.
* Registered styles are retained for the lifetime of the page so they can be
* replayed into documents that are registered later.
*
* @param hash Stable hash for the transformed CSS.
* @param css CSS text to inject.
*/
function registerStyle(hash, css) {
const runtime = getRuntime();
runtime.styles.set(hash, css);
for (const targetDocument of runtime.documents.keys()) injectStyle(targetDocument, hash, css);
}
// packages/components/src/unit-control/style.module.scss
if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("abc278533a", ".c259d71ec42c1f39__value-input.c259d71ec42c1f39__value-input.c259d71ec42c1f39__value-input input{display:block;width:100%}.c259d71ec42c1f39__value-input.c259d71ec42c1f39__value-input.c259d71ec42c1f39__value-input .components-input-control__backdrop{transition:box-shadow .1s linear}._432c86bd74f61719__unit-label._432c86bd74f61719__unit-label._432c86bd74f61719__unit-label{color:#1e1e1e;pointer-events:none}._432c86bd74f61719__unit-label._432c86bd74f61719__unit-label._432c86bd74f61719__unit-label:where(:not(.dd21e6d701b2835d__is-small)){field-sizing:content;box-sizing:border-box;font-size:13px;height:24px;line-height:1;margin-inline-end:8px;max-width:48px;min-width:24px;overflow:hidden;padding:4px;text-align-last:center;text-overflow:ellipsis;white-space:nowrap}._432c86bd74f61719__unit-label._432c86bd74f61719__unit-label._432c86bd74f61719__unit-label:where(.dd21e6d701b2835d__is-small){box-sizing:border-box;font-size:8px;letter-spacing:-.5px;line-height:1;padding:2px 1px;text-align-last:center;text-transform:uppercase;width:20px}._432c86bd74f61719__unit-label._432c86bd74f61719__unit-label._432c86bd74f61719__unit-label:where(.dd21e6d701b2835d__is-small):not(:disabled){color:#2f2f2f}._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select{appearance:none;background:transparent;border:none;border-radius:1px;display:block;font-family:inherit;margin:0;min-height:auto;outline:none}._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select:not(:disabled){cursor:var(--wpds-cursor-control,pointer)}._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select:not(:disabled):hover{background-color:#f0f0f0}._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select:focus{box-shadow:none;outline:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px)) solid var(--focus-color,var(--wpds-color-stroke-focus,var(--wp-admin-theme-color,#3858e9)));outline-offset:var(--wpds-border-width-focus,var(--wp-admin-border-width-focus,2px))}._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select:where(.dd21e6d701b2835d__is-small){box-sizing:border-box;font-size:8px;letter-spacing:-.5px;line-height:1;padding:2px 1px;text-align-last:center;text-transform:uppercase;width:20px}._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select:where(.dd21e6d701b2835d__is-small):not(:disabled){color:#2f2f2f}._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select:where(.dd21e6d701b2835d__is-small){border-end-start-radius:0;border-start-start-radius:0;height:100%}._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select:where(.dd21e6d701b2835d__is-small):focus{outline-offset:calc(var(--wpds-border-width-focus, var(--wp-admin-border-width-focus, 2px))*-1);z-index:1}._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select:where(:not(.dd21e6d701b2835d__is-small)){field-sizing:content;align-items:center;border-radius:var(--wpds-border-radius-sm,2px);box-sizing:border-box;display:flex;font-size:13px;height:24px;justify-content:center;line-height:1;margin-inline-end:8px;max-width:48px;min-width:24px;overflow:hidden;padding:4px;text-align-last:center;text-overflow:ellipsis;white-space:nowrap}._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select._60ab6e3748cd9e88__unit-select:where(:not(.dd21e6d701b2835d__is-small)):not(:disabled){color:var(--wp-components-color-accent,var(--wp-admin-theme-color,#3858e9))}");
var style_module_default = {
"value-input": "c259d71ec42c1f39__value-input",
"unit-label": "_432c86bd74f61719__unit-label",
"is-small": "dd21e6d701b2835d__is-small",
"unit-select": "_60ab6e3748cd9e88__unit-select"
};
// packages/components/src/unit-control/index.tsx
function UnforwardedUnitControl(unitControlProps, forwardedRef) {
const { __unstableStateReducer, autoComplete = "off", 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, ...props } = unitControlProps;
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 ?? 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", "components-unit-control-wrapper", style_module_default["value-input"], className);
const handleOnQuantityChange = (nextQuantityValue, changeProps) => {
if (nextQuantityValue === "" || typeof nextQuantityValue === "undefined" || nextQuantityValue === null) {
onChangeProp?.("", changeProps);
return;
}
const fallbackUnit = units.some((option) => option.value === unit) ? unit : void 0;
const onChangeValue = getValidParsedQuantityAndUnit(nextQuantityValue, units, parsedQuantity, fallbackUnit).join("");
onChangeProp?.(onChangeValue, changeProps);
};
const handleOnUnitChange = (nextUnitValue, changeProps) => {
const { data } = changeProps;
let nextValue = `${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) ? "small" : "default",
unit,
units,
onFocus: onFocusProp,
onBlur: unitControlProps.onBlur
}) : null;
let step = props.step;
let spinFactor = props.spinFactor;
if (step === void 0) {
const unitStep = (units?.find((option) => option.value === unit))?.step ?? 1;
step = "any";
spinFactor = multiply(props.spinFactor ?? 1, unitStep);
}
return /* @__PURE__ */ jsx(NumberControl, {
...props,
autoComplete,
className: classes,
disabled,
spinControls: "none",
isPressEnterToChange,
label,
onKeyDown: handleOnKeyDown,
onChange: handleOnQuantityChange,
ref: forwardedRef,
size,
suffix: inputSuffix,
type: isPressEnterToChange ? "text" : "number",
value: parsedQuantity ?? "",
step,
spinFactor,
onFocus: onFocusProp,
__unstableStateReducer
});
}
/**
* `UnitControl` allows the user to set a numeric quantity as well as a unit (e.g. `px`).
*
*
* ```jsx
* import { __experimentalUnitControl as UnitControl } from '@wordpress/components';
* import { useState } from '@wordpress/element';
*
* const Example = () => {
* const [ value, setValue ] = useState( '10px' );
*
* return <UnitControl onChange={ setValue } value={ value } />;
* };
* ```
*/
const UnitControl = forwardRef(UnforwardedUnitControl);
UnitControl.displayName = "UnitControl";
export { UnitControl, UnitControl as default, parseQuantityAndUnitFromRawValue, useCustomUnits };
//# sourceMappingURL=index.mjs.map