@wordpress/components
Version:
UI components for WordPress.
261 lines (260 loc) • 10.9 kB
JavaScript
import clsx from "clsx";
import { forwardRef, useRef } from "@wordpress/element";
import { __, isRTL } from "@wordpress/i18n";
import { plus, reset } from "@wordpress/icons";
import { useMergeRefs } from "@wordpress/compose";
import deprecated from "@wordpress/deprecated";
import InputControl from "../input-control/index.mjs";
import Button from "../button/index.mjs";
import * as inputControlActionTypes from "../input-control/reducer/actions.mjs";
import { add, clamp, ensureValidStep, multiply, subtract } from "../utils/math.mjs";
import { ensureNumber, isValueEmpty } from "../utils/values.mjs";
import { HStack } from "../h-stack/index.mjs";
import { Spacer } from "../spacer/index.mjs";
import { Fragment, jsx, jsxs } 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/number-control/style.module.scss
if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("7d52c7afa0", ".c794a48869c16ec0__hide-html-arrows input[type=number]::-webkit-inner-spin-button,.c794a48869c16ec0__hide-html-arrows input[type=number]::-webkit-outer-spin-button{-webkit-appearance:none!important;margin:0!important}.c794a48869c16ec0__hide-html-arrows input[type=number]{-moz-appearance:textfield}.de349b6ad4bad326__spin-button.de349b6ad4bad326__spin-button.de349b6ad4bad326__spin-button.de349b6ad4bad326__spin-button.de349b6ad4bad326__spin-button{color:var(--wp-components-color-accent,var(--wp-admin-theme-color,#3858e9))}.de349b6ad4bad326__spin-button:where(._234e97eac6085724__is-small){height:20px;min-width:20px;width:20px}");
var style_module_default = {
"hide-html-arrows": "c794a48869c16ec0__hide-html-arrows",
"spin-button": "de349b6ad4bad326__spin-button",
"is-small": "_234e97eac6085724__is-small"
};
// packages/components/src/number-control/index.tsx
const noop = () => {};
function UnforwardedNumberControl(props, forwardedRef) {
const { __unstableStateReducer: stateReducerProp, className, dragDirection = "n", hideHTMLArrows = false, spinControls = hideHTMLArrows ? "none" : "native", isDragEnabled = true, isShiftStepEnabled = true, label, max = Infinity, min = -Infinity, required = false, shiftStep = 10, step = 1, spinFactor = 1, type: typeProp = "number", value: valueProp, size = "default", suffix, onChange = noop, ...restProps } = props;
if (hideHTMLArrows) deprecated("wp.components.NumberControl hideHTMLArrows prop ", {
alternative: "spinControls=\"none\"",
since: "6.2",
version: "6.3"
});
const inputRef = useRef(null);
const mergedRef = useMergeRefs([inputRef, forwardedRef]);
const isStepAny = step === "any";
const baseStep = isStepAny ? 1 : ensureNumber(step);
const baseSpin = multiply(ensureNumber(spinFactor), baseStep);
const constrainValue = (value, stepOverride) => {
if (!isStepAny) value = ensureValidStep(value, min, stepOverride ?? baseStep);
return `${clamp(value, min, max)}`;
};
const baseValue = constrainValue(0);
const autoComplete = typeProp === "number" ? "off" : void 0;
const classes = clsx("components-number-control", className, { [style_module_default["hide-html-arrows"]]: spinControls !== "native" });
const spinButtonClasses = clsx(style_module_default["spin-button"], { [style_module_default["is-small"]]: size === "small" });
const spinValue = (value, direction, event) => {
event?.preventDefault();
const shift = event?.shiftKey && isShiftStepEnabled;
const delta = shift ? multiply(ensureNumber(shiftStep), baseSpin) : baseSpin;
let nextValue = isValueEmpty(value) ? baseValue : value;
if (direction === "up") nextValue = add(nextValue, delta);
else if (direction === "down") nextValue = subtract(nextValue, delta);
return constrainValue(nextValue, shift ? delta : void 0);
};
/**
* "Middleware" function that intercepts updates from InputControl.
* This allows us to tap into actions to transform the (next) state for
* InputControl.
*
* @return The updated state to apply to InputControl
*/
const numberControlStateReducer = (state, action) => {
const nextState = { ...state };
const { type, payload } = action;
const event = payload.event;
const currentValue = nextState.value;
/**
* Handles custom UP and DOWN Keyboard events
*/
if (type === inputControlActionTypes.PRESS_UP || type === inputControlActionTypes.PRESS_DOWN) nextState.value = spinValue(currentValue, type === inputControlActionTypes.PRESS_UP ? "up" : "down", event);
/**
* Handles drag to update events
*/
if (type === inputControlActionTypes.DRAG && isDragEnabled) {
const [x, y] = payload.delta;
const enableShift = payload.shiftKey && isShiftStepEnabled;
const modifier = enableShift ? multiply(ensureNumber(shiftStep), baseSpin) : baseSpin;
let directionModifier;
let delta;
switch (dragDirection) {
case "n":
delta = y;
directionModifier = -1;
break;
case "e":
delta = x;
directionModifier = isRTL() ? -1 : 1;
break;
case "s":
delta = y;
directionModifier = 1;
break;
case "w":
delta = x;
directionModifier = isRTL() ? 1 : -1;
}
if (delta !== 0) {
delta = Math.ceil(Math.abs(delta)) * Math.sign(delta);
const distance = multiply(delta, modifier, directionModifier);
nextState.value = constrainValue(add(currentValue, distance), enableShift ? modifier : void 0);
}
}
/**
* Handles commit (ENTER key press or blur)
*/
if (type === inputControlActionTypes.PRESS_ENTER || type === inputControlActionTypes.COMMIT) nextState.value = required === false && currentValue === "" ? currentValue : constrainValue(currentValue);
return stateReducerProp?.(nextState, action) ?? nextState;
};
const buildSpinButtonClickHandler = (direction) => (event) => onChange(String(spinValue(valueProp, direction, event)), { event: {
...event,
target: inputRef.current
} });
return /* @__PURE__ */ jsx(InputControl, {
autoComplete,
inputMode: "numeric",
...restProps,
className: classes,
dragDirection,
isDragEnabled,
label,
max: max === Infinity ? void 0 : max,
min: min === -Infinity ? void 0 : min,
ref: mergedRef,
required,
step,
type: typeProp,
value: valueProp,
__unstableStateReducer: numberControlStateReducer,
size,
suffix: spinControls === "custom" ? /* @__PURE__ */ jsxs(Fragment, { children: [suffix, /* @__PURE__ */ jsx(Spacer, {
marginBottom: 0,
marginRight: 2,
children: /* @__PURE__ */ jsxs(HStack, {
spacing: 1,
children: [/* @__PURE__ */ jsx(Button, {
className: spinButtonClasses,
icon: plus,
size: "small",
label: __("Increment"),
onClick: buildSpinButtonClickHandler("up")
}), /* @__PURE__ */ jsx(Button, {
className: spinButtonClasses,
icon: reset,
size: "small",
label: __("Decrement"),
onClick: buildSpinButtonClickHandler("down")
})]
})
})] }) : suffix,
onChange
});
}
/**
* `NumberControl` is a text input control that lets users enter and adjust a
* numeric value.
*/
const NumberControl = forwardRef(UnforwardedNumberControl);
NumberControl.displayName = "NumberControl";
export { NumberControl, NumberControl as default };
//# sourceMappingURL=index.mjs.map