UNPKG

@wordpress/components

Version:
52 lines (51 loc) • 2.44 kB
import { colord, extend } from "colord"; import namesPlugin from "colord/plugins/names"; import a11yPlugin from "colord/plugins/a11y"; import { __ } from "@wordpress/i18n"; // packages/components/src/color-palette/utils.ts extend([namesPlugin, a11yPlugin]); /** * Checks if a color value is a simple CSS color. * * @param value The color value to check. * @return A boolean indicating whether the color value is a simple CSS color. */ const isSimpleCSSColor = (value) => { const valueIsCssVariable = /var\(/.test(value ?? ""); const valueIsColorMix = /color-mix\(/.test(value ?? ""); return !valueIsCssVariable && !valueIsColorMix; }; const extractColorNameFromCurrentValue = (currentValue, colors = [], showMultiplePalettes = false, selectedSlug) => { if (!currentValue) return ""; const currentValueIsSimpleColor = currentValue ? isSimpleCSSColor(currentValue) : false; const normalizedCurrentValue = currentValueIsSimpleColor ? colord(currentValue).toHex() : currentValue; const colorPalettes = showMultiplePalettes ? colors : [{ colors }]; for (const { colors: paletteColors } of colorPalettes) for (const { name: colorName, color: colorValue, slug } of paletteColors) { if (selectedSlug) { if (slug === selectedSlug) return colorName; continue; } if (normalizedCurrentValue === (currentValueIsSimpleColor ? colord(colorValue).toHex() : colorValue)) return colorName; } return __("Custom"); }; const isMultiplePaletteObject = (obj) => Array.isArray(obj.colors) && !("color" in obj); const isMultiplePaletteArray = (arr) => { return arr.length > 0 && arr.every((colorObj) => isMultiplePaletteObject(colorObj)); }; /** * Transform a CSS variable used as background color into the color value itself. * * @param value The color value that may be a CSS variable. * @param element The element for which to get the computed style. * @return The background color value computed from a element. */ const normalizeColorValue = (value, element) => { if (!value || !element || isSimpleCSSColor(value)) return value; const { ownerDocument } = element; const { defaultView } = ownerDocument; const computedBackgroundColor = defaultView?.getComputedStyle(element).backgroundColor; return computedBackgroundColor ? colord(computedBackgroundColor).toHex() : value; }; export { extractColorNameFromCurrentValue, isMultiplePaletteArray, isMultiplePaletteObject, normalizeColorValue }; //# sourceMappingURL=utils.mjs.map