UNPKG

@wordpress/components

Version:
175 lines (174 loc) • 6.18 kB
import gradientParser from "gradient-parser"; import { colord, extend } from "colord"; import namesPlugin from "colord/plugins/names"; import { DEFAULT_GRADIENT, DIRECTIONAL_ORIENTATION_ANGLE_MAP, HORIZONTAL_GRADIENT_ORIENTATION, HUE_INTERPOLATION_METHODS, POLAR_INTERPOLATION_COLOR_SPACES, RECTANGULAR_INTERPOLATION_COLOR_SPACES } from "./constants.mjs"; import { serializeGradient } from "./serializer.mjs"; // packages/components/src/custom-gradient-picker/utils.ts extend([namesPlugin]); const ANGLE_UNIT_TO_DEGREES = { deg: 1, rad: 180 / Math.PI, grad: .9, turn: 360 }; function getLinearGradientRepresentation(gradientAST) { return serializeGradient({ type: "linear-gradient", orientation: HORIZONTAL_GRADIENT_ORIENTATION, colorStops: gradientAST.colorStops }); } function hasUnsupportedLength(item) { return item.length === void 0 || item.length.type !== "%"; } /** * Reads the first argument of a gradient, the one that holds the orientation * and the color interpolation method, as a list of space separated tokens. * * @param gradient CSS gradient. * @param start Index right after the opening parenthesis. */ function readFirstArgument(gradient, start) { const tokens = []; let token = ""; let depth = 0; for (let index = start; index < gradient.length; index++) { const char = gradient[index]; if (depth === 0 && (char === "," || char === ")")) { if (token) tokens.push(token); return { tokens, end: index }; } if (char === "(") depth++; else if (char === ")") depth--; if (depth === 0 && /\s/.test(char)) { if (token) tokens.push(token); token = ""; } else token += char; } } /** * `gradient-parser` can't read a color interpolation method such as * `in oklch`, so it is taken out of the gradient before it is parsed. * * Only the first argument is searched, at its top level, so a color stop like * `color-mix( in srgb, … )` is never mistaken for one. * * This is a workaround until `gradient-parser` supports color interpolation * methods. It can be removed once an upstream release does: * https://github.com/rafaelcaricio/gradient-parser/issues/57 * * @param gradient CSS gradient. */ function extractColorInterpolation(gradient) { const start = gradient.indexOf("(") + 1; const firstArgument = start && readFirstArgument(gradient, start); if (!firstArgument) return { gradient }; const { tokens, end } = firstArgument; const words = tokens.map((token) => token.toLowerCase()); const index = words.indexOf("in"); if (index === -1) return { gradient }; const colorSpace = words[index + 1]; let length; if (POLAR_INTERPOLATION_COLOR_SPACES.includes(colorSpace) && HUE_INTERPOLATION_METHODS.includes(words[index + 2]) && words[index + 3] === "hue") length = 4; else if (RECTANGULAR_INTERPOLATION_COLOR_SPACES.includes(colorSpace) || POLAR_INTERPOLATION_COLOR_SPACES.includes(colorSpace)) length = 2; else return { gradient }; const remainder = [...tokens.slice(0, index), ...tokens.slice(index + length)].join(" "); const hasEmptyFirstArgument = !remainder && gradient[end] === ","; return { gradient: gradient.slice(0, start) + remainder + gradient.slice(hasEmptyFirstArgument ? end + 1 : end), colorInterpolation: words.slice(index, index + length).join(" ") }; } function getGradientAstWithDefault(value) { let gradientAST; let hasGradient = !!value; const { gradient: valueToParse, colorInterpolation } = extractColorInterpolation(value ?? DEFAULT_GRADIENT); try { gradientAST = gradientParser.parse(valueToParse)[0]; if (colorInterpolation) gradientAST.colorInterpolation = colorInterpolation; } catch (error) { console.warn("wp.components.CustomGradientPicker failed to parse the gradient with error", error); } if (!gradientAST || gradientAST.type === "conic-gradient" || gradientAST.type === "repeating-conic-gradient" || gradientAST.colorStops.some((stop) => stop.length2 !== void 0)) { gradientAST = gradientParser.parse(DEFAULT_GRADIENT)[0]; hasGradient = false; } if (!Array.isArray(gradientAST.orientation) && gradientAST.orientation?.type === "directional") { const direction = gradientAST.orientation.value.toLowerCase(); gradientAST.orientation = { type: "angular", value: DIRECTIONAL_ORIENTATION_ANGLE_MAP[direction].toString(), unit: "deg" }; } if (!Array.isArray(gradientAST.orientation) && gradientAST.orientation?.type === "angular" && gradientAST.orientation.unit !== "deg") { const { value: angle, unit } = gradientAST.orientation; gradientAST.orientation = { type: "angular", value: `${Number(angle) * ANGLE_UNIT_TO_DEGREES[unit]}`, unit: "deg" }; } if (gradientAST.colorStops.some(hasUnsupportedLength)) { const { colorStops } = gradientAST; const step = 100 / (colorStops.length - 1); colorStops.forEach((stop, index) => { stop.length = { value: `${step * index}`, type: "%" }; }); } return { gradientAST, hasGradient }; } function getGradientAstWithControlPoints(gradientAST, newControlPoints) { return { ...gradientAST, colorStops: newControlPoints.map(({ position, color }) => { const { r, g, b, a } = colord(color).toRgb(); return { length: { type: "%", value: position?.toString() }, type: a < 1 ? "rgba" : "rgb", value: a < 1 ? [ `${r}`, `${g}`, `${b}`, `${a}` ] : [ `${r}`, `${g}`, `${b}` ] }; }) }; } function getStopCssColor(colorStop) { switch (colorStop.type) { case "hex": return `#${colorStop.value}`; case "literal": return colorStop.value; case "var": return `${colorStop.type}(${colorStop.value})`; case "rgb": case "rgba": return `${colorStop.type}(${colorStop.value.join(",")})`; case "hsl": { const [hue, saturation, lightness] = colorStop.value; return `hsl(${hue},${saturation}%,${lightness}%)`; } case "hsla": { const [hue, saturation, lightness, alpha = "1"] = colorStop.value; return `hsla(${hue},${saturation}%,${lightness}%,${alpha})`; } default: return "transparent"; } } export { getGradientAstWithControlPoints, getGradientAstWithDefault, getLinearGradientRepresentation, getStopCssColor }; //# sourceMappingURL=utils.mjs.map