@wordpress/components
Version:
UI components for WordPress.
284 lines (283 loc) • 11.9 kB
JavaScript
import clsx from "clsx";
import { colord, extend, getFormat } from "colord";
import namesPlugin from "colord/plugins/names";
import { useCallback, useEffect, useMemo, useRef, useState } from "@wordpress/element";
import { __ } from "@wordpress/i18n";
import { Select, useEnableWpCompatOverlaySlot } from "@wordpress/ui";
import { contextConnect, useContextSystem } from "../context/index.mjs";
import { HStack } from "../h-stack/index.mjs";
import { Flex } from "../flex/index.mjs";
import { PolymorphicElement } from "../utils/polymorphic-element.mjs";
import { ColorCopyButton } from "./color-copy-button.mjs";
import { ColorInput } from "./color-input.mjs";
import { Picker } from "./picker.mjs";
import { useControlledValue } 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/color-picker/style.module.scss
if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("7c9da4804d", ".fc84b54ab7eadaac__prefix{color:var(--wp-components-color-accent,var(--wp-admin-theme-color,#3858e9))}._0931450c28ea78af__number-control{width:96px}.d5340e8c9e22c868__select{margin-left:-8px}._96be3f8f4bf140d7__range{flex:1;margin-right:8px}.ba153a3ef3adbfdc__auxiliary{padding:8px 0 0}._8b76d21b029c2e21__header{padding-inline:16px}._10f48d0e75fe17ef__color-input{padding-block:16px 20px;padding-left:16px;padding-right:12px}.a2ba900a769046e5__colorful{box-sizing:border-box}.a2ba900a769046e5__colorful *,.a2ba900a769046e5__colorful :after,.a2ba900a769046e5__colorful :before{box-sizing:inherit}.a2ba900a769046e5__colorful{width:216px}.a2ba900a769046e5__colorful .react-colorful{align-items:center;display:flex;flex-direction:column;height:auto;width:216px}.a2ba900a769046e5__colorful .react-colorful__saturation{border-bottom:none;border-radius:0;height:216px;margin-bottom:16px;width:100%}.a2ba900a769046e5__colorful .react-colorful__alpha,.a2ba900a769046e5__colorful .react-colorful__hue{border-radius:9999px;height:16px;margin-bottom:8px;width:184px}.a2ba900a769046e5__colorful .react-colorful__pointer{border:none;box-shadow:0 0 2px 0 rgba(0,0,0,.25);height:16px;outline:2px solid transparent;width:16px}@media not (prefers-reduced-motion){.a2ba900a769046e5__colorful .react-colorful__pointer{transition:transform .16s ease-in-out}}.a2ba900a769046e5__colorful .react-colorful__interactive:focus .react-colorful__pointer{border:1.5px solid #000;box-shadow:0 0 0 1.5px #fff;transform:translate(-50%,-50%) scale(1.5)}.a2ba900a769046e5__colorful .react-colorful__pointer-fill{box-shadow:inset 0 0 0 1.5px #fff}.a2ba900a769046e5__colorful .react-colorful__interactive{margin-left:4px;width:calc(100% - 8px)}");
var style_module_default = {
"prefix": "fc84b54ab7eadaac__prefix",
"number-control": "_0931450c28ea78af__number-control",
"select": "d5340e8c9e22c868__select",
"range": "_96be3f8f4bf140d7__range",
"auxiliary": "ba153a3ef3adbfdc__auxiliary",
"header": "_8b76d21b029c2e21__header",
"color-input": "_10f48d0e75fe17ef__color-input",
"colorful": "a2ba900a769046e5__colorful"
};
// packages/components/src/color-picker/component.tsx
extend([namesPlugin]);
/**
* Merges incoming HSLA with previous state, preserving hue for achromatic
* colors and saturation only at lightness extremes (black/white) where
* it has no visual effect.
*/
function mergeHSLA(nextHSLA, prevHSLA) {
if (nextHSLA.s === 0) {
if (nextHSLA.l === 0 || nextHSLA.l === 100) return {
...nextHSLA,
h: prevHSLA.h,
s: prevHSLA.s
};
return {
...nextHSLA,
h: prevHSLA.h
};
}
return nextHSLA;
}
const options = [
{
label: "RGB",
value: "rgb"
},
{
label: "HSL",
value: "hsl"
},
{
label: "Hex",
value: "hex"
}
];
const UnconnectedColorPicker = (props, forwardedRef) => {
useEnableWpCompatOverlaySlot();
const { enableAlpha = false, color: colorProp, onChange, defaultValue = "#fff", copyFormat, className, ...divProps } = useContextSystem(props, "ColorPicker");
const [color, setColor] = useControlledValue({
onChange,
value: colorProp,
defaultValue
});
const safeColordColor = useMemo(() => {
return colord(color || "");
}, [color]);
const [internalHSLA, setInternalHSLA] = useState(() => ({ ...safeColordColor.toHsl() }));
const lastProducedHexRef = useRef(safeColordColor.toHex());
const isPickerInteractingRef = useRef(false);
useEffect(() => {
if (isPickerInteractingRef.current) return;
if (safeColordColor.isEqual(lastProducedHexRef.current)) return;
lastProducedHexRef.current = safeColordColor.toHex();
const externalHSLA = safeColordColor.toHsl();
setInternalHSLA((prev) => mergeHSLA(externalHSLA, prev));
}, [safeColordColor]);
const handleHSLAChange = useCallback((nextHSLA) => {
const previousHex = lastProducedHexRef.current;
const isAlphaOnlyChange = nextHSLA.h === internalHSLA.h && nextHSLA.s === internalHSLA.s && nextHSLA.l === internalHSLA.l;
setInternalHSLA(nextHSLA);
const nextHex = isAlphaOnlyChange ? colord(previousHex).alpha(nextHSLA.a).toHex() : colord(nextHSLA).toHex();
if (!colord(nextHex).isEqual(previousHex)) {
lastProducedHexRef.current = nextHex;
setColor(nextHex);
}
}, [internalHSLA, setColor]);
const handleChange = useCallback((nextValue) => {
const nextHSLA = nextValue.toHsl();
setInternalHSLA((prev) => mergeHSLA(nextHSLA, prev));
const nextHex = nextValue.toHex();
lastProducedHexRef.current = nextHex;
setColor(nextHex);
}, [setColor]);
const [colorType, setColorType] = useState(copyFormat || "hex");
const maybeHandlePaste = useCallback((event) => {
const pastedText = event.clipboardData?.getData("text")?.trim();
if (!pastedText) return;
const parsedColor = colord(pastedText);
if (!parsedColor.isValid()) return;
handleChange(parsedColor);
const newColorType = {
hex: "hex",
rgb: "rgb",
hsl: "hsl"
}[String(getFormat(pastedText))];
if (newColorType) setColorType(newColorType);
event.stopPropagation();
event.preventDefault();
}, [handleChange, setColorType]);
return /* @__PURE__ */ jsxs(PolymorphicElement, {
ref: forwardedRef,
...divProps,
className: clsx(style_module_default.colorful, className),
onPasteCapture: maybeHandlePaste,
children: [/* @__PURE__ */ jsx(Picker, {
onChange: handleHSLAChange,
hsla: internalHSLA,
enableAlpha,
onInteractionStart: () => {
isPickerInteractingRef.current = true;
},
onInteractionEnd: () => {
isPickerInteractingRef.current = false;
}
}), /* @__PURE__ */ jsxs("div", {
className: style_module_default.auxiliary,
children: [/* @__PURE__ */ jsxs(HStack, {
className: style_module_default.header,
justify: "space-between",
children: [/* @__PURE__ */ jsxs(Select.Root, {
items: options,
value: colorType,
onValueChange: (nextColorType) => {
if (nextColorType !== null) setColorType(nextColorType);
},
children: [/* @__PURE__ */ jsx(Select.Trigger, {
size: "compact",
variant: "minimal",
"aria-label": __("Color format"),
className: style_module_default.select
}), /* @__PURE__ */ jsx(Select.Popup, {
width: "content",
children: options.map((option) => /* @__PURE__ */ jsx(Select.Item, {
value: option.value,
children: /* @__PURE__ */ jsx(Select.ItemLabel, { children: option.label })
}, option.value))
})]
}), /* @__PURE__ */ jsx(ColorCopyButton, {
color: safeColordColor,
colorType: copyFormat || colorType
})]
}), /* @__PURE__ */ jsx(Flex, {
className: style_module_default["color-input"],
direction: "column",
gap: 2,
children: /* @__PURE__ */ jsx(ColorInput, {
colorType,
color: safeColordColor,
hsla: internalHSLA,
onChange: handleChange,
onHSLChange: handleHSLAChange,
enableAlpha
})
})]
})]
});
};
/**
* `ColorPicker` lets users select a color from a visual color surface, or by
* editing its hex, RGB, or HSL values.
*/
const ColorPicker = contextConnect(UnconnectedColorPicker, "ColorPicker");
export { ColorPicker, ColorPicker as default };
//# sourceMappingURL=component.mjs.map