UNPKG

@wordpress/components

Version:
251 lines (250 loc) • 10.3 kB
import clsx from "clsx"; import { useInstanceId } from "@wordpress/compose"; import { useState } from "@wordpress/element"; import { __ } from "@wordpress/i18n"; import warning from "@wordpress/warning"; import { BaseControl } from "../base-control/index.mjs"; import BoxInputControl from "./box-input-control.mjs"; import LinkedButton from "./linked-button.mjs"; import Button from "../button/index.mjs"; import { Grid } from "../grid/index.mjs"; import { HStack } from "../h-stack/index.mjs"; import { DEFAULT_VALUES, getAllowedSides, getSelectedUnits, isValueMixed, isValuesDefined } from "./utils.mjs"; import { useControlledState } from "../utils/hooks/index.mjs"; import { 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/index.tsx const defaultInputProps = { min: 0 }; const noop = () => {}; function useUniqueId(idProp) { const instanceId = useInstanceId(BoxControl, "inspector-box-control"); return idProp || instanceId; } /** * A control that lets users set values for top, right, bottom, and left. Can be * used as an input control for values like `padding` or `margin`. * * ```jsx * import { useState } from 'react'; * import { BoxControl } from '@wordpress/components'; * * function Example() { * const [ values, setValues ] = useState( { * top: '50px', * left: '10%', * right: '10%', * bottom: '50px', * } ); * * return ( * <BoxControl values={ values } onChange={ setValues } /> * ); * }; * ``` */ function BoxControl({ id: idProp, inputProps = defaultInputProps, onChange = noop, label = __("Box Control"), values: valuesProp, units, sides, splitOnAxis = false, allowReset = true, resetValues = DEFAULT_VALUES, presets, presetKey, onMouseOver, onMouseOut }) { const [values, setValues] = useControlledState(valuesProp, { fallback: DEFAULT_VALUES }); const inputValues = values || DEFAULT_VALUES; const hasInitialValue = isValuesDefined(valuesProp); const hasOneSide = sides?.length === 1; const [isDirty, setIsDirty] = useState(hasInitialValue); const [isLinked, setIsLinked] = useState(!hasInitialValue || !isValueMixed(inputValues) || hasOneSide); const [selectedUnits, setSelectedUnits] = useState(getSelectedUnits(valuesProp)); const id = useUniqueId(idProp); const headingId = `${id}-heading`; const toggleLinked = () => { setIsLinked(!isLinked); }; const handleOnChange = (nextValues) => { onChange(nextValues); setValues(nextValues); setIsDirty(true); }; const handleOnReset = () => { onChange(resetValues); setValues(resetValues); setSelectedUnits(getSelectedUnits(resetValues)); setIsDirty(false); }; const inputControlProps = { onMouseOver, onMouseOut, ...inputProps, onChange: handleOnChange, isLinked, units, selectedUnits, setSelectedUnits, sides, values: inputValues, presets, presetKey }; const sidesToRender = getAllowedSides(sides); if (presets && !presetKey || !presets && presetKey) warning(`wp.components.BoxControl: the '${presets ? "presetKey" : "presets"}' prop is required when the '${presets ? "presets" : "presetKey"}' prop is defined.`); return /* @__PURE__ */ jsxs(Grid, { id, columns: 3, templateColumns: "1fr min-content min-content", role: "group", "aria-labelledby": headingId, children: [ /* @__PURE__ */ jsx(BaseControl.VisualLabel, { id: headingId, children: label }), isLinked && /* @__PURE__ */ jsx(HStack, { className: style_module_default["input-wrapper"], children: /* @__PURE__ */ jsx(BoxInputControl, { side: "all", ...inputControlProps }) }), !hasOneSide && /* @__PURE__ */ jsx("div", { className: style_module_default["linked-button-wrapper"], children: /* @__PURE__ */ jsx(LinkedButton, { onClick: toggleLinked, isLinked }) }), !isLinked && splitOnAxis && ["vertical", "horizontal"].map((axis) => /* @__PURE__ */ jsx(BoxInputControl, { side: axis, ...inputControlProps }, axis)), !isLinked && !splitOnAxis && Array.from(sidesToRender).map((axis) => /* @__PURE__ */ jsx(BoxInputControl, { side: axis, ...inputControlProps }, axis)), allowReset && /* @__PURE__ */ jsx(Button, { className: clsx(style_module_default["reset-button"], "component-box-control__reset-button"), variant: "secondary", size: "small", onClick: handleOnReset, disabled: !isDirty, accessibleWhenDisabled: true, children: __("Reset") }) ] }); } export { BoxControl as default }; //# sourceMappingURL=index.mjs.map