UNPKG

@wordpress/components

Version:
305 lines (304 loc) • 12.8 kB
import clsx from "clsx"; import { useInstanceId } from "@wordpress/compose"; import { __ } from "@wordpress/i18n"; import { useState } from "@wordpress/element"; import { settings } from "@wordpress/icons"; import Tooltip from "../tooltip/index.mjs"; import { parseQuantityAndUnitFromRawValue } from "../unit-control/utils.mjs"; import { CUSTOM_VALUE_SETTINGS, LABELS, getAllowedSides, getMergedValue, getPresetIndexFromValue, getPresetValueFromIndex, isValueMixed, isValuePreset, isValuesDefined } from "./utils.mjs"; import BoxControlIcon from "./icon.mjs"; import Button from "../button/index.mjs"; import { HStack } from "../h-stack/index.mjs"; import RangeControl from "../range-control/index.mjs"; import UnitControl from "../unit-control/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/box-control/style.module.scss if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("688a11782c", ".a691e367f1b55f62__unit-control{max-width:90px}._0e04b2962bc33dbb__input-wrapper{grid-column:1/span 3}._2e0e779ca7284bc5__reset-button{grid-area:1/2;justify-self:end}._2feb1869b0c8a32c__linked-button-wrapper{grid-area:1/3;justify-self:end}._3952789640f98f27__icon{flex:0 0 auto}._1155863d57b9789a__range-control{margin-inline-end:8px;width:100%}._2a7a06bc9e98a8bf__icon-root{box-sizing:border-box;display:block;height:24px;padding:4px;position:relative;width:24px}._78a67da593233b1d__icon-viewbox{box-sizing:border-box;display:block;height:100%;position:relative;width:100%}._80edddeeefc17880__icon-stroke{background-color:currentColor;box-sizing:border-box;display:block;opacity:.3;pointer-events:none;position:absolute}.d3e186923be6807c__is-highlighted{opacity:1}._5126d15f8bb86c74__icon-left,.cbbba3ba3bed8033__icon-right{bottom:3px;top:3px;width:2px}._43ffaa6905d27840__icon-bottom,._9543c21b4cb17eaa__icon-top{height:2px;left:3px;right:3px}._9543c21b4cb17eaa__icon-top{top:0}.cbbba3ba3bed8033__icon-right{right:0}._43ffaa6905d27840__icon-bottom{bottom:0}._5126d15f8bb86c74__icon-left{left:0}"); var style_module_default = { "unit-control": "a691e367f1b55f62__unit-control", "input-wrapper": "_0e04b2962bc33dbb__input-wrapper", "reset-button": "_2e0e779ca7284bc5__reset-button", "linked-button-wrapper": "_2feb1869b0c8a32c__linked-button-wrapper", "icon": "_3952789640f98f27__icon", "range-control": "_1155863d57b9789a__range-control", "icon-root": "_2a7a06bc9e98a8bf__icon-root", "icon-viewbox": "_78a67da593233b1d__icon-viewbox", "icon-stroke": "_80edddeeefc17880__icon-stroke", "is-highlighted": "d3e186923be6807c__is-highlighted", "icon-left": "_5126d15f8bb86c74__icon-left", "icon-right": "cbbba3ba3bed8033__icon-right", "icon-top": "_9543c21b4cb17eaa__icon-top", "icon-bottom": "_43ffaa6905d27840__icon-bottom" }; // packages/components/src/box-control/box-input-control.tsx const noop = () => {}; function getSidesToModify(side, sides, isAlt) { const allowedSides = getAllowedSides(sides); let modifiedSides = []; switch (side) { case "all": modifiedSides = [ "top", "bottom", "left", "right" ]; break; case "horizontal": modifiedSides = ["left", "right"]; break; case "vertical": modifiedSides = ["top", "bottom"]; break; default: modifiedSides = [side]; } if (isAlt) switch (side) { case "top": modifiedSides.push("bottom"); break; case "bottom": modifiedSides.push("top"); break; case "left": modifiedSides.push("right"); break; case "right": modifiedSides.push("left"); } return modifiedSides.filter((s) => allowedSides.has(s)); } function BoxInputControl({ onChange = noop, onFocus = noop, values, selectedUnits, setSelectedUnits, units, sides, side, min = 0, presets, presetKey, placeholder: placeholderProp, ...props }) { const defaultValuesToModify = getSidesToModify(side, sides); const handleOnFocus = (event) => { onFocus(event, { side }); }; const handleOnChange = (nextValues) => { onChange(nextValues); }; const handleRawOnValueChange = (next) => { const nextValues = { ...values }; defaultValuesToModify.forEach((modifiedSide) => { nextValues[modifiedSide] = next; }); handleOnChange(nextValues); }; const handleOnValueChange = (next, extra) => { const nextValues = { ...values }; const nextValue = next !== void 0 && !isNaN(parseFloat(next)) ? next : void 0; getSidesToModify( side, sides, /** * Supports changing pair sides. For example, holding the ALT key * when changing the TOP will also update BOTTOM. */ !!extra?.event.altKey ).forEach((modifiedSide) => { nextValues[modifiedSide] = nextValue; }); handleOnChange(nextValues); }; const handleOnUnitChange = (next) => { const newUnits = { ...selectedUnits }; defaultValuesToModify.forEach((modifiedSide) => { newUnits[modifiedSide] = next; }); setSelectedUnits(newUnits); }; const mergedValue = getMergedValue(values, defaultValuesToModify); const isMixed = isValuesDefined(values) && defaultValuesToModify.length > 1 && isValueMixed(values, defaultValuesToModify); const [parsedQuantity, parsedUnit] = parseQuantityAndUnitFromRawValue(mergedValue); const resolvedUnit = parsedUnit ?? selectedUnits[defaultValuesToModify[0]]; const computedUnit = resolvedUnit ?? units?.[0]?.value ?? "px"; const inputId = [useInstanceId(BoxInputControl, "box-control-input"), side].join("-"); const isMixedUnit = defaultValuesToModify.length > 1 && mergedValue === void 0 && defaultValuesToModify.some((s) => selectedUnits[s] !== resolvedUnit); const usedValue = mergedValue ?? computedUnit; const mixedPlaceholder = isMixed || isMixedUnit ? __("Mixed") : void 0; const hasPresets = presets && presets.length > 0 && presetKey; const hasPresetValue = hasPresets && mergedValue !== void 0 && !isMixed && isValuePreset(mergedValue, presetKey); const [showCustomValueControl, setShowCustomValueControl] = useState(!hasPresets || !hasPresetValue && !isMixed && mergedValue !== void 0); const presetIndex = hasPresetValue ? getPresetIndexFromValue(mergedValue, presetKey, presets) : void 0; const marks = hasPresets ? [{ value: 0, label: "", tooltip: __("None") }, ...presets.map((preset, index) => ({ value: index + 1, label: "", tooltip: preset.name ?? preset.slug }))] : []; return /* @__PURE__ */ jsxs(HStack, { className: style_module_default["input-wrapper"], expanded: true, children: [ /* @__PURE__ */ jsx(BoxControlIcon, { className: style_module_default.icon, side, sides }), showCustomValueControl && /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx(Tooltip, { placement: "top-end", text: LABELS[side], children: /* @__PURE__ */ jsx(UnitControl, { ...props, min, units, className: clsx(style_module_default["unit-control"], "component-box-control__unit-control"), id: inputId, isPressEnterToChange: true, disableUnits: isMixed || isMixedUnit, value: usedValue, onChange: handleOnValueChange, onUnitChange: handleOnUnitChange, onFocus: handleOnFocus, label: LABELS[side], placeholder: mixedPlaceholder ?? placeholderProp, hideLabelFromVision: true }) }), /* @__PURE__ */ jsx(RangeControl, { className: style_module_default["range-control"], "aria-controls": inputId, label: LABELS[side], hideLabelFromVision: true, onChange: (newValue) => { handleOnValueChange(newValue !== void 0 ? [newValue, computedUnit].join("") : void 0); }, min: isFinite(min) ? min : 0, max: CUSTOM_VALUE_SETTINGS[computedUnit]?.max ?? 10, step: CUSTOM_VALUE_SETTINGS[computedUnit]?.step ?? .1, value: parsedQuantity ?? 0, withInputField: false })] }), hasPresets && !showCustomValueControl && /* @__PURE__ */ jsx(RangeControl, { className: clsx(style_module_default["range-control"], "spacing-sizes-control__range-control"), value: presetIndex !== void 0 ? presetIndex + 1 : 0, onChange: (newIndex) => { const newValue = newIndex === 0 || newIndex === void 0 ? void 0 : getPresetValueFromIndex(newIndex - 1, presetKey, presets); handleRawOnValueChange(newValue); }, withInputField: false, "aria-valuenow": presetIndex !== void 0 ? presetIndex + 1 : 0, "aria-valuetext": marks[presetIndex !== void 0 ? presetIndex + 1 : 0].tooltip, renderTooltipContent: (index) => marks[!index ? 0 : index].tooltip, min: 0, max: marks.length - 1, marks, label: LABELS[side], hideLabelFromVision: true }), hasPresets && /* @__PURE__ */ jsx(Button, { label: showCustomValueControl ? __("Use size preset") : __("Set custom size"), icon: settings, onClick: () => { setShowCustomValueControl(!showCustomValueControl); }, isPressed: showCustomValueControl, size: "small", iconSize: 24 }) ] }, `box-control-${side}`); } export { BoxInputControl as default }; //# sourceMappingURL=box-input-control.mjs.map