@wordpress/components
Version:
UI components for WordPress.
738 lines (737 loc) • 31.3 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
// \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
key = keys[i];
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
get: ((k) => from[k]).bind(null, key),
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
});
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
value: mod,
enumerable: true
}) : target, mod));
let clsx = require("clsx");
clsx = __toESM(clsx);
let colord = require("colord");
let colord_plugins_names = require("colord/plugins/names");
colord_plugins_names = __toESM(colord_plugins_names);
let _wordpress_element = require("@wordpress/element");
let _wordpress_i18n = require("@wordpress/i18n");
let _wordpress_icons = require("@wordpress/icons");
let _wordpress_compose = require("@wordpress/compose");
let _wordpress_ui = require("@wordpress/ui");
let ___button_index_tsx = require("../button/index.cjs");
___button_index_tsx = __toESM(___button_index_tsx);
let ___color_picker_index_ts = require("../color-picker/index.cjs");
let ___flex_index_ts = require("../flex/index.cjs");
let ___h_stack_index_ts = require("../h-stack/index.cjs");
let ___item_group_index_ts = require("../item-group/index.cjs");
let ___v_stack_index_ts = require("../v-stack/index.cjs");
let ___gradient_picker_index_tsx = require("../gradient-picker/index.cjs");
___gradient_picker_index_tsx = __toESM(___gradient_picker_index_tsx);
let ___color_palette_index_tsx = require("../color-palette/index.cjs");
___color_palette_index_tsx = __toESM(___color_palette_index_tsx);
let ___duotone_picker_index_ts = require("../duotone-picker/index.cjs");
let ___duotone_picker_color_list_picker_index_tsx = require("../duotone-picker/color-list-picker/index.cjs");
___duotone_picker_color_list_picker_index_tsx = __toESM(___duotone_picker_color_list_picker_index_tsx);
let ___duotone_picker_custom_duotone_bar_tsx = require("../duotone-picker/custom-duotone-bar.cjs");
___duotone_picker_custom_duotone_bar_tsx = __toESM(___duotone_picker_custom_duotone_bar_tsx);
let ___duotone_picker_utils_ts = require("../duotone-picker/utils.cjs");
let ___popover_index_tsx = require("../popover/index.cjs");
___popover_index_tsx = __toESM(___popover_index_tsx);
let ___heading_index_ts = require("../heading/index.cjs");
let ___view_index_ts = require("../view/index.cjs");
let ___input_control_index_tsx = require("../input-control/index.cjs");
___input_control_index_tsx = __toESM(___input_control_index_tsx);
let ___color_indicator_index_tsx = require("../color-indicator/index.cjs");
___color_indicator_index_tsx = __toESM(___color_indicator_index_tsx);
let ___visually_hidden_index_ts = require("../visually-hidden/index.cjs");
let ___custom_gradient_picker_constants_ts = require("../custom-gradient-picker/constants.cjs");
let ___custom_gradient_picker_index_tsx = require("../custom-gradient-picker/index.cjs");
___custom_gradient_picker_index_tsx = __toESM(___custom_gradient_picker_index_tsx);
let react_jsx_runtime = require("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/palette-edit/style.module.scss
if (typeof process === "undefined" || process.env.NODE_ENV !== "test") registerStyle("f4eb55addf", ".ce4c8b60ce26cd40__indicator.ce4c8b60ce26cd40__indicator{flex-shrink:0;height:24px;width:24px}._27b731a5fa03652c__name-input .components-input-control__container{background:#f0f0f0;border-radius:1px}._27b731a5fa03652c__name-input .components-input-control__container .components-input-control__input.components-input-control__input.components-input-control__input.components-input-control__input{height:32px}._27b731a5fa03652c__name-input .components-input-control__container .components-input-control__backdrop.components-input-control__backdrop.components-input-control__backdrop{border-color:transparent;box-shadow:none}._90fbcd29050eff95__name{line-height:32px;margin-inline:8px;overflow:hidden;white-space:nowrap}.e267ee4e2f5fccb1__heading{font-weight:600;text-transform:uppercase}.e267ee4e2f5fccb1__heading.e267ee4e2f5fccb1__heading.e267ee4e2f5fccb1__heading{font-size:11px;line-height:24px;margin-bottom:0}.b15e60b747d187cb__contents{margin-top:8px}._1c9bfc0b814efd11__palette._1c9bfc0b814efd11__palette._1c9bfc0b814efd11__palette .components-button.has-icon{min-width:0;padding:0}._6bce1c1c19fe8564__done._6bce1c1c19fe8564__done{color:var(--wp-components-color-accent,var(--wp-admin-theme-color,#3858e9))}.f9865da1ded0a784__remove.f9865da1ded0a784__remove{margin-top:4px}");
var style_module_default = {
"indicator": "ce4c8b60ce26cd40__indicator",
"name-input": "_27b731a5fa03652c__name-input",
"name": "_90fbcd29050eff95__name",
"heading": "e267ee4e2f5fccb1__heading",
"contents": "b15e60b747d187cb__contents",
"palette": "_1c9bfc0b814efd11__palette",
"done": "_6bce1c1c19fe8564__done",
"remove": "f9865da1ded0a784__remove"
};
// packages/components/src/palette-edit/index.tsx
(0, colord.extend)([colord_plugins_names.default]);
const DEFAULT_COLOR = "#000";
/**
* Filters a color palette down to the colors a duotone can actually be built
* from, and normalizes each one to hex.
*
* Duotone values are turned into SVG filter matrices, so each color has to
* resolve to a concrete value. A theme palette may legitimately contain CSS
* that does not, such as `color-mix()` or `currentColor` — Twenty Twenty-Five
* ships one — and picking such a color would produce a duotone that neither the
* editor nor the front end can render.
*
* Surviving colors are normalized because the two ends disagree on syntax. The
* front end parses duotone colors with a PHP port of colord that only accepts
* hex, `rgb()` and `hsl()` (`WP_Duotone::colord_parse`), while colord in the
* editor also accepts CSS named colors such as `red`, since `namesPlugin` is
* registered. Passing a palette value straight through would let a named color
* be saved as a duotone that renders in the editor and is dropped, with a
* `_doing_it_wrong` notice, on the front end.
*
* @param colorPalette The colors to filter.
*
* @return The colors usable in a duotone, as hex.
*/
function getUsableDuotoneColors(colorPalette = []) {
return colorPalette.flatMap((paletteColor) => {
if (typeof paletteColor.color !== "string") return [];
const parsed = (0, colord.colord)(paletteColor.color);
return parsed.isValid() ? [{
...paletteColor,
color: parsed.toHex()
}] : [];
});
}
/**
* Reads the colors off a duotone element. Duotone presets can come from a
* theme's `theme.json`, so the value is not guaranteed to be an array.
*
* @param element The palette element.
*
* @return The duotone's colors, or an empty array if it has none usable.
*/
function getDuotoneColors(element) {
const colors = element?.colors;
return Array.isArray(colors) ? colors : [];
}
/**
* Returns the single CSS value that represents a palette element, used both for
* its swatch and for the labels that refer to it. Duotones have two colors, so
* they are represented by the same gradient the duotone swatches use.
*
* @param element The palette element.
* @param variant The kind of preset being edited.
*
* @return A CSS color or gradient string.
*/
function getElementValue(element, variant) {
if (!element) return;
switch (variant) {
case "duotone": return (0, ___duotone_picker_utils_ts.getGradientFromCSSColors)(getDuotoneColors(element), "135deg");
case "gradient": return element.gradient;
default: return element.color;
}
}
/**
* Returns the hidden label for the name input of a palette element.
*
* @param variant The kind of preset being edited.
*/
function getNameInputLabel(variant) {
switch (variant) {
case "duotone": return (0, _wordpress_i18n.__)("Duotone name");
case "gradient": return (0, _wordpress_i18n.__)("Gradient name");
default: return (0, _wordpress_i18n.__)("Color name");
}
}
/**
* Returns the `sprintf` format string for the remove button label.
*
* @param variant The kind of preset being edited.
*/
function getRemoveLabelFormat(variant) {
return variant === "duotone" ? (0, _wordpress_i18n.__)("Remove duotone: %s") : (0, _wordpress_i18n.__)("Remove color: %s");
}
/**
* Returns the label for the button that adds a new palette element.
*
* @param variant The kind of preset being edited.
*/
function getAddLabel(variant) {
switch (variant) {
case "duotone": return (0, _wordpress_i18n.__)("Add duotone");
case "gradient": return (0, _wordpress_i18n.__)("Add gradient");
default: return (0, _wordpress_i18n.__)("Add color");
}
}
/**
* Returns the label for the palette's options menu.
*
* @param variant The kind of preset being edited.
*/
function getOptionsLabel(variant) {
switch (variant) {
case "duotone": return (0, _wordpress_i18n.__)("Duotone options");
case "gradient": return (0, _wordpress_i18n.__)("Gradient options");
default: return (0, _wordpress_i18n.__)("Color options");
}
}
/**
* Returns the label for the menu item that empties the palette.
*
* @param variant The kind of preset being edited.
*/
function getRemoveAllLabel(variant) {
switch (variant) {
case "duotone": return (0, _wordpress_i18n.__)("Remove all duotones");
case "gradient": return (0, _wordpress_i18n.__)("Remove all gradients");
default: return (0, _wordpress_i18n.__)("Remove all colors");
}
}
/**
* Returns the label for the menu item that resets the palette.
*
* @param variant The kind of preset being edited.
*/
function getResetLabel(variant) {
switch (variant) {
case "duotone": return (0, _wordpress_i18n.__)("Reset duotones");
case "gradient": return (0, _wordpress_i18n.__)("Reset gradient");
default: return (0, _wordpress_i18n.__)("Reset colors");
}
}
function NameInput({ value, onChange, label }) {
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___input_control_index_tsx.default, {
className: style_module_default["name-input"],
size: "compact",
label,
hideLabelFromVision: true,
value,
onChange
});
}
function deduplicateElementSlugs(elements) {
const usedSlugs = new Set(elements.map(({ slug }) => slug));
const nextSuffixes = /* @__PURE__ */ new Map();
return elements.map((element) => {
const { slug } = element;
let newSlug = slug;
let suffix = nextSuffixes.get(slug) ?? 1;
if (nextSuffixes.has(slug)) {
do {
newSlug = `${slug}-${suffix}`;
suffix++;
} while (usedSlugs.has(newSlug));
usedSlugs.add(newSlug);
}
nextSuffixes.set(slug, suffix);
return {
...element,
slug: newSlug
};
});
}
/**
* Returns a name and slug for a palette item. The name takes the format "Color + id".
* To ensure there are no duplicate ids, this function checks all slugs.
* It expects slugs to be in the format: slugPrefix + color- + number.
* It then sets the id component of the new name based on the incremented id of the highest existing slug id.
*
* @param elements An array of color palette items.
* @param slugPrefix The slug prefix used to match the element slug.
* @param variant The kind of preset being edited. Duotones are named
* "Duotone + id" and slugged with a `duotone-` stem;
* colors and gradients both use `color-`.
*
* @return A name and slug for the new palette item.
*/
function getNameAndSlugForPosition(elements, slugPrefix, variant = "color") {
const stem = variant === "duotone" ? "duotone" : "color";
const nameRegex = new RegExp(`^${slugPrefix}${stem}-([\\d]+)$`);
const position = elements.reduce((previousValue, currentValue) => {
if (typeof currentValue?.slug === "string") {
const matches = currentValue?.slug.match(nameRegex);
if (matches) {
const id = parseInt(matches[1], 10);
if (id >= previousValue) return id + 1;
}
}
return previousValue;
}, 1);
return {
name: variant === "duotone" ? (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n.__)("Duotone %d"), position) : (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n.__)("Color %d"), position),
slug: `${slugPrefix}${stem}-${position}`
};
}
function ColorPickerPopover({ variant, colorPalette, element, onChange, popoverProps: receivedPopoverProps, onClose = () => {} }) {
const dismissButton = /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___visually_hidden_index_ts.VisuallyHidden, {
as: "button",
type: "button",
tabIndex: -1,
onClick: onClose,
children: (0, _wordpress_i18n.__)("Close")
});
const popoverProps = (0, _wordpress_element.useMemo)(() => ({
shift: true,
offset: 20,
resize: false,
placement: "left-start",
...receivedPopoverProps,
className: (0, clsx.default)("components-palette-edit__popover", receivedPopoverProps?.className)
}), [receivedPopoverProps]);
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(___popover_index_tsx.default, {
role: "dialog",
"aria-label": (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n.__)("Edit: %s"), element.name.trim().length ? element.name : getElementValue(element, variant) || ""),
...popoverProps,
onClose,
children: [
dismissButton,
variant === "color" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___color_picker_index_ts.ColorPicker, {
color: element.color,
enableAlpha: true,
onChange: (newColor) => {
onChange({
...element,
color: newColor
});
}
}),
variant === "gradient" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "components-palette-edit__popover-gradient-picker",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___custom_gradient_picker_index_tsx.default, {
__experimentalIsRenderedInSidebar: true,
value: element.gradient,
onChange: (newGradient) => {
onChange({
...element,
gradient: newGradient
});
}
})
}),
variant === "duotone" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: "components-palette-edit__popover-duotone-picker",
children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(___v_stack_index_ts.VStack, {
spacing: 3,
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(___duotone_picker_custom_duotone_bar_tsx.default, {
value: getDuotoneColors(element),
onChange: (newColors) => {
if (!newColors?.length) return;
onChange({
...element,
colors: newColors
});
}
}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___duotone_picker_color_list_picker_index_tsx.default, {
labels: [(0, _wordpress_i18n.__)("Shadows"), (0, _wordpress_i18n.__)("Highlights")],
colors: colorPalette ?? [],
value: getDuotoneColors(element),
enableAlpha: true,
onChange: (newColors) => {
const [defaultDark, defaultLight] = (0, ___duotone_picker_utils_ts.getDefaultColors)(colorPalette ?? []);
onChange({
...element,
colors: [newColors[0] || defaultDark, newColors[1] || defaultLight]
});
}
})]
})
}),
dismissButton
]
});
}
function Option({ canOnlyChangeValues, element, onChange, onRemove, popoverProps: receivedPopoverProps, variant, colorPalette }) {
const value = getElementValue(element, variant);
const [isEditingColor, setIsEditingColor] = (0, _wordpress_element.useState)(false);
const [popoverAnchor, setPopoverAnchor] = (0, _wordpress_element.useState)(null);
const popoverProps = (0, _wordpress_element.useMemo)(() => ({
...receivedPopoverProps,
anchor: popoverAnchor
}), [popoverAnchor, receivedPopoverProps]);
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(___item_group_index_ts.Item, {
ref: setPopoverAnchor,
size: "small",
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(___h_stack_index_ts.HStack, {
justify: "flex-start",
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(___button_index_tsx.default, {
size: "small",
onClick: () => {
setIsEditingColor(true);
},
"aria-label": (0, _wordpress_i18n.sprintf)((0, _wordpress_i18n.__)("Edit: %s"), element.name.trim().length ? element.name : value || ""),
style: { padding: 0 },
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___color_indicator_index_tsx.default, {
className: style_module_default.indicator,
colorValue: value
})
}),
/* @__PURE__ */ (0, react_jsx_runtime.jsx)(___flex_index_ts.FlexBlock, { children: !canOnlyChangeValues ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NameInput, {
label: getNameInputLabel(variant),
value: element.name,
onChange: (nextName) => onChange({
...element,
name: nextName
})
}) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
className: style_module_default.name,
children: element.name.trim().length ? element.name : "\xA0"
}) }),
!canOnlyChangeValues && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___flex_index_ts.FlexItem, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___button_index_tsx.default, {
className: style_module_default.remove,
size: "small",
icon: _wordpress_icons.lineSolid,
label: (0, _wordpress_i18n.sprintf)(getRemoveLabelFormat(variant), element.name.trim().length ? element.name : value || ""),
onClick: onRemove
}) })
]
}), isEditingColor && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ColorPickerPopover, {
variant,
colorPalette,
onChange,
element,
popoverProps,
onClose: () => setIsEditingColor(false)
})]
});
}
function PaletteEditListView({ elements, onChange, canOnlyChangeValues, variant, colorPalette, popoverProps, addColorRef }) {
const elementsReferenceRef = (0, _wordpress_element.useRef)(void 0);
(0, _wordpress_element.useEffect)(() => {
elementsReferenceRef.current = elements;
}, [elements]);
const debounceOnChange = (0, _wordpress_compose.useDebounce)((updatedElements) => onChange(deduplicateElementSlugs(updatedElements)), 100);
return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___v_stack_index_ts.VStack, {
spacing: 3,
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___item_group_index_ts.ItemGroup, {
isRounded: true,
isBordered: true,
isSeparated: true,
children: elements.map((element, index) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Option, {
variant,
colorPalette,
canOnlyChangeValues,
element,
onChange: (newElement) => {
debounceOnChange(elements.map((currentElement, currentIndex) => {
if (currentIndex === index) return newElement;
return currentElement;
}));
},
onRemove: () => {
const newElements = elements.filter((_currentElement, currentIndex) => {
if (currentIndex === index) return false;
return true;
});
onChange(newElements.length ? newElements : void 0);
addColorRef.current?.focus();
},
popoverProps
}, index))
})
});
}
const EMPTY_ARRAY = [];
/**
* Allows editing a palette of colors, gradients or duotones.
*
* ```jsx
* import { PaletteEdit } from '@wordpress/components';
* const MyPaletteEdit = () => {
* const [ controlledColors, setControlledColors ] = useState( colors );
*
* return (
* <PaletteEdit
* colors={ controlledColors }
* onChange={ ( newColors?: Color[] ) => {
* setControlledColors( newColors );
* } }
* paletteLabel="Here is a label"
* />
* );
* };
* ```
*/
function PaletteEdit({ gradients, duotones, colors = EMPTY_ARRAY, colorPalette, onChange, paletteLabel, paletteLabelHeadingLevel = 2, emptyMessage, canOnlyChangeValues, canReset, slugPrefix = "", popoverProps }) {
(0, _wordpress_ui.useEnableWpCompatOverlaySlot)();
let variant = "color";
if (gradients) variant = "gradient";
else if (duotones) variant = "duotone";
const elements = gradients ?? duotones ?? colors;
const duotoneColorPalette = (0, _wordpress_element.useMemo)(() => getUsableDuotoneColors(colorPalette), [colorPalette]);
const [isEditing, setIsEditing] = (0, _wordpress_element.useState)(false);
const [editingElement, setEditingElement] = (0, _wordpress_element.useState)(null);
const isAdding = isEditing && !!editingElement && elements[editingElement] && !elements[editingElement].slug;
const hasElements = elements.length > 0;
const debounceOnChange = (0, _wordpress_compose.useDebounce)(onChange, 100);
const onSelectPaletteItem = (0, _wordpress_element.useCallback)((value, newEditingElementIndex) => {
const selectedElement = newEditingElementIndex === void 0 ? void 0 : elements[newEditingElementIndex];
if (!!selectedElement && selectedElement[variant === "gradient" ? "gradient" : "color"] === value) setEditingElement(newEditingElementIndex);
else setIsEditing(true);
}, [variant, elements]);
const onSelectDuotoneItem = (0, _wordpress_element.useCallback)((value, newEditingElementIndex) => {
if (newEditingElementIndex !== void 0 && (duotones ?? [])[newEditingElementIndex]) setEditingElement(newEditingElementIndex);
else setIsEditing(true);
}, [duotones]);
const addColorRef = (0, _wordpress_element.useRef)(null);
const paletteLabelId = (0, _wordpress_compose.useInstanceId)(PaletteEdit, "components-palette-edit__heading");
return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(___view_index_ts.View, {
className: style_module_default.palette,
children: [
/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(___h_stack_index_ts.HStack, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(___heading_index_ts.Heading, {
className: style_module_default.heading,
id: paletteLabelId,
level: paletteLabelHeadingLevel,
children: paletteLabel
}), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_wordpress_ui.Stack, {
direction: "row",
gap: "xs",
children: [
hasElements && isEditing && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___button_index_tsx.default, {
className: style_module_default.done,
size: "small",
onClick: () => {
setIsEditing(false);
setEditingElement(null);
},
children: (0, _wordpress_i18n.__)("Done")
}),
!canOnlyChangeValues && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___button_index_tsx.default, {
ref: addColorRef,
size: "small",
isPressed: isAdding,
icon: _wordpress_icons.plus,
label: getAddLabel(variant),
onClick: () => {
const { name, slug } = getNameAndSlugForPosition(elements, slugPrefix, variant);
if (!!gradients) onChange([...gradients, {
gradient: ___custom_gradient_picker_constants_ts.DEFAULT_GRADIENT,
name,
slug
}]);
else if (!!duotones) onChange([...duotones, {
colors: (0, ___duotone_picker_utils_ts.getDefaultColors)(duotoneColorPalette),
name,
slug
}]);
else onChange([...colors, {
color: DEFAULT_COLOR,
name,
slug
}]);
setIsEditing(true);
setEditingElement(elements.length);
}
}),
hasElements && (!isEditing || !canOnlyChangeValues || canReset) && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_wordpress_ui.Menu.Root, {
modal: false,
children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Menu.Trigger, { render: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___button_index_tsx.default, {
size: "small",
icon: _wordpress_icons.moreVertical,
label: getOptionsLabel(variant),
showTooltip: true
}) }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_wordpress_ui.Menu.Popup, {
positioner: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Menu.Positioner, { align: "end" }),
children: [
!isEditing && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Menu.Item, {
onClick: () => setIsEditing(true),
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Menu.ItemLabel, { children: (0, _wordpress_i18n.__)("Show details") })
}),
!canOnlyChangeValues && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Menu.Item, {
onClick: () => {
setEditingElement(null);
setIsEditing(false);
onChange();
},
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Menu.ItemLabel, { children: getRemoveAllLabel(variant) })
}),
canReset && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Menu.Item, {
onClick: () => {
setEditingElement(null);
onChange();
},
children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_wordpress_ui.Menu.ItemLabel, { children: getResetLabel(variant) })
})
]
})]
})
]
})] }),
hasElements && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(___view_index_ts.View, {
className: style_module_default.contents,
children: [
isEditing && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(PaletteEditListView, {
canOnlyChangeValues,
elements,
onChange,
variant,
colorPalette: duotoneColorPalette,
popoverProps,
addColorRef
}),
!isEditing && editingElement !== null && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ColorPickerPopover, {
variant,
colorPalette: duotoneColorPalette,
onClose: () => setEditingElement(null),
onChange: (newElement) => {
debounceOnChange(elements.map((currentElement, currentIndex) => {
if (currentIndex === editingElement) return newElement;
return currentElement;
}));
},
element: elements[editingElement ?? -1],
popoverProps
}),
!isEditing && variant === "gradient" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___gradient_picker_index_tsx.default, {
presentation: "command-buttons",
"aria-labelledby": paletteLabelId,
gradients,
onChange: onSelectPaletteItem,
clearable: false,
disableCustomGradients: true
}),
!isEditing && variant === "duotone" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___duotone_picker_index_ts.DuotonePicker, {
presentation: "command-buttons",
"aria-labelledby": paletteLabelId,
duotonePalette: duotones ?? [],
colorPalette: duotoneColorPalette,
onChange: onSelectDuotoneItem,
clearable: false,
unsetable: false,
disableCustomDuotone: true,
disableCustomColors: true
}),
!isEditing && variant === "color" && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___color_palette_index_tsx.default, {
presentation: "command-buttons",
"aria-labelledby": paletteLabelId,
colors,
onChange: onSelectPaletteItem,
clearable: false,
disableCustomColors: true
})
]
}),
!hasElements && emptyMessage && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(___view_index_ts.View, {
className: style_module_default.contents,
children: emptyMessage
})
]
});
}
exports.PaletteEdit = PaletteEdit;
exports.default = PaletteEdit;
exports.deduplicateElementSlugs = deduplicateElementSlugs;
exports.getNameAndSlugForPosition = getNameAndSlugForPosition;
//# sourceMappingURL=index.cjs.map