Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: New color formats and color picker (#5661)
Oleg Isonen9e72cc23c087
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.test.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.test.tsindex 4e96accdb2..210a0e2012 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.test.ts+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/gradient-utils.test.ts@@ -638,7 +638,7 @@ describe("styleValueToColor", () => {};expect(styleValueToColor(style)).toEqual({type: "color",- colorSpace: "srgb",+ colorSpace: "hex",components: [0, 0, 1],alpha: 1,});diff --git a/apps/builder/app/builder/features/style-panel/shared/color-picker.tsx b/apps/builder/app/builder/features/style-panel/shared/color-picker.tsxindex 322fb59f88..e714870504 100644--- a/apps/builder/app/builder/features/style-panel/shared/color-picker.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/color-picker.tsx@@ -6,7 +6,7 @@ import {type VarValue,type CssProperty,} from "@webstudio-is/css-engine";-import { Box, ColorPickerPopover } from "@webstudio-is/design-system";+import { Box, ColorPicker } from "@webstudio-is/design-system";import { CssValueInput } from "./css-value-input";import type { IntermediateStyleValue } from "./css-value-input/css-value-input";@@ -43,7 +43,7 @@ export const ColorPickerControl = ({styleSource="default"prefix={<Box css={{ paddingLeft: 2 }}>- <ColorPickerPopover+ <ColorPickervalue={currentColor}onChange={(styleValue) => {setIntermediateValue(styleValue);@@ -80,6 +80,7 @@ export const ColorPickerControl = ({styleValue.type === "color" ||styleValue.type === "keyword" ||styleValue.type === "var" ||+ styleValue.type === "unparsed" ||styleValue.type === "invalid") {setIntermediateValue(styleValue);@@ -104,7 +105,8 @@ export const ColorPickerControl = ({value.type === "rgb" ||value.type === "color" ||value.type === "keyword" ||- value.type === "var"+ value.type === "var" ||+ value.type === "unparsed") {setIntermediateValue(undefined);onChangeComplete(value);diff --git a/apps/builder/app/builder/features/style-panel/shared/css-fragment.test.ts b/apps/builder/app/builder/features/style-panel/shared/css-fragment.test.tsindex 2beca5ea2c..2b76a77a04 100644--- a/apps/builder/app/builder/features/style-panel/shared/css-fragment.test.ts+++ b/apps/builder/app/builder/features/style-panel/shared/css-fragment.test.ts@@ -30,10 +30,7 @@ test("fallback further to valid values", () => {["background-attachment", parseCssValue("background-attachment", "scroll")],["background-origin", parseCssValue("background-origin", "padding-box")],["background-clip", parseCssValue("background-clip", "border-box")],- [- "background-color",- parseCssValue("background-color", "rgba(255, 255, 255, 1)"),- ],+ ["background-color", parseCssValue("background-color", "#fff")],]);expect(parseCssFragment("#fff", ["background-image", "background"])).toEqual(resultdiff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.ts b/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.tsindex 3a918b95bf..66683df9f8 100644--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.ts+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts.test.ts@@ -470,7 +470,7 @@ describe("Colors", () => {expect(result).toEqual({type: "color",alpha: 1,- colorSpace: "srgb",+ colorSpace: "hex",components: [1, 0, 0],});});@@ -484,7 +484,7 @@ describe("Colors", () => {expect(result).toEqual({type: "color",alpha: 1,- colorSpace: "srgb",+ colorSpace: "hex",components: [0.9412, 0.9333, 0.0588],});});@@ -498,7 +498,7 @@ describe("Colors", () => {expect(result).toEqual({type: "color",alpha: 1,- colorSpace: "srgb",+ colorSpace: "hex",components: [1, 0, 0],});});@@ -512,7 +512,7 @@ describe("Colors", () => {expect(result).toEqual({type: "color",alpha: 1,- colorSpace: "srgb",+ colorSpace: "hex",components: [0.9412, 0.9333, 0.0588],});});@@ -531,6 +531,188 @@ describe("Colors", () => {components: [0.0392, 0.0784, 0.1176],});});++ test("hsl color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "hsl(120 100% 50%)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "hsl",+ alpha: 1,+ components: [120, 100, 50],+ });+ });++ test("hwb color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "hwb(120 0% 0%)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "hwb",+ alpha: 1,+ components: [120, 0, 0],+ });+ });++ test("lab color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "lab(50 20 30)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "lab",+ alpha: 1,+ components: [50, 20, 30],+ });+ });++ test("lch color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "lch(50 40 120)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "lch",+ alpha: 1,+ components: [50, 40, 120],+ });+ });++ test("oklab color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "oklab(0.7 0.1 -0.1)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "oklab",+ alpha: 1,+ components: [0.7, 0.1, -0.1],+ });+ });++ test("oklch color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "oklch(0.7 0.1 180)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "oklch",+ alpha: 1,+ components: [0.7, 0.1, 180],+ });+ });++ test("srgb-linear color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "color(srgb-linear 1 0 0)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "srgb-linear",+ alpha: 1,+ components: [1, 0, 0],+ });+ });++ test("display-p3 color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "color(display-p3 0.4 0.6 0.3)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "p3",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });++ test("a98-rgb color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "color(a98-rgb 0.4 0.6 0.3)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "a98rgb",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });++ test("prophoto-rgb color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "color(prophoto-rgb 0.4 0.6 0.3)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "prophoto",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });++ test("rec2020 color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "color(rec2020 0.4 0.6 0.3)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "rec2020",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });++ test("xyz-d65 color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "color(xyz-d65 0.4 0.6 0.3)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "xyz-d65",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });++ test("xyz-d50 color", () => {+ expect(+ parseIntermediateOrInvalidValue("color", {+ type: "intermediate",+ value: "color(xyz-d50 0.4 0.6 0.3)",+ })+ ).toEqual({+ type: "color",+ colorSpace: "xyz-d50",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });});test("parse css variable reference", () => {@@ -595,7 +777,7 @@ test("parse color in css variable", () => {})).toEqual({type: "color",- colorSpace: "srgb",+ colorSpace: "hex",components: [0.0588, 0.0588, 0.0588],alpha: 1,});diff --git a/apps/builder/app/builder/shared/css-editor/css-editor.tsx b/apps/builder/app/builder/shared/css-editor/css-editor.tsxindex 9a0a3c4d1c..61d4a6cf8d 100644--- a/apps/builder/app/builder/shared/css-editor/css-editor.tsx+++ b/apps/builder/app/builder/shared/css-editor/css-editor.tsx@@ -1,5 +1,5 @@import { mergeRefs } from "@react-aria/utils";-import * as colorjs from "colorjs.io/fn";+import { color } from "@webstudio-is/css-engine";import {memo,useEffect,@@ -35,7 +35,7 @@ import {import { CssValueInputContainer } from "../../features/style-panel/shared/css-value-input";import { $availableVariables } from "../../features/style-panel/shared/model";import { PropertyInfo } from "../../features/style-panel/property-label";-import { ColorPickerPopover } from "@webstudio-is/design-system";+import { ColorPicker } from "@webstudio-is/design-system";import { useClientSupports } from "~/shared/client-supports";import { CssEditorContextMenu, copyAttribute } from "./css-editor-context-menu";import { AddStyleInput } from "./add-style-input";@@ -134,7 +134,7 @@ const AdvancedPropertyValue = ({const inputRef = useRef<HTMLInputElement>(null);let isColor = false;try {- colorjs.parse(toValue(styleDecl.usedValue));+ color.parse(toValue(styleDecl.usedValue));isColor = true;} catch {isColor = false;@@ -148,7 +148,7 @@ const AdvancedPropertyValue = ({fieldSizing="content"prefix={isColor && (- <ColorPickerPopover+ <ColorPickervalue={styleDecl.usedValue}onChange={(styleValue) => {const options = { isEphemeral: true, listed: true };diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsxindex 565c3add1b..82761e5952 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx@@ -1,4 +1,4 @@-import * as colorjs from "colorjs.io/fn";+import { color } from "@webstudio-is/css-engine";import {useState,useEffect,@@ -146,8 +146,8 @@ const CaretColorPlugin = () => {let isLightBackground = false;try {- const color = colorjs.parse(elementColor);- const alpha = color.alpha ?? 1;+ const parsed = color.parse(elementColor);+ const alpha = parsed.alpha ?? 1;isLightBackground = alpha < 0.1;} catch {// If we can't parse the color, assume it's not lightdiff --git a/apps/builder/app/routes/_ui.(builder).tsx b/apps/builder/app/routes/_ui.(builder).tsxindex 306b96fe5b..b6165d81b5 100644--- a/apps/builder/app/routes/_ui.(builder).tsx+++ b/apps/builder/app/routes/_ui.(builder).tsx@@ -189,9 +189,11 @@ export const loader = async (loaderArgs: LoaderFunctionArgs) => {// Disallowing iframes from loading any content except the canvas// Still possible create iframes on canvas itself (but we use credentialless attribute)// Still possible create iframe without src attribute- // Disable workers on builder+ // Allow blob: workers so hdr-color-input can spawn its inline canvas-rendering worker.+ // blob: workers can only be created from JS already running in this page, so the+ // attack surface is no wider than allowing eval."Content-Security-Policy",- `frame-src ${url.origin}/canvas https://app.goentri.com/ https://help.webstudio.is/; worker-src 'none'`+ `frame-src ${url.origin}/canvas https://app.goentri.com/ https://help.webstudio.is/; worker-src blob:`);return json(diff --git a/apps/builder/app/shared/commands-emitter.ts b/apps/builder/app/shared/commands-emitter.tsindex c365baa286..c617ce0d26 100644--- a/apps/builder/app/shared/commands-emitter.ts+++ b/apps/builder/app/shared/commands-emitter.ts@@ -162,7 +162,7 @@ export const createCommandsEmitter = <CommandName extends string>({if (disableOnInputLikeControls) {const element = event.target as HTMLElement;const isOnInputLikeControl =- ["input", "select", "textarea"].includes(+ ["input", "select", "textarea", "color-input"].includes(element.tagName.toLowerCase()) ||element.isContentEditable ||diff --git a/apps/builder/app/shared/pubsub/create.test.ts b/apps/builder/app/shared/pubsub/create.test.tsindex e21dc3d390..f0eb0e0664 100644--- a/apps/builder/app/shared/pubsub/create.test.ts+++ b/apps/builder/app/shared/pubsub/create.test.ts@@ -21,53 +21,34 @@ describe("createPubsub", () => {let addEventListenerSpy: ReturnType<typeof vi.fn>;beforeEach(() => {- // Setup window and crypto- if (!global.window) {- (global as typeof globalThis).window = {} as Window & typeof globalThis;- }-- // Mock crypto.getRandomValues- global.window.crypto = {- getRandomValues: vi.fn((arr: Uint8Array) => {- for (let i = 0; i < arr.length; i++) {- arr[i] = i;- }- return arr;- }),- } as unknown as Crypto;-- // Mock requestAnimationFrame - execute callbacks immediately- global.requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {- // Execute the callback immediately for testing- setTimeout(() => callback(0), 0);- return 0;- }) as typeof requestAnimationFrame;-- postMessageSpy = vi.fn();- parentPostMessageSpy = vi.fn();- addEventListenerSpy = vi.fn();-- global.window.postMessage = postMessageSpy;- global.window.addEventListener = addEventListenerSpy;- global.window.parent = {- postMessage: parentPostMessageSpy,- } as unknown as Window;+ vi.useFakeTimers();+ vi.spyOn(window, "postMessage").mockImplementation(() => {});+ vi.spyOn(window.parent, "postMessage").mockImplementation(() => {});+ vi.spyOn(window, "addEventListener");++ postMessageSpy = window.postMessage as ReturnType<typeof vi.fn>;+ parentPostMessageSpy = window.parent.postMessage as ReturnType<+ typeof vi.fn+ >;+ addEventListenerSpy = window.addEventListener as ReturnType<typeof vi.fn>;// Set NODE_ENV for consistent testingprocess.env.NODE_ENV = "test";});afterEach(() => {- vi.clearAllMocks();- delete (global.window as Window & { __webstudio__$__api_token?: string })+ // Flush any pending fake rAF callbacks so raf-queue module state is+ // clean (handle reset to undefined) before the next test.+ vi.runAllTimers();+ vi.useRealTimers();+ vi.restoreAllMocks();+ delete (window as Window & { __webstudio__$__api_token?: string }).__webstudio__$__api_token;});describe("SSR environment", () => {test("should throw errors when used in SSR", () => {- const originalWindow = global.window;- (global as typeof globalThis).window = undefined as unknown as Window &- typeof globalThis;+ vi.stubGlobal("window", undefined);const pubsub = createPubsub<TestPublishMap>();@@ -84,26 +65,26 @@ describe("createPubsub", () => {"subscribe is not available in this environment");- global.window = originalWindow;+ vi.unstubAllGlobals();});});describe("token generation and validation", () => {test("should generate random token when window.self === window.top", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);createPubsub<TestPublishMap>();- expect(global.window.__webstudio__$__api_token).toBeDefined();+ expect(window.__webstudio__$__api_token).toBeDefined();});test("should use development token in non-production", () => {const originalNodeEnv = process.env.NODE_ENV;process.env.NODE_ENV = "development";- global.window.self = asWindow({});- global.window.top = asWindow(global.window);+ window.self = asWindow({});+ window.top = asWindow(window);createPubsub<TestPublishMap>();@@ -119,29 +100,29 @@ describe("createPubsub", () => {test("should read token from top window when not top", () => {const mockToken = "test-token";- global.window.top = {+ window.top = {__webstudio__$__api_token: mockToken,} as unknown as Window & typeof globalThis;- global.window.self = asWindow({});+ window.self = asWindow({});createPubsub<TestPublishMap>();// Token should be reset to undefined on canvas- expect(global.window.top.__webstudio__$__api_token).toBeUndefined();+ expect(window.top.__webstudio__$__api_token).toBeUndefined();});});describe("publish (Canvas -> Builder)", () => {test("should publish action to parent and self", () => {- global.window.self = asWindow({});- global.window.top = asWindow(global.window);- global.window.top.__webstudio__$__api_token = "test-token";+ window.self = asWindow({});+ window.top = asWindow(window);+ window.top.__webstudio__$__api_token = "test-token";const pubsub = createPubsub<TestPublishMap>();// Clear the token since it gets reset in createPubsub for Canvas context// Set it again after initialization- global.window.top.__webstudio__$__api_token = "test-token";+ window.top.__webstudio__$__api_token = "test-token";pubsub.publish({ type: "testAction", payload: { value: "hello" } });@@ -160,8 +141,8 @@ describe("createPubsub", () => {});test("should throw error when publish is called from Builder (self === top)", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -171,14 +152,14 @@ describe("createPubsub", () => {});test("should handle action with no payload", () => {- global.window.self = asWindow({});- global.window.top = asWindow(global.window);- global.window.top.__webstudio__$__api_token = "test-token";+ window.self = asWindow({});+ window.top = asWindow(window);+ window.top.__webstudio__$__api_token = "test-token";const pubsub = createPubsub<TestPublishMap>();// Set token again after initialization- global.window.top.__webstudio__$__api_token = "test-token";+ window.top.__webstudio__$__api_token = "test-token";pubsub.publish({ type: "noPayloadAction" });@@ -193,8 +174,8 @@ describe("createPubsub", () => {describe("usePublish (Builder -> Canvas)", () => {test("should be available when self === top", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -203,8 +184,8 @@ describe("createPubsub", () => {});test("should be available for iframe context", () => {- global.window.self = asWindow({});- global.window.top = asWindow(global.window);+ window.self = asWindow({});+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -215,8 +196,8 @@ describe("createPubsub", () => {describe("subscribe", () => {test("should subscribe to messages and call handler", async () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -236,15 +217,14 @@ describe("createPubsub", () => {messageHandler(mockEvent);- // Wait for requestAnimationFrame callback to execute- await new Promise((resolve) => setTimeout(resolve, 10));+ vi.runAllTimers();expect(handler).toHaveBeenCalledWith({ value: "test" });});test("should return unsubscribe function", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -272,12 +252,12 @@ describe("createPubsub", () => {});test("should handle multiple subscribers", async () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);// Create a fresh addEventListener spy for this testconst localAddEventListenerSpy = vi.fn();- global.window.addEventListener = localAddEventListenerSpy;+ window.addEventListener = localAddEventListenerSpy;const pubsub = createPubsub<TestPublishMap>();@@ -303,8 +283,7 @@ describe("createPubsub", () => {// Call messageHandler and let it emitmessageHandler(mockEvent);- // Wait for requestAnimationFrame callback to execute- await new Promise((resolve) => setTimeout(resolve, 10));+ vi.runAllTimers();expect(handler1).toHaveBeenCalledTimes(1);expect(handler1).toHaveBeenCalledWith({ value: "test" });@@ -315,8 +294,8 @@ describe("createPubsub", () => {describe("useSubscribe", () => {test("should be available as a hook function", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -327,8 +306,8 @@ describe("createPubsub", () => {describe("message unwrapping and validation", () => {test("should reject invalid payload (not an object)", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -354,8 +333,8 @@ describe("createPubsub", () => {});test("should reject payload without token", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -370,8 +349,8 @@ describe("createPubsub", () => {});test("should reject payload with invalid token", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -391,8 +370,8 @@ describe("createPubsub", () => {});test("should reject payload without action", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -411,8 +390,8 @@ describe("createPubsub", () => {});test("should hide token from subsequent subscribers", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const pubsub = createPubsub<TestPublishMap>();@@ -436,12 +415,12 @@ describe("createPubsub", () => {const originalIsStorybook = process.env.IS_STROYBOOK;process.env.IS_STROYBOOK = "true";- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);// Create a fresh addEventListener spy for this testconst localAddEventListenerSpy = vi.fn();- global.window.addEventListener = localAddEventListenerSpy;+ window.addEventListener = localAddEventListenerSpy;const pubsub = createPubsub<TestPublishMap>();@@ -453,8 +432,7 @@ describe("createPubsub", () => {messageHandler({ data: "storybook-data" });- // Wait for requestAnimationFrame callback to execute- await new Promise((resolve) => setTimeout(resolve, 10));+ vi.runAllTimers();expect(handler).toHaveBeenCalledWith("storybook-data");@@ -464,14 +442,14 @@ describe("createPubsub", () => {describe("action types", () => {test("should handle action with undefined payload", () => {- global.window.self = asWindow({});- global.window.top = asWindow(global.window);- global.window.top.__webstudio__$__api_token = "test-token";+ window.self = asWindow({});+ window.top = asWindow(window);+ window.top.__webstudio__$__api_token = "test-token";const pubsub = createPubsub<TestPublishMap>();// Set token again after initialization- global.window.top.__webstudio__$__api_token = "test-token";+ window.top.__webstudio__$__api_token = "test-token";pubsub.publish({ type: "noPayloadAction", payload: undefined });@@ -484,14 +462,14 @@ describe("createPubsub", () => {});test("should handle action with number payload", () => {- global.window.self = asWindow({});- global.window.top = asWindow(global.window);- global.window.top.__webstudio__$__api_token = "test-token";+ window.self = asWindow({});+ window.top = asWindow(window);+ window.top.__webstudio__$__api_token = "test-token";const pubsub = createPubsub<TestPublishMap>();// Set token again after initialization- global.window.top.__webstudio__$__api_token = "test-token";+ window.top.__webstudio__$__api_token = "test-token";pubsub.publish({ type: "numberAction", payload: 42 });@@ -506,8 +484,8 @@ describe("createPubsub", () => {describe("event listener registration", () => {test("should register message event listener on initialization", () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);createPubsub<TestPublishMap>();@@ -521,11 +499,11 @@ describe("createPubsub", () => {describe("command-specific subscriptions", () => {test("should subscribe to specific command and call handler", async () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const localAddEventListenerSpy = vi.fn();- global.window.addEventListener = localAddEventListenerSpy;+ window.addEventListener = localAddEventListenerSpy;const pubsub = createPubsub<TestPublishMap>();@@ -546,8 +524,7 @@ describe("createPubsub", () => {messageHandler(mockEvent);- // Wait for requestAnimationFrame callback- await new Promise((resolve) => setTimeout(resolve, 10));+ vi.runAllTimers();expect(handler).toHaveBeenCalledWith({source: "builder",@@ -556,11 +533,11 @@ describe("createPubsub", () => {});test("should only call handler for matching command", async () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const localAddEventListenerSpy = vi.fn();- global.window.addEventListener = localAddEventListenerSpy;+ window.addEventListener = localAddEventListenerSpy;const pubsub = createPubsub<TestPublishMap>();@@ -585,18 +562,18 @@ describe("createPubsub", () => {messageHandler(mockEvent);- await new Promise((resolve) => setTimeout(resolve, 10));+ vi.runAllTimers();expect(handler1).toHaveBeenCalledTimes(1);expect(handler2).not.toHaveBeenCalled();});test("should call both general command handler and specific command handler", async () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const localAddEventListenerSpy = vi.fn();- global.window.addEventListener = localAddEventListenerSpy;+ window.addEventListener = localAddEventListenerSpy;const pubsub = createPubsub<TestPublishMap>();@@ -620,7 +597,7 @@ describe("createPubsub", () => {messageHandler(mockEvent);- await new Promise((resolve) => setTimeout(resolve, 10));+ vi.runAllTimers();expect(generalHandler).toHaveBeenCalledWith({source: "builder",@@ -633,11 +610,11 @@ describe("createPubsub", () => {});test("should unsubscribe from specific command", async () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const localAddEventListenerSpy = vi.fn();- global.window.addEventListener = localAddEventListenerSpy;+ window.addEventListener = localAddEventListenerSpy;const pubsub = createPubsub<TestPublishMap>();@@ -660,17 +637,17 @@ describe("createPubsub", () => {messageHandler(mockEvent);- await new Promise((resolve) => setTimeout(resolve, 10));+ vi.runAllTimers();expect(handler).not.toHaveBeenCalled();});test("should handle multiple subscribers to the same specific command", async () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const localAddEventListenerSpy = vi.fn();- global.window.addEventListener = localAddEventListenerSpy;+ window.addEventListener = localAddEventListenerSpy;const pubsub = createPubsub<TestPublishMap>();@@ -694,7 +671,7 @@ describe("createPubsub", () => {messageHandler(mockEvent);- await new Promise((resolve) => setTimeout(resolve, 10));+ vi.runAllTimers();expect(handler1).toHaveBeenCalledWith({source: "builder",@@ -707,11 +684,11 @@ describe("createPubsub", () => {});test("should pass payload to command-specific subscribers", async () => {- global.window.self = asWindow(global.window);- global.window.top = asWindow(global.window);+ window.self = asWindow(window);+ window.top = asWindow(window);const localAddEventListenerSpy = vi.fn();- global.window.addEventListener = localAddEventListenerSpy;+ window.addEventListener = localAddEventListenerSpy;const pubsub = createPubsub<TestPublishMap>();@@ -737,7 +714,7 @@ describe("createPubsub", () => {messageHandler(mockEvent);- await new Promise((resolve) => setTimeout(resolve, 10));+ vi.runAllTimers();expect(handler).toHaveBeenCalledWith({source: "builder",diff --git a/apps/builder/app/shared/style-object-model.test.tsx b/apps/builder/app/shared/style-object-model.test.tsxindex e7acb83476..90e51040ce 100644--- a/apps/builder/app/shared/style-object-model.test.tsx+++ b/apps/builder/app/shared/style-object-model.test.tsx@@ -441,7 +441,7 @@ test("compute custom properties in shadows", () => {blur: { type: "unit", value: 30, unit: "px" },color: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",components: [1, 0, 0],alpha: 1,},@@ -477,7 +477,7 @@ test("resolve custom property in color alpha channel", () => {}).computedValue).toEqual({type: "color",- colorSpace: "srgb",+ colorSpace: "hex",components: [1, 0, 0],alpha: 0.5,});diff --git a/apps/builder/vitest.config.ts b/apps/builder/vitest.config.tsindex b4815cf3bc..f9809724ba 100644--- a/apps/builder/vitest.config.ts+++ b/apps/builder/vitest.config.ts@@ -19,4 +19,9 @@ export default defineConfig({// conditions: ["webstudio", ...defaultServerConditions],},},+ test: {+ environment: "jsdom",+ environmentMatchGlobs: [["**/*.server.test.*", "node"]],+ setupFiles: ["@webstudio-is/design-system/test-setup"],+ },});diff --git a/lostpixel.config.js b/lostpixel.config.jsindex ec48b7f4e9..b0b39d1262 100644--- a/lostpixel.config.js+++ b/lostpixel.config.js@@ -3,4 +3,5 @@ import * as process from "process";export const config = {lostPixelProjectId: "cleiive6c0gchi40em3uzx1xv",apiKey: process.env.LOST_PIXEL_API_KEY,+ waitBeforeScreenshot: 2000,};diff --git a/packages/css-data/package.json b/packages/css-data/package.jsonindex 1c4ab48a89..ccf72a2ca1 100644--- a/packages/css-data/package.json+++ b/packages/css-data/package.json@@ -34,7 +34,6 @@"dependencies": {"@webstudio-is/css-engine": "workspace:*","change-case": "^5.4.4",- "colorjs.io": "^0.6.1","css-tree": "^3.1.0","openai": "^3.2.1","p-retry": "^6.2.1",diff --git a/packages/css-data/src/parse-css-value.test.ts b/packages/css-data/src/parse-css-value.test.tsindex c0a16af641..0252be0406 100644--- a/packages/css-data/src/parse-css-value.test.ts+++ b/packages/css-data/src/parse-css-value.test.ts@@ -1,6 +1,10 @@import { describe, test, expect } from "vitest";-import { parseCssValue } from "./parse-css-value";-import { toValue, type CssProperty } from "@webstudio-is/css-engine";+import { parseCssValue, isValidDeclaration } from "./parse-css-value";+import {+ toValue,+ type CssProperty,+ type ColorValue,+} from "@webstudio-is/css-engine";describe("Parse CSS value", () => {describe("number value", () => {@@ -117,7 +121,7 @@ describe("Parse CSS value", () => {test("Color rgba values", () => {expect(parseCssValue("background-color", "#00220011")).toEqual({type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 0.0667,components: [0, 0.1333, 0],});@@ -160,11 +164,200 @@ describe("Parse CSS value", () => {components: [0.8, 0.15, 240],});});++ test("hsl color", () => {+ expect(parseCssValue("color", "hsl(120 100% 50%)")).toEqual({+ type: "color",+ colorSpace: "hsl",+ alpha: 1,+ components: [120, 100, 50],+ });+ });++ test("hwb color", () => {+ expect(parseCssValue("color", "hwb(120 0% 0%)")).toEqual({+ type: "color",+ colorSpace: "hwb",+ alpha: 1,+ components: [120, 0, 0],+ });+ });++ test("lab color", () => {+ expect(parseCssValue("color", "lab(50 20 30)")).toEqual({+ type: "color",+ colorSpace: "lab",+ alpha: 1,+ components: [50, 20, 30],+ });+ });++ test("lch color", () => {+ expect(parseCssValue("color", "lch(50 40 120)")).toEqual({+ type: "color",+ colorSpace: "lch",+ alpha: 1,+ components: [50, 40, 120],+ });+ });++ test("oklab color", () => {+ expect(parseCssValue("color", "oklab(0.7 0.1 -0.1)")).toEqual({+ type: "color",+ colorSpace: "oklab",+ alpha: 1,+ components: [0.7, 0.1, -0.1],+ });+ });++ test("srgb-linear color", () => {+ expect(parseCssValue("color", "color(srgb-linear 1 0 0)")).toEqual({+ type: "color",+ colorSpace: "srgb-linear",+ alpha: 1,+ components: [1, 0, 0],+ });+ });++ test("display-p3 color", () => {+ expect(parseCssValue("color", "color(display-p3 0.4 0.6 0.3)")).toEqual({+ type: "color",+ colorSpace: "p3",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });++ test("a98-rgb color", () => {+ expect(parseCssValue("color", "color(a98-rgb 0.4 0.6 0.3)")).toEqual({+ type: "color",+ colorSpace: "a98rgb",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });++ test("prophoto-rgb color", () => {+ expect(parseCssValue("color", "color(prophoto-rgb 0.4 0.6 0.3)")).toEqual(+ {+ type: "color",+ colorSpace: "prophoto",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ }+ );+ });++ test("rec2020 color", () => {+ expect(parseCssValue("color", "color(rec2020 0.4 0.6 0.3)")).toEqual({+ type: "color",+ colorSpace: "rec2020",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });++ test("xyz-d65 color", () => {+ expect(parseCssValue("color", "color(xyz-d65 0.4 0.6 0.3)")).toEqual({+ type: "color",+ colorSpace: "xyz-d65",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });++ test("xyz-d50 color", () => {+ expect(parseCssValue("color", "color(xyz-d50 0.4 0.6 0.3)")).toEqual({+ type: "color",+ colorSpace: "xyz-d50",+ alpha: 1,+ components: [0.4, 0.6, 0.3],+ });+ });});- test("parse rgb color with CSS variable as alpha channel", () => {+ describe("CSS variable in alpha channel", () => {+ // hex is excluded: #RRGGBB syntax has no / alpha slot in CSS.+ // Using satisfies Record<Exclude<...>, unknown> ensures TypeScript errors+ // when a new color space is added to ColorValue without a test entry here.+ const cases = {+ srgb: {+ css: "rgb(255 0 0 / var(--opacity))",+ components: [1, 0, 0],+ },+ hsl: {+ css: "hsl(120 100% 50% / var(--opacity))",+ components: [120, 100, 50],+ },+ hwb: {+ css: "hwb(120 0% 0% / var(--opacity))",+ components: [120, 0, 0],+ },+ lab: {+ css: "lab(50 20 30 / var(--opacity))",+ components: [50, 20, 30],+ },+ lch: {+ css: "lch(50 40 120 / var(--opacity))",+ components: [50, 40, 120],+ },+ oklab: {+ css: "oklab(0.7 0.1 -0.1 / var(--opacity))",+ components: [0.7, 0.1, -0.1],+ },+ oklch: {+ css: "oklch(0.5 0.1 180 / var(--opacity))",+ components: [0.5, 0.1, 180],+ },+ p3: {+ css: "color(display-p3 0.4 0.6 0.3 / var(--opacity))",+ components: [0.4, 0.6, 0.3],+ },+ "srgb-linear": {+ css: "color(srgb-linear 1 0 0 / var(--opacity))",+ components: [1, 0, 0],+ },+ a98rgb: {+ css: "color(a98-rgb 0.5 0.3 0.7 / var(--opacity))",+ components: [0.5, 0.3, 0.7],+ },+ prophoto: {+ css: "color(prophoto-rgb 0.6 0.4 0.2 / var(--opacity))",+ components: [0.6, 0.4, 0.2],+ },+ rec2020: {+ css: "color(rec2020 0.4 0.6 0.3 / var(--opacity))",+ components: [0.4, 0.6, 0.3],+ },+ "xyz-d65": {+ css: "color(xyz-d65 0.5 0.3 0.2 / var(--opacity))",+ components: [0.5, 0.3, 0.2],+ },+ "xyz-d50": {+ css: "color(xyz-d50 0.4 0.6 0.3 / var(--opacity))",+ components: [0.4, 0.6, 0.3],+ },+ } satisfies Record<Exclude<ColorValue["colorSpace"], "hex">, unknown>;++ for (const [colorSpace, { css, components }] of Object.entries(cases)) {+ test(colorSpace, () => {+ expect(parseCssValue("color", css)).toEqual({+ type: "color",+ colorSpace,+ components,+ alpha: {+ type: "var",+ value: "opacity",+ fallback: { type: "unit", unit: "number", value: 1 },+ },+ });+ });+ }+ });++ test("preserve explicit CSS fallback in var alpha channel", () => {expect(- parseCssValue("color", "rgb(24 24 27 / var(--tw-bg-opacity))")+ parseCssValue("color", "rgb(24 24 27 / var(--tw-bg-opacity, 0.5))")).toEqual({type: "color",colorSpace: "srgb",@@ -172,59 +365,115 @@ describe("Parse CSS value", () => {alpha: {type: "var",value: "tw-bg-opacity",- fallback: { type: "unit", unit: "number", value: 1 },+ fallback: { type: "unparsed", value: "0.5" },},});});+});++test("parse color-mix() as unparsed value", () => {+ expect(parseCssValue("color", "color-mix(in oklch, red 50%, blue)")).toEqual({+ type: "unparsed",+ value: "color-mix(in oklch, red 50%, blue)",+ });+});- test("parse color() function with CSS variable as alpha channel", () => {+test("parse color-mix() on background-color as unparsed value", () => {+ expect(+ parseCssValue(+ "background-color",+ "color-mix(in srgb, #ff0000 30%, transparent)"+ )+ ).toEqual({+ type: "unparsed",+ value: "color-mix(in srgb, #ff0000 30%, transparent)",+ });+});++test("parse color-mix() with var() as first color argument", () => {+ expect(+ parseCssValue("color", "color-mix(in oklch, var(--primary), blue)")+ ).toEqual({+ type: "unparsed",+ value: "color-mix(in oklch, var(--primary), blue)",+ });+});++test("parse color-mix() with var() as second color argument", () => {+ expect(+ parseCssValue("color", "color-mix(in oklch, red, var(--secondary))")+ ).toEqual({+ type: "unparsed",+ value: "color-mix(in oklch, red, var(--secondary))",+ });+});++test("parse color-mix() with var() as percentage", () => {+ expect(+ parseCssValue("color", "color-mix(in srgb, red var(--pct), blue)")+ ).toEqual({+ type: "unparsed",+ value: "color-mix(in srgb, red var(--pct), blue)",+ });+});++describe("relative color syntax", () => {+ test("static relative color (no var)", () => {+ expect(parseCssValue("color", "rgb(from blue r g b / 50%)")).toEqual({+ type: "unparsed",+ value: "rgb(from blue r g b / 50%)",+ });+ });++ test("var() as origin color", () => {expect(- parseCssValue(- "background-color",- "color(display-p3 0.4 0.6 0.3 / var(--tw-bg-opacity))"- )+ parseCssValue("color", "rgb(from var(--brand-primary) r g b / 25%)")).toEqual({- type: "color",- colorSpace: "p3",- components: [0.4, 0.6, 0.3],- alpha: {- type: "var",- value: "tw-bg-opacity",- fallback: { type: "unit", unit: "number", value: 1 },- },+ type: "unparsed",+ value: "rgb(from var(--brand-primary) r g b / 25%)",});});- test("parse oklch color with CSS variable as alpha channel", () => {+ test("var() as channel value", () => {+ expect(parseCssValue("color", "oklch(from red l var(--chroma) h)")).toEqual(+ {+ type: "unparsed",+ value: "oklch(from red l var(--chroma) h)",+ }+ );+ });++ test("var() as alpha", () => {expect(- parseCssValue(- "color",- "oklch(59.686% 0.1009 29.234 / var(--tw-text-opacity))"- )+ parseCssValue("color", "rgb(from red r g b / var(--alpha))")).toEqual({- type: "color",- colorSpace: "oklch",- components: [0.5969, 0.1009, 29.234],- alpha: {- type: "var",- value: "tw-text-opacity",- fallback: { type: "unit", unit: "number", value: 1 },- },+ type: "unparsed",+ value: "rgb(from red r g b / var(--alpha))",});});- test("preserve explicit CSS fallback in var alpha channel", () => {+ test("hsl relative with var() as origin", () => {+ expect(parseCssValue("color", "hsl(from var(--brand) h s 75%)")).toEqual({+ type: "unparsed",+ value: "hsl(from var(--brand) h s 75%)",+ });+ });++ test("oklch relative on background-color", () => {expect(- parseCssValue("color", "rgb(24 24 27 / var(--tw-bg-opacity, 0.5))")+ parseCssValue("background-color", "oklch(from var(--brand) l c h / 0.5)")).toEqual({- type: "color",- colorSpace: "srgb",- components: [0.0941, 0.0941, 0.1059],- alpha: {- type: "var",- value: "tw-bg-opacity",- fallback: { type: "unparsed", value: "0.5" },- },+ type: "unparsed",+ value: "oklch(from var(--brand) l c h / 0.5)",+ });+ });++ test("var() in both origin and alpha", () => {+ expect(+ parseCssValue("color", "rgb(from var(--brand) r g b / var(--alpha))")+ ).toEqual({+ type: "unparsed",+ value: "rgb(from var(--brand) r g b / var(--alpha))",});});});@@ -697,7 +946,7 @@ test("support color in custom property", () => {});expect(parseCssValue("--color", "#3d4d04")).toEqual({type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [0.2392, 0.302, 0.0157],});@@ -1008,7 +1257,7 @@ describe("parse filters", () => {blur: { type: "unit", unit: "px", value: 25 },color: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [0, 0, 1],},@@ -1243,3 +1492,211 @@ test("parse perspective-origin", () => {],});});++describe("isValidDeclaration", () => {+ test("custom properties always accept any value", () => {+ expect(isValidDeclaration("--my-color", "anything")).toBe(true);+ expect(isValidDeclaration("--x", "rgb(0 0 0)")).toBe(true);+ expect(isValidDeclaration("--x", "not-valid-garbage")).toBe(true);+ });++ test("var() is valid on any property, detected via AST", () => {+ expect(isValidDeclaration("color", "var(--primary)")).toBe(true);+ expect(isValidDeclaration("color", "var(--primary, red)")).toBe(true);+ expect(isValidDeclaration("width", "var(--size)")).toBe(true);+ });++ // Critical: var() must be detected by the AST walk before reaching the+ // keyword-only check, otherwise var() on these properties would be rejected.+ test("var() on keyword-only properties is valid", () => {+ expect(isValidDeclaration("white-space-collapse", "var(--ws)")).toBe(true);+ expect(isValidDeclaration("text-wrap-mode", "var(--tw)")).toBe(true);+ expect(isValidDeclaration("text-wrap-style", "var(--ts)")).toBe(true);+ });++ test("white-space-collapse: valid keywords accepted", () => {+ expect(isValidDeclaration("white-space-collapse", "collapse")).toBe(true);+ expect(isValidDeclaration("white-space-collapse", "preserve")).toBe(true);+ });++ test("white-space-collapse: unknown keywords rejected", () => {+ expect(isValidDeclaration("white-space-collapse", "not-valid")).toBe(false);+ expect(isValidDeclaration("white-space-collapse", "wrap")).toBe(false);+ });++ test("text-wrap-mode: valid keywords accepted", () => {+ expect(isValidDeclaration("text-wrap-mode", "wrap")).toBe(true);+ expect(isValidDeclaration("text-wrap-mode", "nowrap")).toBe(true);+ });++ test("text-wrap-mode: unknown keywords rejected", () => {+ expect(isValidDeclaration("text-wrap-mode", "not-valid")).toBe(false);+ });++ test("text-wrap-style: valid keywords accepted", () => {+ expect(isValidDeclaration("text-wrap-style", "balance")).toBe(true);+ expect(isValidDeclaration("text-wrap-style", "auto")).toBe(true);+ });++ test("text-wrap-style: unknown keywords rejected", () => {+ expect(isValidDeclaration("text-wrap-style", "not-valid")).toBe(false);+ });++ // Relative color syntax: csstree returns identical "Mismatch" errors for both+ // relative colors and genuinely invalid values, so we detect structurally via+ // the `from` identifier being the first child of the color function node.+ test("static relative color syntax is valid", () => {+ expect(isValidDeclaration("color", "rgb(from blue r g b / 50%)")).toBe(+ true+ );+ expect(isValidDeclaration("color", "oklch(from red l c h)")).toBe(true);+ expect(+ isValidDeclaration("background-color", "hsl(from green h s 75%)")+ ).toBe(true);+ });++ test("relative color with var() origin is valid", () => {+ expect(isValidDeclaration("color", "rgb(from var(--brand) r g b)")).toBe(+ true+ );+ expect(+ isValidDeclaration(+ "color",+ "oklch(from var(--brand) l c h / var(--alpha))"+ )+ ).toBe(true);+ });++ test("standard color values are valid via csstree lexer", () => {+ expect(isValidDeclaration("color", "oklch(0.7 0.15 200)")).toBe(true);+ expect(isValidDeclaration("color", "color-mix(in oklch, red, blue)")).toBe(+ true+ );+ expect(isValidDeclaration("color", "rgb(255 0 0)")).toBe(true);+ expect(isValidDeclaration("color", "#ff0000")).toBe(true);+ });++ test("genuinely invalid CSS values are rejected", () => {+ expect(isValidDeclaration("color", "not-valid-garbage")).toBe(false);+ // blur() is not a valid <color> value+ expect(isValidDeclaration("color", "blur(4)")).toBe(false);+ // red is not a valid <length>+ expect(isValidDeclaration("width", "red")).toBe(false);+ });++ // The AST walk is deep, not shallow. var() nested inside calc() or color-mix()+ // must be detected even though it isn't the top-level node.+ test("var() nested deep inside another function is valid", () => {+ expect(isValidDeclaration("width", "calc(var(--size) + 10px)")).toBe(true);+ expect(+ isValidDeclaration("color", "color-mix(in oklch, var(--primary), blue)")+ ).toBe(true);+ });++ // When csstree's tokenizer itself fails (malformed syntax like unmatched braces)+ // cssTryParseValue returns undefined. In the non-browser path this must return false.+ test("syntactically broken value that csstree cannot parse at all is rejected", () => {+ expect(isValidDeclaration("color", "}")).toBe(false);+ });++ // The newer CSS linear() easing function isn't in csstree's grammar for+ // transition/animation-timing-function, so there's a special lexer.match() call+ // before the normal lexer.matchProperty() call.+ test("transition-timing-function: CSS linear() easing syntax is valid", () => {+ expect(+ isValidDeclaration("transition-timing-function", "linear(0 0%, 1 100%)")+ ).toBe(true);+ expect(+ isValidDeclaration("transition-timing-function", "linear(0, 0.5 25%, 1)")+ ).toBe(true);+ });++ test("animation-timing-function: CSS linear() easing syntax is valid", () => {+ expect(+ isValidDeclaration("animation-timing-function", "linear(0 0%, 1 100%)")+ ).toBe(true);+ });++ // Unknown CSS properties (future or vendor-prefixed) are allowed through so they+ // can be stored as UnparsedValue rather than silently dropped.+ test("unknown CSS properties are accepted via the 'Unknown property' error path", () => {+ expect(+ isValidDeclaration("animation-timeline" as CssProperty, "auto")+ ).toBe(true);+ expect(+ isValidDeclaration("animation-range-start" as CssProperty, "normal")+ ).toBe(true);+ });+});++describe("keyword-only properties via parseCssValue", () => {+ test("white-space-collapse: valid keyword", () => {+ expect(parseCssValue("white-space-collapse", "collapse")).toEqual({+ type: "keyword",+ value: "collapse",+ });+ expect(parseCssValue("white-space-collapse", "preserve")).toEqual({+ type: "keyword",+ value: "preserve",+ });+ });++ test("white-space-collapse: invalid keyword returns invalid", () => {+ expect(parseCssValue("white-space-collapse", "not-valid")).toEqual({+ type: "invalid",+ value: "not-valid",+ });+ });++ test("white-space-collapse: var() is accepted and returned as VarValue", () => {+ expect(parseCssValue("white-space-collapse", "var(--ws-collapse)")).toEqual(+ {+ type: "var",+ value: "ws-collapse",+ }+ );+ });++ test("text-wrap-mode: valid keyword", () => {+ expect(parseCssValue("text-wrap-mode", "wrap")).toEqual({+ type: "keyword",+ value: "wrap",+ });+ expect(parseCssValue("text-wrap-mode", "nowrap")).toEqual({+ type: "keyword",+ value: "nowrap",+ });+ });++ test("text-wrap-mode: invalid value", () => {+ expect(parseCssValue("text-wrap-mode", "not-valid")).toEqual({+ type: "invalid",+ value: "not-valid",+ });+ });++ test("text-wrap-mode: var() is accepted", () => {+ expect(parseCssValue("text-wrap-mode", "var(--tw-mode)")).toEqual({+ type: "var",+ value: "tw-mode",+ });+ });++ test("text-wrap-style: valid keyword", () => {+ expect(parseCssValue("text-wrap-style", "balance")).toEqual({+ type: "keyword",+ value: "balance",+ });+ expect(parseCssValue("text-wrap-style", "auto")).toEqual({+ type: "keyword",+ value: "auto",+ });+ });++ test("text-wrap-style: var() is accepted", () => {+ expect(parseCssValue("text-wrap-style", "var(--style)")).toEqual({+ type: "var",+ value: "style",+ });+ });+});diff --git a/packages/css-data/src/parse-css-value.ts b/packages/css-data/src/parse-css-value.tsindex 718478b38d..3d0a6ff07d 100644--- a/packages/css-data/src/parse-css-value.ts+++ b/packages/css-data/src/parse-css-value.ts@@ -1,4 +1,3 @@-import * as colorjs from "colorjs.io/fn";import {type CssNode,type FunctionNode,@@ -6,9 +5,13 @@ import {lexer,List,parse,+ walk,} from "css-tree";import warnOnce from "warn-once";import {+ color,+ toColorSpace,+ toColorComponent,cssWideKeywords,type ImageValue,type KeywordValue,@@ -30,21 +33,6 @@ import {import { keywordValues } from "./__generated__/keyword-values";import { units } from "./__generated__/units";-colorjs.ColorSpace.register(colorjs.sRGB);-colorjs.ColorSpace.register(colorjs.sRGB_Linear);-colorjs.ColorSpace.register(colorjs.HSL);-colorjs.ColorSpace.register(colorjs.HWB);-colorjs.ColorSpace.register(colorjs.Lab);-colorjs.ColorSpace.register(colorjs.LCH);-colorjs.ColorSpace.register(colorjs.OKLab);-colorjs.ColorSpace.register(colorjs.OKLCH);-colorjs.ColorSpace.register(colorjs.P3);-colorjs.ColorSpace.register(colorjs.A98RGB);-colorjs.ColorSpace.register(colorjs.ProPhoto);-colorjs.ColorSpace.register(colorjs.REC_2020);-colorjs.ColorSpace.register(colorjs.XYZ_D65);-colorjs.ColorSpace.register(colorjs.XYZ_D50);-export const cssTryParseValue = (input: string): undefined | CssNode => {try {const ast = parse(input, { context: "value" });@@ -72,10 +60,41 @@ export const isValidDeclaration = (property: CssProperty,value: string): boolean => {- if (property.startsWith("--") || value.includes("var(")) {+ // Custom properties accept any value.+ if (property.startsWith("--")) {return true;}+ // Parse once upfront for structural inspection. cssTryParseValue may return+ // null for values that the browser can still handle (csstree has known gaps),+ // so null here does NOT mean the value is invalid — we fall through to other paths.+ const ast = cssTryParseValue(value);++ // Two CSS constructs cannot be validated by any lexer path and must be accepted+ // unconditionally regardless of property:+ // var() — the variable's value is unknown at validation time+ // relative color (rgb(from ...), oklch(from ...), etc.) — csstree lexer+ // returns the same "Mismatch" error as genuinely invalid values+ // Detecting these here also ensures var() stays valid for the keyword-only+ // properties below, which don't go through CSSStyleValue.parse.+ if (ast != null) {+ let hasUncheckedSyntax = false;+ walk(ast, (node) => {+ if (node.type === "Function") {+ if (+ node.name === "var" ||+ (node.children.first?.type === "Identifier" &&+ node.children.first.name === "from")+ ) {+ hasUncheckedSyntax = true;+ }+ }+ });+ if (hasUncheckedSyntax) {+ return true;+ }+ }+// these properties have poor support in browser// though rendered styles are merged as shorthand// so validate artifically@@ -99,8 +118,8 @@ export const isValidDeclaration = (}}- const ast = cssTryParseValue(value);-+ // Non-browser (test) path — use csstree lexer.+ // Bail out if the AST parse above failed; the lexer can't work without it.if (ast == null) {return false;}@@ -116,6 +135,7 @@ export const isValidDeclaration = (}}+ // Reuse the AST parsed above — no second cssTryParseValue call needed.const matchResult = lexer.matchProperty(property, ast);// allow to parse unknown properties as unparsed@@ -158,45 +178,23 @@ const tupleProps = new Set<CssProperty>([const availableUnits = new Set<string>(Object.values(units).flat());-// Map color space names to supported ColorValue color spaces-const colorSpace: Record<string, ColorValue["colorSpace"]> = {- srgb: "srgb",- "srgb-linear": "srgb-linear",- "display-p3": "p3",- p3: "p3",- hsl: "hsl",- hwb: "hwb",- lab: "lab",- lch: "lch",- oklab: "oklab",- oklch: "oklch",- "a98-rgb": "a98rgb",- a98rgb: "a98rgb",- "prophoto-rgb": "prophoto",- prophoto: "prophoto",- rec2020: "rec2020",- "xyz-d65": "xyz-d65",- "xyz-d50": "xyz-d50",- xyz: "xyz-d65", // default to d65-};--const toColorComponent = (value: undefined | null | number) =>- Math.round((value ?? 0) * 10000) / 10000;-export const parseColor = (colorString: string): undefined | ColorValue => {// does not match css variables which are incorrectly treated by colorjs.ioif (!lexer.match("<color>", colorString).matched) {return;}try {- const color = colorjs.parse(colorString);+ // css-tree's generator strips the space before negative values (e.g. "0.1-0.2").+ // Restore it so colorjs can tokenize color function arguments correctly.+ const normalized = colorString.replace(/([\d.])-(\d)/g, "$1 -$2");+ const colorResult = color.parse(normalized);return {type: "color",- colorSpace: colorSpace[color.spaceId],- components: color.coords.map(+ colorSpace: toColorSpace(color.ColorSpace.get(colorResult.spaceId)),+ components: colorResult.coords.map(toColorComponent) as ColorValue["components"],- alpha: toColorComponent(color.alpha),+ alpha: toColorComponent(colorResult.alpha),};} catch {// Invalid colors or relative color syntax are treated as unparsed@@ -391,9 +389,10 @@ const parseLiteral = (};}if (node?.type === "Hash") {- const color = parseColor(`#${node.value}`);+ const hexString = `#${node.value}`;+ const color = parseColor(hexString);if (color) {- return color;+ return { ...color, colorSpace: "hex" };}}if (node?.type === "Function") {diff --git a/packages/css-data/src/parse-css.test.ts b/packages/css-data/src/parse-css.test.tsindex baf5d45385..da708e99c2 100644--- a/packages/css-data/src/parse-css.test.ts+++ b/packages/css-data/src/parse-css.test.ts@@ -24,7 +24,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -159,7 +159,7 @@ describe("Parse CSS", () => {property: "background-color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [0.9216, 1, 0.9882],},@@ -217,7 +217,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -232,7 +232,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -249,7 +249,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -265,7 +265,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -280,7 +280,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -291,7 +291,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -307,7 +307,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -318,7 +318,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -342,7 +342,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -568,7 +568,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -583,7 +583,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},@@ -598,7 +598,7 @@ describe("Parse CSS", () => {property: "color",value: {type: "color",- colorSpace: "srgb",+ colorSpace: "hex",alpha: 1,components: [1, 0, 0],},diff --git a/packages/css-engine/package.json b/packages/css-engine/package.jsonindex ec3d83e2b8..8bc2454d0b 100644--- a/packages/css-engine/package.json+++ b/packages/css-engine/package.json@@ -14,6 +14,7 @@"dependencies": {"@emotion/hash": "^0.9.2","@webstudio-is/fonts": "workspace:*",+ "colorjs.io": "^0.6.1","zod": "^3.24.2"},"devDependencies": {diff --git a/packages/css-engine/src/color.test.ts b/packages/css-engine/src/color.test.tsnew file mode 100644index 0000000000..9bc0e7fcc3--- /dev/null+++ b/packages/css-engine/src/color.test.ts@@ -0,0 +1,191 @@+import { describe, test, expect } from "vitest";+import { sRGB } from "colorjs.io/fn";+import {+ color,+ toColorSpace,+ toColorComponent,+ srgbColor,+ transparentColor,+ whiteColor,+ parseColor,+ colorDistance,+ lerpColor,+ serializeColor,+} from "./color";++describe("toColorComponent", () => {+ test("rounds to 4 decimal places", () => {+ expect(toColorComponent(0.123456789)).toBe(0.1235);+ });+ test("treats null/undefined as 0", () => {+ expect(toColorComponent(null)).toBe(0);+ expect(toColorComponent(undefined)).toBe(0);+ });+ test("preserves exact values", () => {+ expect(toColorComponent(1)).toBe(1);+ expect(toColorComponent(0)).toBe(0);+ });+});++describe("toColorSpace", () => {+ test("maps all registered spaces", () => {+ expect(toColorSpace(color.sRGB)).toBe("srgb");+ expect(toColorSpace(color.sRGB_Linear)).toBe("srgb-linear");+ expect(toColorSpace(color.HSL)).toBe("hsl");+ expect(toColorSpace(color.HWB)).toBe("hwb");+ expect(toColorSpace(color.Lab)).toBe("lab");+ expect(toColorSpace(color.LCH)).toBe("lch");+ expect(toColorSpace(color.OKLab)).toBe("oklab");+ expect(toColorSpace(color.OKLCH)).toBe("oklch");+ expect(toColorSpace(color.P3)).toBe("p3");+ expect(toColorSpace(color.A98RGB)).toBe("a98rgb");+ expect(toColorSpace(color.ProPhoto)).toBe("prophoto");+ expect(toColorSpace(color.REC_2020)).toBe("rec2020");+ expect(toColorSpace(color.XYZ_D65)).toBe("xyz-d65");+ expect(toColorSpace(color.XYZ_D50)).toBe("xyz-d50");+ });+ test("resolves CSS aliases via ColorSpace.get()", () => {+ expect(toColorSpace(color.ColorSpace.get("display-p3"))).toBe("p3");+ expect(toColorSpace(color.ColorSpace.get("a98-rgb"))).toBe("a98rgb");+ expect(toColorSpace(color.ColorSpace.get("prophoto-rgb"))).toBe("prophoto");+ expect(toColorSpace(color.ColorSpace.get("xyz"))).toBe("xyz-d65");+ });+});++describe("srgbColor", () => {+ test("creates a PlainColorObject with sRGB space", () => {+ const color = srgbColor(0.5, 0.25, 0.75);+ expect(color.coords).toEqual([0.5, 0.25, 0.75]);+ expect(color.alpha).toBe(1);+ expect(color.space).toBe(sRGB);+ });+ test("accepts custom alpha", () => {+ const color = srgbColor(1, 0, 0, 0.5);+ expect(color.alpha).toBe(0.5);+ });+});++describe("transparentColor", () => {+ test("is black with zero alpha", () => {+ expect(transparentColor.coords).toEqual([0, 0, 0]);+ expect(transparentColor.alpha).toBe(0);+ });+});++describe("whiteColor", () => {+ test("is white with full alpha", () => {+ expect(whiteColor.coords).toEqual([1, 1, 1]);+ expect(whiteColor.alpha).toBe(1);+ });+});++describe("parseColor", () => {+ test("parses hex color to sRGB", () => {+ const color = parseColor("#ff0000");+ expect(color.coords[0]).toBeCloseTo(1, 4);+ expect(color.coords[1]).toBeCloseTo(0, 4);+ expect(color.coords[2]).toBeCloseTo(0, 4);+ expect(color.alpha).toBe(1);+ });+ test("parses rgba color", () => {+ const color = parseColor("rgba(0, 128, 255, 0.5)");+ expect(color.coords[0]).toBeCloseTo(0, 4);+ expect(color.coords[1]).toBeCloseTo(128 / 255, 2);+ expect(color.coords[2]).toBeCloseTo(1, 4);+ expect(color.alpha).toBeCloseTo(0.5, 4);+ });+ test("parses named colors", () => {+ const color = parseColor("white");+ expect(color.coords[0]).toBeCloseTo(1, 4);+ expect(color.coords[1]).toBeCloseTo(1, 4);+ expect(color.coords[2]).toBeCloseTo(1, 4);+ });+ test("parses oklch color to sRGB", () => {+ const color = parseColor("oklch(0.7 0.15 180)");+ // Just check it returns valid sRGB coords+ expect(color.coords).toHaveLength(3);+ expect(color.alpha).toBe(1);+ });+ test("returns transparentColor for unparseable strings", () => {+ const color = parseColor("not-a-color");+ // In non-browser env, canvas fallback returns undefined, so we get transparentColor+ expect(color.alpha).toBe(0);+ });+});++describe("colorDistance", () => {+ test("distance between identical colors is 0", () => {+ const red = srgbColor(1, 0, 0);+ expect(colorDistance(red, red)).toBe(0);+ });+ test("distance between black and white", () => {+ const black = srgbColor(0, 0, 0);+ const white = srgbColor(1, 1, 1);+ expect(colorDistance(black, white)).toBeCloseTo(Math.sqrt(3), 10);+ });+ test("includes alpha in distance calculation", () => {+ const a = srgbColor(0, 0, 0, 0);+ const b = srgbColor(0, 0, 0, 1);+ expect(colorDistance(a, b)).toBe(1);+ });+ test("distance between red and green", () => {+ const red = srgbColor(1, 0, 0);+ const green = srgbColor(0, 1, 0);+ expect(colorDistance(red, green)).toBeCloseTo(Math.sqrt(2), 10);+ });+});++describe("lerpColor", () => {+ test("ratio 0 returns first color", () => {+ const a = srgbColor(0, 0, 0);+ const b = srgbColor(1, 1, 1);+ const result = lerpColor(a, b, 0);+ expect(result.coords).toEqual([0, 0, 0]);+ expect(result.alpha).toBe(1);+ });+ test("ratio 1 returns second color", () => {+ const a = srgbColor(0, 0, 0);+ const b = srgbColor(1, 1, 1);+ const result = lerpColor(a, b, 1);+ expect(result.coords).toEqual([1, 1, 1]);+ expect(result.alpha).toBe(1);+ });+ test("ratio 0.5 returns midpoint", () => {+ const a = srgbColor(0, 0, 0);+ const b = srgbColor(1, 1, 1);+ const result = lerpColor(a, b, 0.5);+ expect(result.coords[0]).toBeCloseTo(0.5, 10);+ expect(result.coords[1]).toBeCloseTo(0.5, 10);+ expect(result.coords[2]).toBeCloseTo(0.5, 10);+ });+ test("interpolates alpha", () => {+ const a = srgbColor(0, 0, 0, 0);+ const b = srgbColor(0, 0, 0, 1);+ const result = lerpColor(a, b, 0.25);+ expect(result.alpha).toBeCloseTo(0.25, 10);+ });+});++describe("serializeColor", () => {+ test("serializes opaque sRGB color to rgb()", () => {+ const color = srgbColor(1, 0, 0.5);+ expect(serializeColor(color)).toBe("rgb(255, 0, 128)");+ });+ test("serializes semi-transparent color to rgba()", () => {+ const color = srgbColor(0, 1, 0, 0.5);+ expect(serializeColor(color)).toBe("rgba(0, 255, 0, 0.5)");+ });+ test("serializes black", () => {+ expect(serializeColor(srgbColor(0, 0, 0))).toBe("rgb(0, 0, 0)");+ });+ test("serializes white", () => {+ expect(serializeColor(whiteColor)).toBe("rgb(255, 255, 255)");+ });+ test("serializes transparent color", () => {+ expect(serializeColor(transparentColor)).toBe("rgba(0, 0, 0, 0)");+ });+ test("rounds components to integers", () => {+ const color = srgbColor(0.502, 0.502, 0.502);+ expect(serializeColor(color)).toBe("rgb(128, 128, 128)");+ });+});diff --git a/packages/css-engine/src/color.ts b/packages/css-engine/src/color.tsnew file mode 100644index 0000000000..4e7bfd1ad8--- /dev/null+++ b/packages/css-engine/src/color.ts@@ -0,0 +1,177 @@+import * as colorjs from "colorjs.io/fn";+export type {+ PlainColorObject,+ ColorConstructor,+ ColorSpace,+ Coords,+} from "colorjs.io/fn";+import type { ColorSpace, PlainColorObject } from "colorjs.io/fn";+import type { ColorValue } from "./schema";++// ─── Color space registration ────────────────────────────────────────────────+// Registers all color spaces once on import so every consumer gets them+// automatically. This is a side-effect import for downstream modules.++colorjs.ColorSpace.register(colorjs.sRGB);+colorjs.ColorSpace.register(colorjs.sRGB_Linear);+colorjs.ColorSpace.register(colorjs.HSL);+colorjs.ColorSpace.register(colorjs.HWB);+colorjs.ColorSpace.register(colorjs.Lab);+colorjs.ColorSpace.register(colorjs.LCH);+colorjs.ColorSpace.register(colorjs.OKLab);+colorjs.ColorSpace.register(colorjs.OKLCH);+colorjs.ColorSpace.register(colorjs.P3);+colorjs.ColorSpace.register(colorjs.A98RGB);+colorjs.ColorSpace.register(colorjs.ProPhoto);+colorjs.ColorSpace.register(colorjs.REC_2020);+colorjs.ColorSpace.register(colorjs.XYZ_D65);+colorjs.ColorSpace.register(colorjs.XYZ_D50);++// Register CSS aliases that differ from the internal colorjs id so that+// ColorSpace.get() resolves them (e.g. from hdr-color-input values).+colorjs.ColorSpace.registry["display-p3"] = colorjs.P3;+colorjs.ColorSpace.registry["a98-rgb"] = colorjs.A98RGB;+colorjs.ColorSpace.registry["prophoto-rgb"] = colorjs.ProPhoto;++// Re-export colorjs as `color` so consumers never need to import colorjs.io/fn+// directly. Importing this module guarantees all color spaces are registered.+export const color = colorjs;++// ─── Shared utilities ────────────────────────────────────────────────────────++// Map each registered ColorSpace to its canonical ColorValue["colorSpace"] string.+// For all currently registered spaces, space.id already matches, but the map+// ensures exhaustiveness: registering a new space without adding it here will+// cause toColorSpace() to throw at runtime.+const registeredSpaces = new Map<ColorSpace, ColorValue["colorSpace"]>([+ [colorjs.sRGB, "srgb"],+ [colorjs.sRGB_Linear, "srgb-linear"],+ [colorjs.HSL, "hsl"],+ [colorjs.HWB, "hwb"],+ [colorjs.Lab, "lab"],+ [colorjs.LCH, "lch"],+ [colorjs.OKLab, "oklab"],+ [colorjs.OKLCH, "oklch"],+ [colorjs.P3, "p3"],+ [colorjs.A98RGB, "a98rgb"],+ [colorjs.ProPhoto, "prophoto"],+ [colorjs.REC_2020, "rec2020"],+ [colorjs.XYZ_D65, "xyz-d65"],+ [colorjs.XYZ_D50, "xyz-d50"],+]);++// Convert a colorjs ColorSpace instance to the canonical ColorValue["colorSpace"].+export const toColorSpace = (space: ColorSpace): ColorValue["colorSpace"] => {+ const id = registeredSpaces.get(space);+ if (id === undefined) {+ throw new Error(`Unregistered color space: ${space.id}`);+ }+ return id;+};++// Round a color component to 4 decimal places, treating undefined/null as 0.+export const toColorComponent = (value: undefined | null | number) =>+ Math.round((value ?? 0) * 10000) / 10000;++// ─── Color helpers ───────────────────────────────────────────────────────────++// Create an sRGB PlainColorObject. Coords are in the [0, 1] range.+export const srgbColor = (+ r: number,+ g: number,+ b: number,+ alpha: number = 1+): PlainColorObject => ({+ space: colorjs.sRGB,+ coords: [r, g, b],+ alpha,+});++export const transparentColor = srgbColor(0, 0, 0, 0);+export const whiteColor = srgbColor(1, 1, 1, 1);++// Resolve a color string via the browser canvas API. Handles color-mix(),+// relative color syntax, and other browser-native color functions that colorjs+// can't parse. Returns undefined in non-browser environments.+const resolveColorViaCanvas = (+ colorString: string+): PlainColorObject | undefined => {+ if (typeof document === "undefined") {+ return;+ }+ const canvas = document.createElement("canvas");+ canvas.width = 1;+ canvas.height = 1;+ const ctx = canvas.getContext("2d");+ if (!ctx) {+ return;+ }+ ctx.fillStyle = colorString;+ ctx.fillRect(0, 0, 1, 1);+ const [r, g, b, a] = ctx.getImageData(0, 0, 1, 1).data;+ return srgbColor(+ (r ?? 0) / 255,+ (g ?? 0) / 255,+ (b ?? 0) / 255,+ (a ?? 255) / 255+ );+};++// Parse a CSS color string to an sRGB PlainColorObject.+// Falls back to a canvas-based resolution for color-mix() and relative color+// syntax that colorjs doesn't handle. Returns transparentColor when parsing+// fails entirely (or in SSR environments).+export const parseColor = (cssString: string): PlainColorObject => {+ try {+ return colorjs.to(cssString, "srgb");+ } catch {+ return resolveColorViaCanvas(cssString) ?? transparentColor;+ }+};++// Euclidean distance between two sRGB colors (including alpha channel).+export const colorDistance = (+ a: PlainColorObject,+ b: PlainColorObject+): number => {+ const [ar, ag, ab] = a.coords;+ const [br, bg, bb] = b.coords;+ return Math.sqrt(+ ((ar ?? 0) - (br ?? 0)) ** 2 ++ ((ag ?? 0) - (bg ?? 0)) ** 2 ++ ((ab ?? 0) - (bb ?? 0)) ** 2 ++ ((a.alpha ?? 1) - (b.alpha ?? 1)) ** 2+ );+};++// Linear interpolation between two colors.+export const lerpColor = (+ a: PlainColorObject,+ b: PlainColorObject,+ ratio: number+): PlainColorObject => {+ const lerp = (start: number, end: number, t: number) =>+ start * (1 - t) + end * t;+ return {+ space: a.space,+ coords: [+ lerp(a.coords[0] ?? 0, b.coords[0] ?? 0, ratio),+ lerp(a.coords[1] ?? 0, b.coords[1] ?? 0, ratio),+ lerp(a.coords[2] ?? 0, b.coords[2] ?? 0, ratio),+ ],+ alpha: lerp(a.alpha ?? 1, b.alpha ?? 1, ratio),+ };+};++// Serialize an sRGB PlainColorObject to a CSS rgb()/rgba() string.+export const serializeColor = (color: PlainColorObject): string => {+ const [r, g, b] = color.coords;+ const red = Math.round((r ?? 0) * 255);+ const green = Math.round((g ?? 0) * 255);+ const blue = Math.round((b ?? 0) * 255);+ const alpha = color.alpha ?? 1;+ if (alpha < 1) {+ return `rgba(${red}, ${green}, ${blue}, ${alpha})`;+ }+ return `rgb(${red}, ${green}, ${blue})`;+};diff --git a/packages/css-engine/src/core/to-value.test.ts b/packages/css-engine/src/core/to-value.test.tsindex 01b7bb12de..8319ed53f5 100644--- a/packages/css-engine/src/core/to-value.test.ts+++ b/packages/css-engine/src/core/to-value.test.ts@@ -1,5 +1,6 @@import { describe, test, expect } from "vitest";import { toValue } from "./to-value";+import type { ColorValue } from "../schema";describe("Convert WS CSS Values to native CSS strings", () => {test("keyword", () => {@@ -331,37 +332,120 @@ describe("Convert WS CSS Values to native CSS strings", () => {components: [0.8, 0.4, 0.6],alpha: 0.8,});- expect(value).toBe("color(p3 0.8 0.4 0.6 / 0.8)");+ expect(value).toBe("color(display-p3 0.8 0.4 0.6 / 0.8)");});- test("color with xyz-d65 uses color() function", () => {+ test("color with a98rgb color space uses a98-rgb CSS name", () => {const value = toValue({type: "color",- colorSpace: "xyz-d65",- components: [0.5, 0.3, 0.2],+ colorSpace: "a98rgb",+ components: [0.5, 0.3, 0.7],alpha: 1,});- expect(value).toBe("color(xyz-d65 0.5 0.3 0.2 / 1)");+ expect(value).toBe("color(a98-rgb 0.5 0.3 0.7 / 1)");});- test("color with CSS variable as alpha channel (srgb)", () => {+ test("color with prophoto color space uses prophoto-rgb CSS name", () => {const value = toValue({type: "color",- colorSpace: "srgb",- components: [0.1098, 0.098, 0.0902],- alpha: { type: "var", value: "tw-text-opacity" },+ colorSpace: "prophoto",+ components: [0.6, 0.4, 0.2],+ alpha: 1,});- expect(value).toBe("rgb(28 25 23 / var(--tw-text-opacity))");+ expect(value).toBe("color(prophoto-rgb 0.6 0.4 0.2 / 1)");});- test("color with CSS variable as alpha channel (p3)", () => {+ test("color with xyz-d65 uses color() function", () => {const value = toValue({type: "color",- colorSpace: "p3",- components: [0.4, 0.6, 0.3],- alpha: { type: "var", value: "tw-bg-opacity" },+ colorSpace: "xyz-d65",+ components: [0.5, 0.3, 0.2],+ alpha: 1,});- expect(value).toBe("color(p3 0.4 0.6 0.3 / var(--tw-bg-opacity))");+ expect(value).toBe("color(xyz-d65 0.5 0.3 0.2 / 1)");+ });++ describe("CSS variable as alpha channel", () => {+ // hex is excluded: the hex serializer ignores non-numeric alpha (no / slot).+ // Using satisfies Record<Exclude<...>, unknown> ensures TypeScript errors+ // when a new color space is added to ColorValue without a test entry here.+ const cases = {+ srgb: {+ components: [1, 0, 0] as ColorValue["components"],+ expected: "rgb(255 0 0 / var(--opacity))",+ },+ hsl: {+ components: [120, 100, 50] as ColorValue["components"],+ expected: "hsl(120 100% 50% / var(--opacity))",+ },+ hwb: {+ components: [45, 10, 20] as ColorValue["components"],+ expected: "hwb(45 10% 20% / var(--opacity))",+ },+ lab: {+ components: [50, 20, 30] as ColorValue["components"],+ expected: "lab(50% 20 30 / var(--opacity))",+ },+ lch: {+ components: [50, 20, 120] as ColorValue["components"],+ expected: "lch(50% 20 120 / var(--opacity))",+ },+ oklab: {+ components: [0.6, 0.1, -0.1] as ColorValue["components"],+ expected: "oklab(0.6 0.1 -0.1 / var(--opacity))",+ },+ oklch: {+ components: [0.5, 0.1, 180] as ColorValue["components"],+ expected: "oklch(0.5 0.1 180 / var(--opacity))",+ },+ p3: {+ components: [0.4, 0.6, 0.3] as ColorValue["components"],+ expected: "color(display-p3 0.4 0.6 0.3 / var(--opacity))",+ },+ "srgb-linear": {+ components: [1, 0, 0] as ColorValue["components"],+ expected: "color(srgb-linear 1 0 0 / var(--opacity))",+ },+ a98rgb: {+ components: [0.5, 0.3, 0.7] as ColorValue["components"],+ expected: "color(a98-rgb 0.5 0.3 0.7 / var(--opacity))",+ },+ prophoto: {+ components: [0.6, 0.4, 0.2] as ColorValue["components"],+ expected: "color(prophoto-rgb 0.6 0.4 0.2 / var(--opacity))",+ },+ rec2020: {+ components: [0.4, 0.6, 0.3] as ColorValue["components"],+ expected: "color(rec2020 0.4 0.6 0.3 / var(--opacity))",+ },+ "xyz-d65": {+ components: [0.5, 0.3, 0.2] as ColorValue["components"],+ expected: "color(xyz-d65 0.5 0.3 0.2 / var(--opacity))",+ },+ "xyz-d50": {+ components: [0.4, 0.6, 0.3] as ColorValue["components"],+ expected: "color(xyz-d50 0.4 0.6 0.3 / var(--opacity))",+ },+ } satisfies Record<Exclude<ColorValue["colorSpace"], "hex">, unknown>;++ for (const [colorSpace, { components, expected }] of Object.entries(+ cases+ ) as Array<+ [+ Exclude<ColorValue["colorSpace"], "hex">,+ { components: ColorValue["components"]; expected: string },+ ]+ >) {+ test(colorSpace, () => {+ const value = toValue({+ type: "color",+ colorSpace,+ components,+ alpha: { type: "var", value: "opacity" },+ });+ expect(value).toBe(expected);+ });+ }});test("color in tuple", () => {@@ -380,6 +464,56 @@ describe("Convert WS CSS Values to native CSS strings", () => {expect(value).toBe("oklch(0.5 0.1 180 / 1) 10px");});+ test("color with hex color space (opaque)", () => {+ const value = toValue({+ type: "color",+ colorSpace: "hex",+ components: [1, 0, 0],+ alpha: 1,+ });+ expect(value).toBe("#ff0000");+ });++ test("color with hex color space (with alpha)", () => {+ const value = toValue({+ type: "color",+ colorSpace: "hex",+ components: [1, 0, 0],+ alpha: 0.5,+ });+ expect(value).toBe("#ff000080");+ });++ test("color with srgb-linear color space", () => {+ const value = toValue({+ type: "color",+ colorSpace: "srgb-linear",+ components: [1, 0, 0],+ alpha: 1,+ });+ expect(value).toBe("color(srgb-linear 1 0 0 / 1)");+ });++ test("color with rec2020 color space", () => {+ const value = toValue({+ type: "color",+ colorSpace: "rec2020",+ components: [0.4, 0.6, 0.3],+ alpha: 1,+ });+ expect(value).toBe("color(rec2020 0.4 0.6 0.3 / 1)");+ });++ test("color with xyz-d50 color space", () => {+ const value = toValue({+ type: "color",+ colorSpace: "xyz-d50",+ components: [0.4, 0.6, 0.3],+ alpha: 1,+ });+ expect(value).toBe("color(xyz-d50 0.4 0.6 0.3 / 1)");+ });+test("color in shadow", () => {const value = toValue({type: "shadow",diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.tsindex faed7e8a9e..cd4dec85b0 100644--- a/packages/css-engine/src/core/to-value.ts+++ b/packages/css-engine/src/core/to-value.ts@@ -94,6 +94,15 @@ export const toValue = (// Use specific CSS functions when availableswitch (value.colorSpace) {+ case "hex": {+ const toHex = (v: number) =>+ Math.round(Math.min(Math.max(v, 0), 1) * 255)+ .toString(16)+ .padStart(2, "0");+ const hex = `#${toHex(c1)}${toHex(c2)}${toHex(c3)}`;+ const alphaNum = typeof alpha === "number" ? alpha : 1;+ return alphaNum < 1 ? hex + toHex(alphaNum) : hex;+ }case "srgb": {c1 = Math.round(c1 * 255);c2 = Math.round(c2 * 255);@@ -112,11 +121,15 @@ export const toValue = (return `oklab(${c1} ${c2} ${c3} / ${alpha})`;case "oklch":return `oklch(${c1} ${c2} ${c3} / ${alpha})`;- // Fall back to color() function for less common color spaces+ // Fall back to color() function for less common color spaces.+ // colorjs uses internal short names that differ from CSS predefined color space identifiers.case "p3":- case "srgb-linear":+ return `color(display-p3 ${c1} ${c2} ${c3} / ${alpha})`;case "a98rgb":+ return `color(a98-rgb ${c1} ${c2} ${c3} / ${alpha})`;case "prophoto":+ return `color(prophoto-rgb ${c1} ${c2} ${c3} / ${alpha})`;+ case "srgb-linear":case "rec2020":case "xyz-d65":case "xyz-d50":diff --git a/packages/css-engine/src/index.ts b/packages/css-engine/src/index.tsindex 6f0def93eb..8a4800549d 100644--- a/packages/css-engine/src/index.ts+++ b/packages/css-engine/src/index.ts@@ -1,6 +1,7 @@export * from "./core/index";export * from "./schema";export * from "./css";+export * from "./color";// necessary for sdk dts generationexport type { Unit as __Unit } from "./__generated__/types";diff --git a/packages/css-engine/src/schema.ts b/packages/css-engine/src/schema.tsindex de7e81e46c..bdd28ac69f 100644--- a/packages/css-engine/src/schema.ts+++ b/packages/css-engine/src/schema.ts@@ -69,6 +69,7 @@ export type RgbValue = z.infer<typeof RgbValue>;export type ColorValue = {type: "color";colorSpace:+ | "hex"| "srgb"| "p3"| "srgb-linear"@@ -92,6 +93,7 @@ export const ColorValue: z.ZodType<ColorValue> = z.object({type: z.literal("color"),// all these color spaces are defined by design tokens specificationcolorSpace: z.union([+ z.literal("hex"),z.literal("srgb"),z.literal("p3"),z.literal("srgb-linear"),diff --git a/packages/design-system/package.json b/packages/design-system/package.jsonindex 9dc00465c2..ffc7e89522 100644--- a/packages/design-system/package.json+++ b/packages/design-system/package.json@@ -63,8 +63,8 @@"@webstudio-is/icons": "workspace:*","change-case": "^5.4.4","cmdk": "^1.1.1",- "colorjs.io": "^0.6.1","downshift": "^6.1.7",+ "hdr-color-input": "^0.4.0","match-sorter": "^8.0.0","react-colorful": "^5.6.1","react-hot-toast": "^2.5.1",@@ -74,7 +74,10 @@"warn-once": "^0.1.1"},"exports": {- "webstudio": "./src/index.ts"+ ".": {+ "webstudio": "./src/index.ts"+ },+ "./test-setup": "./src/test-setup.ts"},"license": "AGPL-3.0-or-later","private": true,diff --git a/packages/design-system/src/components/color-picker.stories.tsx b/packages/design-system/src/components/color-picker.stories.tsxindex 75570a55c0..55d579ee8a 100644--- a/packages/design-system/src/components/color-picker.stories.tsx+++ b/packages/design-system/src/components/color-picker.stories.tsx@@ -2,11 +2,9 @@ import { useState } from "react";import type { RgbValue, StyleValue } from "@webstudio-is/css-engine";import {ColorPicker as ColorPickerComponent,- ColorPickerPopover,ColorThumb,} from "./color-picker";import { Flex } from "./flex";-import { Grid } from "./grid";import { Text } from "./text";import { StorySection } from "./storybook";@@ -23,38 +21,25 @@ const initialColor: RgbValue = {};export const ColorPicker = () => {- const [inlineValue, setInlineValue] = useState<StyleValue>(initialColor);- const [popoverValue, setPopoverValue] = useState<StyleValue>(initialColor);+ const [value, setValue] = useState<StyleValue>(initialColor);+ const [open, setOpen] = useState(true);return (<>- <StorySection title="Inline">+ <StorySection title="Color Picker"><Flex direction="column" gap="2"><ColorPickerComponent- value={inlineValue}- onChange={(value) => {- if (value !== undefined) {- setInlineValue(value);+ value={value}+ open={open}+ onOpenChange={setOpen}+ onChange={(val) => {+ if (val !== undefined) {+ setValue(val);}}}- onChangeComplete={setInlineValue}+ onChangeComplete={setValue}/>- <Text>{JSON.stringify(inlineValue)}</Text>- </Flex>- </StorySection>-- <StorySection title="Popover">- <Flex direction="column" gap="2">- <ColorPickerPopover- value={popoverValue}- onChange={(value) => {- if (value !== undefined) {- setPopoverValue(value);- }- }}- onChangeComplete={setPopoverValue}- />- <Text>{JSON.stringify(popoverValue)}</Text>+ <Text>{JSON.stringify(value)}</Text></Flex></StorySection>@@ -69,63 +54,3 @@ export const ColorPicker = () => {</>);};--export const PopoverPositioning = () => {- const [value, setValue] = useState<StyleValue>(initialColor);- const handleChange = (val: StyleValue | undefined) => {- if (val !== undefined) {- setValue(val);- }- };- return (- <Grid- columns={2}- gap="9"- align="center"- justify="center"- style={{ padding: 100, minHeight: "100vh" }}- >- <Flex direction="column" gap="2" align="center">- <Text variant="labels">Side top</Text>- <ColorPickerPopover- value={value}- onChange={handleChange}- onChangeComplete={setValue}- side="top"- open={true}- />- </Flex>- <Flex direction="column" gap="2" align="center">- <Text variant="labels">Side right</Text>- <ColorPickerPopover- value={value}- onChange={handleChange}- onChangeComplete={setValue}- side="right"- open={true}- />- </Flex>- <Flex direction="column" gap="2" align="center">- <Text variant="labels">Align start</Text>- <ColorPickerPopover- value={value}- onChange={handleChange}- onChangeComplete={setValue}- side="bottom"- align="start"- open={true}- />- </Flex>- <Flex direction="column" gap="2" align="center">- <Text variant="labels">Side offset 16</Text>- <ColorPickerPopover- value={value}- onChange={handleChange}- onChangeComplete={setValue}- sideOffset={16}- open={true}- />- </Flex>- </Grid>- );-};diff --git a/packages/design-system/src/components/color-picker.test.ts b/packages/design-system/src/components/color-picker.test.tsnew file mode 100644index 0000000000..20f757617c--- /dev/null+++ b/packages/design-system/src/components/color-picker.test.ts@@ -0,0 +1,165 @@+import { describe, test, expect } from "vitest";+import type { ColorSpace } from "hdr-color-input";+import type { ColorValue } from "@webstudio-is/css-engine";+import { __testing__ } from "./color-picker";+const { cssStringToStyleValue } = __testing__;++// All ColorSpace values from hdr-color-input and their expected CSS input strings+// (as <color-input> would emit in its change event).+describe("cssStringToStyleValue", () => {+ // Keyed by ColorValue["colorSpace"] so TypeScript errors when a new color+ // space is added to the schema without adding a corresponding test entry.+ const cases = {+ hex: {+ css: "#ff0000",+ space: "hex",+ colorSpace: "hex",+ components: [1, 0, 0],+ alpha: 1,+ },+ srgb: {+ css: "rgb(0 128 255)",+ space: "srgb",+ colorSpace: "srgb",+ components: [0, 0.502, 1],+ alpha: 1,+ },+ hsl: {+ css: "hsl(120 100% 50%)",+ space: "hsl",+ colorSpace: "hsl",+ components: [120, 100, 50],+ alpha: 1,+ },+ hwb: {+ css: "hwb(120 0% 0%)",+ space: "hwb",+ colorSpace: "hwb",+ components: [120, 0, 0],+ alpha: 1,+ },+ lab: {+ css: "lab(50 20 30)",+ space: "lab",+ colorSpace: "lab",+ components: [50, 20, 30],+ alpha: 1,+ },+ lch: {+ css: "lch(50 40 120)",+ space: "lch",+ colorSpace: "lch",+ components: [50, 40, 120],+ alpha: 1,+ },+ oklab: {+ css: "oklab(0.7 0.1 -0.1)",+ space: "oklab",+ colorSpace: "oklab",+ components: [0.7, 0.1, -0.1],+ alpha: 1,+ },+ oklch: {+ css: "oklch(0.7 0.1 180)",+ space: "oklch",+ colorSpace: "oklch",+ components: [0.7, 0.1, 180],+ alpha: 1,+ },+ "srgb-linear": {+ css: "color(srgb-linear 1 0 0)",+ space: "srgb-linear",+ colorSpace: "srgb-linear",+ components: [1, 0, 0],+ alpha: 1,+ },+ // display-p3 CSS name maps to internal p3 color space+ p3: {+ css: "color(display-p3 0.4 0.6 0.3)",+ space: "display-p3",+ colorSpace: "p3",+ components: [0.4, 0.6, 0.3],+ alpha: 1,+ },+ // a98-rgb CSS name maps to internal a98rgb color space+ a98rgb: {+ css: "color(a98-rgb 0.4 0.6 0.3)",+ space: "a98-rgb",+ colorSpace: "a98rgb",+ components: [0.4, 0.6, 0.3],+ alpha: 1,+ },+ prophoto: {+ css: "color(prophoto-rgb 0.4 0.6 0.3)",+ space: "prophoto",+ colorSpace: "prophoto",+ components: [0.4, 0.6, 0.3],+ alpha: 1,+ },+ rec2020: {+ css: "color(rec2020 0.4 0.6 0.3)",+ space: "rec2020",+ colorSpace: "rec2020",+ components: [0.4, 0.6, 0.3],+ alpha: 1,+ },+ "xyz-d65": {+ css: "color(xyz-d65 0.4 0.6 0.3)",+ space: "xyz-d65",+ colorSpace: "xyz-d65",+ components: [0.4, 0.6, 0.3],+ alpha: 1,+ },+ "xyz-d50": {+ css: "color(xyz-d50 0.4 0.6 0.3)",+ space: "xyz-d50",+ colorSpace: "xyz-d50",+ components: [0.4, 0.6, 0.3],+ alpha: 1,+ },+ } satisfies Record<+ ColorValue["colorSpace"],+ { space: ColorSpace; [k: string]: unknown }+ >;++ for (const [+ key,+ { css, space, colorSpace, components, alpha },+ ] of Object.entries(cases)) {+ test(key, () => {+ expect(cssStringToStyleValue(css, space as ColorSpace)).toEqual({+ type: "color",+ colorSpace,+ components,+ alpha,+ });+ });+ }++ test("xyz alias maps to xyz-d65", () => {+ expect(cssStringToStyleValue("color(xyz 0.4 0.6 0.3)", "xyz")).toEqual({+ type: "color",+ colorSpace: "xyz-d65",+ components: [0.4, 0.6, 0.3],+ alpha: 1,+ });+ });++ test("hex with alpha", () => {+ expect(cssStringToStyleValue("#ff000080", "hex")).toEqual({+ type: "color",+ colorSpace: "hex",+ components: [1, 0, 0],+ alpha: 0.502,+ });+ });++ test("alpha channel is preserved", () => {+ expect(cssStringToStyleValue("oklch(0.7 0.1 180 / 0.5)", "oklch")).toEqual({+ type: "color",+ colorSpace: "oklch",+ components: [0.7, 0.1, 180],+ alpha: 0.5,+ });+ });+});diff --git a/packages/design-system/src/components/color-picker.tsx b/packages/design-system/src/components/color-picker.tsxindex ae0b92a2ff..c9074fccbb 100644--- a/packages/design-system/src/components/color-picker.tsx+++ b/packages/design-system/src/components/color-picker.tsx@@ -1,115 +1,86 @@-import * as colorjs from "colorjs.io/fn";+import "hdr-color-input";+import type { ChangeDetail, ColorInput, ColorSpace } from "hdr-color-input";+import {+ color,+ toColorSpace,+ toColorComponent,+ parseColor,+ colorDistance,+ lerpColor,+ serializeColor,+ transparentColor,+ whiteColor,+ toValue,+ type PlainColorObject,+ type StyleValue,+ type ColorValue,+} from "@webstudio-is/css-engine";import {forwardRef,+ useCallback,type ComponentProps,type ElementRef,useEffect,- useState,+ useId,+ useRef,} from "react";import { clamp } from "@react-aria/utils";-import { useDebouncedCallback } from "use-debounce";-import { RgbaColorPicker } from "react-colorful";-import { EyedropperIcon } from "@webstudio-is/icons";-import {- toValue,- type StyleValue,- type Unit,- type RgbValue,-} from "@webstudio-is/css-engine";import { css, rawTheme, theme, type CSS } from "../stitches.config";import { useDisableCanvasPointerEvents } from "../utilities";-import { Grid } from "./grid";-import { IconButton } from "./icon-button";-import { InputField } from "./input-field";-import { Popover, PopoverContent, PopoverTrigger } from "./popover";--colorjs.ColorSpace.register(colorjs.sRGB);-colorjs.ColorSpace.register(colorjs.sRGB_Linear);-colorjs.ColorSpace.register(colorjs.HSL);-colorjs.ColorSpace.register(colorjs.HWB);-colorjs.ColorSpace.register(colorjs.Lab);-colorjs.ColorSpace.register(colorjs.LCH);-colorjs.ColorSpace.register(colorjs.OKLab);-colorjs.ColorSpace.register(colorjs.OKLCH);-colorjs.ColorSpace.register(colorjs.P3);-colorjs.ColorSpace.register(colorjs.A98RGB);-colorjs.ColorSpace.register(colorjs.ProPhoto);-colorjs.ColorSpace.register(colorjs.REC_2020);-colorjs.ColorSpace.register(colorjs.XYZ_D65);-colorjs.ColorSpace.register(colorjs.XYZ_D50);--type RgbaColor = {- r: number;- g: number;- b: number;- a: number;-};--// Helper to create RgbaColor from colorjs.io Color-const colorToRgba = (color: colorjs.PlainColorObject): RgbaColor => {- const [r, g, b] = color.coords;+import { textStyle } from "./text";++declare global {+ // eslint-disable-next-line @typescript-eslint/no-namespace+ namespace React.JSX {+ interface IntrinsicElements {+ "color-input": React.HTMLAttributes<HTMLElement> & {+ ref?: React.Ref<HTMLElement>;+ value?: string;+ colorspace?: string;+ theme?: "auto" | "light" | "dark";+ "no-alpha"?: boolean | string;+ class?: string;+ };+ }+ }+}++// ─── Color utilities ─────────────────────────────────────────────────────────++// Convert a CSS color string emitted by <color-input> into a StyleValue.+const cssStringToStyleValue = (+ cssString: string,+ colorspace: ColorSpace+): ColorValue => {+ // hdr-color-input uses a few CSS aliases that differ from our canonical ids.+ // "hex" is a UI-only format (not a real color space) that serializes as hex.+ const colorSpace: ColorValue["colorSpace"] =+ colorspace === "hex"+ ? "hex"+ : toColorSpace(color.ColorSpace.get(colorspace));+ // For hex, colorjs parses to sRGB coords under the "srgb" spaceId — we keep+ // those coords but override the colorSpace to "hex" so toValue() serializes+ // back to hex format. For other spaces, use coords as-is.+ const parsed = color.parse(cssString);+ const colorValue = colorSpace === "hex" ? color.to(parsed, "srgb") : parsed;return {- r: (r ?? 0) * 255,- g: (g ?? 0) * 255,- b: (b ?? 0) * 255,- a: color.alpha ?? 1,+ type: "color",+ colorSpace,+ components: colorValue.coords.map(+ toColorComponent+ ) as ColorValue["components"],+ alpha: toColorComponent(colorValue.alpha),};};-const transparentColor: RgbaColor = { r: 0, g: 0, b: 0, a: 0 };--// Helper to parse color string to RgbaColor-export const parseColorString = (colorString: string): RgbaColor => {- try {- return colorToRgba(colorjs.to(colorString, "srgb"));- } catch {- return transparentColor;- }-};--// Helper to convert RgbaColor to RGB string-const rgbaToRgbString = (color: RgbaColor): string => {- const { r, g, b, a } = color;- if (a < 1) {- return `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${a})`;- }- return `rgb(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)})`;-};--// Helper to convert RgbaColor to hex-const rgbaToHex = (color: RgbaColor): string => {- const { r, g, b, a } = color;- const toHex = (n: number) => {- const hex = Math.round(n).toString(16);- return hex.length === 1 ? "0" + hex : hex;- };- return `#${toHex(r)}${toHex(g)}${toHex(b)}${toHex(a * 255)}`.toUpperCase();-};+// ─── ColorThumb ──────────────────────────────────────────────────────────────-const colorfulStyles = css({- ".react-colorful__pointer": {- width: theme.spacing[10],- height: theme.spacing[10],- },-});+const borderColorSwatch = parseColor(rawTheme.colors.borderColorSwatch);-const whiteColor: RgbaColor = { r: 255, g: 255, b: 255, a: 1 };-const borderColorSwatch = colorToRgba(- colorjs.to(rawTheme.colors.borderColorSwatch, "srgb")-);--const distance = (a: RgbaColor, b: RgbaColor) =>- Math.sqrt(- Math.pow(a.r / 255 - b.r / 255, 2) +- Math.pow(a.g / 255 - b.g / 255, 2) +- Math.pow(a.b / 255 - b.b / 255, 2) +- Math.pow(a.a - b.a, 2)- );--const calcBorderColor = (color: RgbaColor) => {+const calcBorderColor = (color: PlainColorObject) => {const distanceToStartDrawBorder = 0.15;const alpha = clamp(- (distanceToStartDrawBorder - distance(whiteColor, color)) /+ (distanceToStartDrawBorder - colorDistance(whiteColor, color)) /distanceToStartDrawBorder,0,1@@ -117,17 +88,9 @@ const calcBorderColor = (color: RgbaColor) => {return lerpColor(transparentColor, borderColorSwatch, alpha);};-const lerp = (a: number, b: number, t: number) => a * (1 - t) + b * t;--const lerpColor = (a: RgbaColor, b: RgbaColor, t: number) => ({- r: lerp(a.r, b.r, t),- g: lerp(a.g, b.g, t),- b: lerp(a.b, b.b, t),- a: lerp(a.a, b.a, t),-});-const thumbStyle = css({display: "block",+ position: "relative",width: theme.spacing[9],height: theme.spacing[9],backgroundBlendMode: "difference",@@ -140,10 +103,7 @@ const thumbStyle = css({},});-export type ColorThumbProps = Omit<- ComponentProps<"button" | "span">,- "color"-> & {+type ColorThumbProps = Omit<ComponentProps<"button" | "span">, "color"> & {interactive?: boolean;color?: string;css?: CSS;@@ -151,12 +111,14 @@ export type ColorThumbProps = Omit<export const ColorThumb = forwardRef<ElementRef<"button">, ColorThumbProps>(({ interactive, color = "transparent", css, ...rest }, ref) => {- const rgba = parseColorString(color);+ const parsed = parseColor(color);+ const alpha = parsed.alpha ?? 1;const background =- rgba.a < 1- ? `repeating-conic-gradient(rgba(0,0,0,0.22) 0% 25%, transparent 0% 50%) 0% 33.33% / 40% 40%, ${color}`+ alpha < 1+ ? `repeating-conic-gradient(rgba(0,0,0,0.22) 0% 25%, transparent 0% 50%)+ 0% 33.33% / 40% 40%, ${color}`: color;- const borderColor = calcBorderColor(rgba);+ const borderColor = calcBorderColor(parsed);const Component = interactive ? "button" : "span";@@ -164,8 +126,8 @@ export const ColorThumb = forwardRef<ElementRef<"button">, ColorThumbProps>(<Componentstyle={{background,- borderColor: rgbaToRgbString(borderColor),- borderWidth: borderColor.a === 0 ? 0 : 1,+ borderColor: serializeColor(borderColor),+ borderWidth: (borderColor.alpha ?? 1) === 0 ? 0 : 1,}}className={thumbStyle({ css })}tabIndex={-1}@@ -178,206 +140,189 @@ export const ColorThumb = forwardRef<ElementRef<"button">, ColorThumbProps>(ColorThumb.displayName = "ColorThumb";-const colorResultToRgbValue = (rgb: RgbaColor): RgbValue => ({- type: "rgb",- r: rgb.r,- g: rgb.g,- b: rgb.b,- alpha: rgb.a ?? 1,-});--const normalizeHex = (value: string) => {- const trimmed = value.trim();- const hex = trimmed.startsWith("#") ? trimmed : `#${trimmed}`;- return hex;-};--const getEyeDropper = () => {- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const Constructor = (window as any).EyeDropper;- if (Constructor === undefined) {- return;- }- const eyeDropper = new Constructor();- return (callback: (rgb: string) => void) => {- eyeDropper.open().then((result: { sRGBHex: string }) => {- callback(result.sRGBHex);- });- };-};--type IntermediateColorValue = {- type: "intermediate";- value: string;- unit?: Unit;-};--type ColorPickerValue = StyleValue | IntermediateColorValue;-type ColorPickerProps = {- value: ColorPickerValue;- onChange: (value: StyleValue | undefined) => void;- onChangeComplete: (value: StyleValue) => void;-};--type ColorPickerPopoverProps = {value: StyleValue;onChange: (value: StyleValue | undefined) => void;onChangeComplete: (value: StyleValue) => void;open?: boolean;onOpenChange?: (open: boolean) => void;- thumb?: React.ReactElement;- side?: "top" | "right" | "bottom" | "left";- align?: "start" | "center" | "end";- sideOffset?: number;-};--const fixColor = (value: ColorPickerValue, color: RgbaColor) => {- if (value.type === "keyword" && value.value === "transparent") {- return { ...color, a: 1 };- }- return color;+ css?: CSS;};-const EyeDropper = ({ onChange }: { onChange: (rgb: string) => void }) => {- const open = getEyeDropper();- return (- <IconButton- disabled={open === undefined}- onClick={() => {- open?.(onChange);- }}- >- <EyedropperIcon />- </IconButton>- );-};+// Renders <color-input> with its built-in trigger chip, hiding the text input.+// The chip opens the panel natively via the Popover API.+// Our own ColorThumb is rendered on top (pointer-events: none) so that clicks+// pass through to the real chip underneath.+export const __testing__ = { cssStringToStyleValue };export const ColorPicker = ({value,onChange,onChangeComplete,-}: ColorPickerProps) => {- const [hex, setHex] = useState(() => {- const colorString =- value.type === "intermediate" ? value.value : toValue(value);- return rgbaToHex(parseColorString(colorString));- });- const normalizedHex = normalizeHex(hex);- const handleCompleteDebounced = useDebouncedCallback(- (newValue: RgbValue) => onChangeComplete(newValue),- 500- );-- return (- <>- <RgbaColorPicker- className={colorfulStyles.toString()}- color={parseColorString(normalizedHex)}- onChange={(newRgb) => {- const fixedRgb = fixColor(value, newRgb);- setHex(rgbaToHex(fixedRgb));- const newValue = colorResultToRgbValue(fixedRgb);- onChange(newValue);- handleCompleteDebounced(newValue);- }}- />- <Grid css={{ gridTemplateColumns: "auto 1fr" }} gap="1">- <EyeDropper- onChange={(newHex) => {- setHex(newHex);- const newValue = colorResultToRgbValue(parseColorString(newHex));- onChangeComplete(newValue);- }}- />- <InputField- value={hex}- onChange={(event) => {- setHex(event.target.value);- try {- const color = colorjs.to(- normalizeHex(event.target.value),- "srgb"- );- const rgba = colorToRgba(color);- const newValue = colorResultToRgbValue(rgba);- onChange(newValue);- handleCompleteDebounced(newValue);- } catch {- // Invalid color, don't update- }- }}- />- </Grid>- </>- );-};--export const ColorPickerPopover = ({- value,- onChange,- onChangeComplete,open,onOpenChange,- thumb,- side = "bottom",- align = "center",- sideOffset,-}: ColorPickerPopoverProps) => {- const [displayColorPicker, setDisplayColorPicker] = useState(false);+ css,+}: ColorPickerProps) => {+ const colorInputRef = useRef<ColorInput>(null);+ const scopeClass = useId().replace(/:/g, "");const { enableCanvasPointerEvents, disableCanvasPointerEvents } =useDisableCanvasPointerEvents();- const isControlled = open !== undefined;- const isOpen = isControlled ? open : displayColorPicker;+ // Keep stable refs to callbacks so the event-wiring effect never needs to+ // re-run (and tear down / re-attach listeners) just because a prop changed.+ const callbacksRef = useRef({+ onChange,+ onChangeComplete,+ onOpenChange,+ disableCanvasPointerEvents,+ enableCanvasPointerEvents,+ value,+ });+ callbacksRef.current = {+ onChange,+ onChangeComplete,+ onOpenChange,+ disableCanvasPointerEvents,+ enableCanvasPointerEvents,+ value,+ };++ const colorString = toValue(value);++ const overrideContrast = useCallback(() => {+ const colorInputElement = colorInputRef.current;+ if (!colorInputElement) {+ return;+ }+ colorInputElement.style.setProperty("--contrast", "inherit");+ colorInputElement.shadowRoot+ ?.querySelector<HTMLElement>(".preview")+ ?.style.setProperty("--value", rawTheme.colors.backgroundPanel);+ }, []);+ // Sync externally-controlled open state into the web component.useEffect(() => {- if (isOpen) {- disableCanvasPointerEvents();- document.body.style.userSelect = "none";- } else {- document.body.style.removeProperty("user-select");- enableCanvasPointerEvents();+ if (open === undefined) {+ return;+ }+ // hdr-color-input is loaded lazily; wait for the element to be defined+ // before calling .show()/.close() so the methods are available.+ customElements.whenDefined("color-input").then(() => {+ try {+ if (open === true) {+ colorInputRef.current?.show();+ } else {+ colorInputRef.current?.close();+ }+ } catch {}+ });+ }, [open]);++ // Sync external value changes into the web component.+ useEffect(() => {+ const colorInputElement = colorInputRef.current;+ if (colorInputElement && colorInputElement.value !== colorString) {+ colorInputElement.value = colorString;+ }+ overrideContrast();+ }, [colorString, overrideContrast]);++ // Wire up change / open / close events.+ useEffect(() => {+ const colorInputElement = colorInputRef.current;+ if (!colorInputElement) {+ return;}+ const controller = new AbortController();+ const { signal } = controller;+ let lastStyleValue: StyleValue = callbacksRef.current.value;++ colorInputElement.addEventListener(+ "change",+ (event: Event) => {+ const { value, colorspace } = (event as CustomEvent<ChangeDetail>)+ .detail;+ lastStyleValue = cssStringToStyleValue(value, colorspace);+ callbacksRef.current.onChange(lastStyleValue);+ overrideContrast();+ },+ { signal }+ );++ colorInputElement.addEventListener(+ "open",+ () => {+ // Set contrast immediately on open so the initial color is correct+ // before any change event fires (the component's own JS sets --contrast+ // based on raw color only, ignoring alpha).+ callbacksRef.current.disableCanvasPointerEvents();+ document.body.style.userSelect = "none";+ callbacksRef.current.onOpenChange?.(true);+ overrideContrast();+ },+ { signal }+ );++ colorInputElement.addEventListener(+ "close",+ () => {+ callbacksRef.current.enableCanvasPointerEvents();+ document.body.style.removeProperty("user-select");+ callbacksRef.current.onOpenChange?.(false);+ callbacksRef.current.onChangeComplete(lastStyleValue);+ },+ { signal }+ );++ // The component's JS re-sets --contrast on each color change, ignoring alpha.+ // Re-apply our override whenever the window regains focus (e.g. after the+ // user switches away and back while the picker is open).+ window.addEventListener("focus", overrideContrast, { signal });+return () => {+ controller.abort();+ callbacksRef.current.enableCanvasPointerEvents();document.body.style.removeProperty("user-select");- enableCanvasPointerEvents();};- }, [isOpen, disableCanvasPointerEvents, enableCanvasPointerEvents]);+ }, [overrideContrast]);- const handleOpenChange = (nextOpen: boolean) => {- if (!isControlled) {- setDisplayColorPicker(nextOpen);- }- onOpenChange?.(nextOpen);- };+ const { className: textClass } = textStyle();return (- <Popover modal open={isOpen} onOpenChange={handleOpenChange}>- <PopoverTrigger- asChild- aria-label="Open color picker"- onClick={() => handleOpenChange(!isOpen)}- >- {thumb ?? <ColorThumb color={toValue(value)} interactive={true} />}- </PopoverTrigger>- <PopoverContent- side={side}- align={align}- sideOffset={sideOffset}- css={{- display: "grid",- padding: theme.spacing[5],- gap: theme.spacing[5],- }}- >- <ColorPicker- value={value}- onChange={onChange}- onChangeComplete={onChangeComplete}+ <>+ <style>{`+ /* Stitches can't handle ::part, need to migrate a new styling approach */+ .${scopeClass},+ .${scopeClass}::part(trigger),+ .${scopeClass}::part(chip) {+ position: absolute;+ inset: 0;+ opacity: 0;+ width: auto;+ height: auto;+ }+ .${scopeClass}::part(input) {+ display: none;+ }+ .${scopeClass}::part(controls) {+ /* Hack to fix as we can't reach into .control and change grid-template-columns */+ font-size: 16px;+ }+ .${scopeClass}::part(output) {+ font-size: inherit;+ height: 2em;+ }+ `}</style>++ <ColorThumb color={colorString} css={css}>+ <color-input+ ref={colorInputRef}+ value={colorString}+ theme="light"+ class={`${textClass} ${scopeClass}`}/>- </PopoverContent>- </Popover>+ </ColorThumb>+ </>);};diff --git a/packages/design-system/src/components/gradient-picker.tsx b/packages/design-system/src/components/gradient-picker.tsxindex ede86ef4c3..81fd3ae7bb 100644--- a/packages/design-system/src/components/gradient-picker.tsx+++ b/packages/design-system/src/components/gradient-picker.tsx@@ -19,12 +19,12 @@ import type {GradientStop,ParsedGradient,} from "@webstudio-is/css-data";-import * as colorjs from "colorjs.io/fn";+import { color, type ColorConstructor } from "@webstudio-is/css-engine";import { ChevronFilledUpIcon } from "@webstudio-is/icons";import { styled, theme } from "../stitches.config";import { Flex } from "./flex";import { Box } from "./box";-import { ColorPickerPopover, ColorThumb } from "./color-picker";+import { ColorPicker } from "./color-picker";// Helper to mix two RGB colorsconst mixColors = (@@ -32,7 +32,7 @@ const mixColors = (color2: RgbValue,ratio: number): RgbValue => {- const c1: colorjs.ColorConstructor = {+ const c1: ColorConstructor = {spaceId: "srgb",coords: [(color1.r ?? 0) / 255,@@ -41,7 +41,7 @@ const mixColors = (],alpha: undefined,};- const c2: colorjs.ColorConstructor = {+ const c2: ColorConstructor = {spaceId: "srgb",coords: [(color2.r ?? 0) / 255,@@ -50,7 +50,7 @@ const mixColors = (],alpha: undefined,};- const mixed = colorjs.mix(c1, c2, ratio);+ const mixed = color.mix(c1, c2, ratio);const [r, g, b] = mixed.coords;return {type: "rgb",@@ -74,7 +74,6 @@ export type GradientPickerProps<T extends ParsedGradient = ParsedGradient> = {const THUMB_INTERACTION_DISTANCE = 12;const DRAG_THRESHOLD = 3;const SLIDER_HEIGHT = 16;-const THUMB_HEIGHT = 14;const defaultStopColor: RgbValue = {type: "rgb",@@ -85,18 +84,18 @@ const defaultStopColor: RgbValue = {};const toRgbColor = (- color: GradientStop["color"] | undefined+ stopColor: GradientStop["color"] | undefined): RgbValue | undefined => {- if (color === undefined) {+ if (stopColor === undefined) {return;}- if (color.type === "rgb") {- return color;+ if (stopColor.type === "rgb") {+ return stopColor;}try {- const parsed = colorjs.parse(toValue(color));+ const parsed = color.parse(toValue(stopColor));const [r, g, b] = parsed.coords;const alpha = parsed.alpha;return {@@ -434,7 +433,10 @@ export const GradientPicker = <T extends ParsedGradient>({const isGradientColorValue = (value: StyleValue): value is GradientColorValue =>- value.type === "rgb" || value.type === "keyword" || value.type === "var";+ value.type === "rgb" ||+ value.type === "color" ||+ value.type === "keyword" ||+ value.type === "var";const handleStopColorChange = useCallback((@@ -924,7 +926,7 @@ export const GradientPicker = <T extends ParsedGradient>({handleStopSelected(index, stop);}}>- <ColorPickerPopover+ <ColorPickervalue={stopColor}onChange={(value) =>handleStopColorChange(index, value, "change")@@ -936,19 +938,11 @@ export const GradientPicker = <T extends ParsedGradient>({onOpenChange={(open) =>handleColorPickerOpenChange(index, open)}- sideOffset={SLIDER_HEIGHT + THUMB_HEIGHT}- thumb={- <ColorThumb- color={stop.color ? toValue(stop.color) : "transparent"}- interactive={true}- css={{- margin: 1,- width: THUMB_HEIGHT,- height: THUMB_HEIGHT,- }}- data-gradient-thumb="true"- />- }+ css={{+ width: theme.spacing[8],+ height: theme.spacing[8],+ margin: 1,+ }}/><SliderThumbPointer aria-hidden /></SliderThumb>diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.tsindex 4422f98b23..81d9478984 100644--- a/packages/design-system/src/index.ts+++ b/packages/design-system/src/index.ts@@ -58,7 +58,7 @@ export * from "./components/focus-ring";export * from "./components/tree";export * from "./components/command";export * from "./components/gradient-picker";-export * from "./components/color-picker";+export { ColorThumb, ColorPicker } from "./components/color-picker";// Not aligneddiff --git a/packages/design-system/src/test-setup.ts b/packages/design-system/src/test-setup.tsnew file mode 100644index 0000000000..926c76ed97--- /dev/null+++ b/packages/design-system/src/test-setup.ts@@ -0,0 +1,8 @@+// Polyfill CSS.supports for jsdom (not available natively).+/* eslint-disable @typescript-eslint/no-explicit-any */++const g = globalThis as any;++if (typeof g.CSS === "undefined") {+ g.CSS = { supports: () => false };+}diff --git a/packages/design-system/vitest.config.ts b/packages/design-system/vitest.config.tsindex fd63d166f1..859af910b9 100644--- a/packages/design-system/vitest.config.ts+++ b/packages/design-system/vitest.config.ts@@ -12,5 +12,6 @@ export default defineConfig({},test: {environment: "jsdom",+ setupFiles: ["./src/test-setup.ts"],},});diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex a9624fd55e..ced3c68556 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -1234,9 +1234,6 @@ importers:change-case:specifier: ^5.4.4version: 5.4.4- colorjs.io:- specifier: ^0.6.1- version: 0.6.1css-tree:specifier: ^3.1.0version: 3.1.0@@ -1274,6 +1271,9 @@ importers:'@webstudio-is/fonts':specifier: workspace:*version: link:../fonts+ colorjs.io:+ specifier: ^0.6.1+ version: 0.6.1zod:specifier: ^3.24.2version: 3.24.2@@ -1435,12 +1435,12 @@ importers:cmdk:specifier: ^1.1.1version: 1.1.1(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])- colorjs.io:- specifier: ^0.6.1- version: 0.6.1downshift:specifier: ^6.1.7version: 6.1.7([email protected])+ hdr-color-input:+ specifier: ^0.4.0+ version: 0.4.0match-sorter:specifier: ^8.0.0version: 8.0.0@@ -4147,6 +4147,9 @@ packages:'@polka/[email protected]':resolution: {integrity: sha512-8LduaNlMZGwdZ6qWrKlfa+2M4gahzFkprZiAt2TF8uS0qQgBizKXpXURqvTJ4WtmupWxaLqjRb2UCTe72mu+Aw==}+ '@preact/[email protected]':+ resolution: {integrity: sha512-AowtCcCU/33lFlh1zRFf/u+12rfrhtNakj7UpaGEsmMwUKpKWMVvcktOGcwBBNiB4lWrZWc01LhiyyzVklJyaQ==}+'@prisma/[email protected]':resolution: {integrity: sha512-6/JnizEdlSBxDIdiLbrBdMW5NqDxOmhXAJaNXiPpgzAPr/nLZResT6MMpbOHLo5yAbQ1Vv5UU8PTPRzb0WIxdA==}engines: {node: '>=16.13'}@@ -6807,6 +6810,9 @@ packages:resolution: {integrity: sha512-nAxA0v8+vXSBDt3AnRUNjyRIQ0rD+ntpbAp4LnPkumc5M9yUbSMa4XDU9Q6etY4f1Wp4bNgvc1yjiZtsTTrSng==}+ resolution: {integrity: sha512-Wv7UgbOswBXYMWQCrzuf5j6Yxs3Dz4Gm3hdrrMV88mD1bbL4khX5aojJvMRLOe30bj6eRo5TYRdcDwTEWl4Wbg==}+resolution: {integrity: sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ==}@@ -11098,6 +11104,8 @@ snapshots:'@polka/[email protected]': {}+ '@preact/[email protected]': {}+'@prisma/[email protected]([email protected])':optionalDependencies:prisma: 5.12.1@@ -14209,6 +14217,11 @@ snapshots:+ dependencies:+ '@preact/signals-core': 1.14.0+ colorjs.io: 0.6.1+optional: true