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
fix: Improve editor selection and project tag contrast (#6302)
Oleg Isonend4b1994a6ae9
diff --git a/.storybook/preview.tsx b/.storybook/preview.tsxindex 81be7d65d9..667bd2ef82 100644--- a/.storybook/preview.tsx+++ b/.storybook/preview.tsx@@ -5,16 +5,10 @@ import { TooltipProvider } from "@radix-ui/react-tooltip";import { setEnv } from "../packages/feature-flags/src/index";import {cssVar,- globalCss,- theme,type ThemeVariableName,} from "../packages/design-system/src/index";-// this adds <style> tags to the <head> of the document-import "@fontsource-variable/inter";-import "@fontsource-variable/manrope";-import "@fontsource/roboto-mono";-import "../packages/design-system/src/colors/colors.css";+import "../packages/design-system/src/global.css";const themeTestCases = {default: {},@@ -78,7 +72,6 @@ const ThemeGlobals = ({const previousBodyBackground = document.body.style.backgroundColor;const previousBodyBackgroundPriority =document.body.style.getPropertyPriority("background-color");- const previousBodyColor = document.body.style.color;const previousTheme = new Map(Array.from(themeVariableNames, (name) => [name,@@ -100,7 +93,6 @@ const ThemeGlobals = ({"var(--background-primary)","important");- document.body.style.color = "var(--foreground-primary)";}return () => {@@ -121,7 +113,6 @@ const ThemeGlobals = ({previousBodyBackground,previousBodyBackgroundPriority);- document.body.style.color = previousBodyColor;};}, [colorScheme, themeTestCase]);@@ -155,16 +146,8 @@ const WaitForFonts = ({ children }) => {);};-const globalStyles = globalCss({- body: {- color: cssVar("--foreground-primary"),- fontFamily: theme.fonts.sans,- },-});-const decorators: Preview["decorators"] = [(Story, { globals }) => {- globalStyles();setEnv("*");const themeTestCase = isThemeTestCase(globals.themeTestCase)? globals.themeTestCasediff --git a/apps/builder/app/auth/login.css b/apps/builder/app/auth/login.cssnew file mode 100644index 0000000000..d2281ec790--- /dev/null+++ b/apps/builder/app/auth/login.css@@ -0,0 +1,4 @@+/* Login alone locks the UI document; dashboard routes retain document scrolling. */+body {+ overflow: hidden;+}diff --git a/apps/builder/app/auth/login.tsx b/apps/builder/app/auth/login.tsxindex 607f9a60bc..e56752ed62 100644--- a/apps/builder/app/auth/login.tsx+++ b/apps/builder/app/auth/login.tsx@@ -2,7 +2,6 @@ import { TooltipProvider } from "@radix-ui/react-tooltip";import {Button,Flex,- globalCss,rawTheme,Text,theme,@@ -14,13 +13,6 @@ import { Form } from "@remix-run/react";import { authPath } from "~/shared/router-utils";import { SecretLogin } from "./secret-login";-const globalStyles = globalCss({- body: {- margin: 0,- overflow: "hidden",- },-});-export type LoginProps = {errorMessage?: string;isGithubEnabled?: boolean;@@ -36,7 +28,6 @@ export const Login = ({isSecretLoginEnabled,devPlanNames,}: LoginProps) => {- globalStyles();return (<Flexalign="center"diff --git a/apps/builder/app/builder/features/style-panel/shared/css-fragment.stories.tsx b/apps/builder/app/builder/features/style-panel/shared/css-fragment.stories.tsxnew file mode 100644index 0000000000..44aa178381--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/shared/css-fragment.stories.tsx@@ -0,0 +1,31 @@+import { useState } from "react";+import { StorySection, theme } from "@webstudio-is/design-system";+import { CssFragmentEditorContent } from "./css-fragment";++export default {+ title: "Style panel/CSS Fragment Editor",+ component: CssFragmentEditorContent,+};++const CssFragmentEditorStory = () => {+ const [value, setValue] = useState(+ "color: var(--foreground-primary);\nbackground: var(--background-primary);"+ );++ return (+ <StorySection title="CSS fragment editor">+ <CssFragmentEditorContent+ value={value}+ onChange={setValue}+ onChangeComplete={setValue}+ autoFocus+ />+ </StorySection>+ );+};++export const CSSFragmentEditor = () => (+ <div style={{ width: theme.sizes.sidebarWidth }}>+ <CssFragmentEditorStory />+ </div>+);diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsxindex 04c38fdb93..18dfbdc60c 100644--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx@@ -18,7 +18,6 @@ import {Flex,styled,ColorThumb,- declareCssVar,} from "@webstudio-is/design-system";import type {CssProperty,@@ -53,14 +52,14 @@ import { convertUnits } from "./convert-units";import { mergeRefs } from "@react-aria/utils";import { composeEventHandlers } from "~/shared/event-utils";import type { StyleValueSourceColor } from "~/shared/style-object-model";-import { isComplexValue, ValueEditorDialog } from "./value-editor-dialog";+import {+ cssValueInputMaximizeButtonDisplay,+ isComplexValue,+ ValueEditorDialog,+} from "./value-editor-dialog";import { useEffectEvent } from "~/shared/hook-utils/effect-event";import { scrollByPointer } from "../scroll-by-pointer";-const cssButtonDisplay = declareCssVar(- "--css-value-input-maximize-button-display"-);-// Subjective adjust ment based on how it feels on macbook/trackpad.// It won't be ideal for everyone with different input devices and preferences.// Ideally we also need some kind of acceleration setting with 1 value.@@ -958,7 +957,7 @@ export const CssValueInput = ({cursor: "default",minWidth,"&:hover": {- [cssButtonDisplay]: "block",+ [cssValueInputMaximizeButtonDisplay]: "block",},}}text={text}diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/value-editor-dialog.tsx b/apps/builder/app/builder/features/style-panel/shared/css-value-input/value-editor-dialog.tsxindex 9e89b6e1d7..a9a26658a6 100644--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/value-editor-dialog.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/value-editor-dialog.tsx@@ -1,6 +1,7 @@import { useEffect, useState } from "react";import {cssVar,+ declareCssVar,NestedInputButton,rawTheme,} from "@webstudio-is/design-system";@@ -18,6 +19,10 @@ import type {} from "./css-value-input";import { parseIntermediateOrInvalidValue } from "./parse-intermediate-or-invalid-value";+export const cssValueInputMaximizeButtonDisplay = declareCssVar(+ "--css-value-input-maximize-button-display"+);+// Hand-picking values that are considered complex and should get a maximize button for the dialog.// Not showing the maximize everywhere because most values don't need that and it takes space.export const isComplexValue = (value: CssValueInputValue) => {@@ -105,7 +110,7 @@ export const ValueEditorDialog = ({<NestedInputButtontabIndex={-1}css={{- display: cssVar("--css-value-input-maximize-button-display", "none"),+ display: cssVar(cssValueInputMaximizeButtonDisplay, "none"),background: cssVar("--background-secondary"),'&[data-state="open"]': {display: "block",diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-control.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-control.tsxindex d98c350908..77e6913c68 100644--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-control.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-control.tsx@@ -14,13 +14,13 @@ import { type ReactNode } from "react";import { useContentEditable } from "~/shared/dom-hooks";import { styleSourceColors } from "./color-recipes";-const menuTriggerVisibilityVar = declareCssVar(+export const menuTriggerVisibilityVar = declareCssVar("--style-source-menu-trigger-visibility");-const menuTriggerVisibilityOverrideVar = declareCssVar(+export const menuTriggerVisibilityOverrideVar = declareCssVar("--style-source-menu-trigger-visibility-override");-const menuTriggerGradientVar = declareCssVar(+export const menuTriggerGradientVar = declareCssVar("--style-source-menu-trigger-gradient");diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsxindex b3ad5bdc85..05622d02c9 100644--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-menu.tsx@@ -22,6 +22,9 @@ import {validateSelector,} from "@webstudio-is/css-data";import {+ menuTriggerGradientVar,+ menuTriggerVisibilityOverrideVar,+ menuTriggerVisibilityVar,menuCssVars,type ItemSource,type ItemSelector,@@ -46,8 +49,8 @@ type IntermediateItem = {};const visibility = cssVar(- "--style-source-menu-trigger-visibility-override",- cssVar("--style-source-menu-trigger-visibility")+ menuTriggerVisibilityOverrideVar,+ cssVar(menuTriggerVisibilityVar));const MenuTrigger = styled("button", {@@ -91,7 +94,7 @@ const MenuTriggerGradient = styled(Box, {width: theme.sizes.controlHeight,height: "100%",visibility,- background: cssVar("--style-source-menu-trigger-gradient"),+ background: cssVar(menuTriggerGradientVar),borderTopRightRadius: theme.borderRadius[4],borderBottomRightRadius: theme.borderRadius[4],pointerEvents: "none",diff --git a/apps/builder/app/builder/features/workspace/canvas-iframe.tsx b/apps/builder/app/builder/features/workspace/canvas-iframe.tsxindex 5bc5ce154e..440f021b5a 100644--- a/apps/builder/app/builder/features/workspace/canvas-iframe.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-iframe.tsx@@ -1,5 +1,9 @@import { forwardRef, useMemo, useRef, type JSX, type RefObject } from "react";-import { css, cssVar } from "@webstudio-is/design-system";+import {+ canvasPointerEventsPropertyName,+ css,+ cssVar,+} from "@webstudio-is/design-system";import { useUnmount } from "~/shared/hook-utils/use-mount";import { $canvasIframeState } from "~/shared/nano-states";import { useCallback, useEffect, useState } from "react";@@ -13,7 +17,7 @@ import { mergeRefs } from "@react-aria/utils";const iframeStyle = css({border: "none",- pointerEvents: cssVar("--canvas-pointer-events"),+ pointerEvents: cssVar(canvasPointerEventsPropertyName),height: "100%",width: "100%",// The canvas displays the authored page, whose initial canvas is white anddiff --git a/apps/builder/app/builder/sidebar-left/sidebar-left.tsx b/apps/builder/app/builder/sidebar-left/sidebar-left.tsxindex 7f996c926f..db241de83b 100644--- a/apps/builder/app/builder/sidebar-left/sidebar-left.tsx+++ b/apps/builder/app/builder/sidebar-left/sidebar-left.tsx@@ -1,10 +1,10 @@import { useRef, type ReactNode } from "react";import {cssVar,- declareCssVar,Kbd,rawTheme,Text,+ treeActionBoundary,} from "@webstudio-is/design-system";import { useSubscribe, type Publish } from "~/shared/pubsub";import {@@ -54,7 +54,6 @@ import { MarketplacePanel } from "~/builder/features/marketplace";import type { SidebarPanelName } from "./types";const none = { Panel: () => null };-const sidebarLeftPanelWidth = declareCssVar("--sidebar-left-panel-width");const HelpTabTrigger = () => {return (@@ -305,8 +304,8 @@ export const SidebarLeft = ({ publish }: SidebarLeftProps) => {}}resizablecss={{- [sidebarLeftPanelWidth]: `${getSidebarPanelWidth(activePanel)}`,- width: cssVar(sidebarLeftPanelWidth),+ [treeActionBoundary]: `${getSidebarPanelWidth(activePanel)}`,+ width: cssVar(treeActionBoundary),minWidth: theme.sizes.sidebarWidth,maxWidth: theme.spacing[35],// We need the node to be rendered but hiddendiff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex 00b3da929a..7281b9b9e1 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -41,7 +41,7 @@ import {standardAttributesToReactProps,getCollectionEntries,} from "@webstudio-is/react-sdk";-import { cssVar, rawTheme, toast } from "@webstudio-is/design-system";+import { rawTheme, toast } from "@webstudio-is/design-system";import {Input,Link,@@ -80,7 +80,10 @@ import {import { Block } from "../build-mode/block";import { BlockBody } from "../build-mode/block-body";import { BlockTemplate } from "../build-mode/block-template";-import { editablePlaceholderAttribute } from "~/canvas/shared/styles";+import {+ editablePlaceholderAttribute,+ editingPlaceholderVariable,+} from "~/canvas/shared/styles";import { richTextPlaceholders } from "@webstudio-is/project-build/runtime";import {acquireExternalContentRoot,@@ -235,7 +238,7 @@ const ContentEditable = ({if (placeholder !== undefined) {rootElement.style.setProperty(- "--editing-placeholder",+ editingPlaceholderVariable,`'${placeholder.replaceAll("'", "\\'")}'`);}@@ -248,6 +251,9 @@ const ContentEditable = ({return renderComponentWithRef(ref);};+// Canvas documents intentionally do not inherit Builder theme variables.+const canvasErrorColor = "#d13a3a";+const ErrorStub = forwardRef<HTMLDivElement,{@@ -260,8 +266,8 @@ const ErrorStub = forwardRef<ref={ref}style={{padding: rawTheme.spacing[5],- border: `1px solid ${cssVar("--border-negative")}`,- color: cssVar("--foreground-negative"),+ border: `1px solid ${canvasErrorColor}`,+ color: canvasErrorColor,}}/>);diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.tsindex dd5033b54e..98d291823c 100644--- a/apps/builder/app/canvas/shared/styles.ts+++ b/apps/builder/app/canvas/shared/styles.ts@@ -81,7 +81,9 @@ export const editablePlaceholderAttribute = "data-ws-editable-placeholder";// @todo replace with modern typed attr() when supported in all browsers// see the second edge case// https://developer.mozilla.org/en-US/docs/Web/CSS/attr#backwards_compatibility-const editingPlaceholderVariable = declareCssVar("--editing-placeholder");+export const editingPlaceholderVariable = declareCssVar(+ "--editing-placeholder"+);const helperStylesShared = [// Display a placeholder text for elements that are editable but currently emptydiff --git a/apps/builder/app/dashboard/dashboard.tsx b/apps/builder/app/dashboard/dashboard.tsxindex cae64700dd..f4c98b7cea 100644--- a/apps/builder/app/dashboard/dashboard.tsx+++ b/apps/builder/app/dashboard/dashboard.tsx@@ -8,7 +8,6 @@ import {TooltipProvider,Toaster,css,- globalCss,theme,PanelBanner,Link,@@ -17,7 +16,7 @@ import {Grid,IconButton,cssVar,- selectionBackground,+ selectedItemBackground,} from "@webstudio-is/design-system";import { BodyIcon } from "@webstudio-is/icons";import {@@ -52,12 +51,6 @@ import {} from "~/shared/notifications/subscription";import { requestNotificationPermission } from "~/shared/notifications/browser-notification";-const globalStyles = globalCss({- body: {- margin: 0,- },-});-const CloneProject = ({projectToClone,}: {@@ -110,7 +103,7 @@ const sidebarLinkStyle = css({background: cssVar("--overlay-interaction-hover"),},"&[aria-current=page]": {- background: selectionBackground,+ background: selectedItemBackground,color: cssVar("--foreground-primary"),},});@@ -192,7 +185,6 @@ export const DashboardSetup = ({ data }: { data: DashboardData }) => {startSubscription();return stopSubscription;}, []);- globalStyles();return null;};diff --git a/apps/builder/app/dashboard/projects/project-card.browser.test.tsx b/apps/builder/app/dashboard/projects/project-card.browser.test.tsxnew file mode 100644index 0000000000..0fae65d677--- /dev/null+++ b/apps/builder/app/dashboard/projects/project-card.browser.test.tsx@@ -0,0 +1,96 @@+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, test } from "vitest";+import { createMemoryRouter, RouterProvider } from "react-router-dom";+import { TooltipProvider } from "@webstudio-is/design-system";+import type { DashboardProject } from "@webstudio-is/dashboard";+import "@webstudio-is/design-system/global.css";+import { ProjectCard } from "./project-card";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ document.documentElement.removeAttribute("data-color-scheme");+});++test.each(["light", "dark"] as const)(+ "uses the original fixed scrim treatment for project tags in %s mode",+ (mode) => {+ document.documentElement.dataset.colorScheme = mode;+ const project = {+ id: "project",+ createdAt: new Date().toISOString(),+ title: "Tagged project",+ domain: "tagged-project",+ userId: "user",+ isDeleted: false,+ isPublished: false,+ latestBuild: null,+ previewImageAsset: null,+ previewImageAssetId: null,+ latestBuildVirtual: null,+ marketplaceApprovalStatus: "UNLISTED",+ tags: ["production"],+ domainsVirtual: [],+ workspaceId: null,+ } as DashboardProject;++ const router = createMemoryRouter(+ [+ {+ path: "/",+ element: (+ <TooltipProvider>+ <ProjectCard+ project={project}+ publisherHost="wstd.work"+ projectsTags={[{ id: "production", label: "Prod" }]}+ />+ </TooltipProvider>+ ),+ },+ ],+ { future: { v7_relativeSplatPath: true } }+ );+ act(() => {+ root.render(+ <RouterProvider router={router} future={{ v7_startTransition: true }} />+ );+ });++ const tag = Array.from(container.querySelectorAll<HTMLElement>("div")).find(+ (element) =>+ element.textContent === "#Prod" && element.childElementCount === 0+ );+ if (tag === undefined) {+ throw new Error("Expected the project tag");+ }+ const reference = document.createElement("span");+ reference.style.background = "oklch(0 0 0 / 0.3)";+ reference.style.color = "#fff";+ document.body.appendChild(reference);++ const tagStyle = getComputedStyle(tag);+ const referenceStyle = getComputedStyle(reference);+ const tagBackground = tagStyle.backgroundColor;+ const tagColor = tagStyle.color;+ const referenceBackground = referenceStyle.backgroundColor;+ const referenceColor = referenceStyle.color;+ reference.remove();+ expect(tagBackground).toBe(referenceBackground);+ expect(tagColor).toBe(referenceColor);+ }+);diff --git a/apps/builder/app/dashboard/projects/project-card.tsx b/apps/builder/app/dashboard/projects/project-card.tsxindex 48dc8c2276..dc8cde9a76 100644--- a/apps/builder/app/dashboard/projects/project-card.tsx+++ b/apps/builder/app/dashboard/projects/project-card.tsx@@ -155,12 +155,10 @@ export const ProjectCard = ({if (isApplied) {return (<Text- color="contrast"key={tag.id}css={{- background: `oklch(from ${cssVar(- "--overlay-scrim"- )} l c h / 30%)`,+ background: "oklch(0 0 0 / 0.3)",+ color: "#fff",borderRadius: theme.borderRadius[3],paddingInline: theme.spacing[3],}}diff --git a/apps/builder/app/routes/_ui.login._index.tsx b/apps/builder/app/routes/_ui.login._index.tsxindex 2f9ecf3030..adbca9d64e 100644--- a/apps/builder/app/routes/_ui.login._index.tsx+++ b/apps/builder/app/routes/_ui.login._index.tsx@@ -18,6 +18,7 @@ import {import { returnToCookie } from "~/services/cookie.server";import { ClientOnly } from "~/shared/client-only";import { lazy } from "react";+import loginStyles from "~/auth/login.css?url";import { preventCrossOriginCookie } from "~/services/no-cross-origin-cookie";import { redirect } from "~/services/no-store-redirect";import { allowedDestinations } from "~/services/destinations.server";@@ -26,6 +27,10 @@ export { ErrorBoundary } from "~/shared/error/error-boundary";export const links: LinksFunction = () => {return [+ {+ rel: "stylesheet",+ href: loginStyles,+ },{rel: "canonical",href: "https://apps.webstudio.is/login",diff --git a/apps/builder/app/routes/_ui.tsx b/apps/builder/app/routes/_ui.tsxindex 5ed6ebe068..c88203867c 100644--- a/apps/builder/app/routes/_ui.tsx+++ b/apps/builder/app/routes/_ui.tsx@@ -8,11 +8,7 @@ import {type ClientLoaderFunctionArgs,type ShouldRevalidateFunction,} from "@remix-run/react";-import interFont from "@fontsource-variable/inter/index.css?url";-import manropeVariableFont from "@fontsource-variable/manrope/index.css?url";-import robotoMonoFont from "@fontsource/roboto-mono/index.css?url";-import designSystemColors from "@webstudio-is/design-system/colors.css?url";-import appCss from "../shared/app.css?url";+import designSystemGlobalCss from "@webstudio-is/design-system/global.css?url";import {json,type LinksFunction,@@ -39,13 +35,7 @@ import {export const links: LinksFunction = () => {// `links` returns an array of objects whose// properties map to the `<link />` component props- return [- { rel: "stylesheet", href: interFont },- { rel: "stylesheet", href: manropeVariableFont },- { rel: "stylesheet", href: robotoMonoFont },- { rel: "stylesheet", href: designSystemColors },- { rel: "stylesheet", href: appCss },- ];+ return [{ rel: "stylesheet", href: designSystemGlobalCss }];};const Document = (props: {diff --git a/apps/builder/app/shared/app.css b/apps/builder/app/shared/app.cssdeleted file mode 100644index 2a1488ce39..0000000000--- a/apps/builder/app/shared/app.css+++ /dev/null@@ -1,5 +0,0 @@-body {- margin: 0;- font-family: var(--fonts-sans);- font-size: var(--fontSizes-1);-}diff --git a/apps/builder/app/shared/code-editor-base.browser.test.tsx b/apps/builder/app/shared/code-editor-base.browser.test.tsxnew file mode 100644index 0000000000..80d58c9c3d--- /dev/null+++ b/apps/builder/app/shared/code-editor-base.browser.test.tsx@@ -0,0 +1,139 @@+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { EditorSelection } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { cssVar } from "@webstudio-is/design-system";+import "@webstudio-is/design-system/global.css";+import { EditorContent } from "./code-editor-base";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;+const rangeGetClientRects = Object.getOwnPropertyDescriptor(+ Range.prototype,+ "getClientRects"+);++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ Object.defineProperty(Range.prototype, "getClientRects", {+ configurable: true,+ value: () => [new DOMRect(0, 0, 20, 16)],+ });+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ document.documentElement.removeAttribute("data-color-scheme");+ vi.unstubAllGlobals();+ if (rangeGetClientRects === undefined) {+ delete (Range.prototype as { getClientRects?: unknown }).getClientRects;+ } else {+ Object.defineProperty(+ Range.prototype,+ "getClientRects",+ rangeGetClientRects+ );+ }+});++test.each(["light", "dark"] as const)(+ "uses the shared selection color in %s mode",+ async (mode) => {+ document.documentElement.dataset.colorScheme = mode;+ act(() => {+ root.render(+ <EditorContent+ value="selected text"+ onChange={() => {}}+ onChangeComplete={() => {}}+ />+ );+ });++ const editor = container.querySelector<HTMLElement>('[role="textbox"]');+ if (editor === null) {+ throw new Error("Expected the code editor");+ }+ const view = EditorView.findFromDOM(editor);+ if (view === null) {+ throw new Error("Expected the CodeMirror view");+ }+ act(() => {+ view.dispatch({+ selection: EditorSelection.range(0, view.state.doc.length),+ });+ view.focus();+ });+ await act(+ () =>+ new Promise<void>((resolve) =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()))+ )+ );++ const selection = container.querySelector<HTMLElement>(+ ".cm-selectionBackground"+ );+ if (selection === null) {+ throw new Error("Expected a rendered selection");+ }+ const reference = document.createElement("span");+ reference.style.background = cssVar("--background-text-selection");+ reference.style.color = "var(--foreground-on-text-selection)";+ document.body.appendChild(reference);++ const selectionColor = getComputedStyle(selection).backgroundColor;+ const referenceColor = getComputedStyle(reference).backgroundColor;+ const content = container.querySelector<HTMLElement>(".cm-content");+ if (content === null) {+ throw new Error("Expected editor content");+ }+ const selectedTextColor = getComputedStyle(content, "::selection").color;+ const referenceTextColor = getComputedStyle(reference).color;+ reference.remove();+ expect(selectionColor).toBe(referenceColor);+ expect(selectedTextColor).toBe(referenceTextColor);+ }+);++test("scopes disabled styles to the Webstudio code editor", () => {+ act(() => {+ root.render(+ <fieldset disabled>+ <EditorContent+ value="disabled editor"+ onChange={() => {}}+ onChangeComplete={() => {}}+ />+ <div className="cm-editor" data-foreign-editor />+ </fieldset>+ );+ });++ const editors = container.querySelectorAll<HTMLElement>(".cm-editor");+ const foreignEditor = container.querySelector<HTMLElement>(+ "[data-foreign-editor]"+ );+ if (editors[0] === undefined || foreignEditor === null) {+ throw new Error("Expected both code editors");+ }++ expect(getComputedStyle(editors[0]).opacity).toBe("0.3");+ expect(getComputedStyle(foreignEditor).opacity).toBe("1");+});diff --git a/apps/builder/app/shared/code-editor-base.tsx b/apps/builder/app/shared/code-editor-base.tsxindex fa76b89a71..b22c6d3988 100644--- a/apps/builder/app/shared/code-editor-base.tsx+++ b/apps/builder/app/shared/code-editor-base.tsx@@ -37,7 +37,6 @@ import {Grid,Flex,rawTheme,- globalCss,Kbd,Text,FloatingPanel,@@ -88,12 +87,6 @@ export const getCodeEditorCssVars = ({[maxHeightVar]: maxHeight,});-const globalStyles = globalCss({- "fieldset[disabled] .cm-editor": {- opacity: 0.3,- },-});-const editorContentStyle = css({...textVariants.mono,// fit editor into parent if stretched@@ -137,6 +130,12 @@ const editorContentStyle = css({"& .cm-activeLine": {backgroundColor: cssVar("--overlay-interaction-hover"),},+ "& .cm-selectionBackground, & .cm-content ::selection": {+ backgroundColor: `${cssVar("--background-text-selection")} !important`,+ },+ "& .cm-content ::selection": {+ color: `${cssVar("--foreground-on-text-selection")} !important`,+ },// fix scrolls appear on mount"& .cm-scroller": {overflowX: "hidden",@@ -156,6 +155,9 @@ const editorContentStyle = css({minHeight: cssVar(minHeightVar, "auto"),maxHeight: cssVar(maxHeightVar, "none"),},+ "fieldset[disabled] & .cm-editor": {+ opacity: 0.3,+ },".cm-lintRange-error": {textDecoration: `underline wavy ${cssVar("--foreground-negative")}`,backgroundColor: cssVar("--background-negative-subtle"),@@ -329,8 +331,6 @@ export const EditorContent = ({onChange,onChangeComplete,}: EditorContentProps) => {- globalStyles();-const editorRef = useRef<HTMLDivElement>(null);const viewRef = useRef<undefined | EditorView>(undefined);diff --git a/apps/builder/app/shared/error/error-message.browser.test.tsx b/apps/builder/app/shared/error/error-message.browser.test.tsxnew file mode 100644index 0000000000..3af53e8b75--- /dev/null+++ b/apps/builder/app/shared/error/error-message.browser.test.tsx@@ -0,0 +1,64 @@+import { act } from "react-dom/test-utils";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, test } from "vitest";+import { ErrorMessage } from "./error-message.client";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let container: HTMLDivElement;+let root: Root;++beforeEach(() => {+ container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++test("renders without design-system global color variables", () => {+ act(() => {+ root.render(+ <ErrorMessage+ error={{+ status: 500,+ message: "Canvas failed to render",+ }}+ />+ );+ });++ const page = container.firstElementChild;+ const link = container.querySelector("a");+ const panel = link?.previousElementSibling;+ if (+ page instanceof HTMLElement === false ||+ panel instanceof HTMLElement === false ||+ link instanceof HTMLElement === false+ ) {+ throw new Error("Expected the error page, panel, and link");+ }++ expect(getComputedStyle(page).color).toBe("rgb(17, 24, 28)");+ expect(getComputedStyle(panel).backgroundColor).toBe("rgb(255, 255, 255)");+ expect(getComputedStyle(link).backgroundColor).toBe("rgb(9, 108, 255)");+ expect(getComputedStyle(link).color).toBe("rgb(255, 255, 255)");++ for (const state of ["hover", "pressed"]) {+ link.dataset.state = state;+ const style = getComputedStyle(link);+ expect(style.backgroundImage, state).not.toBe("none");+ expect(style.color, state).toBe("rgb(255, 255, 255)");+ }++ link.dataset.state = "focus";+ const focusStyle = getComputedStyle(link);+ expect(focusStyle.outlineColor).toBe("rgb(41, 122, 255)");+ expect(focusStyle.outlineStyle).not.toBe("none");+ expect(focusStyle.color).toBe("rgb(255, 255, 255)");+});diff --git a/apps/builder/app/shared/error/error-message.client.tsx b/apps/builder/app/shared/error/error-message.client.tsxindex ce42c81b5a..1576bd5406 100644--- a/apps/builder/app/shared/error/error-message.client.tsx+++ b/apps/builder/app/shared/error/error-message.client.tsx@@ -19,11 +19,34 @@ const pageStyle = css({paddingTop: "10vh",// prevent global root styles override error colorcolor: `light-dark(- ${cssVar("--foreground-primary")},- ${cssVar("--foreground-on-inverse")}+ ${cssVar("--foreground-primary", "#11181c")},+ ${cssVar("--foreground-on-inverse", "#fff")})`,});+const standaloneButtonBackground = cssVar("--background-accent", "#096cff");+const standaloneButtonForeground = cssVar("--foreground-on-accent", "#fff");+const standaloneButtonHoverOverlay = `oklch(from ${standaloneButtonForeground} 0 0 h / 6.2745%)`;+const standaloneButtonPressedOverlay = `oklch(from ${standaloneButtonForeground} 0 0 h / 10.9804%)`;++const standaloneButtonStyle = {+ background: standaloneButtonBackground,+ color: standaloneButtonForeground,+ "&&[data-state=auto]:hover, &&[data-state=hover]": {+ background: `linear-gradient(${standaloneButtonHoverOverlay}, ${standaloneButtonHoverOverlay}), ${standaloneButtonBackground}`,+ color: standaloneButtonForeground,+ },+ "&&[data-state=auto]:focus-visible, &&[data-state=focus]": {+ color: standaloneButtonForeground,+ outline: `1px solid ${cssVar("--border-focus", "#297aff")}`,+ outlineOffset: "1px",+ },+ "&&[data-state=auto]:active, &&[data-state=pressed]": {+ background: `linear-gradient(${standaloneButtonPressedOverlay}, ${standaloneButtonPressedOverlay}), ${standaloneButtonBackground}`,+ color: standaloneButtonForeground,+ },+};+export const ErrorMessage = ({error,}: {@@ -62,8 +85,8 @@ export const ErrorMessage = ({<Gridcss={{background: `light-dark(- ${cssVar("--background-primary")},- ${cssVar("--background-inverse")}+ ${cssVar("--background-primary", "#fff")},+ ${cssVar("--background-inverse", "#11181c")})`,padding: theme.spacing[7],borderRadius: theme.spacing[5],@@ -96,7 +119,7 @@ export const ErrorMessage = ({</Text>)}</Grid>- <LinkButton color="primary" href="/">+ <LinkButton color="primary" href="/" css={standaloneButtonStyle}>Go home</LinkButton></Grid>diff --git a/apps/builder/app/shared/project-settings/project-settings.tsx b/apps/builder/app/shared/project-settings/project-settings.tsxindex b1ca55330b..87b439c258 100644--- a/apps/builder/app/shared/project-settings/project-settings.tsx+++ b/apps/builder/app/shared/project-settings/project-settings.tsx@@ -13,7 +13,7 @@ import {Text,rawTheme,cssVar,- selectionBackground,+ selectedItemBackground,} from "@webstudio-is/design-system";import { SpinnerIcon } from "@webstudio-is/icons";import {@@ -112,7 +112,7 @@ export const ProjectSettingsDialog = ({background: cssVar("--overlay-interaction-hover"),},"&[aria-current=true]": {- background: selectionBackground,+ background: selectedItemBackground,color: cssVar("--foreground-primary"),},}}diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex 6daec101b8..880e050cad 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -44,9 +44,6 @@"@codemirror/view": "^6.36.4","@emotion/hash": "^0.9.2","@floating-ui/dom": "^1.6.13",- "@fontsource-variable/inter": "^5.0.20",- "@fontsource-variable/manrope": "^5.0.20",- "@fontsource/roboto-mono": "^5.0.18","@lexical/headless": "^0.21.0","@lexical/link": "^0.21.0","@lexical/react": "^0.21.0",diff --git a/package.json b/package.jsonindex c03707fed7..d6ff77461f 100644--- a/package.json+++ b/package.json@@ -55,9 +55,6 @@"pre-commit": "./node_modules/.bin/nano-staged"},"devDependencies": {- "@fontsource-variable/inter": "^5.0.20",- "@fontsource-variable/manrope": "^5.0.20",- "@fontsource/roboto-mono": "^5.0.18","@modelcontextprotocol/sdk": "^1.10.0","@radix-ui/react-tooltip": "^1.2.4","@storybook/addon-actions": "^8.6.4",diff --git a/packages/asset-uploader/package.json b/packages/asset-uploader/package.jsonindex 41dde00db9..5864c6feea 100644--- a/packages/asset-uploader/package.json+++ b/packages/asset-uploader/package.json@@ -24,6 +24,7 @@"warn-once": "^0.1.1"},"devDependencies": {+ "@fontsource-variable/inter": "^5.0.20","@types/fontkit": "^2.0.8","@webstudio-is/tsconfig": "workspace:*","msw": "^2.13.2",diff --git a/packages/design-system/README.md b/packages/design-system/README.mdindex 25ebf6dff6..606ec28f8d 100644--- a/packages/design-system/README.md+++ b/packages/design-system/README.md@@ -15,10 +15,19 @@ Craft and this package have different responsibilities:consumes those semantics in composite component styles.The implementation defines each color seed once. A shared light or dark profile-transforms six theme colors into a deliberately-small semantic vocabulary. Components load the CSS directly and compose those-semantics without component-specific color variables. These implementation-choices are not requirements for other Craft projects.+transforms six theme colors into a deliberately small semantic vocabulary. Full+UI documents load `@webstudio-is/design-system/global.css` once at their root;+components then compose its semantics without injecting global CSS.+Component-owned custom properties stay locally typed instead of entering the+color manifest. These implementation choices are not requirements for other+Craft projects.++The global entry contains only document-wide behavior required by every full+design-system UI: font faces, root theme and semantic color variables, base+document defaults, and browser-native treatments such as text selection.+Component styles remain with their component, while route layout, scroll+locking, and feature integrations remain application-owned. The Builder canvas+intentionally does not load this entry because it hosts authored user documents.See [Color tokens](src/colors/README.md) for the CSS source format, validation,type-only generation workflow, and naming rules.diff --git a/packages/design-system/package.json b/packages/design-system/package.jsonindex d7d33f52de..24335cb0a2 100644--- a/packages/design-system/package.json+++ b/packages/design-system/package.json@@ -11,7 +11,6 @@"test": "vitest run"},"devDependencies": {- "@babel/parser": "^7.29.7","@types/react": "^18.2.70","@types/react-dom": "^18.2.25","@vitest/browser": "3.1.1",@@ -33,6 +32,9 @@"@atlaskit/pragmatic-drag-and-drop-auto-scroll": "^2.1.0","@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.0.3","@floating-ui/dom": "^1.6.13",+ "@fontsource-variable/inter": "^5.0.20",+ "@fontsource-variable/manrope": "^5.0.20",+ "@fontsource/roboto-mono": "^5.0.18","@radix-ui/colors": "^3.0.0","@radix-ui/react-accessible-icon": "^1.1.4","@radix-ui/react-avatar": "^1.1.7",@@ -80,10 +82,7 @@".": {"webstudio": "./src/index.ts"},- "./colors": {- "webstudio": "./src/colors.ts"- },- "./colors.css": "./src/colors/colors.css"+ "./global.css": "./src/global.css"},"license": "AGPL-3.0-or-later","private": true,diff --git a/packages/design-system/src/colors/README.md b/packages/design-system/src/colors/README.mdindex 3fe168e405..cc5402584e 100644--- a/packages/design-system/src/colors/README.md+++ b/packages/design-system/src/colors/README.md@@ -4,8 +4,13 @@colors. Do not edit files in `__generated__/` directly; generated files containtypes only.-Each application must load `@webstudio-is/design-system/colors.css` once at its-UI root. Design-system component imports do not inject global styles.+Each full design-system UI must load+`@webstudio-is/design-system/global.css` once at its root. This is the single+public stylesheet entry for font faces, color tokens, and shared browser-native+treatments such as text selection. It also applies the shared body reset,+interface font, and foreground color. Design-system component imports do not+inject global styles. The Builder canvas intentionally excludes this entry+because it hosts authored user documents.The implementation follows the public[Craft specification](https://docs.webstudio.is/university/craft): bounded theme@@ -32,47 +37,46 @@ scheme derivation bounds rather than maintaining a second theme or semanticcolor set. Cross-hue variants mix in `oklab`, so the neutral family cannotrotate an intent into another color family.-Chromatic fills keep the same bounded luminance in both schemes. Dark mode-derives lighter foreground and focus variants from the same color family and-uses light content on strong chromatic fills. This keeps accent buttons stable-between schemes without making dark-mode accent text unreadable.+Default chromatic fills keep the same bounded luminance in both schemes. Dark+mode derives lighter foreground and focus variants from the same color family+and uses light content on strong chromatic fills.## Theme parametersTheme authors set colors and relationships, not semantic outputs. Every publicparameter is commented at its declaration in [`colors.css`](colors.css).-| Parameter | Meaning |-| --------------------------- | ------------------------------------------------------- |-| `--theme-color-neutral` | Surfaces, content, borders, and shadows |-| `--theme-color-accent` | Interactive emphasis and keyboard focus |-| `--theme-color-positive` | Successful or positive outcomes |-| `--theme-color-negative` | Errors, danger, and destructive actions |-| `--theme-color-warning` | Caution and warning states |-| `--theme-color-informative` | Neutral information |-| `--theme-contrast-content` | Content contrast from the readable minimum to strongest |-| `--theme-contrast-surface` | Separation between primary and secondary surfaces |-| `--theme-contrast-border` | Separation between decorative borders and surfaces |--Theme colors accept any CSS color. The recipe converts chromatic inputs into-the display gamut, limits their OKLCH source to `0.2–0.8` lightness and `0.3`-chroma, then bounds luminance for the active scheme by mixing toward black or-white. Neutral chroma is limited to `0.02`. These bounds preserve the selected-color family while keeping required text and focus relationships safe.--The default parameters reproduce the design system's established light palette-within small per-channel tolerances. Decorative subtle backgrounds and borders-are allowed a wider tolerance because their legacy relationships do not meet a-meaningful 3:1 contrast threshold.--Contrast parameters are percentages. `0%` selects the soft end and `100%`-selects the strong end. CSS clamps values outside that range, so the recipe-preserves its relative hierarchy regardless of the authoring UI. Content and-focus contracts are tested for accessibility; surface and decorative border-contrast remain visual theme choices.+| Parameter | Meaning |+| --------------------------- | -------------------------------------------------- |+| `--theme-color-neutral` | Surfaces, content, borders, and shadows |+| `--theme-color-accent` | Interactive emphasis and keyboard focus |+| `--theme-color-positive` | Successful or positive outcomes |+| `--theme-color-negative` | Errors, danger, and destructive actions |+| `--theme-color-warning` | Caution and warning states |+| `--theme-color-informative` | Neutral information |+| `--theme-contrast-content` | Content contrast from the soft bound to strongest |+| `--theme-contrast-surface` | Separation between primary and secondary surfaces |+| `--theme-contrast-border` | Separation between decorative borders and surfaces |++Theme colors support opaque, context-independent CSS colors such as hex,+`rgb()`, and `oklch()` values. Alpha colors and context-dependent keywords such+as `currentColor` are outside the contract. The recipe converts chromatic+inputs into the display gamut, limits their OKLCH source to `0.2–0.8` lightness+and `0.3` chroma, then caps relative luminance by scaling XYZ toward black.+Neutral chroma is limited to `0.02`.++The default light and dark outputs are regression tested. Custom theme values+can produce lower-contrast combinations, so theme authors must verify the+resulting interface instead of treating the derivation bounds as an+accessibility guarantee.++Contrast parameters support percentages from `0%` (soft) through `100%`+(strong). Values outside that range are outside the contract. Each control+names its primary effect, but downstream recipes share inputs; the controls are+not independent accessibility guarantees.```css-.custom-theme {+:root {--theme-color-neutral: oklch(55% 0.02 285);--theme-color-accent: oklch(60% 0.2 295);--theme-color-positive: oklch(55% 0.14 152);@@ -86,8 +90,9 @@ contrast remain visual theme choices.}```-Set `data-color-scheme` on the document root. Scheme bounds are deliberately-root-scoped; nested light and dark theme islands are not part of this contract.+Set theme parameters and `data-color-scheme` on the document root. Derivations+are computed there, so descendant overrides and nested theme islands are not+part of this contract.## Semantic colors@@ -115,17 +120,18 @@ styled("button", {The package extends Craft's core registry only for reusable component needs:-| Family | Meaning and required pairing |-| ------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |-| `inverse` | A surface with reversed polarity; pair `--background-inverse` with `--foreground-on-inverse`. |-| `accent` | Interactive emphasis; pair a strong accent background with `--foreground-on-accent`. |-| `accent-secondary` | Secondary interactive emphasis; use the foreground on surfaces and pair the strong background with `--foreground-on-accent-secondary`. |-| `positive` | Successful outcomes; pair strong or subtle backgrounds with their registered foreground. |-| `negative` | Errors and destructive actions; pair strong or subtle backgrounds with their registered foreground. |-| `warning` | Caution; pair the subtle background with the warning foreground and border. |-| `informative` | Neutral information; pair the subtle background with the informative foreground and border. |-| `interaction` | Translucent hover and pressed feedback composed over regular surfaces. |-| `on-inverse` | Translucent hover and pressed feedback composed over inverse surfaces. |+| Family | Meaning and required pairing |+| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |+| `inverse` | A surface with reversed polarity; pair `--background-inverse` with `--foreground-on-inverse`. |+| `accent` | Interactive emphasis; pair a strong accent background with `--foreground-on-accent`. |+| `text-selection` | Strong text selection shared by native fields and code editors; pair `--background-text-selection` with `--foreground-on-text-selection`. |+| `accent-secondary` | Secondary interactive emphasis; use the foreground on surfaces and pair the strong background with `--foreground-on-accent-secondary`. |+| `positive` | Successful outcomes; pair strong or subtle backgrounds with their registered foreground. |+| `negative` | Errors and destructive actions; pair strong or subtle backgrounds with their registered foreground. |+| `warning` | Caution; pair the subtle background with the warning foreground and border. |+| `informative` | Neutral information; pair the subtle background with the informative foreground and border. |+| `interaction` | Translucent hover and pressed feedback composed over regular surfaces. |+| `on-inverse` | Translucent hover and pressed feedback composed over inverse surfaces. |`--overlay-scrim` always derives from a dark version of the neutral themecolor, so it dims content in both schemes rather than following foreground@@ -142,19 +148,22 @@ cssVar("--foreground-primary", "currentColor");```Component-owned and third-party variables stay with their component instead of-entering the color manifest. Declare each name once in its owning source file:+entering the color manifest. Declare each shared contract in its owning source+file:```ts-declareCssVar("--panel-banner-icon-color");+const panelBannerIconColor = declareCssVar("--panel-banner-icon-color");-cssVar("--panel-banner-icon-color");-cssVar("--panel-banner-icon-color", "currentColor");+cssVar(panelBannerIconColor);+cssVar(panelBannerIconColor, "currentColor");```-The generator collects `declareCssVar()` calls into the global name type. It-rejects duplicate declarations and conflicts with every variable in-`colors.css`. An unregistered string is rejected by `cssVar()` without requiring-component variable constants to be exported or imported.+`declareCssVar()` brands the local name for `cssVar()` without registering it+globally. Scope variables to the owning component and use a component-specific+prefix unless a third-party API fixes the name. Import the declared constant+when another module participates in the same contract. Color-system namespaces+are reserved for [`colors.css`](colors.css), and unregistered string literals+are rejected.## Fixed brand artwork@@ -174,27 +183,26 @@ Type generation parses CSS structurally and rejects:- Standalone semantic color literals.- Circular color references.- Semantic names outside the Craft grammar.-- Duplicate component variable declarations or conflicts with color variables.+- Color variables declared outside the owned root selectors.-TypeScript rejects unknown public variable names passed to `cssVar()`.+TypeScript rejects unknown semantic names and unbranded private names passed to+`cssVar()`.-Browser tests load the real stylesheet and sweep theme color and contrast-boundaries in both schemes. They reject foreground/background text pairs below-4.5:1 contrast and focus borders below 3:1 contrast. They also compare every-default light semantic color with the established design-system palette and-protect the dark neutral hierarchy, stable chromatic fills, light on-color-content, and light interaction overlays.+Chromium browser tests load the real stylesheet, freeze every default semantic+color in both schemes, and verify the default foreground/background contracts.+They also protect the neutral hierarchy, stable chromatic fills, on-color+content, and interaction overlays.The generator emits `ThemeVariableName` for public theme inputs and-`CssVariableName` for semantic colors and declared component variables in-`__generated__/css-variable-names.d.ts`. It does not generate JavaScript or-duplicate color values. CSS is imported directly and performs all runtime-derivation and scheme switching.--Run `pnpm generate:color-types` after changing a color or `declareCssVar()`-declaration. The package `typecheck` verifies that generated declarations are-current, and the normal workspace CI runs that command. Run `pnpm test` to-verify structural contracts and browser-computed contrast.+`SemanticColorName` for semantic colors in+`__generated__/css-variable-names.d.ts`. Component variables remain local. The+generator does not scan applications, generate JavaScript, or duplicate color+values. CSS performs all runtime derivation and scheme switching.++Run `pnpm generate:color-types` after changing a theme or semantic variable+name. The package `typecheck` verifies that generated declarations are current,+and the normal workspace CI runs that command. Run `pnpm test` to verify+structural contracts, default colors, and browser-computed contrast.The Storybook **Foundations/Colors** story loads the runtime stylesheet directlyand parses the same file only for names and source declarations. It rendersdiff --git a/packages/design-system/src/colors/__generated__/css-variable-names.d.ts b/packages/design-system/src/colors/__generated__/css-variable-names.d.tsindex c14bce8ec4..351fe3b366 100644--- a/packages/design-system/src/colors/__generated__/css-variable-names.d.ts+++ b/packages/design-system/src/colors/__generated__/css-variable-names.d.ts@@ -1,4 +1,4 @@-// Generated by generate-color-types.ts from colors.css and declareCssVar() calls. Do not edit directly.+// Generated by generate-color-types.ts from colors.css. Do not edit directly.export type ThemeVariableName =| "--theme-color-neutral"@@ -11,12 +11,13 @@ export type ThemeVariableName =| "--theme-contrast-surface"| "--theme-contrast-border";-export type CssVariableName =+export type SemanticColorName =| "--background-primary"| "--background-secondary"| "--background-disabled"| "--background-inverse"| "--background-accent"+ | "--background-text-selection"| "--background-accent-secondary"| "--background-positive"| "--background-positive-subtle"@@ -32,6 +33,7 @@ export type CssVariableName =| "--foreground-on-accent-secondary"| "--foreground-on-positive"| "--foreground-on-negative"+ | "--foreground-on-text-selection"| "--foreground-accent"| "--foreground-accent-secondary"| "--foreground-positive"@@ -47,44 +49,4 @@ export type CssVariableName =| "--overlay-interaction-pressed"| "--overlay-on-inverse-hover"| "--overlay-on-inverse-pressed"- | "--overlay-scrim"- | "--binding-opacity"- | "--canvas-pointer-events"- | "--clear-selection-trigger"- | "--code-editor-max-height"- | "--code-editor-maximize-icon-visibility"- | "--code-editor-min-height"- | "--command-input-border-bottom-width"- | "--contrast"- | "--css-value-input-maximize-button-display"- | "--dashboard-card-border-color"- | "--dot-display"- | "--editing-placeholder"- | "--outline-angle"- | "--panel-banner-icon-color"- | "--plus-display"- | "--project-card-prefetch-image-background"- | "--radix-collapsible-content-height"- | "--radix-popper-anchor-width"- | "--radix-scroll-area-thumb-height"- | "--radix-select-trigger-width"- | "--radix-toast-swipe-end-x"- | "--radix-toast-swipe-move-x"- | "--section-title-button-content-color"- | "--section-title-chevron-display"- | "--section-title-label-content-color"- | "--select-button-chevron-color"- | "--sidebar-left-panel-width"- | "--style-node-trigger"- | "--style-source-menu-trigger-gradient"- | "--style-source-menu-trigger-visibility"- | "--style-source-menu-trigger-visibility-override"- | "--thumb-border-color"- | "--thumbnail-action-visibility"- | "--tree-action-opacity"- | "--tree-action-width"- | "--tree-node-background-color"- | "--tree-node-level"- | "--tree-node-outline"- | "--tree-node-selection-background-color"- | "--value";+ | "--overlay-scrim";diff --git a/packages/design-system/src/colors/color-contrast.browser.test.ts b/packages/design-system/src/colors/color-contrast.browser.test.tsindex fe5a11ef1b..698cf2ef28 100644--- a/packages/design-system/src/colors/color-contrast.browser.test.ts+++ b/packages/design-system/src/colors/color-contrast.browser.test.ts@@ -1,10 +1,9 @@import { describe, expect, test } from "vitest";import "./colors.css";-import { __testing__, getColorContrast } from "./color-contrast";+import type { SemanticColorName } from "./__generated__/css-variable-names";+import { getColorContrast } from "./color-contrast";import type { ColorMode } from "./color-source-utils";-const { createColorContrastReader } = __testing__;-const readColor = (name: string) => {const sample = document.createElement("span");sample.style.color = `var(${name})`;@@ -25,46 +24,88 @@ const readColor = (name: string) => {return color;};-const expectedLightColors = {- "--background-primary": "#ffffff",- "--background-secondary": "#e8eaeb",- "--background-disabled": "#f8f8f8",- "--background-inverse": "#11181c",- "--background-accent": "#096cff",- "--background-accent-secondary": "#ab38d4",- "--background-positive": "#00894a",- "--background-positive-subtle": "#e9f9ee",- "--background-negative": "#dc2929",- "--background-negative-subtle": "#ffe9e9",- "--background-warning-subtle": "#f8edad",- "--background-informative-subtle": "#e1f0ff",- "--foreground-primary": "#11181c",- "--foreground-secondary": "#595f63",- "--foreground-disabled": "#898d90",- "--foreground-on-inverse": "#ffffff",- "--foreground-on-accent": "#ffffff",- "--foreground-on-accent-secondary": "#ffffff",- "--foreground-on-positive": "#ffffff",- "--foreground-on-negative": "#ffffff",- "--foreground-accent": "#096cff",- "--foreground-accent-secondary": "#ab38d4",- // Darkened from the legacy green so positive text remains accessible on its subtle background.- "--foreground-positive": "#0b7b45",- "--foreground-negative": "#d13a3a",- // Darkened from the legacy yellow so warning text meets 4.5:1 contrast.- "--foreground-warning": "#6f6100",- "--foreground-informative": "#016ccc",- "--border-default": "#e6e6e6",- "--border-focus": "#3c86ff",- "--border-negative": "#d13a3a",- "--border-warning": "#f5d90a",- "--border-informative": "#b7d9f8",- "--overlay-interaction-hover": "#00000010",- "--overlay-interaction-pressed": "#0000001c",- "--overlay-on-inverse-hover": "#ffffff10",- "--overlay-on-inverse-pressed": "#ffffff1c",- "--overlay-scrim": "#11181ca8",-} as const;+const expectedDefaultColors = {+ light: {+ "--background-primary": "#feffff",+ "--background-secondary": "#e8eaeb",+ "--background-disabled": "#f7f8f9",+ "--background-inverse": "#11181c",+ "--background-accent": "#096cff",+ "--background-text-selection": "#096cff",+ "--background-accent-secondary": "#ab38d4",+ "--background-positive": "#008849",+ "--background-positive-subtle": "#e4f1e9",+ "--background-negative": "#dc2929",+ "--background-negative-subtle": "#ffe9e6",+ "--background-warning-subtle": "#f8edad",+ "--background-informative-subtle": "#e3effd",+ "--foreground-primary": "#11181c",+ "--foreground-secondary": "#595f63",+ "--foreground-disabled": "#898d90",+ "--foreground-on-inverse": "#feffff",+ "--foreground-on-accent": "#feffff",+ "--foreground-on-accent-secondary": "#feffff",+ "--foreground-on-positive": "#feffff",+ "--foreground-on-negative": "#feffff",+ "--foreground-on-text-selection": "#feffff",+ "--foreground-accent": "#096cff",+ "--foreground-accent-secondary": "#ab38d4",+ "--foreground-positive": "#0b7b45",+ "--foreground-negative": "#c52a28",+ "--foreground-warning": "#6f6100",+ "--foreground-informative": "#0a6bc7",+ "--border-default": "#e5e6e7",+ "--border-focus": "#297aff",+ "--border-negative": "#c52a28",+ "--border-warning": "#f5d90a",+ "--border-informative": "#bcd7f8",+ "--overlay-interaction-hover": "#00000010",+ "--overlay-interaction-pressed": "#0000001c",+ "--overlay-on-inverse-hover": "#ffffff10",+ "--overlay-on-inverse-pressed": "#ffffff1c",+ "--overlay-scrim": "#11171ba8",+ },+ dark: {+ "--background-primary": "#151617",+ "--background-secondary": "#222425",+ "--background-disabled": "#191b1b",+ "--background-inverse": "#e6e8e9",+ "--background-accent": "#096cff",+ "--background-text-selection": "#439cff",+ "--background-accent-secondary": "#ab38d4",+ "--background-positive": "#008849",+ "--background-positive-subtle": "#18221d",+ "--background-negative": "#dc2929",+ "--background-negative-subtle": "#2b1c1b",+ "--background-warning-subtle": "#2d2c1f",+ "--background-informative-subtle": "#1a2839",+ "--foreground-primary": "#e6e8e9",+ "--foreground-secondary": "#959798",+ "--foreground-disabled": "#6a6c6d",+ "--foreground-on-inverse": "#151617",+ "--foreground-on-accent": "#fdffff",+ "--foreground-on-accent-secondary": "#fdffff",+ "--foreground-on-positive": "#fdffff",+ "--foreground-on-negative": "#fdffff",+ "--foreground-on-text-selection": "#151617",+ "--foreground-accent": "#a0c1f6",+ "--foreground-accent-secondary": "#da6bff",+ "--foreground-positive": "#abcab5",+ "--foreground-negative": "#ff594f",+ "--foreground-warning": "#c4c1a5",+ "--foreground-informative": "#a9c6e8",+ "--border-default": "#252627",+ "--border-focus": "#1a6df2",+ "--border-negative": "#ff594f",+ "--border-warning": "#f5d90a",+ "--border-informative": "#1b314c",+ "--overlay-interaction-hover": "#ffffff10",+ "--overlay-interaction-pressed": "#ffffff1c",+ "--overlay-on-inverse-hover": "#00000010",+ "--overlay-on-inverse-pressed": "#0000001c",+ "--overlay-scrim": "#11171ba8",+ },+} as const satisfies Record<ColorMode, Record<SemanticColorName, string>>;const parseHex = (hex: string) => {const channels = hex.slice(1).match(/.{2}/g);@@ -98,6 +139,37 @@ const getContrastRatio = (};describe("Craft color contrast", () => {+ test("default semantic colors stay unchanged", () => {+ const root = document.documentElement;+ const previousMode = root.getAttribute("data-color-scheme");++ try {+ for (const mode of ["light", "dark"] as const) {+ root.dataset.colorScheme = mode;+ for (const [name, expectedHex] of Object.entries(+ expectedDefaultColors[mode]+ )) {+ const actual = Array.from(readColor(name));+ const expected = parseHex(expectedHex);+ for (const [index, expectedChannel] of expected.entries()) {+ expect+ .soft(+ Math.abs(actual[index] - expectedChannel),+ `${mode} ${name} channel ${index}: ${actual.join(", ")} versus ${expected.join(", ")}`+ )+ .toBeLessThanOrEqual(1);+ }+ }+ }+ } finally {+ if (previousMode === null) {+ root.removeAttribute("data-color-scheme");+ } else {+ root.setAttribute("data-color-scheme", previousMode);+ }+ }+ });+test("default secondary colors preserve a clear visual hierarchy", () => {const root = document.documentElement;const previousMode = root.getAttribute("data-color-scheme");@@ -188,45 +260,6 @@ describe("Craft color contrast", () => {}});- test("default light semantics resolve to the expected palette", () => {- const root = document.documentElement;- const previousMode = root.getAttribute("data-color-scheme");- root.dataset.colorScheme = "light";-- try {- for (const [name, expectedHex] of Object.entries(expectedLightColors)) {- const actual = Array.from(readColor(name));- const expected = parseHex(expectedHex);- let tolerance = 9;- if (name === "--background-negative-subtle") {- tolerance = 4;- } else if (- name !== "--background-warning-subtle" &&- (name.includes("subtle") ||- name.startsWith("--border-") ||- name === "--foreground-negative")- ) {- tolerance = 24;- }-- for (const [index, expectedChannel] of expected.entries()) {- expect- .soft(- Math.abs(actual[index] - expectedChannel),- `${name} channel ${index}: ${actual.join(", ")} versus ${expected.join(", ")}`- )- .toBeLessThanOrEqual(index === 3 ? 1 : tolerance);- }- }- } finally {- if (previousMode === null) {- root.removeAttribute("data-color-scheme");- } else {- root.setAttribute("data-color-scheme", previousMode);- }- }- });-test("dark focus borders preserve accent color instead of using accent text", () => {const root = document.documentElement;const previousMode = root.getAttribute("data-color-scheme");@@ -288,7 +321,7 @@ describe("Craft color contrast", () => {sample.remove();});- test("theme contrast parameters are effective and clamp to their range", () => {+ test("theme contrast parameters affect their primary outputs", () => {const root = document.documentElement;const relationships = {content: "--foreground-primary",@@ -307,15 +340,6 @@ describe("Craft color contrast", () => {const strong = Array.from(readColor(semanticColor));expect(strong, relationship).not.toEqual(soft);-- root.style.setProperty(parameter, "-100%");- expect(Array.from(readColor(semanticColor)), relationship).toEqual(- soft- );- root.style.setProperty(parameter, "200%");- expect(Array.from(readColor(semanticColor)), relationship).toEqual(- strong- );}} finally {for (const relationship of Object.keys(relationships)) {@@ -467,92 +491,4 @@ describe("Craft color contrast", () => {}}});-- test("supported theme parameter range preserves every contrast contract", () => {- const root = document.documentElement;- const contrastReader = createColorContrastReader();- const chromaticColors = [- "accent",- "positive",- "negative",- "warning",- "informative",- ];- const contrasts = ["content", "surface", "border"];- const violations = new Map<string, { ratio: number; message: string }>();-- const recordFailures = (scenario: string, mode: ColorMode) => {- const failures = contrastReader- .read(mode)- .filter(({ ratio, minimum }) => ratio < minimum);- for (const failure of failures) {- const relationship = `${failure.foreground} on ${failure.background}`;- const previous = violations.get(relationship);- const message = `${scenario}: ${relationship} is ${failure.ratio.toFixed(2)}:1, expected ${failure.minimum}:1`;- if (previous === undefined || previous.ratio > failure.ratio) {- violations.set(relationship, { ratio: failure.ratio, message });- }- }- };-- try {- for (const mode of ["light", "dark"] as const) {- for (const content of [0, 100]) {- for (const surface of [0, 100]) {- for (const border of [0, 100]) {- root.style.setProperty("--theme-contrast-content", `${content}%`);- root.style.setProperty("--theme-contrast-surface", `${surface}%`);- root.style.setProperty("--theme-contrast-border", `${border}%`);- for (const lightness of [0, 100]) {- for (const chroma of [0, 0.4]) {- for (let hue = 0; hue < 360; hue += 15) {- for (const color of chromaticColors) {- root.style.setProperty(- `--theme-color-${color}`,- `oklch(${lightness}% ${chroma} ${hue})`- );- }- recordFailures(- `${mode}, contrast ${content}/${surface}/${border}, ${lightness}%, ${chroma} chroma, ${hue}deg`,- mode- );- }- }- }- for (const color of chromaticColors) {- root.style.removeProperty(`--theme-color-${color}`);- }- for (const lightness of [0, 100]) {- for (const chroma of [0, 0.2]) {- for (let hue = 0; hue < 360; hue += 15) {- root.style.setProperty(- "--theme-color-neutral",- `oklch(${lightness}% ${chroma} ${hue})`- );- recordFailures(- `${mode} neutral, contrast ${content}/${surface}/${border}, ${lightness}%, ${chroma} chroma, ${hue}deg`,- mode- );- }- }- }- }- }- }- }- } finally {- contrastReader.dispose();- for (const color of chromaticColors) {- root.style.removeProperty(`--theme-color-${color}`);- }- for (const contrast of contrasts) {- root.style.removeProperty(`--theme-contrast-${contrast}`);- }- root.style.removeProperty("--theme-color-neutral");- }-- expect(Array.from(violations.values(), ({ message }) => message)).toEqual(- []- );- }, 30_000);});diff --git a/packages/design-system/src/colors/color-contrast.ts b/packages/design-system/src/colors/color-contrast.tsindex 402375a7aa..509ebb5b76 100644--- a/packages/design-system/src/colors/color-contrast.ts+++ b/packages/design-system/src/colors/color-contrast.ts@@ -1,10 +1,10 @@-import type { CssVariableName } from "./__generated__/css-variable-names";+import type { SemanticColorName } from "./__generated__/css-variable-names";import type { ColorMode } from "./color-source-utils";import { cssVar } from "../css-var";export type ColorContrastResult = {- foreground: CssVariableName;- background: CssVariableName;+ foreground: SemanticColorName;+ background: SemanticColorName;minimum: number;ratio: number;};@@ -20,6 +20,10 @@ const contrastContracts = [["--foreground-negative", "--background-primary", 4.5],["--foreground-warning", "--background-primary", 4.5],["--foreground-informative", "--background-primary", 4.5],+ ["--foreground-on-text-selection", "--background-text-selection", 4.5],+ // Text selection appears on both regular surfaces and secondary editor fields.+ ["--background-text-selection", "--background-primary", 3],+ ["--background-text-selection", "--background-secondary", 3],["--foreground-on-inverse", "--background-inverse", 4.5],["--foreground-on-accent", "--background-accent", 4.5],["--foreground-on-accent-secondary", "--background-accent-secondary", 4.5],@@ -34,12 +38,12 @@ const contrastContracts = [["--foreground-negative", "--background-informative-subtle", 4.5],["--border-focus", "--background-secondary", 3],] as const satisfies readonly (readonly [- CssVariableName,- CssVariableName,+ SemanticColorName,+ SemanticColorName,number,])[];-const contrastColorNames = new Set<CssVariableName>(+const contrastColorNames = new Set<SemanticColorName>(contrastContracts.flatMap(([foreground, background]) => [foreground,background,@@ -59,7 +63,7 @@ const getLuminance = (color: Uint8ClampedArray) =>0.0722 * toLinearChannel(color[2]);const createColorReader = () => {- const samples = new Map<CssVariableName, HTMLElement>();+ const samples = new Map<SemanticColorName, HTMLElement>();const container = document.createElement("div");container.hidden = true;for (const name of contrastColorNames) {@@ -79,7 +83,7 @@ const createColorReader = () => {throw new Error("Canvas color evaluation is unavailable");}- const read = (name: CssVariableName) => {+ const read = (name: SemanticColorName) => {const sample = samples.get(name);if (sample === undefined) {throw new Error(`Unknown contrast color: ${name}`);@@ -104,8 +108,8 @@ const createColorContrastReader = () => {const read = (mode: ColorMode): ColorContrastResult[] => {root.setAttribute("data-color-scheme", mode);- const luminances = new Map<CssVariableName, number>();- const readLuminance = (name: CssVariableName) => {+ const luminances = new Map<SemanticColorName, number>();+ const readLuminance = (name: SemanticColorName) => {const cached = luminances.get(name);if (cached !== undefined) {return cached;diff --git a/packages/design-system/src/colors/color-source-utils.test.ts b/packages/design-system/src/colors/color-source-utils.test.tsindex 4b725d918d..80245168a2 100644--- a/packages/design-system/src/colors/color-source-utils.test.ts+++ b/packages/design-system/src/colors/color-source-utils.test.ts@@ -102,7 +102,9 @@ describe("Craft color CSS source", () => {(count, category) => count + Object.keys(category).length,0)- ).toBe(36);+ ).toBe(38);+ expect(colors.semantic.background).toHaveProperty("text-selection");+ expect(colors.semantic.foreground).toHaveProperty("on-text-selection");expect(colors.semantic.background).toHaveProperty("positive-subtle");expect(colors.semantic.background).toHaveProperty("accent-secondary");expect(colors.semantic.foreground).toHaveProperty("accent-secondary");@@ -126,6 +128,31 @@ describe("Craft color CSS source", () => {expect(colors.semantic.foreground.custom).toContain("var(--color-custom)");});+ test("rejects color variables outside the owned root selectors", () => {+ const invalidSource = `${source}+ .feature {+ --foreground-unvalidated: var(--color-foreground);+ }+ `;++ expect(() => parseColorSource(invalidSource)).toThrow(+ "Color variables may not be declared in .feature"+ );+ });++ test("rejects owned root selectors nested in conditional rules", () => {+ const invalidSource = source+ .replace(":root {", "@media (prefers-contrast: more) { :root {")+ .replace(+ ':root[data-color-scheme="dark"] {',+ '} :root[data-color-scheme="dark"] {'+ );++ expect(() => parseColorSource(invalidSource)).toThrow(+ "Color variables may be declared only in top-level root selectors"+ );+ });+test("rejects standalone semantic color literals", () => {const invalidSource = replaceDeclaration({css: source,diff --git a/packages/design-system/src/colors/color-source-utils.ts b/packages/design-system/src/colors/color-source-utils.tsindex 9dc9f86db9..1d8b291ddd 100644--- a/packages/design-system/src/colors/color-source-utils.ts+++ b/packages/design-system/src/colors/color-source-utils.ts@@ -7,6 +7,10 @@ const colorCategories = ["overlay",] as const;+const rootSelector = ":root";+const darkRootSelector = ':root[data-color-scheme="dark"]';+const colorVariableSelectors = new Set([rootSelector, darkRootSelector]);+type ColorCategory = (typeof colorCategories)[number];export type ColorSource = {@@ -44,27 +48,60 @@ const getDeclarations = (rule: csstree.Rule) => {return declarations;};-const selectDeclarations = (stylesheet: csstree.CssNode, selector: string) => {+const selectDeclarations = (+ stylesheet: csstree.StyleSheet,+ selector: string+) => {let declarations: Record<string, string> | undefined;+ stylesheet.children.forEach((node) => {+ if (node.type !== "Rule" || csstree.generate(node.prelude) !== selector) {+ return;+ }+ if (declarations !== undefined) {+ throw new Error(`Duplicate color selector: ${selector}`);+ }+ declarations = getDeclarations(node);+ });+ if (declarations === undefined) {+ throw new Error(`Missing color selector: ${selector}`);+ }+ return declarations;+};++const validateDeclarationSelectors = (stylesheet: csstree.StyleSheet) => {+ const topLevelRules = new Set<csstree.Rule>();+ stylesheet.children.forEach((node) => {+ if (node.type === "Rule") {+ topLevelRules.add(node);+ }+ });+csstree.walk(stylesheet, {visit: "Rule",enter(node) {if (node.type !== "Rule") {return;}- if (csstree.generate(node.prelude) !== selector) {+ let hasColorVariables = false;+ node.block.children.forEach((child) => {+ if (child.type === "Declaration" && child.property.startsWith("--")) {+ hasColorVariables = true;+ }+ });+ if (hasColorVariables === false) {return;}- if (declarations !== undefined) {- throw new Error(`Duplicate color selector: ${selector}`);+ if (topLevelRules.has(node) === false) {+ throw new Error(+ "Color variables may be declared only in top-level root selectors"+ );+ }+ const selector = csstree.generate(node.prelude);+ if (colorVariableSelectors.has(selector) === false) {+ throw new Error(`Color variables may not be declared in ${selector}`);}- declarations = getDeclarations(node);},});- if (declarations === undefined) {- throw new Error(`Missing color selector: ${selector}`);- }- return declarations;};const getGroup = (declarations: Record<string, string>, prefix: string) =>@@ -74,6 +111,17 @@ const getGroup = (declarations: Record<string, string>, prefix: string) =>.map(([name, value]) => [name.slice(prefix.length), value]));+const prefixDeclarations = (+ prefix: string,+ declarations: Record<string, string>+) =>+ Object.fromEntries(+ Object.entries(declarations).map(([name, value]) => [+ `${prefix}${name}`,+ value,+ ])+ );+const expectValues = (label: string, values: Record<string, string>) => {if (Object.keys(values).length === 0) {throw new Error(`${label} must define at least one value`);@@ -207,12 +255,13 @@ const validateSemanticName = (name: string) => {};export const parseColorSource = (css: string): ColorSource => {- const stylesheet = csstree.parse(css, { positions: true });- const lightDeclarations = selectDeclarations(stylesheet, ":root");- const darkDeclarations = selectDeclarations(- stylesheet,- ':root[data-color-scheme="dark"]'- );+ const stylesheet = csstree.parse(css);+ if (stylesheet.type !== "StyleSheet") {+ throw new Error("Color source must be a stylesheet");+ }+ validateDeclarationSelectors(stylesheet);+ const lightDeclarations = selectDeclarations(stylesheet, rootSelector);+ const darkDeclarations = selectDeclarations(stylesheet, darkRootSelector);const themeColor = getGroup(lightDeclarations, "--theme-color-");const themeContrast = getGroup(lightDeclarations, "--theme-contrast-");@@ -226,6 +275,26 @@ export const parseColorSource = (css: string): ColorSource => {])) as ColorSource["semantic"];+ const themeDeclarations = {+ ...prefixDeclarations("--theme-color-", themeColor),+ ...prefixDeclarations("--theme-contrast-", themeContrast),+ };+ const schemeDeclarations = prefixDeclarations("--scheme-", lightScheme);+ const darkSchemeDeclarations = prefixDeclarations("--scheme-", darkScheme);+ const derivedDeclarations = prefixDeclarations("--color-", derived);+ const semanticDeclarations = Object.assign(+ {},+ ...Object.entries(semantic).map(([category, values]) =>+ prefixDeclarations(`--${category}-`, values)+ )+ );+ const allDeclarations = {+ ...themeDeclarations,+ ...schemeDeclarations,+ ...derivedDeclarations,+ ...semanticDeclarations,+ };+expectValues("Theme color parameters", themeColor);expectValues("Theme contrast parameters", themeContrast);expectValues("Light scheme bounds", lightScheme);@@ -236,37 +305,6 @@ export const parseColorSource = (css: string): ColorSource => {}expectSameNames("Light and dark scheme bounds", lightScheme, darkScheme);- const allDeclarations = {- ...Object.fromEntries(- Object.entries(themeColor).map(([name, value]) => [- `--theme-color-${name}`,- value,- ])- ),- ...Object.fromEntries(- Object.entries(themeContrast).map(([name, value]) => [- `--theme-contrast-${name}`,- value,- ])- ),- ...Object.fromEntries(- Object.entries(lightScheme).map(([name, value]) => [- `--scheme-${name}`,- value,- ])- ),- ...Object.fromEntries(- Object.entries(derived).map(([name, value]) => [`--color-${name}`, value])- ),- ...Object.fromEntries(- Object.entries(semantic).flatMap(([category, values]) =>- Object.entries(values).map(([name, value]) => [- `--${category}-${name}`,- value,- ])- )- ),- };const names = new Set(Object.keys(allDeclarations));const uncategorized = Object.keys(lightDeclarations).filter((name) => names.has(name) === false@@ -285,32 +323,6 @@ export const parseColorSource = (css: string): ColorSource => {);}- const themeDeclarations = Object.fromEntries(- Object.entries(themeColor)- .map(([name, value]) => [`--theme-color-${name}`, value])- .concat(- Object.entries(themeContrast).map(([name, value]) => [- `--theme-contrast-${name}`,- value,- ])- )- );- const schemeDeclarations = Object.fromEntries(- Object.entries(lightScheme).map(([name, value]) => [- `--scheme-${name}`,- value,- ])- );- const darkSchemeDeclarations = Object.fromEntries(- Object.entries(darkScheme).map(([name, value]) => [- `--scheme-${name}`,- value,- ])- );- const derivedDeclarations = Object.fromEntries(- Object.entries(derived).map(([name, value]) => [`--color-${name}`, value])- );-for (const declarations of [schemeDeclarations, darkSchemeDeclarations]) {validateReferences({declarations,@@ -331,14 +343,6 @@ export const parseColorSource = (css: string): ColorSource => {requireReference: true,});- const semanticDeclarations = Object.fromEntries(- Object.entries(semantic).flatMap(([category, values]) =>- Object.entries(values).map(([name, value]) => [- `--${category}-${name}`,- value,- ])- )- );for (const name of Object.keys(semanticDeclarations)) {validateSemanticName(name.slice(2));}diff --git a/packages/design-system/src/colors/colors.css b/packages/design-system/src/colors/colors.cssindex 66612df2f2..77556e1f02 100644--- a/packages/design-system/src/colors/colors.css+++ b/packages/design-system/src/colors/colors.css@@ -21,7 +21,7 @@/* Sets the color family used to communicate neutral information. */--theme-color-informative: #0175dc;- /* Sets content contrast: 0% is softest accessible; 100% is strongest. */+ /* Sets content contrast: 0% is softest; 100% is strongest. */--theme-contrast-content: 0%;/* Sets surface separation: 0% is subtle; 100% is strongest. */--theme-contrast-surface: 0%;@@ -34,7 +34,6 @@--scheme-foreground-soft-lightness: 0.203788;--scheme-foreground-strong-lightness: 0.1;--scheme-foreground-chroma-scale: 1;- --scheme-chromatic-luminance-min: 0;--scheme-chromatic-luminance-max: 0.18;--scheme-chromatic-foreground-mix: 100%;@@ -82,59 +81,12 @@)srgb clamp(0, r, 1) clamp(0, g, 1) clamp(0, b, 1));+ /* Cap relative luminance by scaling XYZ toward black without changing hue. */--color-accent: color(from var(--color-accent-source) xyz-d65- calc(- x *- min(- 1,- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) /- max(y, 0.000001)- ) +- (0.95047 - x) *- max(- 0,- (clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) -- y) /- max(1 - y, 0.000001)- )- )- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- )- calc(- z *- min(- 1,- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) /- max(y, 0.000001)- ) +- (1.08883 - z) *- max(- 0,- (clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) -- y) /- max(1 - y, 0.000001)- )- )+ calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))+ min(y, var(--scheme-chromatic-luminance-max))+ calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001))));--color-accent-secondary-source: color(from oklch(from var(--color-accent) l c calc(h + 55)) srgb clamp(0, r, 1)@@ -148,219 +100,27 @@);--color-positive: color(from var(--color-positive-source) xyz-d65- calc(- x *- min(- 1,- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) /- max(y, 0.000001)- ) +- (0.95047 - x) *- max(- 0,- (clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) -- y) /- max(1 - y, 0.000001)- )- )- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- )- calc(- z *- min(- 1,- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) /- max(y, 0.000001)- ) +- (1.08883 - z) *- max(- 0,- (clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) -- y) /- max(1 - y, 0.000001)- )- )+ calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))+ min(y, var(--scheme-chromatic-luminance-max))+ calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001))));--color-negative: color(from var(--color-negative-source) xyz-d65- calc(- x *- min(- 1,- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) /- max(y, 0.000001)- ) +- (0.95047 - x) *- max(- 0,- (clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) -- y) /- max(1 - y, 0.000001)- )- )- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- )- calc(- z *- min(- 1,- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) /- max(y, 0.000001)- ) +- (1.08883 - z) *- max(- 0,- (clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) -- y) /- max(1 - y, 0.000001)- )- )+ calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))+ min(y, var(--scheme-chromatic-luminance-max))+ calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001))));--color-warning: color(from var(--color-warning-source) xyz-d65- calc(- x *- min(- 1,- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) /- max(y, 0.000001)- ) +- (0.95047 - x) *- max(- 0,- (clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) -- y) /- max(1 - y, 0.000001)- )- )- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- )- calc(- z *- min(- 1,- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) /- max(y, 0.000001)- ) +- (1.08883 - z) *- max(- 0,- (clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) -- y) /- max(1 - y, 0.000001)- )- )+ calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))+ min(y, var(--scheme-chromatic-luminance-max))+ calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001))));--color-informative: color(from var(--color-informative-source) xyz-d65- calc(- x *- min(- 1,- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) /- max(y, 0.000001)- ) +- (0.95047 - x) *- max(- 0,- (clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) -- y) /- max(1 - y, 0.000001)- )- )- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- )- calc(- z *- min(- 1,- clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) /- max(y, 0.000001)- ) +- (1.08883 - z) *- max(- 0,- (clamp(- var(--scheme-chromatic-luminance-min),- y,- var(--scheme-chromatic-luminance-max)- ) -- y) /- max(1 - y, 0.000001)- )- )+ calc(x * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001)))+ min(y, var(--scheme-chromatic-luminance-max))+ calc(z * min(1, var(--scheme-chromatic-luminance-max) / max(y, 0.000001))));--color-shadow: oklch(from var(--theme-color-neutral) 0.203788 min(c, 0.02) h@@ -458,6 +218,10 @@);--background-inverse: var(--color-foreground);--background-accent: var(--color-accent);+ --background-text-selection: light-dark(+ var(--color-accent),+ oklch(from var(--color-accent) max(l, 0.72) c h)+ );--background-accent-secondary: var(--color-accent-secondary);--background-positive: var(--color-positive);--background-positive-subtle: color-mix(@@ -505,6 +269,7 @@--foreground-on-accent-secondary: var(--color-on-chromatic);--foreground-on-positive: var(--color-on-chromatic);--foreground-on-negative: var(--color-on-chromatic);+ --foreground-on-text-selection: var(--color-background);--foreground-accent: var(--color-accent-foreground);--foreground-accent-secondary: var(--color-accent-secondary-foreground);--foreground-positive: var(--color-positive-foreground);@@ -551,7 +316,6 @@--scheme-foreground-soft-lightness: 0.93;--scheme-foreground-strong-lightness: 1;--scheme-foreground-chroma-scale: 0.2;- --scheme-chromatic-luminance-min: 0;--scheme-chromatic-luminance-max: 0.18;--scheme-chromatic-foreground-mix: 35%;}diff --git a/packages/design-system/src/colors/css-variable-source-utils.test.ts b/packages/design-system/src/colors/css-variable-source-utils.test.tsdeleted file mode 100644index 0d101d762a..0000000000--- a/packages/design-system/src/colors/css-variable-source-utils.test.ts+++ /dev/null@@ -1,49 +0,0 @@-import { describe, expect, test } from "vitest";-import {- getUniqueCssVariableNames,- parseCssVariableDeclarations,-} from "./css-variable-source-utils";--describe("CSS variable declarations", () => {- test("collects literal declarations from TypeScript", () => {- expect(- parseCssVariableDeclarations({- source: "component.tsx",- code: `- const state = declareCssVar("--component-state");- const text = "declareCssVar('ignored')";- `,- })- ).toEqual([{ name: "--component-state", source: "component.tsx" }]);- });-- test("rejects declarations that cannot be statically registered", () => {- expect(() =>- parseCssVariableDeclarations({- source: "component.ts",- code: `declareCssVar(variableName)`,- })- ).toThrow("declareCssVar() requires a string literal");- });-- test("rejects duplicate and reserved declarations", () => {- expect(() =>- getUniqueCssVariableNames({- declarations: [- { name: "--component-state", source: "first.ts" },- { name: "--component-state", source: "second.ts" },- ],- reservedNames: new Set(),- })- ).toThrow("Duplicate CSS variable declaration --component-state");-- expect(() =>- getUniqueCssVariableNames({- declarations: [- { name: "--foreground-primary", source: "component.ts" },- ],- reservedNames: new Set(["--foreground-primary"]),- })- ).toThrow("conflicts with colors.css");- });-});diff --git a/packages/design-system/src/colors/css-variable-source-utils.ts b/packages/design-system/src/colors/css-variable-source-utils.tsdeleted file mode 100644index 2a9180b3b5..0000000000--- a/packages/design-system/src/colors/css-variable-source-utils.ts+++ /dev/null@@ -1,93 +0,0 @@-import { parse } from "@babel/parser";--export type CssVariableDeclaration = {- name: `--${string}`;- source: string;-};--export const parseCssVariableDeclarations = ({- code,- source,-}: {- code: string;- source: string;-}): CssVariableDeclaration[] => {- const sourceFile = parse(code, {- sourceType: "module",- plugins: ["typescript", "jsx"],- });- const declarations: CssVariableDeclaration[] = [];-- const visit = (value: unknown) => {- if (Array.isArray(value)) {- for (const item of value) {- visit(item);- }- return;- }- if (typeof value !== "object" || value === null) {- return;- }- const node = value as Record<string, unknown>;- if (- node.type === "CallExpression" &&- typeof node.callee === "object" &&- node.callee !== null &&- (node.callee as Record<string, unknown>).type === "Identifier" &&- (node.callee as Record<string, unknown>).name === "declareCssVar"- ) {- const argument = Array.isArray(node.arguments)- ? node.arguments[0]- : undefined;- if (- typeof argument !== "object" ||- argument === null ||- (argument as Record<string, unknown>).type !== "StringLiteral" ||- typeof (argument as Record<string, unknown>).value !== "string"- ) {- throw new Error(`${source}: declareCssVar() requires a string literal`);- }- const name = (argument as Record<string, unknown>).value as string;- if (name.startsWith("--") === false) {- throw new Error(`${source}: invalid CSS variable ${name}`);- }- declarations.push({- name: name as `--${string}`,- source,- });- }- for (const [key, child] of Object.entries(node)) {- if (key !== "loc" && key !== "start" && key !== "end") {- visit(child);- }- }- };-- visit(sourceFile);- return declarations;-};--export const getUniqueCssVariableNames = ({- declarations,- reservedNames,-}: {- declarations: CssVariableDeclaration[];- reservedNames: ReadonlySet<string>;-}) => {- const sources = new Map<string, string>();- for (const { name, source } of declarations) {- const existingSource = sources.get(name);- if (existingSource !== undefined) {- throw new Error(- `Duplicate CSS variable declaration ${name}: ${existingSource} and ${source}`- );- }- if (reservedNames.has(name)) {- throw new Error(- `CSS variable declaration ${name} in ${source} conflicts with colors.css`- );- }- sources.set(name, source);- }- return [...sources.keys()].sort();-};diff --git a/packages/design-system/src/colors/generate-color-types.ts b/packages/design-system/src/colors/generate-color-types.tsindex 13e0074328..372462b5d7 100644--- a/packages/design-system/src/colors/generate-color-types.ts+++ b/packages/design-system/src/colors/generate-color-types.ts@@ -1,12 +1,6 @@-import { readdir, readFile, writeFile } from "node:fs/promises";-import { relative } from "node:path";+import { readFile, writeFile } from "node:fs/promises";import { fileURLToPath } from "node:url";import { parseColorSource } from "./color-source-utils";-import {- getUniqueCssVariableNames,- parseCssVariableDeclarations,- type CssVariableDeclaration,-} from "./css-variable-source-utils";const sourceUrl = new URL("./colors.css", import.meta.url);const outputUrl = new URL(@@ -15,52 +9,6 @@ const outputUrl = new URL();const source = parseColorSource(await readFile(sourceUrl, "utf8"));-const repositoryUrl = new URL("../../../../", import.meta.url);--const ignoredDirectories = new Set([- ".git",- "__generated__",- "dist",- "lib",- "node_modules",-]);-const isSourceFile = (name: string) =>- (name.endsWith(".ts") || name.endsWith(".tsx")) &&- name.endsWith(".d.ts") === false &&- name.includes(".test.") === false &&- name.includes(".stories.") === false;--const collectDeclarations = async (- directoryUrl: URL-): Promise<CssVariableDeclaration[]> => {- const declarations: CssVariableDeclaration[] = [];- for (const entry of await readdir(directoryUrl, { withFileTypes: true })) {- if (entry.isDirectory()) {- if (ignoredDirectories.has(entry.name)) {- continue;- }- declarations.push(- ...(await collectDeclarations(new URL(`${entry.name}/`, directoryUrl)))- );- continue;- }- if (entry.isFile() === false || isSourceFile(entry.name) === false) {- continue;- }- const fileUrl = new URL(entry.name, directoryUrl);- const fileName = relative(- fileURLToPath(repositoryUrl),- fileURLToPath(fileUrl)- );- declarations.push(- ...parseCssVariableDeclarations({- code: await readFile(fileUrl, "utf8"),- source: fileName,- })- );- }- return declarations;-};const themeNames = [...Object.keys(source.theme.color).map((name) => `--theme-color-${name}`),@@ -68,30 +16,13 @@ const themeNames = [(name) => `--theme-contrast-${name}`),];-const names = Object.entries(source.semantic).flatMap(([category, colors]) =>- Object.keys(colors).map((name) => `--${category}-${name}`)+const semanticNames = Object.entries(source.semantic).flatMap(+ ([category, colors]) =>+ Object.keys(colors).map((name) => `--${category}-${name}`));-const colorDeclarationNames = new Set([- ...themeNames,- ...Object.keys(source.scheme.light).map((name) => `--scheme-${name}`),- ...Object.keys(source.derived).map((name) => `--color-${name}`),- ...names,-]);-const declarations = (- await Promise.all(- ["apps/", "packages/"].map((directory) =>- collectDeclarations(new URL(directory, repositoryUrl))- )- )-).flat();-const componentNames = getUniqueCssVariableNames({- declarations,- reservedNames: colorDeclarationNames,-});-const cssVariableNames = [...names, ...componentNames];-const generated = `// Generated by generate-color-types.ts from colors.css and declareCssVar() calls. Do not edit directly.\n\nexport type ThemeVariableName =\n${themeNames+const generated = `// Generated by generate-color-types.ts from colors.css. Do not edit directly.\n\nexport type ThemeVariableName =\n${themeNames.map((name) => ` | ${JSON.stringify(name)}`)- .join("\n")};\n\nexport type CssVariableName =\n${cssVariableNames+ .join("\n")};\n\nexport type SemanticColorName =\n${semanticNames.map((name) => ` | ${JSON.stringify(name)}`).join("\n")};\n`;diff --git a/packages/design-system/src/components/button.tsx b/packages/design-system/src/components/button.tsxindex d08eb59c7c..1554aec040 100644--- a/packages/design-system/src/components/button.tsx+++ b/packages/design-system/src/components/button.tsx@@ -14,7 +14,7 @@ import { css, styled, theme, type CSS } from "../stitches.config";import { LoadingDotsIcon } from "@webstudio-is/icons";import { Flex } from "./flex";import { cssVar } from "../css-var";-import { withInteractionOverlay } from "./control-state-color";+import { withInteractionOverlay } from "./component-state-color";const colors = ["primary",diff --git a/packages/design-system/src/components/command.tsx b/packages/design-system/src/components/command.tsxindex 41e246f07a..d6c6275f1c 100644--- a/packages/design-system/src/components/command.tsx+++ b/packages/design-system/src/components/command.tsx@@ -35,7 +35,7 @@ import { Flex } from "./flex";import { InputField } from "./input-field";import { SmallIconButton } from "./small-icon-button";import { cssVar, declareCssVar } from "../css-var";-import { selectionBackground } from "./selection-color";+import { selectedItemBackground } from "./component-state-color";const panelWidth = "500px";const itemHeight = "32px";@@ -529,7 +529,7 @@ const CommandItemStyled = styled(CommandPrimitive.Item, {backgroundColor: cssVar("--overlay-interaction-hover"),},"&[aria-selected=true]": {- backgroundColor: selectionBackground,+ backgroundColor: selectedItemBackground,},});diff --git a/packages/design-system/src/components/control-state-color.ts b/packages/design-system/src/components/component-state-color.tssimilarity index 77%rename from packages/design-system/src/components/control-state-color.tsrename to packages/design-system/src/components/component-state-color.tsindex ca8be41ed3..c3ef561fa4 100644--- a/packages/design-system/src/components/control-state-color.ts+++ b/packages/design-system/src/components/component-state-color.ts@@ -1,5 +1,14 @@import { cssVar } from "../css-var";+export const selectedItemBackground = `light-dark(+ color-mix(in oklab, ${cssVar("--background-accent")} 12%, ${cssVar(+ "--background-primary"+ )}),+ color-mix(in oklab, ${cssVar("--background-accent")} 20%, ${cssVar(+ "--background-primary"+ )})+)`;+// Selected controls need more separation in dark mode, while remaining neutral.// This is a component-state composition, not a theme parameter.export const selectedControlBackground = `light-dark(diff --git a/packages/design-system/src/components/icon-button.tsx b/packages/design-system/src/components/icon-button.tsxindex a47eda85ee..e857648c02 100644--- a/packages/design-system/src/components/icon-button.tsx+++ b/packages/design-system/src/components/icon-button.tsx@@ -13,7 +13,7 @@ import {selectedControlHoverBackground,selectedControlPressedBackground,withInteractionOverlay,-} from "./control-state-color";+} from "./component-state-color";const openOrHoverStateStyle = {backgroundColor: cssVar("--overlay-interaction-hover"),diff --git a/packages/design-system/src/components/primitives/small-button.tsx b/packages/design-system/src/components/primitives/small-button.tsxindex 7ab2bea0a5..152113aabb 100644--- a/packages/design-system/src/components/primitives/small-button.tsx+++ b/packages/design-system/src/components/primitives/small-button.tsx@@ -9,7 +9,7 @@ import { cssVar } from "../../css-var";import {selectedControlBackground,withInteractionOverlay,-} from "../control-state-color";+} from "../component-state-color";export const smallButtonVariants = ["normal",diff --git a/packages/design-system/src/components/selection-color.ts b/packages/design-system/src/components/selection-color.tsdeleted file mode 100644index 391c6fa072..0000000000--- a/packages/design-system/src/components/selection-color.ts+++ /dev/null@@ -1,10 +0,0 @@-import { cssVar } from "../css-var";--export const selectionBackground = `light-dark(- color-mix(in oklab, ${cssVar("--background-accent")} 12%, ${cssVar(- "--background-primary"- )}),- color-mix(in oklab, ${cssVar("--background-accent")} 20%, ${cssVar(- "--background-primary"- )})-)`;diff --git a/packages/design-system/src/components/text-selection.browser.test.ts b/packages/design-system/src/components/text-selection.browser.test.tsnew file mode 100644index 0000000000..66bce0c8ee--- /dev/null+++ b/packages/design-system/src/components/text-selection.browser.test.ts@@ -0,0 +1,81 @@+import { afterEach, expect, test } from "vitest";+import { cssVar } from "../css-var";+import { rawTheme } from "../stitches.config";+import "../global.css";+import { selectedItemBackground } from "./component-state-color";++const root = document.documentElement;+const previousMode = root.getAttribute("data-color-scheme");++afterEach(() => {+ if (previousMode === null) {+ root.removeAttribute("data-color-scheme");+ } else {+ root.setAttribute("data-color-scheme", previousMode);+ }+ document.body.replaceChildren();+});++test.each(["light", "dark"] as const)(+ "applies the shared document defaults in %s mode",+ (mode) => {+ root.dataset.colorScheme = mode;+ const reference = document.createElement("span");+ reference.style.color = cssVar("--foreground-primary");+ reference.style.fontFamily = rawTheme.fonts.sans;+ document.body.append(reference);++ const bodyStyle = getComputedStyle(document.body);+ const referenceStyle = getComputedStyle(reference);+ expect(bodyStyle.margin).toBe("0px");+ expect(bodyStyle.color).toBe(referenceStyle.color);+ expect(bodyStyle.fontFamily).toBe(referenceStyle.fontFamily);+ }+);++test.each(["light", "dark"] as const)(+ "uses the shared text selection colors for native editors in %s mode",+ (mode) => {+ root.dataset.colorScheme = mode;+ const reference = document.createElement("span");+ reference.style.backgroundColor = cssVar("--background-text-selection");+ reference.style.color = "var(--foreground-on-text-selection)";+ document.body.append(reference);+ const expectedBackground = getComputedStyle(reference).backgroundColor;+ const expectedForeground = getComputedStyle(reference).color;++ for (const editor of [+ document.createElement("input"),+ document.createElement("textarea"),+ document.createElement("div"),+ ]) {+ editor.contentEditable = "true";+ document.body.append(editor);++ expect(+ getComputedStyle(editor, "::selection").backgroundColor,+ editor.tagName.toLowerCase()+ ).toBe(expectedBackground);+ expect(+ getComputedStyle(editor, "::selection").color,+ editor.tagName.toLowerCase()+ ).toBe(expectedForeground);+ }+ }+);++test.each(["light", "dark"] as const)(+ "keeps selected item backgrounds separate from text selection in %s mode",+ (mode) => {+ root.dataset.colorScheme = mode;+ const selectedItem = document.createElement("span");+ selectedItem.style.background = selectedItemBackground;+ const textSelection = document.createElement("span");+ textSelection.style.background = cssVar("--background-text-selection");+ document.body.append(selectedItem, textSelection);++ expect(getComputedStyle(selectedItem).backgroundColor).not.toBe(+ getComputedStyle(textSelection).backgroundColor+ );+ }+);diff --git a/packages/design-system/src/components/tree.tsx b/packages/design-system/src/components/tree.tsxindex c736f4d695..090e69d910 100644--- a/packages/design-system/src/components/tree.tsx+++ b/packages/design-system/src/components/tree.tsx@@ -30,7 +30,7 @@ import { Box } from "./box";import { Text } from "./text";import { TreePositionIndicator } from "./list-position-indicator";import { cssVar, declareCssVar } from "../css-var";-import { selectionBackground } from "./selection-color";+import { selectedItemBackground } from "./component-state-color";const treeNodeLevel = declareCssVar("--tree-node-level");const treeNodeOutline = declareCssVar("--tree-node-outline");@@ -40,6 +40,7 @@ const treeNodeSelectionBackgroundColor = declareCssVar(const treeNodeBackgroundColor = declareCssVar("--tree-node-background-color");const treeActionOpacity = declareCssVar("--tree-action-opacity");const treeActionWidth = declareCssVar("--tree-action-width");+export const treeActionBoundary = declareCssVar("--tree-action-boundary");const TreeFocusRestoreContext = createContext<| undefined@@ -148,12 +149,12 @@ const NodeContainer = styled("div", {[treeActionOpacity]: 1,},'&[data-selection-state="selected-descendant"]': {- [treeNodeSelectionBackgroundColor]: `color-mix(in oklab, ${selectionBackground} 50%, ${cssVar(+ [treeNodeSelectionBackgroundColor]: `color-mix(in oklab, ${selectedItemBackground} 50%, ${cssVar("--background-primary")})`,},'&[data-selection-state="selected"]': {- [treeNodeSelectionBackgroundColor]: selectionBackground,+ [treeNodeSelectionBackgroundColor]: selectedItemBackground,},});@@ -196,9 +197,7 @@ const ActionContainer = styled("div", {opacity: cssVar(treeActionOpacity, "0"),position: "sticky",translate: `-100% -100%`,- left: `calc(${cssVar(- "--sidebar-left-panel-width"- )} - ${ITEM_PADDING_RIGHT}px)`,+ left: `calc(${cssVar(treeActionBoundary)} - ${ITEM_PADDING_RIGHT}px)`,height: "inherit",display: "inline-flex",justifyContent: "center",diff --git a/packages/design-system/src/css-var.test.ts b/packages/design-system/src/css-var.test.tsindex 15c462b995..0c62ee9e1f 100644--- a/packages/design-system/src/css-var.test.ts+++ b/packages/design-system/src/css-var.test.ts@@ -3,14 +3,18 @@ import { cssVar, declareCssVar } from "./css-var";const verifyPublicVariableType = () => {cssVar("--foreground-primary");- declareCssVar("--select-button-chevron-color");- cssVar("--select-button-chevron-color");+ const componentState = declareCssVar("--component-state");+ cssVar(componentState);// @ts-expect-error Authoring inputs are not public component variables.cssVar("--theme-color-accent");- // @ts-expect-error Component variables must be explicitly declared.+ // @ts-expect-error Private variables must be passed through declareCssVar().cssVar("--component-state");+ // @ts-expect-error Private variables are local, not generator-registered globals.+ cssVar("--select-button-chevron-color");// @ts-expect-error CSS variable declarations must use custom property syntax.declareCssVar("component-state");+ // @ts-expect-error Color-system namespaces are reserved for colors.css.+ declareCssVar("--foreground-component-state");};void verifyPublicVariableType;@@ -25,12 +29,10 @@ describe("cssVar", () => {).toBe("var(--foreground-primary, var(--foreground-secondary))");});- test("accepts globally declared component variables", () => {- expect(cssVar("--select-button-chevron-color")).toBe(- "var(--select-button-chevron-color)"- );- expect(cssVar("--select-button-chevron-color", "none")).toBe(- "var(--select-button-chevron-color, none)"- );+ test("accepts locally declared private variables", () => {+ const componentState = declareCssVar("--component-state");++ expect(cssVar(componentState)).toBe("var(--component-state)");+ expect(cssVar(componentState, "none")).toBe("var(--component-state, none)");});});diff --git a/packages/design-system/src/css-var.ts b/packages/design-system/src/css-var.tsindex bed26f0321..346c7fcdb5 100644--- a/packages/design-system/src/css-var.ts+++ b/packages/design-system/src/css-var.ts@@ -1,7 +1,25 @@-import type { CssVariableName } from "./colors/__generated__/css-variable-names";+import type { SemanticColorName } from "./colors/__generated__/css-variable-names";-export const declareCssVar = <const Name extends `--${string}`>(name: Name) =>- name;+declare const declaredCssVariableNameBrand: unique symbol;-export const cssVar = (name: CssVariableName, fallback?: string) =>- fallback === undefined ? `var(${name})` : `var(${name}, ${fallback})`;+export type DeclaredCssVariableName = `--${string}` & {+ readonly [declaredCssVariableNameBrand]: true;+};++type ColorVariableName =+ | `--theme-${string}`+ | `--scheme-${string}`+ | `--color-${string}`+ | `--background-${string}`+ | `--foreground-${string}`+ | `--border-${string}`+ | `--overlay-${string}`;++export const declareCssVar = <const Name extends `--${string}`>(+ name: Name & (Name extends ColorVariableName ? never : unknown)+) => name as unknown as Name & DeclaredCssVariableName;++export const cssVar = (+ name: SemanticColorName | DeclaredCssVariableName,+ fallback?: string+) => (fallback === undefined ? `var(${name})` : `var(${name}, ${fallback})`);diff --git a/packages/design-system/src/global.css b/packages/design-system/src/global.cssnew file mode 100644index 0000000000..bf9812dd01--- /dev/null+++ b/packages/design-system/src/global.css@@ -0,0 +1,35 @@+/*+ * Single public stylesheet for document-wide design-system prerequisites.+ *+ * Include a style here only when every full design-system UI requires it and+ * it cannot be scoped to a component: font faces, root theme tokens, base+ * document defaults, and shared browser-native treatments. Add small rules+ * directly; import a separate source only when it owns a substantial global+ * subsystem such as colors.+ *+ * Keep component styles with their component. Route layout, scroll locking,+ * feature presets, and third-party overrides remain with the application.+ * This file is intentionally not loaded in the Builder canvas because it+ * hosts authored user documents. Keep every @import before the style rules.+ */++/* Font faces required by the design-system typography variants. */+@import "@fontsource-variable/inter/index.css";+@import "@fontsource-variable/manrope/index.css";+@import "@fontsource/roboto-mono/index.css";++/* Root theme inputs, derivations, and semantic color tokens. */+@import "./colors/colors.css";++/* Base document defaults shared by Builder, dashboard, auth, and Storybook. */+body {+ margin: 0;+ color: var(--foreground-primary);+ font-family: var(--fonts-sans);+}++/* Native text selection across inputs, textareas, and editable content. */+::selection {+ background-color: var(--background-text-selection);+ color: var(--foreground-on-text-selection);+}diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.tsindex ec36cc229d..3d35614493 100644--- a/packages/design-system/src/index.ts+++ b/packages/design-system/src/index.ts@@ -3,7 +3,7 @@ export { cssVar, declareCssVar } from "./css-var";export type { ThemeVariableName } from "./colors/__generated__/css-variable-names";export { rotateBoundedBackgroundHue } from "./color-utils";export { webstudioBrand } from "./brand";-export { selectionBackground } from "./components/selection-color";+export { selectedItemBackground } from "./components/component-state-color";export { chromeControlStyle } from "./components/chrome-control-style";export * from "./components/storybook";export * from "./utilities";diff --git a/packages/design-system/src/utilities.ts b/packages/design-system/src/utilities.tsindex 08e92a1b27..49af28a3e9 100644--- a/packages/design-system/src/utilities.ts+++ b/packages/design-system/src/utilities.ts@@ -3,7 +3,7 @@ import warnOnce from "warn-once";import type { CSS } from "./stitches.config";import { declareCssVar } from "./css-var";-const canvasPointerEventsPropertyName = declareCssVar(+export const canvasPointerEventsPropertyName = declareCssVar("--canvas-pointer-events");diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 75c442b272..a5d7927cfc 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -28,15 +28,6 @@ importers:.:devDependencies:- '@fontsource-variable/inter':- specifier: ^5.0.20- version: 5.0.20- '@fontsource-variable/manrope':- specifier: ^5.0.20- version: 5.0.20- '@fontsource/roboto-mono':- specifier: ^5.0.18- version: 5.0.18'@modelcontextprotocol/sdk':specifier: ^1.10.0version: 1.29.0([email protected])@@ -166,15 +157,6 @@ importers:'@floating-ui/dom':specifier: ^1.6.13version: 1.6.13- '@fontsource-variable/inter':- specifier: ^5.0.20- version: 5.0.20- '@fontsource-variable/manrope':- specifier: ^5.0.20- version: 5.0.20- '@fontsource/roboto-mono':- specifier: ^5.0.18- version: 5.0.18'@lexical/headless':specifier: ^0.21.0version: 0.21.0@@ -1217,6 +1199,9 @@ importers:specifier: ^0.1.1version: 0.1.1devDependencies:+ '@fontsource-variable/inter':+ specifier: ^5.0.20+ version: 5.0.20'@types/fontkit':specifier: ^2.0.8version: 2.0.8@@ -1739,6 +1724,15 @@ importers:'@floating-ui/dom':specifier: ^1.6.13version: 1.6.13+ '@fontsource-variable/inter':+ specifier: ^5.0.20+ version: 5.0.20+ '@fontsource-variable/manrope':+ specifier: ^5.0.20+ version: 5.0.20+ '@fontsource/roboto-mono':+ specifier: ^5.0.18+ version: 5.0.18'@radix-ui/colors':specifier: ^3.0.0version: 3.0.0@@ -1866,9 +1860,6 @@ importers:specifier: ^0.1.1version: 0.1.1devDependencies:- '@babel/parser':- specifier: ^7.29.7- version: 7.29.7'@types/react':specifier: ^18.2.70version: 18.2.79