UNPKG

@wordpress/components

Version:
318 lines (317 loc) • 12.4 kB
import { colord, extend } from "colord"; import namesPlugin from "colord/plugins/names"; import a11yPlugin from "colord/plugins/a11y"; import clsx from "clsx"; import { useInstanceId } from "@wordpress/compose"; import { __, sprintf } from "@wordpress/i18n"; import { forwardRef, useCallback, useMemo, useState } from "@wordpress/element"; import Dropdown from "../dropdown/index.mjs"; import { ColorPicker } from "../color-picker/index.mjs"; import CircularOptionPicker, { getComputeCircularOptionPickerCommonProps, warnIfCircularOptionPickerAsButtonsIsSet } from "../circular-option-picker/index.mjs"; import { VStack } from "../v-stack/index.mjs"; import { Truncate } from "../truncate/index.mjs"; import { Heading } from "../heading/index.mjs"; import DropdownContentWrapper from "../dropdown/dropdown-content-wrapper.mjs"; import { extractColorNameFromCurrentValue, isMultiplePaletteArray, normalizeColorValue } from "./utils.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-palette/style.module.scss if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("ba988b4dc4", ".d557a658e7010f86__color-heading{text-transform:uppercase}.d557a658e7010f86__color-heading.d557a658e7010f86__color-heading.d557a658e7010f86__color-heading{font-size:11px;line-height:24px;margin-bottom:0}"); var style_module_default = { "color-heading": "d557a658e7010f86__color-heading" }; // packages/components/src/color-palette/index.tsx extend([namesPlugin, a11yPlugin]); function SinglePalette({ className, clearColor, colors, onChange, value, selectedSlug, presentation, ...additionalProps }) { const colorOptions = useMemo(() => { return colors.map(({ color, name, slug }, index) => { const colordColor = colord(color); const isSelected = presentation !== "command-buttons" && (selectedSlug ? slug === selectedSlug : value === color); return /* @__PURE__ */ jsx(CircularOptionPicker.Option, { isSelected, selectedIconProps: isSelected ? { color: colordColor.contrast() > colordColor.contrast("#000") ? "#fff" : "#000" } : {}, tooltipText: name || sprintf(__("Color code: %s"), color), style: { backgroundColor: color, color }, onClick: isSelected ? clearColor : () => onChange(color, index, slug) }, slug ?? `${color}-${index}`); }); }, [ colors, value, selectedSlug, onChange, clearColor, presentation ]); return /* @__PURE__ */ jsx(CircularOptionPicker.OptionGroup, { className, options: colorOptions, ...additionalProps }); } function MultiplePalettes({ className, clearColor, colors, onChange, value, selectedSlug, headingLevel, presentation }) { const instanceId = useInstanceId(MultiplePalettes, "color-palette"); if (colors.length === 0) return null; return /* @__PURE__ */ jsx(VStack, { spacing: 3, className, children: colors.map(({ name, colors: colorPalette }, index) => { const id = `${instanceId}-${index}`; return /* @__PURE__ */ jsxs(VStack, { spacing: 2, children: [/* @__PURE__ */ jsx(Heading, { className: style_module_default["color-heading"], id, level: headingLevel, children: name }), /* @__PURE__ */ jsx(SinglePalette, { clearColor, colors: colorPalette, onChange: (newColor, _colorIndex, slug) => onChange(newColor, index, slug), value, selectedSlug, presentation, "aria-labelledby": id })] }, index); }) }); } function CustomColorPickerDropdown({ isRenderedInSidebar, popoverProps: receivedPopoverProps, ...props }) { const popoverProps = useMemo(() => ({ shift: true, resize: false, ...isRenderedInSidebar ? { placement: "left-start", offset: 34 } : { placement: "bottom", offset: 8 }, ...receivedPopoverProps }), [isRenderedInSidebar, receivedPopoverProps]); return /* @__PURE__ */ jsx(Dropdown, { contentClassName: "components-color-palette__custom-color-dropdown-content", popoverProps, ...props }); } function UnforwardedColorPalette(props, forwardedRef) { const { asButtons, presentation, loop, clearable = true, colors = [], disableCustomColors = false, enableAlpha = false, onChange, value, selectedSlug, __experimentalIsRenderedInSidebar = false, headingLevel = 2, "aria-label": ariaLabel, "aria-labelledby": ariaLabelledby, ...additionalProps } = props; warnIfCircularOptionPickerAsButtonsIsSet("ColorPalette", asButtons); const [normalizedColorValue, setNormalizedColorValue] = useState(value); const clearColor = useCallback(() => onChange(void 0), [onChange]); const customColorPaletteCallbackRef = useCallback((node) => { setNormalizedColorValue(normalizeColorValue(value, node)); }, [value]); const hasMultipleColorOrigins = isMultiplePaletteArray(colors); const buttonLabelName = useMemo(() => extractColorNameFromCurrentValue(value, colors, hasMultipleColorOrigins, selectedSlug), [ value, colors, hasMultipleColorOrigins, selectedSlug ]); const renderCustomColorPicker = () => /* @__PURE__ */ jsx(DropdownContentWrapper, { paddingSize: "none", children: /* @__PURE__ */ jsx(ColorPicker, { color: normalizedColorValue, onChange: (color) => onChange(color), enableAlpha }) }); const isHex = value?.startsWith("#"); const displayValue = value?.replace(/^var\((.+)\)$/, "$1"); const customColorAccessibleLabel = !!displayValue ? sprintf(__("Custom color picker. The currently selected color is called \"%1$s\" and has a value of \"%2$s\"."), buttonLabelName, displayValue) : __("Custom color picker"); const { metaProps, labelProps, resolvedPresentation } = getComputeCircularOptionPickerCommonProps(asButtons, loop, ariaLabel, ariaLabelledby, presentation); const paletteCommonProps = { clearColor, onChange, value, selectedSlug, presentation: resolvedPresentation }; const actions = !!clearable && /* @__PURE__ */ jsx(CircularOptionPicker.ButtonAction, { onClick: clearColor, accessibleWhenDisabled: true, disabled: !value, children: __("Clear") }); if (disableCustomColors && colors.length === 0 && !actions) return null; return /* @__PURE__ */ jsxs(VStack, { spacing: 3, ref: forwardedRef, ...additionalProps, children: [!disableCustomColors && /* @__PURE__ */ jsx(CustomColorPickerDropdown, { isRenderedInSidebar: __experimentalIsRenderedInSidebar, renderContent: renderCustomColorPicker, renderToggle: ({ isOpen, onToggle }) => /* @__PURE__ */ jsxs(VStack, { className: "components-color-palette__custom-color-wrapper", spacing: 0, children: [/* @__PURE__ */ jsx("button", { ref: customColorPaletteCallbackRef, className: "components-color-palette__custom-color-button", "aria-expanded": isOpen, "aria-haspopup": "true", onClick: onToggle, "aria-label": customColorAccessibleLabel, style: { background: value }, type: "button" }), /* @__PURE__ */ jsxs(VStack, { className: "components-color-palette__custom-color-text-wrapper", spacing: .5, children: [/* @__PURE__ */ jsx(Truncate, { className: "components-color-palette__custom-color-name", children: value ? buttonLabelName : __("No color selected") }), /* @__PURE__ */ jsx(Truncate, { className: clsx("components-color-palette__custom-color-value", { "components-color-palette__custom-color-value--is-hex": isHex }), children: displayValue })] })] }) }), (colors.length > 0 || actions) && /* @__PURE__ */ jsx(CircularOptionPicker, { ...metaProps, ...labelProps, actions, options: hasMultipleColorOrigins ? /* @__PURE__ */ jsx(MultiplePalettes, { ...paletteCommonProps, headingLevel, colors, value }) : /* @__PURE__ */ jsx(SinglePalette, { ...paletteCommonProps, colors, value }) })] }); } /** * Allows the user to pick a color from a list of pre-defined color entries. * * ```jsx * import { ColorPalette } from '@wordpress/components'; * import { useState } from '@wordpress/element'; * * const MyColorPalette = () => { * const [ color, setColor ] = useState ( '#f00' ) * const colors = [ * { name: 'red', color: '#f00' }, * { name: 'white', color: '#fff' }, * { name: 'blue', color: '#00f' }, * ]; * return ( * <ColorPalette * colors={ colors } * value={ color } * onChange={ ( color ) => setColor( color ) } * /> * ); * } ); * ``` */ const ColorPalette = forwardRef(UnforwardedColorPalette); ColorPalette.displayName = "ColorPalette"; export { ColorPalette, ColorPalette as default, CustomColorPickerDropdown }; //# sourceMappingURL=index.mjs.map