Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Paste HTML with CSS with full selectors and regular syntax support (#5648)
Oleg Isonen1784d635c075
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex dae1a47f50..e36ac09430 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -1,4 +1,5 @@import { toast } from "@webstudio-is/design-system";+import type { WebstudioFragment } from "@webstudio-is/sdk";import {isAutoGridPlacement,resetGridChildPlacement,@@ -456,10 +457,18 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({description: "Convert Tailwind to CSS",handler: async () => {const html = await navigator.clipboard.readText();- let fragment = generateFragmentFromHtml(html);+ const parseResult = generateFragmentFromHtml(html);+ const { skippedSelectors } = parseResult;+ let fragment: WebstudioFragment = parseResult;fragment = await denormalizeSrcProps(fragment);fragment = await generateFragmentFromTailwind(fragment);- return insertWebstudioFragmentAt(fragment);+ const result = insertWebstudioFragmentAt(fragment);+ if (skippedSelectors.length > 0) {+ builderApi.toast.info(+ `Skipped nested selectors (no matching elements): ${skippedSelectors.join(", ")}`+ );+ }+ return result;},},diff --git a/apps/builder/app/shared/copy-paste/plugin-html.ts b/apps/builder/app/shared/copy-paste/plugin-html.tsindex 5f8e77768a..4ea856da36 100644--- a/apps/builder/app/shared/copy-paste/plugin-html.ts+++ b/apps/builder/app/shared/copy-paste/plugin-html.ts@@ -1,8 +1,10 @@+import type { WebstudioFragment } from "@webstudio-is/sdk";import { generateFragmentFromHtml } from "../html";import { insertWebstudioFragmentAt } from "../instance-utils";import { generateFragmentFromTailwind } from "../tailwind/tailwind";import { denormalizeSrcProps } from "./asset-upload";import type { Plugin } from "./init-copy-paste";+import { builderApi } from "../builder-api";const inceptionMark = `<!-- @webstudio/inception/1 -->`;@@ -10,12 +12,19 @@ export const html: Plugin = {name: "html",mimeType: "text/plain",onPaste: async (html: string) => {- let fragment = generateFragmentFromHtml(html);+ const parseResult = generateFragmentFromHtml(html);+ const { skippedSelectors } = parseResult;+ let fragment: WebstudioFragment = parseResult;fragment = await denormalizeSrcProps(fragment);if (html.includes(inceptionMark)) {fragment = await generateFragmentFromTailwind(fragment);}const result = insertWebstudioFragmentAt(fragment);+ if (skippedSelectors.length > 0) {+ builderApi.toast.info(+ `Skipped nested selectors (no matching elements): ${skippedSelectors.join(", ")}`+ );+ }return result;},};diff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.ts b/apps/builder/app/shared/copy-paste/plugin-markdown.tsindex b915a02911..69301e46a5 100644--- a/apps/builder/app/shared/copy-paste/plugin-markdown.ts+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.ts@@ -10,7 +10,8 @@ const parse = (clipboardData: string) => {extensions: [gfm()],htmlExtensions: [gfmHtml()],});- const fragment = generateFragmentFromHtml(html);+ const { skippedSelectors: _skipped, ...fragment } =+ generateFragmentFromHtml(html);const instances = new Map(fragment.instances.map((item) => [item.id, item]));for (const instance of fragment.instances) {if (instance.tag === "img") {diff --git a/apps/builder/app/shared/html.test.tsx b/apps/builder/app/shared/html.test.tsxindex 9c901b9fb7..59a49dcd4f 100644--- a/apps/builder/app/shared/html.test.tsx+++ b/apps/builder/app/shared/html.test.tsx@@ -1,6 +1,13 @@-import { expect, test } from "vitest";-import { $, css, renderTemplate, ws } from "@webstudio-is/template";-import { generateFragmentFromHtml } from "./html";+import { expect, test, describe } from "vitest";+import { $, css, renderTemplate, token, ws } from "@webstudio-is/template";+import { generateFragmentFromHtml as _generateFragmentFromHtml } from "./html";++// Wrapper that strips skippedSelectors for tests that only compare fragment shape+const generateFragmentFromHtml = (html: string) => {+ const { skippedSelectors: _skipped, ...fragment } =+ _generateFragmentFromHtml(html);+ return fragment;+};test("generate instances from html", () => {expect(@@ -340,3 +347,2605 @@ test("strip unsupported attribute names", () => {));});++describe("style tag to tokens", () => {+ test("extract single class from style tag as token", () => {+ const cardToken = token(+ "card",+ css`+ display: flex;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.card { display: flex; }</style>+ <div class="card">Hello</div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" ws:tokens={[cardToken]}>+ Hello+ </ws.element>+ )+ );+ });++ test("extract multiple classes from style tag as tokens", () => {+ const cardToken = token(+ "card",+ css`+ display: flex;+ padding: 16px;+ `+ );+ const titleToken = token(+ "title",+ css`+ font-size: 24px;+ font-weight: bold;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>+ .card { display: flex; padding: 16px; }+ .title { font-size: 24px; font-weight: bold; }+ </style>+ <div class="card">+ <h1 class="title">Hello</h1>+ </div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" ws:tokens={[cardToken]}>+ <ws.element ws:tag="h1" ws:tokens={[titleToken]}>+ Hello+ </ws.element>+ </ws.element>+ )+ );+ });++ test("reuse same token when class appears on multiple elements", () => {+ const cardToken = token(+ "card",+ css`+ display: flex;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.card { display: flex; }</style>+ <div class="card">+ <section class="card">Hello</section>+ </div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" ws:tokens={[cardToken]}>+ <ws.element ws:tag="section" ws:tokens={[cardToken]}>+ Hello+ </ws.element>+ </ws.element>+ )+ );+ });++ test("preserve unresolved class names as class prop", () => {+ const cardToken = token(+ "card",+ css`+ display: flex;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.card { display: flex; }</style>+ <div class="card external-lib">Hello</div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" class="external-lib" ws:tokens={[cardToken]}>+ Hello+ </ws.element>+ )+ );+ });++ test("remove class prop entirely when all classes resolved to tokens", () => {+ const fragment = generateFragmentFromHtml(`+ <style>.card { display: flex; }</style>+ <div class="card">Hello</div>+ `);+ expect(fragment.props.find((p) => p.name === "class")).toBeUndefined();+ });++ test("combine inline style attribute with class token", () => {+ const cardToken = token(+ "card",+ css`+ display: flex;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.card { display: flex; }</style>+ <div class="card" style="color: red">Hello</div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element+ ws:tag="div"+ ws:style={css`+ color: red;+ `}+ ws:tokens={[cardToken]}+ >+ Hello+ </ws.element>+ )+ );+ });++ test("no html embed when all style rules are class rules", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ .title { font-size: 24px; }+ </style>+ <div class="card">+ <h1 class="title">Hello</h1>+ </div>+ `);+ expect(fragment.instances.some((i) => i.component === "HtmlEmbed")).toBe(+ false+ );+ });++ test("keep style tag as html embed when it has no class rules", () => {+ expect(+ generateFragmentFromHtml(`+ <style>#hero { color: red; }</style>+ <div>Hello</div>+ `)+ ).toEqual(+ renderTemplate(+ <>+ <$.HtmlEmbed+ ws:label="Style"+ code={`<style>#hero { color: red; }</style>`}+ />+ <ws.element ws:tag="div">Hello</ws.element>+ </>+ )+ );+ });++ test("extract class rules and keep remaining rules as html embed", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ #hero { color: red; }+ </style>+ <div class="card">Hello</div>+ `);+ // token for .card should be created+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(tokenSource).toBeDefined();+ // remaining #hero rule should stay as HtmlEmbed+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ const codeProp = fragment.props.find(+ (p) => p.instanceId === htmlEmbed!.id && p.name === "code"+ );+ expect(codeProp).toBeDefined();+ expect(codeProp!.type === "string" && codeProp!.value).toContain("#hero");+ // class prop should not be set since .card was resolved+ expect(fragment.props.find((p) => p.name === "class")).toBeUndefined();+ });++ test("extract classes from multiple style tags", () => {+ const cardToken = token(+ "card",+ css`+ display: flex;+ `+ );+ const titleToken = token(+ "title",+ css`+ font-size: 24px;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.card { display: flex; }</style>+ <style>.title { font-size: 24px; }</style>+ <div class="card">+ <h1 class="title">Hello</h1>+ </div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" ws:tokens={[cardToken]}>+ <ws.element ws:tag="h1" ws:tokens={[titleToken]}>+ Hello+ </ws.element>+ </ws.element>+ )+ );+ });++ test("resolve nested selectors - descendant", () => {+ const cardInnerToken = token(+ "card__inner",+ css`+ color: red;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.card .inner { color: red; }</style>+ <div class="card">+ <span class="inner">Hello</span>+ </div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" class="card">+ <ws.element ws:tag="span" ws:tokens={[cardInnerToken]}>+ Hello+ </ws.element>+ </ws.element>+ )+ );+ });++ test("resolve nested selectors - child combinator", () => {+ const parentChildToken = token(+ "parent__child",+ css`+ margin: 0;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.parent > .child { margin: 0; }</style>+ <div class="parent"><span class="child">Hello</span></div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" class="parent">+ <ws.element ws:tag="span" ws:tokens={[parentChildToken]}>+ Hello+ </ws.element>+ </ws.element>+ )+ );+ });++ test("ignore element selectors in style tag", () => {+ // element selectors like `div { }` should not become tokens+ expect(+ generateFragmentFromHtml(`+ <style>div { color: red; }</style>+ <div>Hello</div>+ `)+ ).toEqual(+ renderTemplate(+ <>+ <$.HtmlEmbed+ ws:label="Style"+ code={`<style>div { color: red; }</style>`}+ />+ <ws.element ws:tag="div">Hello</ws.element>+ </>+ )+ );+ });++ test("handle multiple classes on one element with multiple tokens", () => {+ const cardToken = token(+ "card",+ css`+ display: flex;+ `+ );+ const largeToken = token(+ "large",+ css`+ font-size: 32px;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ .large { font-size: 32px; }+ </style>+ <div class="card large">Hello</div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" ws:tokens={[cardToken, largeToken]}>+ Hello+ </ws.element>+ )+ );+ });++ test("handle class with multiple properties", () => {+ const cardToken = token(+ "card",+ css`+ display: flex;+ gap: 16px;+ padding: 24px;+ border-radius: 8px;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>+ .card {+ display: flex;+ gap: 16px;+ padding: 24px;+ border-radius: 8px;+ }+ </style>+ <div class="card">Hello</div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" ws:tokens={[cardToken]}>+ Hello+ </ws.element>+ )+ );+ });++ test("empty style tag produces no html embed", () => {+ expect(+ generateFragmentFromHtml(`+ <style></style>+ <div>Hello</div>+ `)+ ).toEqual(renderTemplate(<ws.element ws:tag="div">Hello</ws.element>));+ });++ test("class attribute without any style tag stays as prop", () => {+ // existing behavior: class is just a prop when no style tag is present+ expect(+ generateFragmentFromHtml(`+ <div class="my-class">Hello</div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" class="my-class">+ Hello+ </ws.element>+ )+ );+ });++ test("style tag with only whitespace produces no html embed", () => {+ expect(+ generateFragmentFromHtml(`+ <style> </style>+ <div>Hello</div>+ `)+ ).toEqual(renderTemplate(<ws.element ws:tag="div">Hello</ws.element>));+ });++ test("extract token and apply to nested structure", () => {+ const wrapperToken = token(+ "wrapper",+ css`+ max-width: 1200px;+ margin-left: auto;+ margin-right: auto;+ `+ );+ const gridToken = token(+ "grid",+ css`+ display: grid;+ gap: 16px;+ `+ );+ const itemToken = token(+ "item",+ css`+ padding: 8px;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>+ .wrapper { max-width: 1200px; margin-left: auto; margin-right: auto; }+ .grid { display: grid; gap: 16px; }+ .item { padding: 8px; }+ </style>+ <div class="wrapper">+ <div class="grid">+ <div class="item">One</div>+ <div class="item">Two</div>+ <div class="item">Three</div>+ </div>+ </div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" ws:tokens={[wrapperToken]}>+ <ws.element ws:tag="div" ws:tokens={[gridToken]}>+ <ws.element ws:tag="div" ws:tokens={[itemToken]}>+ One+ </ws.element>+ <ws.element ws:tag="div" ws:tokens={[itemToken]}>+ Two+ </ws.element>+ <ws.element ws:tag="div" ws:tokens={[itemToken]}>+ Three+ </ws.element>+ </ws.element>+ </ws.element>+ )+ );+ });++ test("element with both resolved and unresolved classes plus inline style", () => {+ const cardToken = token(+ "card",+ css`+ display: flex;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.card { display: flex; }</style>+ <div class="card external" style="color: red">Hello</div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element+ ws:tag="div"+ class="external"+ ws:style={css`+ color: red;+ `}+ ws:tokens={[cardToken]}+ >+ Hello+ </ws.element>+ )+ );+ });++ test("token names preserve original class names", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .my-component { display: flex; }+ .text-lg { font-size: 18px; }+ .bg_primary { background-color: blue; }+ </style>+ <div class="my-component">+ <span class="text-lg bg_primary">Hello</span>+ </div>+ `);+ const tokenNames = fragment.styleSources+ .filter((s) => s.type === "token")+ .map((s) => (s as { name: string }).name);+ expect(tokenNames).toContain("my-component");+ expect(tokenNames).toContain("text-lg");+ expect(tokenNames).toContain("bg_primary");+ });++ test("class defined in style tag but not used by any element", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .used { display: flex; }+ .unused { color: red; }+ </style>+ <div class="used">Hello</div>+ `);+ // all class rules become tokens, even if not referenced by elements+ const tokenNames = fragment.styleSources+ .filter((s) => s.type === "token")+ .map((s) => (s as { name: string }).name);+ expect(tokenNames).toContain("used");+ expect(tokenNames).toContain("unused");+ // only "used" is assigned to the instance+ const divInstance = fragment.instances.find((i) => i.tag === "div");+ const sel = fragment.styleSourceSelections.find(+ (s) => s.instanceId === divInstance?.id+ );+ const usedToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "used"+ );+ const unusedToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "unused"+ );+ expect(sel?.values).toContain(usedToken?.id);+ expect(sel?.values).not.toContain(unusedToken?.id);+ // no HtmlEmbed since all rules are class rules+ expect(fragment.instances.some((i) => i.component === "HtmlEmbed")).toBe(+ false+ );+ });++ test("duplicate class rules across multiple style tags are merged", () => {+ const fragment = generateFragmentFromHtml(`+ <style>.card { display: flex; }</style>+ <style>.card { padding: 16px; }</style>+ <div class="card">Hello</div>+ `);+ // should create a single token with both properties+ const tokens = fragment.styleSources.filter((s) => s.type === "token");+ expect(tokens).toHaveLength(1);+ const tokenId = tokens[0].id;+ const tokenStyles = fragment.styles.filter(+ (s) => s.styleSourceId === tokenId+ );+ const properties = tokenStyles.map((s) => s.property);+ expect(properties).toContain("display");+ expect(properties).toContain("paddingTop");+ });++ test("script tag still becomes html embed alongside token extraction", () => {+ const cardToken = token(+ "card",+ css`+ display: flex;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.card { display: flex; }</style>+ <script>console.log("hi");</script>+ <div class="card">Hello</div>+ `)+ ).toEqual(+ renderTemplate(+ <>+ <$.HtmlEmbed+ ws:label="Script"+ clientOnly={true}+ code={`<script>console.log("hi");</script>`}+ />+ <ws.element ws:tag="div" ws:tokens={[cardToken]}>+ Hello+ </ws.element>+ </>+ )+ );+ });++ test("style tag with pseudo-class creates token with state", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .btn { background-color: blue; }+ .btn:hover { background-color: darkblue; }+ </style>+ <button class="btn">Click me</button>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "btn"+ );+ expect(tokenSource).toBeDefined();+ // base style+ const baseStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "backgroundColor" &&+ s.state === undefined+ );+ expect(baseStyle).toBeDefined();+ // hover state style+ const hoverStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "backgroundColor" &&+ s.state === ":hover"+ );+ expect(hoverStyle).toBeDefined();+ });++ test("style tag with media query creates token with breakpoint styles", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .container { padding: 8px; }+ @media (min-width: 768px) {+ .container { padding: 16px; }+ }+ </style>+ <div class="container">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "container"+ );+ expect(tokenSource).toBeDefined();+ // should have styles on different breakpoints+ const tokenStyles = fragment.styles.filter(+ (s) => s.styleSourceId === tokenSource!.id+ );+ const breakpointIds = new Set(tokenStyles.map((s) => s.breakpointId));+ // should have at least 2 different breakpoints (base + media query)+ expect(breakpointIds.size).toBeGreaterThanOrEqual(2);+ });++ test("handle real-world html snippet with style tag", () => {+ const heroToken = token(+ "hero",+ css`+ display: flex;+ flex-direction: column;+ align-items: center;+ padding: 64px;+ `+ );+ const heroTitleToken = token(+ "hero-title",+ css`+ font-size: 48px;+ font-weight: bold;+ line-height: 1.2;+ `+ );+ const heroTextToken = token(+ "hero-text",+ css`+ font-size: 18px;+ color: gray;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>+ .hero {+ display: flex;+ flex-direction: column;+ align-items: center;+ padding: 64px;+ }+ .hero-title {+ font-size: 48px;+ font-weight: bold;+ line-height: 1.2;+ }+ .hero-text {+ font-size: 18px;+ color: gray;+ }+ </style>+ <section class="hero">+ <h1 class="hero-title">Welcome</h1>+ <p class="hero-text">Build something amazing</p>+ </section>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="section" ws:tokens={[heroToken]}>+ <ws.element ws:tag="h1" ws:tokens={[heroTitleToken]}>+ Welcome+ </ws.element>+ <ws.element ws:tag="p" ws:tokens={[heroTextToken]}>+ Build something amazing+ </ws.element>+ </ws.element>+ )+ );+ });++ test("create tokens from style-only paste without HTML elements", () => {+ const result = generateFragmentFromHtml(`+ <style>.card { display: flex; padding: 16px; }</style>+ `);+ expect(result.children).toEqual([]);+ expect(result.instances).toEqual([]);+ expect(result.styleSources).toEqual([+ { type: "token", id: expect.any(String), name: "card" },+ ]);+ expect(result.styles).toEqual([+ {+ styleSourceId: result.styleSources[0].id,+ breakpointId: expect.any(String),+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ {+ styleSourceId: result.styleSources[0].id,+ breakpointId: expect.any(String),+ property: "paddingTop",+ value: { type: "unit", unit: "px", value: 16 },+ },+ {+ styleSourceId: result.styleSources[0].id,+ breakpointId: expect.any(String),+ property: "paddingRight",+ value: { type: "unit", unit: "px", value: 16 },+ },+ {+ styleSourceId: result.styleSources[0].id,+ breakpointId: expect.any(String),+ property: "paddingBottom",+ value: { type: "unit", unit: "px", value: 16 },+ },+ {+ styleSourceId: result.styleSources[0].id,+ breakpointId: expect.any(String),+ property: "paddingLeft",+ value: { type: "unit", unit: "px", value: 16 },+ },+ ]);+ expect(result.styleSourceSelections).toEqual([]);+ });++ test("create multiple tokens from style-only paste", () => {+ const result = generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ .title { font-weight: bold; }+ </style>+ `);+ expect(result.children).toEqual([]);+ expect(result.styleSources).toEqual([+ { type: "token", id: expect.any(String), name: "card" },+ { type: "token", id: expect.any(String), name: "title" },+ ]);+ expect(result.styles).toHaveLength(2);+ });++ test("create tokens with media queries from style-only paste", () => {+ const result = generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ @media (min-width: 768px) {+ .card { flex-direction: row; }+ }+ </style>+ `);+ expect(result.children).toEqual([]);+ expect(result.styleSources).toEqual([+ { type: "token", id: expect.any(String), name: "card" },+ ]);+ // base style + breakpoint style+ expect(result.styles).toHaveLength(2);+ expect(result.breakpoints).toHaveLength(2); // base + 768px+ });++ test("style-only paste with non-class rules creates leftover embed", () => {+ const result = generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ div { color: red; }+ </style>+ `);+ // card token created+ expect(result.styleSources).toEqual([+ { type: "token", id: expect.any(String), name: "card" },+ ]);+ // leftover non-class rule kept as HtmlEmbed+ expect(result.instances).toHaveLength(1);+ expect(result.instances[0].component).toBe("HtmlEmbed");+ });++ describe("media queries", () => {+ test("extract class with min-width media query into breakpoint", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ @media (min-width: 768px) {+ .card { flex-direction: row; }+ }+ </style>+ <div class="card">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(tokenSource).toBeDefined();+ // base style+ const baseStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "display" &&+ s.state === undefined+ );+ expect(baseStyle).toBeDefined();+ // breakpoint style+ const bpStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id && s.property === "flexDirection"+ );+ expect(bpStyle).toBeDefined();+ expect(bpStyle!.breakpointId).not.toBe(baseStyle!.breakpointId);+ // breakpoint should be created with minWidth+ const bp = fragment.breakpoints.find(+ (b) => b.id === bpStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ expect(bp!.minWidth).toBe(768);+ });++ test("extract class with max-width media query into breakpoint", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .container { padding: 32px; }+ @media (max-width: 480px) {+ .container { padding: 16px; }+ }+ </style>+ <div class="container">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "container"+ );+ expect(tokenSource).toBeDefined();+ const bpStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "paddingTop" &&+ s.breakpointId !== "base"+ );+ expect(bpStyle).toBeDefined();+ const bp = fragment.breakpoints.find(+ (b) => b.id === bpStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ expect(bp!.maxWidth).toBe(480);+ });++ test("extract class across multiple media queries", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { font-size: 14px; }+ @media (min-width: 768px) {+ .card { font-size: 16px; }+ }+ @media (min-width: 1024px) {+ .card { font-size: 18px; }+ }+ </style>+ <div class="card">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(tokenSource).toBeDefined();+ const tokenStyles = fragment.styles.filter(+ (s) => s.styleSourceId === tokenSource!.id+ );+ const breakpointIds = new Set(tokenStyles.map((s) => s.breakpointId));+ // base + 768px + 1024px = 3 breakpoints+ expect(breakpointIds.size).toBe(3);+ });++ test("media query with non-class selectors stays as html embed", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ @media (min-width: 768px) {+ #hero { font-size: 24px; }+ }+ </style>+ <div>Hello</div>+ `);+ expect(fragment.instances.some((i) => i.component === "HtmlEmbed")).toBe(+ true+ );+ expect(+ fragment.styleSources.filter((s) => s.type === "token")+ ).toHaveLength(0);+ });++ test("media query with mixed class and non-class selectors", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ @media (min-width: 768px) {+ .card { display: flex; }+ #hero { color: red; }+ }+ </style>+ <div class="card">Hello</div>+ `);+ // .card in media query should become token+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(tokenSource).toBeDefined();+ // #hero in media query should remain as html embed+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ });++ test("same class in base and media query produces single token", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .btn { padding: 8px; }+ @media (min-width: 768px) {+ .btn { padding: 16px; }+ }+ </style>+ <button class="btn">Click</button>+ `);+ const tokens = fragment.styleSources.filter((s) => s.type === "token");+ expect(tokens).toHaveLength(1);+ expect(tokens[0].type === "token" && tokens[0].name).toBe("btn");+ });++ test("multiple classes in same media query", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ .title { font-size: 16px; }+ @media (min-width: 768px) {+ .card { flex-direction: row; }+ .title { font-size: 24px; }+ }+ </style>+ <div class="card">+ <h1 class="title">Hello</h1>+ </div>+ `);+ const tokens = fragment.styleSources.filter((s) => s.type === "token");+ expect(tokens).toHaveLength(2);+ const cardToken = tokens.find(+ (s) => s.type === "token" && s.name === "card"+ );+ const titleToken = tokens.find(+ (s) => s.type === "token" && s.name === "title"+ );+ expect(cardToken).toBeDefined();+ expect(titleToken).toBeDefined();+ });+ });++ describe("pseudo-classes and pseudo-elements", () => {+ test("extract :hover pseudo-class as state", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .link { color: blue; }+ .link:hover { color: darkblue; }+ </style>+ <a class="link">Click</a>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "link"+ );+ expect(tokenSource).toBeDefined();+ const hoverStyle = fragment.styles.find(+ (s) => s.styleSourceId === tokenSource!.id && s.state === ":hover"+ );+ expect(hoverStyle).toBeDefined();+ });++ test("extract :focus pseudo-class as state", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .input { border-color: gray; }+ .input:focus { border-color: blue; }+ </style>+ <input class="input" />+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "input"+ );+ expect(tokenSource).toBeDefined();+ const focusStyle = fragment.styles.find(+ (s) => s.styleSourceId === tokenSource!.id && s.state === ":focus"+ );+ expect(focusStyle).toBeDefined();+ });++ test("extract multiple pseudo-classes on same class", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .btn { background: blue; }+ .btn:hover { background: darkblue; }+ .btn:focus { outline-color: blue; }+ .btn:active { background: navy; }+ </style>+ <button class="btn">Click</button>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "btn"+ );+ expect(tokenSource).toBeDefined();+ const states = fragment.styles+ .filter((s) => s.styleSourceId === tokenSource!.id && s.state)+ .map((s) => s.state);+ expect(states).toContain(":hover");+ expect(states).toContain(":focus");+ expect(states).toContain(":active");+ });++ test("extract ::before pseudo-element as state", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .decorated { position: relative; }+ .decorated::before { content: "★"; }+ </style>+ <div class="decorated">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "decorated"+ );+ expect(tokenSource).toBeDefined();+ const beforeStyle = fragment.styles.find(+ (s) => s.styleSourceId === tokenSource!.id && s.state === "::before"+ );+ expect(beforeStyle).toBeDefined();+ });++ test("extract ::after pseudo-element as state", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .clearfix::after {+ content: "";+ display: table;+ clear: both;+ }+ </style>+ <div class="clearfix">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "clearfix"+ );+ expect(tokenSource).toBeDefined();+ const afterStyles = fragment.styles.filter(+ (s) => s.styleSourceId === tokenSource!.id && s.state === "::after"+ );+ expect(afterStyles.length).toBeGreaterThanOrEqual(1);+ });++ test("pseudo-class on non-class selector ignored (stays in embed)", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ a:hover { color: red; }+ </style>+ <a>Link</a>+ `);+ expect(+ fragment.styleSources.filter((s) => s.type === "token")+ ).toHaveLength(0);+ expect(fragment.instances.some((i) => i.component === "HtmlEmbed")).toBe(+ true+ );+ });++ test("pseudo-class combined with media query", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .btn { background: blue; }+ .btn:hover { background: darkblue; }+ @media (min-width: 768px) {+ .btn { padding: 16px; }+ .btn:hover { background: royalblue; }+ }+ </style>+ <button class="btn">Click</button>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "btn"+ );+ expect(tokenSource).toBeDefined();+ // should have hover styles on base breakpoint+ const baseHover = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.state === ":hover" &&+ s.breakpointId === "base"+ );+ expect(baseHover).toBeDefined();+ // should have hover styles on 768px breakpoint+ const bpHover = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.state === ":hover" &&+ s.breakpointId !== "base"+ );+ expect(bpHover).toBeDefined();+ });++ test("::placeholder pseudo-element as state", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .input { color: black; }+ .input::placeholder { color: gray; }+ </style>+ <input class="input" />+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "input"+ );+ expect(tokenSource).toBeDefined();+ const placeholderStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id && s.state === "::placeholder"+ );+ expect(placeholderStyle).toBeDefined();+ });+ });++ describe("at-rules and special CSS", () => {+ test("@keyframes stays as html embed", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ @keyframes spin {+ from { transform: rotate(0deg); }+ to { transform: rotate(360deg); }+ }+ .spinner { animation: spin 1s infinite; }+ </style>+ <div class="spinner">Loading</div>+ `);+ // .spinner class should still become a token+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "spinner"+ );+ expect(tokenSource).toBeDefined();+ // @keyframes should remain as html embed+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ const codeProp = fragment.props.find(+ (p) => p.instanceId === htmlEmbed!.id && p.name === "code"+ );+ expect(codeProp).toBeDefined();+ expect(codeProp!.type === "string" && codeProp!.value).toContain(+ "@keyframes"+ );+ });++ test("@font-face stays as html embed", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ @font-face {+ font-family: "MyFont";+ src: url("font.woff2");+ }+ .text { font-family: "MyFont"; }+ </style>+ <p class="text">Hello</p>+ `);+ // .text class should become a token+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "text"+ );+ expect(tokenSource).toBeDefined();+ // @font-face should remain as html embed+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ const codeProp = fragment.props.find(+ (p) => p.instanceId === htmlEmbed!.id && p.name === "code"+ );+ expect(codeProp).toBeDefined();+ expect(codeProp!.type === "string" && codeProp!.value).toContain(+ "@font-face"+ );+ });++ test("@media print stays as html embed", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ @media print {+ .card { display: block; }+ }+ </style>+ <div class="card">Hello</div>+ `);+ // base .card should become a token+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(tokenSource).toBeDefined();+ // @media print should remain as html embed since parseCss ignores print+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ });++ test("grouped class selectors like .a, .b are extracted as separate tokens", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .primary, .secondary { font-weight: bold; }+ </style>+ <span class="primary">One</span>+ <span class="secondary">Two</span>+ `);+ const primaryToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "primary"+ );+ const secondaryToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "secondary"+ );+ expect(primaryToken).toBeDefined();+ expect(secondaryToken).toBeDefined();+ // both should have the same style+ const primaryStyle = fragment.styles.find(+ (s) => s.styleSourceId === primaryToken!.id+ );+ const secondaryStyle = fragment.styles.find(+ (s) => s.styleSourceId === secondaryToken!.id+ );+ expect(primaryStyle?.property).toBe("fontWeight");+ expect(secondaryStyle?.property).toBe("fontWeight");+ });++ test("grouped selector with class + non-class stays partially in embed", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card, #hero { display: flex; }+ </style>+ <div class="card">Hello</div>+ `);+ // .card should become token+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(tokenSource).toBeDefined();+ // #hero part should remain as html embed+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ });+ });++ describe("condition breakpoints", () => {+ test("@media (prefers-color-scheme: dark) creates condition breakpoint", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { background: white; color: black; }+ @media (prefers-color-scheme: dark) {+ .card { background: black; color: white; }+ }+ </style>+ <div class="card">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(tokenSource).toBeDefined();+ // should have base styles+ const baseStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "backgroundColor" &&+ s.state === undefined+ );+ expect(baseStyle).toBeDefined();+ // should have dark mode styles on condition breakpoint+ const darkStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "backgroundColor" &&+ s.breakpointId !== baseStyle!.breakpointId+ );+ expect(darkStyle).toBeDefined();+ const bp = fragment.breakpoints.find(+ (b) => b.id === darkStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ expect(bp!.condition).toBe("prefers-color-scheme:dark");+ expect(bp!.minWidth).toBeUndefined();+ expect(bp!.maxWidth).toBeUndefined();+ });++ test("@media (orientation: portrait) creates condition breakpoint", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .layout { flex-direction: row; }+ @media (orientation: portrait) {+ .layout { flex-direction: column; }+ }+ </style>+ <div class="layout">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "layout"+ );+ expect(tokenSource).toBeDefined();+ const portraitStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "flexDirection" &&+ s.breakpointId !== "base"+ );+ expect(portraitStyle).toBeDefined();+ const bp = fragment.breakpoints.find(+ (b) => b.id === portraitStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ expect(bp!.condition).toBe("orientation:portrait");+ });++ test("@media (hover: hover) creates condition breakpoint", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .interactive { cursor: default; }+ @media (hover: hover) {+ .interactive { cursor: pointer; }+ }+ </style>+ <div class="interactive">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "interactive"+ );+ expect(tokenSource).toBeDefined();+ const hoverStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "cursor" &&+ s.breakpointId !== "base"+ );+ expect(hoverStyle).toBeDefined();+ const bp = fragment.breakpoints.find(+ (b) => b.id === hoverStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ expect(bp!.condition).toBe("hover:hover");+ });++ test("@media (prefers-reduced-motion: reduce) creates condition breakpoint", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .animated { transition: transform 0.3s; }+ @media (prefers-reduced-motion: reduce) {+ .animated { transition: none; }+ }+ </style>+ <div class="animated">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "animated"+ );+ expect(tokenSource).toBeDefined();+ const reduceStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "transitionProperty" &&+ s.breakpointId !== "base"+ );+ expect(reduceStyle).toBeDefined();+ const bp = fragment.breakpoints.find(+ (b) => b.id === reduceStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ expect(bp!.condition).toBe("prefers-reduced-motion:reduce");+ });++ test("combined min-width and max-width uses range breakpoint", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .tablet-only { display: none; }+ @media (min-width: 768px) and (max-width: 1024px) {+ .tablet-only { display: block; }+ }+ </style>+ <div class="tablet-only">Tablet content</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "tablet-only"+ );+ expect(tokenSource).toBeDefined();+ const tabletStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "display" &&+ s.breakpointId !== "base"+ );+ expect(tabletStyle).toBeDefined();+ const bp = fragment.breakpoints.find(+ (b) => b.id === tabletStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ // Combined width queries use both minWidth and maxWidth+ expect(bp!.minWidth).toBe(768);+ expect(bp!.maxWidth).toBe(1024);+ expect(bp!.condition).toBeUndefined();+ });++ test("overlapping min/max-width breakpoints get rounded to non-overlapping values", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a { font-size: 14px; }+ @media (min-width: 600px) and (max-width: 900px) {+ .a { font-size: 16px; }+ }+ @media (min-width: 800px) and (max-width: 1200px) {+ .a { font-size: 18px; }+ }+ </style>+ <div class="a">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "a"+ );+ expect(tokenSource).toBeDefined();+ const tokenStyles = fragment.styles.filter(+ (s) => s.styleSourceId === tokenSource!.id && s.property === "fontSize"+ );+ // base + 2 range breakpoints = 3 styles+ expect(tokenStyles).toHaveLength(3);+ const rangeBreakpoints = tokenStyles+ .filter((s) => s.breakpointId !== "base")+ .map((s) => fragment.breakpoints.find((b) => b.id === s.breakpointId))+ .filter(Boolean)+ .sort((a, b) => (a!.minWidth ?? 0) - (b!.minWidth ?? 0));+ expect(rangeBreakpoints).toHaveLength(2);+ // ranges should not overlap: first.maxWidth < second.minWidth+ const first = rangeBreakpoints[0]!;+ const second = rangeBreakpoints[1]!;+ expect(first.maxWidth).toBeDefined();+ expect(second.minWidth).toBeDefined();+ expect(first.maxWidth!).toBeLessThan(second.minWidth!);+ });++ test("non-overlapping range breakpoints stay unchanged", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a { font-size: 14px; }+ @media (min-width: 400px) and (max-width: 700px) {+ .a { font-size: 16px; }+ }+ @media (min-width: 800px) and (max-width: 1200px) {+ .a { font-size: 18px; }+ }+ </style>+ <div class="a">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "a"+ );+ expect(tokenSource).toBeDefined();+ const rangeBreakpoints = fragment.breakpoints+ .filter((b) => b.minWidth !== undefined && b.maxWidth !== undefined)+ .sort((a, b) => (a.minWidth ?? 0) - (b.minWidth ?? 0));+ expect(rangeBreakpoints).toHaveLength(2);+ // values should remain exactly as authored since they don't overlap+ expect(rangeBreakpoints[0].minWidth).toBe(400);+ expect(rangeBreakpoints[0].maxWidth).toBe(700);+ expect(rangeBreakpoints[1].minWidth).toBe(800);+ expect(rangeBreakpoints[1].maxWidth).toBe(1200);+ });++ test("adjacent range breakpoints (touching) stay unchanged", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a { font-size: 14px; }+ @media (min-width: 400px) and (max-width: 799px) {+ .a { font-size: 16px; }+ }+ @media (min-width: 800px) and (max-width: 1200px) {+ .a { font-size: 18px; }+ }+ </style>+ <div class="a">Hello</div>+ `);+ const rangeBreakpoints = fragment.breakpoints+ .filter((b) => b.minWidth !== undefined && b.maxWidth !== undefined)+ .sort((a, b) => (a.minWidth ?? 0) - (b.minWidth ?? 0));+ expect(rangeBreakpoints).toHaveLength(2);+ // touching but not overlapping — keep as is+ expect(rangeBreakpoints[0].maxWidth).toBe(799);+ expect(rangeBreakpoints[1].minWidth).toBe(800);+ });++ test("overlapping range: first.maxWidth rounded down to second.minWidth - 1", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a { font-size: 14px; }+ @media (min-width: 600px) and (max-width: 1000px) {+ .a { font-size: 16px; }+ }+ @media (min-width: 900px) and (max-width: 1400px) {+ .a { font-size: 18px; }+ }+ </style>+ <div class="a">Hello</div>+ `);+ const rangeBreakpoints = fragment.breakpoints+ .filter((b) => b.minWidth !== undefined && b.maxWidth !== undefined)+ .sort((a, b) => (a.minWidth ?? 0) - (b.minWidth ?? 0));+ expect(rangeBreakpoints).toHaveLength(2);+ // first range's maxWidth should be adjusted to not overlap second's minWidth+ expect(rangeBreakpoints[0].minWidth).toBe(600);+ expect(rangeBreakpoints[0].maxWidth!).toBeLessThan(+ rangeBreakpoints[1].minWidth!+ );+ // second range should keep its original values+ expect(rangeBreakpoints[1].minWidth).toBe(900);+ expect(rangeBreakpoints[1].maxWidth).toBe(1400);+ });++ test("three overlapping ranges all get adjusted", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a { font-size: 14px; }+ @media (min-width: 400px) and (max-width: 800px) {+ .a { font-size: 16px; }+ }+ @media (min-width: 700px) and (max-width: 1100px) {+ .a { font-size: 18px; }+ }+ @media (min-width: 1000px) and (max-width: 1400px) {+ .a { font-size: 20px; }+ }+ </style>+ <div class="a">Hello</div>+ `);+ const rangeBreakpoints = fragment.breakpoints+ .filter((b) => b.minWidth !== undefined && b.maxWidth !== undefined)+ .sort((a, b) => (a.minWidth ?? 0) - (b.minWidth ?? 0));+ expect(rangeBreakpoints).toHaveLength(3);+ // no pair should overlap+ expect(rangeBreakpoints[0].maxWidth!).toBeLessThan(+ rangeBreakpoints[1].minWidth!+ );+ expect(rangeBreakpoints[1].maxWidth!).toBeLessThan(+ rangeBreakpoints[2].minWidth!+ );+ });++ test("exact duplicate range breakpoints get deduplicated", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a { font-size: 14px; }+ .b { color: red; }+ @media (min-width: 768px) and (max-width: 1024px) {+ .a { font-size: 18px; }+ }+ @media (min-width: 768px) and (max-width: 1024px) {+ .b { color: blue; }+ }+ </style>+ <div class="a"><span class="b">Hello</span></div>+ `);+ // same range should reuse a single breakpoint+ const rangeBreakpoints = fragment.breakpoints.filter(+ (b) => b.minWidth !== undefined && b.maxWidth !== undefined+ );+ expect(rangeBreakpoints).toHaveLength(1);+ expect(rangeBreakpoints[0].minWidth).toBe(768);+ expect(rangeBreakpoints[0].maxWidth).toBe(1024);+ });++ test("range breakpoint overlapping with simple min-width breakpoint", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a { font-size: 14px; }+ @media (min-width: 768px) {+ .a { font-size: 18px; }+ }+ @media (min-width: 600px) and (max-width: 900px) {+ .a { font-size: 16px; }+ }+ </style>+ <div class="a">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "a"+ );+ expect(tokenSource).toBeDefined();+ const tokenStyles = fragment.styles.filter(+ (s) => s.styleSourceId === tokenSource!.id && s.property === "fontSize"+ );+ // base + min-width + range = 3 breakpoints+ expect(tokenStyles).toHaveLength(3);+ // simple min-width breakpoint should exist+ const minWidthBp = fragment.breakpoints.find(+ (b) =>+ b.minWidth !== undefined &&+ b.maxWidth === undefined &&+ b.condition === undefined+ );+ expect(minWidthBp).toBeDefined();+ // range breakpoint should exist and not overlap min-width+ const rangeBp = fragment.breakpoints.find(+ (b) => b.minWidth !== undefined && b.maxWidth !== undefined+ );+ expect(rangeBp).toBeDefined();+ // range's maxWidth must be less than the min-width breakpoint's minWidth+ // so they don't overlap+ expect(rangeBp!.maxWidth!).toBeLessThan(minWidthBp!.minWidth!);+ });++ test("range breakpoint overlapping with simple max-width breakpoint", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a { font-size: 14px; }+ @media (max-width: 600px) {+ .a { font-size: 12px; }+ }+ @media (min-width: 400px) and (max-width: 900px) {+ .a { font-size: 16px; }+ }+ </style>+ <div class="a">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "a"+ );+ expect(tokenSource).toBeDefined();+ const tokenStyles = fragment.styles.filter(+ (s) => s.styleSourceId === tokenSource!.id && s.property === "fontSize"+ );+ // base + max-width + range = 3 breakpoints+ expect(tokenStyles).toHaveLength(3);+ // simple max-width breakpoint should exist+ const maxWidthBp = fragment.breakpoints.find(+ (b) =>+ b.maxWidth !== undefined &&+ b.minWidth === undefined &&+ b.condition === undefined+ );+ expect(maxWidthBp).toBeDefined();+ // range breakpoint should exist and not overlap max-width+ const rangeBp = fragment.breakpoints.find(+ (b) => b.minWidth !== undefined && b.maxWidth !== undefined+ );+ expect(rangeBp).toBeDefined();+ // range's minWidth must be greater than the max-width breakpoint's maxWidth+ expect(rangeBp!.minWidth!).toBeGreaterThan(maxWidthBp!.maxWidth!);+ });++ test("completely contained range gets clamped", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a { font-size: 14px; }+ @media (min-width: 400px) and (max-width: 1200px) {+ .a { font-size: 16px; }+ }+ @media (min-width: 600px) and (max-width: 900px) {+ .a { font-size: 18px; }+ }+ </style>+ <div class="a">Hello</div>+ `);+ const rangeBreakpoints = fragment.breakpoints+ .filter((b) => b.minWidth !== undefined && b.maxWidth !== undefined)+ .sort((a, b) => (a.minWidth ?? 0) - (b.minWidth ?? 0));+ expect(rangeBreakpoints).toHaveLength(2);+ // the outer range should be split/adjusted so inner doesn't overlap+ expect(rangeBreakpoints[0].maxWidth!).toBeLessThan(+ rangeBreakpoints[1].minWidth!+ );+ });++ test("combined width and feature uses condition breakpoint", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .widget { font-size: 14px; }+ @media (min-width: 768px) and (orientation: landscape) {+ .widget { font-size: 18px; }+ }+ </style>+ <div class="widget">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "widget"+ );+ expect(tokenSource).toBeDefined();+ const landscapeStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "fontSize" &&+ s.breakpointId !== "base"+ );+ expect(landscapeStyle).toBeDefined();+ const bp = fragment.breakpoints.find(+ (b) => b.id === landscapeStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ // Mixed width + feature query becomes a condition+ expect(bp!.condition).toBeDefined();+ });++ test("multiple condition features combined", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .accessible { font-size: 16px; }+ @media (prefers-color-scheme: dark) and (prefers-contrast: more) {+ .accessible { font-size: 18px; }+ }+ </style>+ <div class="accessible">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "accessible"+ );+ expect(tokenSource).toBeDefined();+ const conditionStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "fontSize" &&+ s.breakpointId !== "base"+ );+ expect(conditionStyle).toBeDefined();+ const bp = fragment.breakpoints.find(+ (b) => b.id === conditionStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ expect(bp!.condition).toBeDefined();+ // condition should contain both features+ expect(bp!.condition).toContain("prefers-color-scheme");+ expect(bp!.condition).toContain("prefers-contrast");+ });++ test("same condition breakpoint reused for multiple classes", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { background: white; }+ .text { color: black; }+ @media (prefers-color-scheme: dark) {+ .card { background: black; }+ .text { color: white; }+ }+ </style>+ <div class="card">+ <p class="text">Hello</p>+ </div>+ `);+ const cardToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ const textToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "text"+ );+ expect(cardToken).toBeDefined();+ expect(textToken).toBeDefined();+ // both dark styles should reference the same breakpoint+ const cardDarkStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === cardToken!.id &&+ s.property === "backgroundColor" &&+ s.breakpointId !== "base"+ );+ const textDarkStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === textToken!.id &&+ s.property === "color" &&+ s.breakpointId !== "base"+ );+ expect(cardDarkStyle).toBeDefined();+ expect(textDarkStyle).toBeDefined();+ expect(cardDarkStyle!.breakpointId).toBe(textDarkStyle!.breakpointId);+ });+ });++ describe("nested at-rules", () => {+ test("nested @media rules extract class with flattened condition", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ @media (min-width: 768px) {+ @media (prefers-color-scheme: dark) {+ .card { background: black; }+ }+ }+ </style>+ <div class="card">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(tokenSource).toBeDefined();+ // nested @media should flatten into a combined condition+ const nestedStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "backgroundColor"+ );+ expect(nestedStyle).toBeDefined();+ const bp = fragment.breakpoints.find(+ (b) => b.id === nestedStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ // flattened condition should include both queries+ expect(bp!.condition).toBeDefined();+ });++ test("deeply nested @media still extracts class tokens", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { padding: 8px; }+ @media (min-width: 768px) {+ @media (orientation: landscape) {+ @media (hover: hover) {+ .card { padding: 32px; }+ }+ }+ }+ </style>+ <div class="card">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(tokenSource).toBeDefined();+ const deepStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "paddingTop" &&+ s.breakpointId !== "base"+ );+ expect(deepStyle).toBeDefined();+ const bp = fragment.breakpoints.find(+ (b) => b.id === deepStyle!.breakpointId+ );+ expect(bp).toBeDefined();+ expect(bp!.condition).toBeDefined();+ });++ test("nested @media with same feature type combines correctly", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .responsive { font-size: 14px; }+ @media (min-width: 768px) {+ .responsive { font-size: 16px; }+ @media (min-width: 1024px) {+ .responsive { font-size: 20px; }+ }+ }+ </style>+ <div class="responsive">Hello</div>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "responsive"+ );+ expect(tokenSource).toBeDefined();+ // outer @media (min-width: 768px) should have simple breakpoint+ const outerStyle = fragment.styles.find(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "fontSize" &&+ s.breakpointId !== "base" &&+ fragment.breakpoints.find(+ (b) => b.id === s.breakpointId && b.minWidth === 768+ )+ );+ expect(outerStyle).toBeDefined();+ // nested @media (min-width: 1024px) inside @media (min-width: 768px)+ // should still produce a breakpoint (the effective min-width is 1024px)+ const innerStyles = fragment.styles.filter(+ (s) =>+ s.styleSourceId === tokenSource!.id &&+ s.property === "fontSize" &&+ s.breakpointId !== "base" &&+ s.breakpointId !== outerStyle!.breakpointId+ );+ expect(innerStyles).toHaveLength(1);+ });++ test("@supports nested inside @media keeps class in embed", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .grid { display: flex; }+ @supports (display: grid) {+ .grid { display: grid; }+ }+ </style>+ <div class="grid">Hello</div>+ `);+ // base class should become token+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "grid"+ );+ expect(tokenSource).toBeDefined();+ // @supports should remain as html embed (not a media query)+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ });+ });++ describe("selector edge cases", () => {+ test("class with compound selector .card.active is extracted as combo token", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card.active { opacity: 1; }+ </style>+ <div class="card active">Hello</div>+ `);+ // compound selectors become combo tokens (Webflow-style naming)+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card.active"+ );+ expect(tokenSource).toBeDefined();+ // no leftover for pure class rule+ expect(fragment.instances.some((i) => i.component === "HtmlEmbed")).toBe(+ false+ );+ });++ test("class with attribute selector .btn[disabled] is extracted with state", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .btn[disabled] { opacity: 0.5; }+ </style>+ <button class="btn" disabled>Click</button>+ `);+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "btn"+ );+ expect(tokenSource).toBeDefined();+ // the style should have [disabled] state+ const style = fragment.styles.find(+ (s) => s.styleSourceId === tokenSource!.id+ );+ expect(style).toBeDefined();+ expect(style!.state).toBe("[disabled]");+ // no leftover+ expect(fragment.instances.some((i) => i.component === "HtmlEmbed")).toBe(+ false+ );+ });++ test("class with sibling combinator .a + .b is not extracted", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a + .b { margin-top: 8px; }+ </style>+ <div class="a">A</div>+ <div class="b">B</div>+ `);+ expect(+ fragment.styleSources.filter((s) => s.type === "token")+ ).toHaveLength(0);+ });++ test("class with general sibling .a ~ .b is not extracted", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a ~ .b { color: red; }+ </style>+ <div class="a">A</div>+ <div class="b">B</div>+ `);+ expect(+ fragment.styleSources.filter((s) => s.type === "token")+ ).toHaveLength(0);+ });++ test(":root selector stays as html embed", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ :root { --color: blue; }+ .card { color: var(--color); }+ </style>+ <div class="card">Hello</div>+ `);+ // .card should become token+ const tokenSource = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(tokenSource).toBeDefined();+ // :root should stay as html embed+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ });++ test("universal selector * stays as html embed", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ * { box-sizing: border-box; }+ </style>+ <div>Hello</div>+ `);+ expect(+ fragment.styleSources.filter((s) => s.type === "token")+ ).toHaveLength(0);+ expect(fragment.instances.some((i) => i.component === "HtmlEmbed")).toBe(+ true+ );+ });+ });++ describe("compound class selectors", () => {+ test("compound .card.active extracts as combo token when element has both classes", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ .card.active { opacity: 1; }+ </style>+ <div class="card active">Hello</div>+ `);+ const cardToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ const comboToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card.active"+ );+ expect(cardToken).toBeDefined();+ expect(comboToken).toBeDefined();+ // instance should reference both tokens+ const sel = fragment.styleSourceSelections.find(+ (s) =>+ s.values.includes(cardToken!.id) && s.values.includes(comboToken!.id)+ );+ expect(sel).toBeDefined();+ });++ test("compound .a.b.c extracts as triple combo token", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a.b.c { color: red; }+ </style>+ <div class="a b c">Hello</div>+ `);+ const comboToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "a.b.c"+ );+ expect(comboToken).toBeDefined();+ const style = fragment.styles.find(+ (s) => s.styleSourceId === comboToken!.id && s.property === "color"+ );+ expect(style).toBeDefined();+ });++ test("compound class not matched when element is missing a class", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card.active { opacity: 1; }+ </style>+ <div class="card">Hello</div>+ `);+ // token is created for all class rules, even if not applied to elements+ const comboToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card.active"+ );+ expect(comboToken).toBeDefined();+ // but NOT assigned to the div (missing "active" class)+ const divInstance = fragment.instances.find((i) => i.tag === "div");+ const sel = fragment.styleSourceSelections.find(+ (s) => s.instanceId === divInstance?.id+ );+ // No selection for this instance, or if one exists, it shouldn't contain the combo token+ expect(sel?.values ?? []).not.toContain(comboToken?.id);+ });++ test("compound class with :hover pseudo extracts correctly", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .btn.primary:hover { background: blue; }+ </style>+ <button class="btn primary">Click</button>+ `);+ const comboToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "btn.primary"+ );+ expect(comboToken).toBeDefined();+ const style = fragment.styles.find(+ (s) => s.styleSourceId === comboToken!.id+ );+ expect(style).toBeDefined();+ expect(style!.state).toBe(":hover");+ });++ test("compound class inside @media query creates breakpoint style", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card.featured { display: block; }+ @media (min-width: 768px) {+ .card.featured { display: flex; }+ }+ </style>+ <div class="card featured">Hello</div>+ `);+ const comboToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card.featured"+ );+ expect(comboToken).toBeDefined();+ // Should have both base and breakpoint styles+ const comboStyles = fragment.styles.filter(+ (s) => s.styleSourceId === comboToken!.id+ );+ expect(comboStyles.length).toBe(2);+ const bpIds = new Set(comboStyles.map((s) => s.breakpointId));+ expect(bpIds.size).toBe(2);+ });+ });++ describe("attribute selectors as state", () => {+ test(".btn[disabled] extracts with [disabled] state", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .btn { padding: 8px; }+ .btn[disabled] { opacity: 0.5; }+ </style>+ <button class="btn" disabled>Click</button>+ `);+ const btnToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "btn"+ );+ expect(btnToken).toBeDefined();+ const baseStyle = fragment.styles.find(+ (s) => s.styleSourceId === btnToken!.id && s.state === undefined+ );+ expect(baseStyle).toBeDefined();+ expect(baseStyle!.property).toBe("paddingTop");+ const stateStyle = fragment.styles.find(+ (s) => s.styleSourceId === btnToken!.id && s.state === "[disabled]"+ );+ expect(stateStyle).toBeDefined();+ expect(stateStyle!.property).toBe("opacity");+ });++ test(".input[readonly] extracts with [readonly] state", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .input[readonly] { background: #eee; }+ </style>+ <input class="input" readonly>+ `);+ const inputToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "input"+ );+ expect(inputToken).toBeDefined();+ const stateStyle = fragment.styles.find(+ (s) => s.styleSourceId === inputToken!.id && s.state === "[readonly]"+ );+ expect(stateStyle).toBeDefined();+ });++ test("attribute selector combined with pseudo keeps pseudo state", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .btn:hover { color: blue; }+ .btn[disabled] { opacity: 0.5; }+ </style>+ <button class="btn" disabled>Click</button>+ `);+ const btnToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "btn"+ );+ expect(btnToken).toBeDefined();+ const hoverStyle = fragment.styles.find(+ (s) => s.styleSourceId === btnToken!.id && s.state === ":hover"+ );+ expect(hoverStyle).toBeDefined();+ const disabledStyle = fragment.styles.find(+ (s) => s.styleSourceId === btnToken!.id && s.state === "[disabled]"+ );+ expect(disabledStyle).toBeDefined();+ });+ });++ describe("mixed comma selectors (partial extraction)", () => {+ test(".card, div {} extracts .card token, keeps div in leftover", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card, div { display: flex; }+ </style>+ <div class="card">Hello</div>+ `);+ const cardToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ expect(cardToken).toBeDefined();+ // div part should stay as html embed+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ const codeProp = fragment.props.find(+ (p) => p.instanceId === htmlEmbed!.id && p.name === "code"+ );+ expect(codeProp).toBeDefined();+ // The leftover should only contain the div selector, not .card+ expect(codeProp!.type === "string" && codeProp!.value).toContain("div");+ expect(codeProp!.type === "string" && codeProp!.value).not.toMatch(+ /\.card/+ );+ });++ test(".a, .b, #id {} extracts .a and .b, keeps #id in leftover", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a, .b, #id { color: red; }+ </style>+ <div class="a">A</div>+ <div class="b">B</div>+ `);+ const tokenA = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "a"+ );+ const tokenB = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "b"+ );+ expect(tokenA).toBeDefined();+ expect(tokenB).toBeDefined();+ // #id should stay in embed+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ });++ test(".a, .b {} with all class selectors produces no leftover", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .a, .b { padding: 4px; }+ </style>+ <div class="a">A</div>+ <div class="b">B</div>+ `);+ // Both should become tokens+ expect(+ fragment.styleSources.filter((s) => s.type === "token")+ ).toHaveLength(2);+ // No leftover embed+ expect(fragment.instances.some((i) => i.component === "HtmlEmbed")).toBe(+ false+ );+ });+ });++ describe("breakpoint labels", () => {+ test("condition breakpoint gets human-readable label", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ @media (prefers-color-scheme: dark) {+ .card { background: black; }+ }+ </style>+ <div class="card">Hello</div>+ `);+ const condBp = fragment.breakpoints.find((b) => b.condition);+ expect(condBp).toBeDefined();+ // capitalCase transforms "prefers-color-scheme:dark" → "Prefers Color Scheme Dark"+ expect(condBp!.label).toBe("Prefers Color Scheme Dark");+ });++ test("width breakpoint gets readable label", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ @media (min-width: 768px) {+ .card { display: flex; }+ }+ </style>+ <div class="card">Hello</div>+ `);+ const bp = fragment.breakpoints.find((b) => b.minWidth === 768);+ expect(bp).toBeDefined();+ expect(bp!.label).toBe("≥ 768px");+ });++ test("range breakpoint gets combined label", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ @media (min-width: 768px) and (max-width: 1024px) {+ .card { display: flex; }+ }+ </style>+ <div class="card">Hello</div>+ `);+ const bp = fragment.breakpoints.find(+ (b) => b.minWidth === 768 && b.maxWidth === 1024+ );+ expect(bp).toBeDefined();+ expect(bp!.label).toBe("≥ 768px and ≤ 1024px");+ });+ });++ describe("complex real-world scenarios", () => {+ test("responsive card component with hover states", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .card {+ display: flex;+ flex-direction: column;+ padding: 16px;+ border-radius: 8px;+ }+ .card:hover {+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);+ }+ @media (min-width: 768px) {+ .card {+ flex-direction: row;+ padding: 24px;+ }+ }+ .card-title {+ font-size: 18px;+ font-weight: bold;+ }+ @media (min-width: 768px) {+ .card-title {+ font-size: 24px;+ }+ }+ </style>+ <div class="card">+ <h2 class="card-title">Title</h2>+ <p>Description</p>+ </div>+ `);+ // both tokens should be created+ const cardToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ );+ const titleToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card-title"+ );+ expect(cardToken).toBeDefined();+ expect(titleToken).toBeDefined();+ // card should have hover state+ expect(+ fragment.styles.some(+ (s) => s.styleSourceId === cardToken!.id && s.state === ":hover"+ )+ ).toBe(true);+ // card should have breakpoint styles+ const cardBreakpoints = new Set(+ fragment.styles+ .filter((s) => s.styleSourceId === cardToken!.id && !s.state)+ .map((s) => s.breakpointId)+ );+ expect(cardBreakpoints.size).toBeGreaterThanOrEqual(2);+ // title should have breakpoint styles+ const titleBreakpoints = new Set(+ fragment.styles+ .filter((s) => s.styleSourceId === titleToken!.id)+ .map((s) => s.breakpointId)+ );+ expect(titleBreakpoints.size).toBeGreaterThanOrEqual(2);+ // no HtmlEmbed (all rules are class-based)+ expect(fragment.instances.some((i) => i.component === "HtmlEmbed")).toBe(+ false+ );+ });++ test("html with mixed class rules, id rules, keyframes, and media queries", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ @keyframes fadeIn {+ from { opacity: 0; }+ to { opacity: 1; }+ }+ .fade-in { animation: fadeIn 0.3s ease-in; }+ .card { display: flex; }+ #app { min-height: 100vh; }+ @media (min-width: 768px) {+ .card { flex-direction: row; }+ }+ </style>+ <div class="card fade-in">+ <p>Hello</p>+ </div>+ `);+ // class tokens should be extracted+ expect(+ fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "card"+ )+ ).toBeDefined();+ expect(+ fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "fade-in"+ )+ ).toBeDefined();+ // @keyframes and #app should remain as html embed+ const htmlEmbed = fragment.instances.find(+ (i) => i.component === "HtmlEmbed"+ );+ expect(htmlEmbed).toBeDefined();+ const codeProp = fragment.props.find(+ (p) => p.instanceId === htmlEmbed!.id && p.name === "code"+ );+ expect(codeProp!.type === "string" && codeProp!.value).toContain(+ "@keyframes"+ );+ expect(codeProp!.type === "string" && codeProp!.value).toContain("#app");+ });++ test("navigation component with multiple states and breakpoints", () => {+ const fragment = generateFragmentFromHtml(`+ <style>+ .nav { display: flex; gap: 8px; }+ .nav-link { color: gray; text-decoration: none; }+ .nav-link:hover { color: blue; }+ .nav-link:focus { outline: 2px solid blue; }+ .nav-link::after { content: ""; display: block; height: 2px; }+ @media (min-width: 768px) {+ .nav { gap: 16px; }+ .nav-link { font-size: 16px; }+ }+ </style>+ <nav class="nav">+ <a class="nav-link">Home</a>+ <a class="nav-link">About</a>+ </nav>+ `);+ const navToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "nav"+ );+ const linkToken = fragment.styleSources.find(+ (s) => s.type === "token" && s.name === "nav-link"+ );+ expect(navToken).toBeDefined();+ expect(linkToken).toBeDefined();+ // nav-link should have hover, focus, and ::after states+ const linkStates = new Set(+ fragment.styles+ .filter((s) => s.styleSourceId === linkToken!.id && s.state)+ .map((s) => s.state)+ );+ expect(linkStates.has(":hover")).toBe(true);+ expect(linkStates.has(":focus")).toBe(true);+ expect(linkStates.has("::after")).toBe(true);+ // both should have breakpoint styles+ const navBreakpoints = new Set(+ fragment.styles+ .filter((s) => s.styleSourceId === navToken!.id)+ .map((s) => s.breakpointId)+ );+ expect(navBreakpoints.size).toBeGreaterThanOrEqual(2);+ // nav-link token should be reused for both <a> elements+ const linkSelections = fragment.styleSourceSelections.filter((sel) =>+ sel.values.includes(linkToken!.id)+ );+ expect(linkSelections).toHaveLength(2);+ });+ });++ describe("nested selectors", () => {+ test("resolve descendant selector to matching element", () => {+ const cardInnerToken = token(+ "card__inner",+ css`+ color: red;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.card .inner { color: red; }</style>+ <div class="card"><span class="inner">Hello</span></div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" class="card">+ <ws.element ws:tag="span" ws:tokens={[cardInnerToken]}>+ Hello+ </ws.element>+ </ws.element>+ )+ );+ });++ test("resolve child combinator to direct child", () => {+ const parentChildToken = token(+ "parent__child",+ css`+ margin: 0;+ `+ );+ expect(+ generateFragmentFromHtml(`+ <style>.parent > .child { margin: 0; }</style>+ <div class="parent"><span class="child">Hello</span></div>+ `)+ ).toEqual(+ renderTemplate(+ <ws.element ws:tag="div" class="parent">+ <ws.element ws:tag="span" ws:tokens={[parentChildToken]}>+ Hello+ </ws.element>+ </ws.element>+ )+ );+ });++ test("child combinator does not match non-direct child", () => {+ const result = _generateFragmentFromHtml(`+ <style>.parent > .child { color: red; }</style>+ <div class="parent"><div><span class="child">Hello</span></div></div>+ `);+ // .child is nested inside an intermediate div, not a direct child of .parent+ expect(result.skippedSelectors).toEqual([".parent > .child"]);+ // no token created for the nested rule+ expect(+ result.styleSources.filter((s) => s.type === "token")+ ).toHaveLength(0);+ });++ test("skip unresolved nested selector and report it", () => {+ const result = _generateFragmentFromHtml(`+ <style>.card .title { color: red; }</style>+ <div class="card"><span>No title class here</span></div>+ `);+ expect(result.skippedSelectors).toEqual([".card .title"]);+ expect(+ result.styleSources.filter((s) => s.type === "token")+ ).toHaveLength(0);+ });++ test("style-only paste with nested selector — all skipped", () => {+ const result = _generateFragmentFromHtml(`+ <style>.card .title { color: red; }</style>+ `);+ expect(result.skippedSelectors).toEqual([".card .title"]);+ expect(result.styleSources).toHaveLength(0);+ });++ test("mixed simple and nested selectors", () => {+ const result = _generateFragmentFromHtml(`+ <style>+ .card { display: flex; }+ .card .title { font-weight: bold; }+ </style>+ <div class="card"><h1 class="title">Hello</h1></div>+ `);+ expect(result.skippedSelectors).toEqual([]);+ // .card token + .card__title nested token+ const tokenNames = result.styleSources+ .filter((s) => s.type === "token")+ .map((s) => s.name);+ expect(tokenNames).toContain("card");+ expect(tokenNames).toContain("card__title");+ });++ test("multiple ancestors: .a .b .c", () => {+ const result = _generateFragmentFromHtml(`+ <style>.a .b .c { color: red; }</style>+ <div class="a"><div class="b"><span class="c">Hi</span></div></div>+ `);+ expect(result.skippedSelectors).toEqual([]);+ const tokenNames = result.styleSources+ .filter((s) => s.type === "token")+ .map((s) => s.name);+ expect(tokenNames).toContain("a__b__c");+ });++ test("nested selector with media query", () => {+ const result = _generateFragmentFromHtml(`+ <style>+ .card .title { color: red; }+ @media (min-width: 768px) {+ .card .title { color: blue; }+ }+ </style>+ <div class="card"><h1 class="title">Hello</h1></div>+ `);+ expect(result.skippedSelectors).toEqual([]);+ const nestedToken = result.styleSources.find(+ (s) => s.type === "token" && s.name === "card__title"+ );+ expect(nestedToken).toBeDefined();+ // should have styles at base breakpoint and 768px breakpoint+ const nestedStyles = result.styles.filter(+ (s) => s.styleSourceId === nestedToken!.id+ );+ const breakpointIds = new Set(nestedStyles.map((s) => s.breakpointId));+ expect(breakpointIds.size).toBe(2);+ });++ test("sibling combinators stay as leftover", () => {+ const result = _generateFragmentFromHtml(`+ <style>.a + .b { color: red; }</style>+ <div class="a">A</div><div class="b">B</div>+ `);+ // sibling selector is not class-based → stays as HtmlEmbed+ expect(result.instances.some((i) => i.component === "HtmlEmbed")).toBe(+ true+ );+ });+ });+});diff --git a/apps/builder/app/shared/html.ts b/apps/builder/app/shared/html.tsindex ee92795e20..e5e6a1581f 100644--- a/apps/builder/app/shared/html.ts+++ b/apps/builder/app/shared/html.ts@@ -15,11 +15,19 @@ import {StyleSourceSelection,} from "@webstudio-is/sdk";import { ariaAttributes, attributesByTag } from "@webstudio-is/html-data";-import { camelCaseProperty, parseCss } from "@webstudio-is/css-data";+import {+ camelCaseProperty,+ parseCss,+ parseClassBasedSelector,+ parseMediaQuery,+ type ParsedStyleDecl,+ type ParsedClassSelector,+} from "@webstudio-is/css-data";import { richTextContentTags } from "./content-model";import { setIsSubsetOf } from "./shim";import { isAttributeNameSafe } from "@webstudio-is/react-sdk";import { capitalCase } from "change-case";+import * as csstree from "css-tree";type ElementNode = DefaultTreeAdapterMap["element"];@@ -73,7 +81,367 @@ const findContentTags = (element: ElementNode, tags = new Set<string>()) => {return tags;};-export const generateFragmentFromHtml = (html: string): WebstudioFragment => {+/**+ * Collect all text content from <style> elements in the parsed HTML tree+ */+const collectStyleTexts = (+ documentFragment: DefaultTreeAdapterMap["documentFragment"]+): string[] => {+ const texts: string[] = [];+ const walk = (node: DefaultTreeAdapterMap["parentNode"]) => {+ for (const child of node.childNodes) {+ if (+ defaultTreeAdapter.isElementNode(child) &&+ child.tagName === "style"+ ) {+ const textContent = child.childNodes+ .filter((c) => defaultTreeAdapter.isTextNode(c))+ .map((c) => (c as DefaultTreeAdapterMap["textNode"]).value)+ .join("");+ texts.push(textContent);+ }+ if (defaultTreeAdapter.isElementNode(child)) {+ walk(child);+ }+ }+ };+ walk(documentFragment);+ return texts;+};++/**+ * Get class names from a parse5 element's class attribute.+ */+const getElementClasses = (element: ElementNode): Set<string> => {+ const classAttr = element.attrs?.find((a) => a.name === "class");+ if (!classAttr) {+ return new Set();+ }+ return new Set(classAttr.value.split(/\s+/).filter(Boolean));+};++/**+ * Get the parent element node, or undefined if the parent is a document/fragment.+ */+const getParentElementNode = (node: ElementNode): ElementNode | undefined => {+ const parent = node.parentNode;+ return parent && defaultTreeAdapter.isElementNode(parent)+ ? parent+ : undefined;+};++/**+ * Check whether an element satisfies the ancestor constraints of a nested+ * selector. Walks up the parse5 tree from the element checking each ancestor+ * constraint from innermost to outermost.+ */+const elementMatchesAncestors = (+ element: ElementNode,+ ancestors: NonNullable<ParsedClassSelector["ancestors"]>+): boolean => {+ let current: ElementNode | undefined = getParentElementNode(element);++ // Check ancestors from innermost (last in array) to outermost (first)+ for (let i = ancestors.length - 1; i >= 0; i--) {+ const { classNames: requiredClasses, combinator } = ancestors[i];+ const requiredSet = new Set(requiredClasses);++ if (combinator === "child") {+ // Direct parent must match+ if (!current) {+ return false;+ }+ if (!setIsSubsetOf(requiredSet, getElementClasses(current))) {+ return false;+ }+ current = getParentElementNode(current);+ } else {+ // "descendant" — search up the tree for any matching ancestor+ let found = false;+ while (current) {+ if (setIsSubsetOf(requiredSet, getElementClasses(current))) {+ current = getParentElementNode(current);+ found = true;+ break;+ }+ current = getParentElementNode(current);+ }+ if (!found) {+ return false;+ }+ }+ }++ return true;+};++type NestedClassRule = {+ parsed: ParsedClassSelector;+ decls: ParsedStyleDecl[];+ selector: string;+};++/**+ * From a list of parsed style declarations, determine which selectors are+ * class-based selectors (extractable as tokens) and which are not.+ *+ * Simple class selectors go into classRules. Nested selectors (with+ * descendant/child combinators) go into nestedClassRules for tree matching.+ */+const classifyRules = (+ decls: ParsedStyleDecl[]+): {+ classRules: Map<string, ParsedStyleDecl[]>;+ nestedClassRules: Map<string, NestedClassRule>;+ hasNonClassRules: boolean;+} => {+ const classRules = new Map<string, ParsedStyleDecl[]>();+ const nestedClassRules = new Map<string, NestedClassRule>();+ let hasNonClassRules = false;++ for (const decl of decls) {+ const parsed = parseClassBasedSelector(decl.selector);+ if (parsed !== undefined) {+ const selectorState = parsed.states?.[0];+ const effectiveDecl = selectorState+ ? { ...decl, state: decl.state ?? selectorState }+ : decl;++ if (parsed.ancestors && parsed.ancestors.length > 0) {+ // Nested selector — needs tree matching+ let entry = nestedClassRules.get(parsed.tokenName);+ if (!entry) {+ entry = { parsed, decls: [], selector: decl.selector };+ nestedClassRules.set(parsed.tokenName, entry);+ }+ entry.decls.push(effectiveDecl);+ } else {+ // Simple class selector+ let rules = classRules.get(parsed.tokenName);+ if (!rules) {+ rules = [];+ classRules.set(parsed.tokenName, rules);+ }+ rules.push(effectiveDecl);+ }+ } else {+ hasNonClassRules = true;+ }+ }+ return { classRules, nestedClassRules, hasNonClassRules };+};++/**+ * Build the leftover CSS (non-class rules) from the original style text.+ * We re-parse with css-tree and walk rules to classify them:+ * - Class-based selectors (simple and compound) are removed (extracted as tokens)+ * - Non-class selectors are kept as leftover+ * - For mixed comma-separated selectors (.card, div {}), only the non-class+ * portions are kept+ */+const buildLeftoverCss = (cssText: string): string => {+ const ast = csstree.parse(cssText);+ const parts: string[] = [];++ /** Re-use parseClassBasedSelector as single source of truth */+ const isClassBasedSelector = (selector: csstree.CssNode): boolean =>+ selector.type === "Selector" &&+ parseClassBasedSelector(csstree.generate(selector)) !== undefined;++ /**+ * Process a Rule: if all selectors are class-based, skip entirely.+ * If none are, keep entirely. If mixed, keep only non-class selectors.+ */+ const getLeftoverRule = (node: csstree.Rule): string | undefined => {+ if (node.prelude?.type !== "SelectorList") {+ return csstree.generate(node);+ }+ const selectors = node.prelude.children.toArray();+ const nonClassSelectors = selectors.filter(+ (sel) => !isClassBasedSelector(sel)+ );+ if (nonClassSelectors.length === selectors.length) {+ // No class selectors found — keep entire rule+ return csstree.generate(node);+ }+ if (nonClassSelectors.length === 0) {+ // All selectors are class-based — skip entirely+ return undefined;+ }+ // Mixed: rebuild rule with only non-class selectors+ const selectorStrs = nonClassSelectors.map((sel) => csstree.generate(sel));+ const body = node.block ? csstree.generate(node.block) : "{}";+ return `${selectorStrs.join(",")}${body}`;+ };++ // Walk only top-level children of the stylesheet+ if (ast.type === "StyleSheet") {+ for (const node of ast.children) {+ if (node.type === "Rule") {+ const leftover = getLeftoverRule(node);+ if (leftover) {+ parts.push(leftover);+ }+ } else if (node.type === "Atrule") {+ if (node.name === "media") {+ // Check if this media query is unsupported by parseCss (print, non-px units)+ // If so, keep the entire block as leftover+ let isUnsupportedMedia = false;+ if (node.prelude) {+ csstree.walk(node.prelude, (walkNode) => {+ if (+ walkNode.type === "MediaQuery" &&+ walkNode.mediaType === "print"+ ) {+ isUnsupportedMedia = true;+ }+ });+ }+ if (isUnsupportedMedia) {+ parts.push(csstree.generate(node));+ } else {+ // For @media, check children — keep non-class rules+ const leftoverRules: string[] = [];+ if (node.block) {+ for (const child of node.block.children) {+ if (child.type === "Rule") {+ const leftover = getLeftoverRule(child);+ if (leftover) {+ leftoverRules.push(leftover);+ }+ } else if (child.type === "Atrule") {+ // Nested at-rule within @media — keep if it contains non-class rules+ const nestedLeftover = collectNonClassFromAtrule(+ child,+ getLeftoverRule+ );+ if (nestedLeftover) {+ leftoverRules.push(nestedLeftover);+ }+ }+ }+ }+ if (leftoverRules.length > 0) {+ const prelude = node.prelude+ ? csstree.generate(node.prelude)+ : "";+ parts.push(`@media ${prelude}{${leftoverRules.join("")}}`);+ }+ }+ } else {+ // @keyframes, @font-face, @supports, etc. — always keep+ parts.push(csstree.generate(node));+ }+ }+ }+ }+ return parts.join("");+};++const collectNonClassFromAtrule = (+ node: csstree.Atrule,+ getLeftoverRule: (rule: csstree.Rule) => string | undefined+): string | undefined => {+ if (node.name === "media" && node.block) {+ // Check if this nested @media is unsupported (e.g. print)+ let isUnsupportedMedia = false;+ if (node.prelude) {+ csstree.walk(node.prelude, (walkNode) => {+ if (walkNode.type === "MediaQuery" && walkNode.mediaType === "print") {+ isUnsupportedMedia = true;+ }+ });+ }+ if (isUnsupportedMedia) {+ return csstree.generate(node);+ }+ const leftoverRules: string[] = [];+ for (const child of node.block.children) {+ if (child.type === "Rule") {+ const leftover = getLeftoverRule(child);+ if (leftover) {+ leftoverRules.push(leftover);+ }+ } else if (child.type === "Atrule") {+ const nested = collectNonClassFromAtrule(child, getLeftoverRule);+ if (nested) {+ leftoverRules.push(nested);+ }+ }+ }+ if (leftoverRules.length > 0) {+ const prelude = node.prelude ? csstree.generate(node.prelude) : "";+ return `@media ${prelude}{${leftoverRules.join("")}}`;+ }+ return undefined;+ }+ // Non-media at-rules (like @supports nested in @media) — always keep+ return csstree.generate(node);+};++/**+ * Resolve overlapping range breakpoints by adjusting maxWidth values.+ * Range breakpoints are those that have both minWidth and maxWidth.+ * When ranges overlap, the earlier range's maxWidth is adjusted to+ * be less than the next range's minWidth.+ */+const resolveOverlappingBreakpoints = (breakpoints: Breakpoint[]) => {+ // Collect all breakpoints that have both minWidth and maxWidth (range breakpoints)+ // plus simple minWidth-only and maxWidth-only breakpoints+ const widthBreakpoints = breakpoints.filter(+ (b) =>+ b.condition === undefined &&+ (b.minWidth !== undefined || b.maxWidth !== undefined)+ );++ if (widthBreakpoints.length < 2) {+ return;+ }++ // Sort range breakpoints by minWidth+ const rangeBreakpoints = widthBreakpoints+ .filter((b) => b.minWidth !== undefined && b.maxWidth !== undefined)+ .sort((a, b) => a.minWidth! - b.minWidth!);++ // Also consider simple min-width breakpoints as potential overlap targets+ const minOnlyBreakpoints = widthBreakpoints.filter(+ (b) => b.minWidth !== undefined && b.maxWidth === undefined+ );+ const maxOnlyBreakpoints = widthBreakpoints.filter(+ (b) => b.maxWidth !== undefined && b.minWidth === undefined+ );++ // Adjust range vs range overlaps+ for (let i = 0; i < rangeBreakpoints.length - 1; i++) {+ const current = rangeBreakpoints[i];+ const next = rangeBreakpoints[i + 1];+ if (current.maxWidth! >= next.minWidth!) {+ current.maxWidth = next.minWidth! - 1;+ }+ }++ // Adjust range vs min-width-only overlaps+ for (const range of rangeBreakpoints) {+ for (const minBp of minOnlyBreakpoints) {+ if (range.maxWidth! >= minBp.minWidth!) {+ range.maxWidth = minBp.minWidth! - 1;+ }+ }+ }++ // Adjust range vs max-width-only overlaps+ for (const range of rangeBreakpoints) {+ for (const maxBp of maxOnlyBreakpoints) {+ if (range.minWidth! <= maxBp.maxWidth!) {+ range.minWidth = maxBp.maxWidth! + 1;+ }+ }+ }+};++export const generateFragmentFromHtml = (+ html: string+): WebstudioFragment & { skippedSelectors: string[] } => {const attributeTypes = getAttributeTypes();const instances = new Map<Instance["id"], Instance>();const styleSourceSelections: StyleSourceSelection[] = [];@@ -97,6 +465,43 @@ export const generateFragmentFromHtml = (html: string): WebstudioFragment => {return baseBreakpoint.id;};+ // Breakpoint deduplication by key — breakpoints use their own ID counter+ let lastBreakpointId = -1;+ const getNewBreakpointId = () => {+ lastBreakpointId += 1;+ return lastBreakpointId.toString();+ };+ const breakpointByKey = new Map<string, Breakpoint>();+ const getOrCreateBreakpoint = (parsed: {+ minWidth?: number;+ maxWidth?: number;+ condition?: string;+ }): string => {+ const key = JSON.stringify(parsed);+ let bp = breakpointByKey.get(key);+ if (!bp) {+ const id = getNewBreakpointId();+ let label: string;+ if (parsed.condition) {+ // e.g. "prefers-color-scheme:dark" → "Prefers Color Scheme Dark"+ label = capitalCase(parsed.condition);+ } else {+ const parts: string[] = [];+ if (parsed.minWidth !== undefined) {+ parts.push(`≥ ${parsed.minWidth}px`);+ }+ if (parsed.maxWidth !== undefined) {+ parts.push(`≤ ${parsed.maxWidth}px`);+ }+ label = parts.join(" and ");+ }+ bp = { id, label, ...parsed };+ breakpointByKey.set(key, bp);+ breakpoints.push(bp);+ }+ return bp.id;+ };+const createLocalStyles = (instanceId: string, css: string) => {const localStyleSource: StyleSource = {type: "local",@@ -114,16 +519,85 @@ export const generateFragmentFromHtml = (html: string): WebstudioFragment => {}};- const convertElementToInstance = (node: ElementNode) => {+ // ---- Pre-parse all <style> tags to extract class-based tokens ----+ const documentFragment = parseFragment(html, {+ scriptingEnabled: false,+ sourceCodeLocationInfo: true,+ });++ // Collect style tag texts and their nodes+ const styleTexts = collectStyleTexts(documentFragment);+ const allCssText = styleTexts.join("\n");++ // Parse all CSS and classify rules+ const allDecls = parseCss(allCssText);+ const { classRules, nestedClassRules } = classifyRules(allDecls);++ // Track which class names are used by elements — IDs will be assigned later+ const usedClassNames = new Set<string>();+ // Track which nested token names were resolved against the tree+ const usedNestedTokenNames = new Set<string>();++ // Classify each style tag: "all-class" (skip embed), "no-class" (keep original),+ // "mixed" (regenerate leftover), or "empty" (skip)+ type StyleTagAction =+ | { type: "skip" }+ | { type: "keep-original" }+ | { type: "leftover"; css: string };++ const styleTagActions: StyleTagAction[] = [];+ for (const text of styleTexts) {+ if (spaceRegex.test(text) || text.length === 0) {+ styleTagActions.push({ type: "skip" });+ continue;+ }+ const parsedDecls = parseCss(text);+ const {+ classRules: tagClassRules,+ nestedClassRules: tagNestedRules,+ hasNonClassRules: tagHasNonClass,+ } = classifyRules(parsedDecls);+if (- (node.tagName === "script" || node.tagName === "style") &&- node.sourceCodeLocation+ parsedDecls.length === 0 &&+ tagClassRules.size === 0 &&+ tagNestedRules.size === 0) {+ // Unparseable CSS — keep original+ styleTagActions.push({ type: "keep-original" });+ } else if (tagClassRules.size === 0 && tagNestedRules.size === 0) {+ // Only non-class rules — keep original+ styleTagActions.push({ type: "keep-original" });+ } else if (!tagHasNonClass) {+ // Only class rules — also check for unsupported media like @media print+ const leftover = buildLeftoverCss(text);+ if (leftover.length > 0) {+ styleTagActions.push({ type: "leftover", css: leftover });+ } else {+ styleTagActions.push({ type: "skip" });+ }+ } else {+ // Mixed — regenerate leftover+ const leftover = buildLeftoverCss(text);+ if (leftover.length > 0) {+ styleTagActions.push({ type: "leftover", css: leftover });+ } else {+ styleTagActions.push({ type: "skip" });+ }+ }+ }++ let styleTagIndex = 0;++ // Map of instanceId → resolved class names (for post-processing token assignments)+ const instanceTokenClasses = new Map<string, string[]>();++ const convertElementToInstance = (node: ElementNode) => {+ if (node.tagName === "script" && node.sourceCodeLocation) {const { startCol, startOffset, endOffset } = node.sourceCodeLocation;const indent = startCol - 1;const htmlFragment = html.slice(startOffset, endOffset)- // try to preserve indentation.split("\n").map((line, index) => {if (index > 0 && /^\s+$/.test(line.slice(0, indent))) {@@ -136,19 +610,17 @@ export const generateFragmentFromHtml = (html: string): WebstudioFragment => {type: "instance",id: getNewId(),component: "HtmlEmbed",- label: capitalCase(node.tagName),+ label: "Script",children: [],};instances.set(instance.id, instance);- if (node.tagName === "script") {- props.push({- id: `${instance.id}:clientOnly`,- instanceId: instance.id,- name: "clientOnly",- type: "boolean",- value: true,- });- }+ props.push({+ id: `${instance.id}:clientOnly`,+ instanceId: instance.id,+ name: "clientOnly",+ type: "boolean",+ value: true,+ });props.push({id: `${instance.id}:code`,instanceId: instance.id,@@ -158,6 +630,64 @@ export const generateFragmentFromHtml = (html: string): WebstudioFragment => {});return { type: "id" as const, value: instance.id };}+ if (node.tagName === "style" && node.sourceCodeLocation) {+ const tagIdx = styleTagIndex++;+ const action = styleTagActions[tagIdx] ?? { type: "skip" };++ if (action.type === "keep-original") {+ // Preserve original formatting — use original HTML fragment+ const { startCol, startOffset, endOffset } = node.sourceCodeLocation;+ const indent = startCol - 1;+ const htmlFragment = html+ .slice(startOffset, endOffset)+ .split("\n")+ .map((line, index) => {+ if (index > 0 && /^\s+$/.test(line.slice(0, indent))) {+ return line.slice(indent);+ }+ return line;+ })+ .join("\n");+ const instance: Instance = {+ type: "instance",+ id: getNewId(),+ component: "HtmlEmbed",+ label: "Style",+ children: [],+ };+ instances.set(instance.id, instance);+ props.push({+ id: `${instance.id}:code`,+ instanceId: instance.id,+ name: "code",+ type: "string",+ value: htmlFragment,+ });+ return { type: "id" as const, value: instance.id };+ }++ if (action.type === "leftover") {+ const instance: Instance = {+ type: "instance",+ id: getNewId(),+ component: "HtmlEmbed",+ label: "Style",+ children: [],+ };+ instances.set(instance.id, instance);+ props.push({+ id: `${instance.id}:code`,+ instanceId: instance.id,+ name: "code",+ type: "string",+ value: `<style>${action.css}</style>`,+ });+ return { type: "id" as const, value: instance.id };+ }++ // action.type === "skip" — all rules were class rules (or empty)+ return undefined;+ }if (!tags.includes(node.tagName)) {return;}@@ -193,6 +723,84 @@ export const generateFragmentFromHtml = (html: string): WebstudioFragment => {createLocalStyles(instanceId, attr.value);continue;}+ // resolve class attribute against class rules from style tags+ if (+ attr.name === "class" &&+ (classRules.size > 0 || nestedClassRules.size > 0)+ ) {+ const classNames = attr.value.split(/\s+/).filter(Boolean);+ const resolvedTokenNames: string[] = [];+ const unresolvedClasses: string[] = [];++ // First: match individual class names as simple tokens+ for (const className of classNames) {+ if (classRules.has(className)) {+ resolvedTokenNames.push(className);+ usedClassNames.add(className);+ } else {+ unresolvedClasses.push(className);+ }+ }++ // Second: match compound class combinations (e.g., class="card active"+ // matches token "card.active" from .card.active {} selector)+ if (classNames.length >= 2) {+ const classSet = new Set(classNames);+ for (const tokenName of classRules.keys()) {+ if (!tokenName.includes(".")) {+ continue;+ }+ const parts = tokenName.split(".");+ if (parts.every((part) => classSet.has(part))) {+ resolvedTokenNames.push(tokenName);+ usedClassNames.add(tokenName);+ }+ }+ }++ // Third: match nested class rules (e.g., .card .title)+ if (nestedClassRules.size > 0) {+ const classSet = new Set(classNames);+ for (const [tokenName, { parsed }] of nestedClassRules) {+ const targetRequired = new Set(parsed.classNames);+ if (!setIsSubsetOf(targetRequired, classSet)) {+ continue;+ }+ if (+ parsed.ancestors &&+ !elementMatchesAncestors(node, parsed.ancestors)+ ) {+ continue;+ }+ resolvedTokenNames.push(tokenName);+ usedNestedTokenNames.add(tokenName);+ // Remove matched target class names from unresolved+ for (const cn of parsed.classNames) {+ const idx = unresolvedClasses.indexOf(cn);+ if (idx >= 0) {+ unresolvedClasses.splice(idx, 1);+ }+ }+ }+ }++ // Token style source selections will be created after all instances+ if (resolvedTokenNames.length > 0) {+ // Store the resolved token names for post-processing+ instanceTokenClasses.set(instanceId, resolvedTokenNames);+ }+ // Keep unresolved class names as class prop+ if (unresolvedClasses.length > 0) {+ props.push({+ id,+ instanceId,+ name: "class",+ type: "string",+ value: unresolvedClasses.join(" "),+ });+ }+ continue;+ }// selected option is represented as fake value attribute on select elementif (node.tagName === "option" && attr.name === "selected") {continue;@@ -317,10 +925,6 @@ export const generateFragmentFromHtml = (html: string): WebstudioFragment => {return { type: "id" as const, value: instance.id };};- const documentFragment = parseFragment(html, {- scriptingEnabled: false,- sourceCodeLocationInfo: true,- });const children: Instance["children"] = [];for (const childNode of documentFragment.childNodes) {if (defaultTreeAdapter.isElementNode(childNode)) {@@ -330,6 +934,119 @@ export const generateFragmentFromHtml = (html: string): WebstudioFragment => {}}}++ // ---- Post-processing: create token style sources and styles ----+ // Now that all instances have been created and IDs assigned,+ // create token style sources (using the shared getNewId counter)+ // in the order that matches template rendering (instances first, then tokens)++ // Ensure all simple class rules become tokens, even when no elements reference them+ // (e.g. pasting just a <style> tag without HTML elements)+ for (const className of classRules.keys()) {+ usedClassNames.add(className);+ }+ // Add resolved nested tokens+ for (const tokenName of usedNestedTokenNames) {+ usedClassNames.add(tokenName);+ }++ const tokenIdMap = new Map<string, string>(); // className → styleSourceId++ for (const className of usedClassNames) {+ const styleSourceId = getNewId();+ tokenIdMap.set(className, styleSourceId);+ styleSources.push({+ type: "token",+ id: styleSourceId,+ name: className,+ });++ const decls =+ classRules.get(className) ?? nestedClassRules.get(className)?.decls;+ if (decls) {+ for (const decl of decls) {+ let breakpointId: string;+ if (decl.breakpoint) {+ const parsed = parseMediaQuery(decl.breakpoint);+ if (parsed === undefined) {+ continue;+ }+ const hasWidth =+ parsed.minWidth !== undefined || parsed.maxWidth !== undefined;+ const hasCondition = parsed.condition !== undefined;+ if (hasCondition) {+ const conditionParts: string[] = [];+ if (parsed.minWidth !== undefined) {+ conditionParts.push(`min-width:${parsed.minWidth}px`);+ }+ if (parsed.maxWidth !== undefined) {+ conditionParts.push(`max-width:${parsed.maxWidth}px`);+ }+ // hasCondition guarantees parsed.condition is defined+ conditionParts.push(parsed.condition as string);+ breakpointId = getOrCreateBreakpoint({+ condition: conditionParts.join(" and "),+ });+ } else if (hasWidth) {+ breakpointId = getOrCreateBreakpoint({+ ...(parsed.minWidth !== undefined+ ? { minWidth: parsed.minWidth }+ : {}),+ ...(parsed.maxWidth !== undefined+ ? { maxWidth: parsed.maxWidth }+ : {}),+ });+ } else {+ continue;+ }+ } else {+ breakpointId = getBaseBreakpointId();+ }+ styles.push({+ styleSourceId,+ breakpointId,+ property: camelCaseProperty(decl.property),+ value: decl.value,+ ...(decl.state ? { state: decl.state } : {}),+ });+ }+ }+ }++ // Create style source selections for instances that use tokens+ const selectionsByInstance = new Map(+ styleSourceSelections.map((sel) => [sel.instanceId, sel])+ );+ for (const [instanceId, classNames] of instanceTokenClasses) {+ const tokenIds = classNames+ .map((name) => tokenIdMap.get(name))+ .filter((id): id is string => id !== undefined);+ if (tokenIds.length > 0) {+ const existingSelection = selectionsByInstance.get(instanceId);+ if (existingSelection) {+ existingSelection.values.push(...tokenIds);+ } else {+ const newSelection: StyleSourceSelection = {+ instanceId,+ values: [...tokenIds],+ };+ styleSourceSelections.push(newSelection);+ selectionsByInstance.set(instanceId, newSelection);+ }+ }+ }++ // Resolve overlapping breakpoints+ resolveOverlappingBreakpoints(breakpoints);++ // Collect skipped nested selectors (no matching elements in the pasted HTML)+ const skippedSelectors: string[] = [];+ for (const [tokenName, { selector }] of nestedClassRules) {+ if (!usedNestedTokenNames.has(tokenName)) {+ skippedSelectors.push(selector);+ }+ }+return {children,instances: Array.from(instances.values()),@@ -341,5 +1058,6 @@ export const generateFragmentFromHtml = (html: string): WebstudioFragment => {styles,breakpoints,assets: [],+ skippedSelectors,};};diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex cc99fd6e8a..7d028d6ccf 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -336,10 +336,28 @@ export const insertWebstudioFragmentAt = (insertable?: Insertable,conflictResolution?: ConflictResolution): boolean => {- // cannot insert empty fragment- if (fragment.children.length === 0) {+ const hasChildren = fragment.children.length > 0;+ const hasTokens = fragment.styleSources.length > 0;+ if (!hasChildren && !hasTokens) {return false;}+ // Tokens-only fragment: insert tokens/breakpoints/styles without instances+ if (!hasChildren && hasTokens) {+ const project = $project.get();+ if (project === undefined) {+ return false;+ }+ updateWebstudioData((data) => {+ insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: [],+ projectId: project.id,+ conflictResolution,+ });+ });+ return true;+ }const project = $project.get();insertable = findClosestInsertable(fragment, insertable) ?? insertable;if (project === undefined || insertable === undefined) {diff --git a/apps/builder/app/shared/tailwind/tailwind.ts b/apps/builder/app/shared/tailwind/tailwind.tsindex 3d364ec2c7..f2652b92fc 100644--- a/apps/builder/app/shared/tailwind/tailwind.ts+++ b/apps/builder/app/shared/tailwind/tailwind.ts@@ -152,6 +152,18 @@ const adaptBreakpoints = (const mediaQuery = styleDecl.breakpoint? parseMediaQuery(styleDecl.breakpoint): undefined;+ // Skip condition-only breakpoints (e.g. dark mode prefers-color-scheme)+ // and combined min+max width breakpoints (e.g. md:max-xl:)+ // @todo support composite breakpoints by splitting into range-based breakpoints+ if (mediaQuery?.condition !== undefined) {+ continue;+ }+ if (+ mediaQuery?.minWidth !== undefined &&+ mediaQuery?.maxWidth !== undefined+ ) {+ continue;+ }if (mediaQuery?.minWidth) {mediaQuery.minWidth =tailwindToWebstudioMappings[mediaQuery.minWidth] ?? mediaQuery.minWidth;diff --git a/packages/css-data/src/parse-css.test.ts b/packages/css-data/src/parse-css.test.tsindex b85074fdb1..baf5d45385 100644--- a/packages/css-data/src/parse-css.test.ts+++ b/packages/css-data/src/parse-css.test.ts@@ -1,5 +1,10 @@import { describe, expect, test } from "vitest";-import { camelCaseProperty, parseCss, parseMediaQuery } from "./parse-css";+import {+ camelCaseProperty,+ parseClassBasedSelector,+ parseCss,+ parseMediaQuery,+} from "./parse-css";describe("Parse CSS", () => {test("longhand property name with keyword value", () => {@@ -764,7 +769,7 @@ test("support only screen media type", () => {]);});-test("ignore unsupported media queries", () => {+test("parse previously unsupported media queries", () => {expect(parseCss(`a {@@ -797,43 +802,721 @@ test("ignore unsupported media queries", () => {property: "color",value: { type: "keyword", value: "red" },},+ {+ breakpoint: "(min-width:768px) and (max-width:1024px)",+ selector: "b",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ {+ breakpoint: "(min-width:768px) and (max-width:1024px)",+ selector: "c",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ {+ breakpoint: "(hover:hover)",+ selector: "d",+ property: "color",+ value: { type: "keyword", value: "yellow" },+ },+ // @media (min-width: 40rem) is still ignored (non-px unit)+ ]);+});++test("parse nested media queries by flattening", () => {+ expect(+ parseCss(`+ @media (min-width: 768px) {+ a {+ color: green;+ }+ @media (max-width: 1024px) {+ a {+ color: red;+ }+ }+ }+ `)+ ).toEqual([+ {+ breakpoint: "(min-width:768px)",+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ {+ breakpoint: "(min-width:768px) and (max-width:1024px)",+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("ignore unsupported at rules", () => {+ expect(+ parseCss(`+ a {+ color: red;+ }+ @supports (display: grid) {+ b {+ color: green;+ }+ }+ `)+ ).toEqual([+ {+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("parse condition-based media queries", () => {+ expect(+ parseCss(`+ @media (prefers-color-scheme: dark) {+ a {+ color: white;+ }+ }+ `)+ ).toEqual([+ {+ breakpoint: `(prefers-color-scheme:dark)`,+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "white" },+ },+ ]);+});++test("parse hover media feature", () => {+ expect(+ parseCss(`+ @media (hover: hover) {+ a {+ color: blue;+ }+ }+ `)+ ).toEqual([+ {+ breakpoint: `(hover:hover)`,+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ]);+});++test("parse orientation media feature", () => {+ expect(+ parseCss(`+ @media (orientation: portrait) {+ a {+ color: green;+ }+ }+ `)+ ).toEqual([+ {+ breakpoint: `(orientation:portrait)`,+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ ]);+});++test("parse prefers-reduced-motion media feature", () => {+ expect(+ parseCss(`+ @media (prefers-reduced-motion: reduce) {+ a {+ color: red;+ }+ }+ `)+ ).toEqual([+ {+ breakpoint: `(prefers-reduced-motion:reduce)`,+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("parse combined min-width and max-width media query", () => {+ expect(+ parseCss(`+ @media (min-width: 768px) and (max-width: 1024px) {+ a {+ color: green;+ }+ }+ `)+ ).toEqual([+ {+ breakpoint: `(min-width:768px) and (max-width:1024px)`,+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ ]);+});++test("parse min-width combined with condition feature", () => {+ expect(+ parseCss(`+ @media (min-width: 768px) and (orientation: landscape) {+ a {+ color: green;+ }+ }+ `)+ ).toEqual([+ {+ breakpoint: `(min-width:768px) and (orientation:landscape)`,+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ ]);+});++test("parse multiple condition features in media query", () => {+ expect(+ parseCss(`+ @media (prefers-color-scheme: dark) and (prefers-contrast: more) {+ a {+ color: white;+ }+ }+ `)+ ).toEqual([+ {+ breakpoint: `(prefers-color-scheme:dark) and (prefers-contrast:more)`,+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "white" },+ },+ ]);+});++test("parse nested media queries", () => {+ expect(+ parseCss(`+ @media (min-width: 768px) {+ a {+ color: green;+ }+ @media (max-width: 1024px) {+ a {+ color: red;+ }+ }+ }+ `)+ ).toEqual([+ {+ breakpoint: "(min-width:768px)",+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ {+ breakpoint: "(min-width:768px) and (max-width:1024px)",+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("parse nested media with condition inside width", () => {+ expect(+ parseCss(`+ @media (min-width: 768px) {+ a {+ color: green;+ }+ @media (prefers-color-scheme: dark) {+ a {+ color: white;+ }+ }+ }+ `)+ ).toEqual([+ {+ breakpoint: "(min-width:768px)",+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ {+ breakpoint: "(min-width:768px) and (prefers-color-scheme:dark)",+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "white" },+ },+ ]);+});++test("parse deeply nested media queries", () => {+ expect(+ parseCss(`+ @media (min-width: 768px) {+ @media (orientation: landscape) {+ @media (hover: hover) {+ a {+ color: red;+ }+ }+ }+ }+ `)+ ).toEqual([+ {+ breakpoint:+ "(min-width:768px) and (orientation:landscape) and (hover:hover)",+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("parse condition and base styles together", () => {+ expect(+ parseCss(`+ a {+ color: black;+ }+ @media (prefers-color-scheme: dark) {+ a {+ color: white;+ }+ }+ `)+ ).toEqual([+ {+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "black" },+ },+ {+ breakpoint: "(prefers-color-scheme:dark)",+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "white" },+ },+ ]);+});++test("still ignore non-px units in media queries", () => {+ expect(+ parseCss(`+ a {+ color: red;+ }+ @media (min-width: 40rem) {+ a {+ color: green;+ }+ }+ `)+ ).toEqual([+ {+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("still ignore @media print", () => {+ expect(+ parseCss(`+ a {+ color: red;+ }+ @media print {+ a {+ color: black;+ }+ }+ `)+ ).toEqual([+ {+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("still ignore @supports", () => {+ expect(+ parseCss(`+ a {+ color: red;+ }+ @supports (display: grid) {+ a {+ color: green;+ }+ }+ `)+ ).toEqual([+ {+ selector: "a",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("parse &:pseudo-classes as state", () => {+ expect(+ parseCss(`+ &:hover {+ color: red;+ }+ `)+ ).toEqual([+ {+ selector: "",+ state: ":hover",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("parse &[attribute=selector] as state", () => {+ expect(+ parseCss(`+ &[data-state=active] {+ color: red;+ }+ `)+ ).toEqual([+ {+ selector: "",+ state: "[data-state=active]",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++// ---- Selector types ----++test("parse class selector with pseudo-class", () => {+ expect(parseCss(`.card:hover { color: red }`)).toEqual([+ {+ selector: ".card",+ state: ":hover",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("parse class selector with pseudo-element", () => {+ expect(parseCss(`.card::before { content: none }`)).toEqual([+ {+ selector: ".card",+ state: "::before",+ property: "content",+ value: { type: "keyword", value: "none" },+ },+ ]);+});++test("parse compound class selector", () => {+ expect(parseCss(`.card.active { opacity: 1 }`)).toEqual([+ {+ selector: ".card.active",+ property: "opacity",+ value: { type: "unit", unit: "number", value: 1 },+ },+ ]);+});++test("parse compound class selector with pseudo-class", () => {+ expect(parseCss(`.card.active:hover { opacity: 0.5 }`)).toEqual([+ {+ selector: ".card.active",+ state: ":hover",+ property: "opacity",+ value: { type: "unit", unit: "number", value: 0.5 },+ },+ ]);+});++test("parse class with attribute selector", () => {+ expect(parseCss(`.btn[disabled] { opacity: 0.5 }`)).toEqual([+ {+ selector: ".btn[disabled]",+ property: "opacity",+ value: { type: "unit", unit: "number", value: 0.5 },+ },+ ]);+});++test("parse class + attribute + pseudo-class", () => {+ expect(parseCss(`.btn[disabled]:focus { outline: none }`)).toEqual([+ {+ selector: ".btn[disabled]",+ state: ":focus",+ property: "outline-width",+ value: { type: "keyword", value: "medium" },+ },+ {+ selector: ".btn[disabled]",+ state: ":focus",+ property: "outline-style",+ value: { type: "keyword", value: "none" },+ },+ {+ selector: ".btn[disabled]",+ state: ":focus",+ property: "outline-color",+ value: { type: "keyword", value: "currentcolor" },+ },+ ]);+});++test("parse ID selector", () => {+ expect(parseCss(`#hero { display: flex }`)).toEqual([+ {+ selector: "#hero",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ ]);+});++test("parse element + class compound selector", () => {+ expect(parseCss(`div.card { display: flex }`)).toEqual([+ {+ selector: "div.card",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ ]);+});++test("parse sibling combinator +", () => {+ expect(parseCss(`.a + .b { color: red }`)).toEqual([+ {+ selector: ".a + .b",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("parse general sibling combinator ~", () => {+ expect(parseCss(`.a ~ .b { color: red }`)).toEqual([+ {+ selector: ".a ~ .b",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("parse :root as pseudo-class selector", () => {+ expect(parseCss(`:root { --color: blue }`)).toEqual([+ {+ selector: ":root",+ property: "--color",+ value: { type: "unparsed", value: "blue" },+ },+ ]);+});++test("parse universal selector *", () => {+ expect(parseCss(`* { box-sizing: border-box }`)).toEqual([+ {+ selector: "*",+ property: "box-sizing",+ value: { type: "keyword", value: "border-box" },+ },+ ]);+});++test("parse &::pseudo-element as state", () => {+ expect(parseCss(`&::after { content: none }`)).toEqual([+ {+ selector: "",+ state: "::after",+ property: "content",+ value: { type: "keyword", value: "none" },+ },+ ]);+});++test("parse &:functional-pseudo as state", () => {+ expect(parseCss(`&:nth-child(2) { color: red }`)).toEqual([+ {+ selector: "",+ state: ":nth-child",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++// ---- Edge cases ----++test("parse empty string returns empty array", () => {+ expect(parseCss("")).toEqual([]);+});++test("parse malformed CSS returns empty array", () => {+ expect(parseCss("{{{{")).toEqual([]);+});++test("parse CSS with no declarations returns empty array", () => {+ expect(parseCss(".card {}")).toEqual([]);+});++test("parse multiple properties from one rule", () => {+ const result = parseCss(`.card { display: flex; color: red; opacity: 1 }`);+ expect(result).toEqual([+ {+ selector: ".card",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ {+ selector: ".card",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ selector: ".card",+ property: "opacity",+ value: { type: "unit", unit: "number", value: 1 },+ },+ ]);+});++test("parse comma-separated class selectors", () => {+ expect(parseCss(`.a, .b { color: red }`)).toEqual([+ {+ selector: ".a",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ {+ selector: ".b",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("parse comma-separated mixed selectors (class + element)", () => {+ expect(parseCss(`.card, div { display: flex }`)).toEqual([+ {+ selector: ".card",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },+ {+ selector: "div",+ property: "display",+ value: { type: "keyword", value: "flex" },+ },]);});-test("ignore nested media queries", () => {+test("parse comma-separated selectors with different states", () => {+ expect(parseCss(`.a:hover, .b:focus { color: blue }`)).toEqual([+ {+ selector: ".a",+ state: ":hover",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ {+ selector: ".b",+ state: ":focus",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ]);+});++// ---- At-rules not supported ----++test("ignore @keyframes", () => {expect(parseCss(`- @media (min-width: 768px) {- a {- color: green;- }- @media (max-width: 1024px) {- a {- color: red;- }+ .card { color: red }+ @keyframes fade { from { opacity: 1 } to { opacity: 0 } }+ `)+ ).toEqual([+ {+ selector: ".card",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("ignore @font-face", () => {+ expect(+ parseCss(`+ .card { color: red }+ @font-face { font-family: "Custom"; src: url(font.woff2); }+ `)+ ).toEqual([+ {+ selector: ".card",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);+});++test("ignore @supports nested inside @media", () => {+ expect(+ parseCss(`+ @media (min-width: 768px) {+ .card { color: green }+ @supports (display: grid) {+ .card { display: grid }}}`)).toEqual([{breakpoint: "(min-width:768px)",- selector: "a",+ selector: ".card",property: "color",value: { type: "keyword", value: "green" },},]);});-test("ignore unsupported at rules", () => {+// ---- Media query edge cases ----++test("parse bare screen media type as base query", () => {expect(parseCss(`- a {- color: red;- }- @supports (display: grid) {- b {- color: green;- }+ @media screen {+ a { color: red }}`)).toEqual([@@ -845,75 +1528,242 @@ test("ignore unsupported at rules", () => {]);});-test("parse &:pseudo-classes as state", () => {+test("ignore @media print with min-width", () => {expect(parseCss(`- &:hover {- color: red;+ @media print and (min-width: 768px) {+ a { color: black }+ }+ `)+ ).toEqual([]);+});++test("parse non-px units in non-width features are allowed", () => {+ expect(+ parseCss(`+ @media (min-resolution: 2dppx) {+ a { color: red }}`)).toEqual([{- selector: "",- state: ":hover",+ breakpoint: "(min-resolution:2dppx)",+ selector: "a",property: "color",value: { type: "keyword", value: "red" },},]);});-test("parse &[attribute=selector] as state", () => {+test("class selector inside media query preserves both breakpoint and selector", () => {expect(parseCss(`- &[data-state=active] {- color: red;+ @media (min-width: 640px) {+ .card:hover { color: blue }}`)).toEqual([{- selector: "",- state: "[data-state=active]",+ breakpoint: "(min-width:640px)",+ selector: ".card",+ state: ":hover",property: "color",- value: { type: "keyword", value: "red" },+ value: { type: "keyword", value: "blue" },},]);});-test("parse media query", () => {- expect(parseMediaQuery(`(min-width: 768px)`)).toEqual({- minWidth: 768,- });- expect(parseMediaQuery(`(max-width: 768px)`)).toEqual({- maxWidth: 768,+test("compound class inside media query", () => {+ expect(+ parseCss(`+ @media (max-width: 768px) {+ .card.featured { display: block }+ }+ `)+ ).toEqual([+ {+ breakpoint: "(max-width:768px)",+ selector: ".card.featured",+ property: "display",+ value: { type: "keyword", value: "block" },+ },+ ]);+});++test("nested media with non-px inner is rejected", () => {+ expect(+ parseCss(`+ @media (min-width: 768px) {+ @media (min-width: 40em) {+ a { color: red }+ }+ }+ `)+ ).toEqual([]);+});++test("nested media with print inner is rejected", () => {+ expect(+ parseCss(`+ @media (min-width: 768px) {+ @media print {+ a { color: red }+ }+ }+ `)+ ).toEqual([]);+});++describe("parseMediaQuery", () => {+ test("simple min-width", () => {+ expect(parseMediaQuery(`(min-width: 768px)`)).toEqual({+ minWidth: 768,+ });});- expect(parseMediaQuery(`(orientation: portrait)`)).toEqual({- condition: "orientation:portrait",++ test("simple max-width", () => {+ expect(parseMediaQuery(`(max-width: 768px)`)).toEqual({+ maxWidth: 768,+ });});- expect(parseMediaQuery(`(orientation: landscape)`)).toEqual({- condition: "orientation:landscape",++ test("orientation portrait condition", () => {+ expect(parseMediaQuery(`(orientation: portrait)`)).toEqual({+ condition: "orientation:portrait",+ });});- expect(parseMediaQuery(`(hover: hover)`)).toEqual({- condition: "hover:hover",++ test("orientation landscape condition", () => {+ expect(parseMediaQuery(`(orientation: landscape)`)).toEqual({+ condition: "orientation:landscape",+ });});- // Test whitespace normalization- expect(parseMediaQuery(`(orientation:portrait)`)).toEqual({- condition: "orientation:portrait",++ test("hover condition", () => {+ expect(parseMediaQuery(`(hover: hover)`)).toEqual({+ condition: "hover:hover",+ });});- expect(parseMediaQuery(`( orientation : portrait )`)).toEqual({- condition: "orientation:portrait",++ test("whitespace normalization", () => {+ expect(parseMediaQuery(`(orientation:portrait)`)).toEqual({+ condition: "orientation:portrait",+ });+ expect(parseMediaQuery(`( orientation : portrait )`)).toEqual({+ condition: "orientation:portrait",+ });});- // Test multiple conditions- expect(parseMediaQuery(`(orientation: portrait) and (hover: hover)`)).toEqual(- {++ test("multiple conditions", () => {+ expect(+ parseMediaQuery(`(orientation: portrait) and (hover: hover)`)+ ).toEqual({condition: "orientation:portrait and hover:hover",- }- );- // Test other media features- expect(parseMediaQuery(`(prefers-color-scheme: dark)`)).toEqual({- condition: "prefers-color-scheme:dark",+ });+ });++ test("prefers-color-scheme dark", () => {+ expect(parseMediaQuery(`(prefers-color-scheme: dark)`)).toEqual({+ condition: "prefers-color-scheme:dark",+ });+ });++ test("prefers-color-scheme light", () => {+ expect(parseMediaQuery(`(prefers-color-scheme: light)`)).toEqual({+ condition: "prefers-color-scheme:light",+ });+ });++ test("pointer coarse", () => {+ expect(parseMediaQuery(`(pointer: coarse)`)).toEqual({+ condition: "pointer:coarse",+ });+ });++ test("prefers-reduced-motion", () => {+ expect(parseMediaQuery(`(prefers-reduced-motion: reduce)`)).toEqual({+ condition: "prefers-reduced-motion:reduce",+ });+ });++ test("prefers-contrast", () => {+ expect(parseMediaQuery(`(prefers-contrast: more)`)).toEqual({+ condition: "prefers-contrast:more",+ });+ });++ test("display-mode", () => {+ expect(parseMediaQuery(`(display-mode: standalone)`)).toEqual({+ condition: "display-mode:standalone",+ });+ });++ test("any-hover", () => {+ expect(parseMediaQuery(`(any-hover: hover)`)).toEqual({+ condition: "any-hover:hover",+ });+ });++ test("any-pointer", () => {+ expect(parseMediaQuery(`(any-pointer: fine)`)).toEqual({+ condition: "any-pointer:fine",+ });+ });++ test("combined min-width and max-width", () => {+ expect(+ parseMediaQuery(`(min-width: 768px) and (max-width: 1024px)`)+ ).toEqual({+ minWidth: 768,+ maxWidth: 1024,+ });+ });++ test("combined max-width and min-width (reversed order)", () => {+ expect(+ parseMediaQuery(`(max-width: 1024px) and (min-width: 768px)`)+ ).toEqual({+ minWidth: 768,+ maxWidth: 1024,+ });+ });++ test("min-width combined with condition feature", () => {+ expect(+ parseMediaQuery(`(min-width: 768px) and (orientation: landscape)`)+ ).toEqual({+ minWidth: 768,+ condition: "orientation:landscape",+ });+ });++ test("max-width combined with condition feature", () => {+ expect(parseMediaQuery(`(max-width: 480px) and (hover: none)`)).toEqual({+ maxWidth: 480,+ condition: "hover:none",+ });+ });++ test("min-width, max-width, and condition feature combined", () => {+ expect(+ parseMediaQuery(+ `(min-width: 768px) and (max-width: 1024px) and (orientation: portrait)`+ )+ ).toEqual({+ minWidth: 768,+ maxWidth: 1024,+ condition: "orientation:portrait",+ });+ });++ test("returns undefined for non-px units", () => {+ expect(parseMediaQuery(`(min-width: 40rem)`)).toBeUndefined();+ expect(parseMediaQuery(`(min-width: 50em)`)).toBeUndefined();});- expect(parseMediaQuery(`(pointer: coarse)`)).toEqual({- condition: "pointer:coarse",++ test("returns undefined for media types without features", () => {+ expect(parseMediaQuery(`print`)).toBeUndefined();+ expect(parseMediaQuery(`screen`)).toBeUndefined();});});@@ -938,3 +1788,223 @@ test("camel case css property multiple times", () => {camelCaseProperty(camelCaseProperty("-moz-osx-font-smoothing"))).toEqual("MozOsxFontSmoothing");});++describe("parseClassBasedSelector", () => {+ test("simple class selector", () => {+ expect(parseClassBasedSelector(".card")).toEqual({+ tokenName: "card",+ classNames: ["card"],+ });+ });++ test("compound class selector", () => {+ expect(parseClassBasedSelector(".card.active")).toEqual({+ tokenName: "card.active",+ classNames: ["card", "active"],+ });+ });++ test("triple compound class selector", () => {+ expect(parseClassBasedSelector(".a.b.c")).toEqual({+ tokenName: "a.b.c",+ classNames: ["a", "b", "c"],+ });+ });++ test("class with attribute selector", () => {+ expect(parseClassBasedSelector(".btn[disabled]")).toEqual({+ tokenName: "btn",+ classNames: ["btn"],+ states: ["[disabled]"],+ });+ });++ test("compound class with attribute selector", () => {+ expect(parseClassBasedSelector(".card.active[open]")).toEqual({+ tokenName: "card.active",+ classNames: ["card", "active"],+ states: ["[open]"],+ });+ });++ test("rejects element selector", () => {+ expect(parseClassBasedSelector("div")).toBeUndefined();+ });++ test("rejects id selector", () => {+ expect(parseClassBasedSelector("#hero")).toBeUndefined();+ });++ test("rejects :root pseudo selector", () => {+ expect(parseClassBasedSelector(":root")).toBeUndefined();+ });++ test("descendant combinator: .card .inner", () => {+ expect(parseClassBasedSelector(".card .inner")).toEqual({+ tokenName: "card__inner",+ classNames: ["inner"],+ ancestors: [{ classNames: ["card"], combinator: "descendant" }],+ });+ });++ test("child combinator: .card>.inner", () => {+ expect(parseClassBasedSelector(".card>.inner")).toEqual({+ tokenName: "card__inner",+ classNames: ["inner"],+ ancestors: [{ classNames: ["card"], combinator: "child" }],+ });+ });++ test("rejects sibling combinator", () => {+ expect(parseClassBasedSelector(".a+.b")).toBeUndefined();+ });++ test("rejects general sibling combinator", () => {+ expect(parseClassBasedSelector(".a~.b")).toBeUndefined();+ });++ test("rejects universal selector", () => {+ expect(parseClassBasedSelector("*")).toBeUndefined();+ });++ test("rejects empty string", () => {+ expect(parseClassBasedSelector("")).toBeUndefined();+ });++ test("attribute selector with value", () => {+ expect(parseClassBasedSelector(".input[type=text]")).toEqual({+ tokenName: "input",+ classNames: ["input"],+ states: ["[type=text]"],+ });+ });++ test("class with :hover pseudo-class", () => {+ expect(parseClassBasedSelector(".card:hover")).toEqual({+ tokenName: "card",+ classNames: ["card"],+ states: [":hover"],+ });+ });++ test("class with ::before pseudo-element", () => {+ expect(parseClassBasedSelector(".card::before")).toEqual({+ tokenName: "card",+ classNames: ["card"],+ states: ["::before"],+ });+ });++ test("class with functional pseudo-class :nth-child(2n+1)", () => {+ expect(parseClassBasedSelector(".item:nth-child(2n+1)")).toEqual({+ tokenName: "item",+ classNames: ["item"],+ states: [":nth-child(2n+1)"],+ });+ });++ test("class with multiple states: attribute + pseudo", () => {+ expect(parseClassBasedSelector(".btn[disabled]:hover")).toEqual({+ tokenName: "btn",+ classNames: ["btn"],+ states: ["[disabled]", ":hover"],+ });+ });++ test("compound class with pseudo-class and pseudo-element", () => {+ expect(parseClassBasedSelector(".card.active:hover::after")).toEqual({+ tokenName: "card.active",+ classNames: ["card", "active"],+ states: [":hover", "::after"],+ });+ });++ test("class with multiple attribute selectors", () => {+ expect(parseClassBasedSelector(".input[type=text][required]")).toEqual({+ tokenName: "input",+ classNames: ["input"],+ states: ["[type=text]", "[required]"],+ });+ });++ test("class with :focus-within pseudo-class", () => {+ expect(parseClassBasedSelector(".form:focus-within")).toEqual({+ tokenName: "form",+ classNames: ["form"],+ states: [":focus-within"],+ });+ });++ test("rejects element.class (type selector prefix)", () => {+ expect(parseClassBasedSelector("div.card")).toBeUndefined();+ });++ test("rejects nesting selector &.class", () => {+ expect(parseClassBasedSelector("&.card")).toBeUndefined();+ });++ // Nested selector tests+ test("multiple ancestors: .a .b .c", () => {+ expect(parseClassBasedSelector(".a .b .c")).toEqual({+ tokenName: "a__b__c",+ classNames: ["c"],+ ancestors: [+ { classNames: ["a"], combinator: "descendant" },+ { classNames: ["b"], combinator: "descendant" },+ ],+ });+ });++ test("compound segments in nested: .card.active .title.bold", () => {+ expect(parseClassBasedSelector(".card.active .title.bold")).toEqual({+ tokenName: "card.active__title.bold",+ classNames: ["title", "bold"],+ ancestors: [{ classNames: ["card", "active"], combinator: "descendant" }],+ });+ });++ test("mixed combinators: .a .b > .c", () => {+ expect(parseClassBasedSelector(".a .b > .c")).toEqual({+ tokenName: "a__b__c",+ classNames: ["c"],+ ancestors: [+ { classNames: ["a"], combinator: "descendant" },+ { classNames: ["b"], combinator: "child" },+ ],+ });+ });++ test("nested with state on target: .card > .title:hover", () => {+ expect(parseClassBasedSelector(".card > .title:hover")).toEqual({+ tokenName: "card__title",+ classNames: ["title"],+ states: [":hover"],+ ancestors: [{ classNames: ["card"], combinator: "child" }],+ });+ });++ test("nested with pseudo-element: .card .title::before", () => {+ expect(parseClassBasedSelector(".card .title::before")).toEqual({+ tokenName: "card__title",+ classNames: ["title"],+ states: ["::before"],+ ancestors: [{ classNames: ["card"], combinator: "descendant" }],+ });+ });++ test("rejects type selector in ancestor: h1 .card", () => {+ expect(parseClassBasedSelector("h1 .card")).toBeUndefined();+ });++ test("rejects type selector in target: .card h1", () => {+ expect(parseClassBasedSelector(".card h1")).toBeUndefined();+ });++ test("rejects id selector in target: .card #hero", () => {+ expect(parseClassBasedSelector(".card #hero")).toBeUndefined();+ });++ test("rejects attribute selector in ancestor: .card[disabled] .title", () => {+ expect(parseClassBasedSelector(".card[disabled] .title")).toBeUndefined();+ });+});diff --git a/packages/css-data/src/parse-css.ts b/packages/css-data/src/parse-css.tsindex 7fbbef961f..17fa6b2c00 100644--- a/packages/css-data/src/parse-css.ts+++ b/packages/css-data/src/parse-css.ts@@ -105,32 +105,21 @@ export const parseCss = (css: string): ParsedStyleDecl[] => {return [];}- // Track context as we traverse- let currentAtrule: csstree.Atrule | undefined;+ // Track context as we traverse — use a stack to support nested @media+ const atruleStack: csstree.Atrule[] = [];let currentRule: csstree.Rule | undefined;- let nestedAtruleDepth = 0;-- const supportedMediaFeatures = ["min-width", "max-width"];- const supportedUnits = ["px"];csstree.walk(ast, {enter(node) {if (node.type === "Atrule") {- if (currentAtrule) {- nestedAtruleDepth++;- }- currentAtrule = node;+ atruleStack.push(node);} else if (node.type === "Rule") {currentRule = node;}},leave(node) {if (node.type === "Atrule") {- if (nestedAtruleDepth > 0) {- nestedAtruleDepth--;- } else {- currentAtrule = undefined;- }+ atruleStack.pop();} else if (node.type === "Rule") {currentRule = undefined;}@@ -144,58 +133,67 @@ export const parseCss = (css: string): ParsedStyleDecl[] => {return;}- // forbid nested at rules- if (nestedAtruleDepth > 0) {- return;- }-- if (currentAtrule && currentAtrule.name !== "media") {+ // All enclosing at-rules must be @media — reject @supports, @keyframes, etc.+ if (atruleStack.some((atrule) => atrule.name !== "media")) {return;}let breakpoint: undefined | string;let invalidBreakpoint = false;- if (currentAtrule?.prelude?.type === "AtrulePrelude") {- csstree.walk(currentAtrule.prelude, {- enter: (node) => {- if (node.type === "MediaQuery") {- if (node.mediaType === "screen" || node.mediaType === "all") {- node.mediaType = null;+ // Collect and flatten all enclosing @media preludes+ const flattenedParts: string[] = [];+ for (const atrule of atruleStack) {+ if (atrule.prelude?.type === "AtrulePrelude") {+ let hasNonPxWidthUnit = false;+ let hasPrintMedia = false;+ let currentFeatureName: string | undefined;+ csstree.walk(atrule.prelude, {+ enter: (node) => {+ if (node.type === "MediaQuery") {+ // Mutates AST in-place to normalize media type for breakpoint string generation;+ // the AST is discarded after parseCss returns so this is safe.+ if (node.mediaType === "screen" || node.mediaType === "all") {+ node.mediaType = null;+ }+ if (node.mediaType === "print") {+ hasPrintMedia = true;+ }}- // prevent saving print styles- if (node.mediaType === "print") {- invalidBreakpoint = true;+ if (node.type === "Feature") {+ currentFeatureName = node.name;}- }- if (- node.type === "Feature" &&- supportedMediaFeatures.includes(node.name) === false- ) {- invalidBreakpoint = true;- }- if (- node.type === "Dimension" &&- supportedUnits.includes(node.unit) === false- ) {- invalidBreakpoint = true;- }- },- leave: (node) => {- // complex media queries are not supported yet- if (node.type === "MediaQuery") {- const children = node.condition?.children;- if (children && children.size > 1) {- invalidBreakpoint = true;+ // Only reject non-px units on width features (min-width, max-width)+ if (+ node.type === "Dimension" &&+ node.unit !== "px" &&+ (currentFeatureName === "min-width" ||+ currentFeatureName === "max-width")+ ) {+ hasNonPxWidthUnit = true;}- }- },- });- const generated = csstree.generate(currentAtrule.prelude);- if (generated) {- breakpoint = generated;+ },+ leave: (node) => {+ if (node.type === "Feature") {+ currentFeatureName = undefined;+ }+ },+ });+ if (hasPrintMedia || hasNonPxWidthUnit) {+ invalidBreakpoint = true;+ break;+ }+ const generated = csstree.generate(atrule.prelude);+ if (generated) {+ flattenedParts.push(generated);+ }}}++ if (!invalidBreakpoint && flattenedParts.length > 0) {+ breakpoint = flattenedParts.join(" and ");+ }+if (invalidBreakpoint || currentRule.prelude.type !== "SelectorList") {return;}@@ -220,6 +218,9 @@ export const parseCss = (css: string): ParsedStyleDecl[] => {case "ClassSelector":name = `.${childNode.name}`;break;+ case "IdSelector":+ name = `#${childNode.name}`;+ break;case "AttributeSelector":// for example &[data-state=active]if (startsWithNesting && index === 1 && children.length === 2) {@@ -297,6 +298,169 @@ export const parseCss = (css: string): ParsedStyleDecl[] => {return Array.from(styles.values());};+export type ParsedClassSelector = {+ /** Token name: "card" for .card, "card__title" for .card .title */+ tokenName: string;+ /** Target class names (the last segment): ["card"] or ["title"] */+ classNames: string[];+ /**+ * Non-class selector suffixes on the target: attribute selectors, pseudo-classes, pseudo-elements.+ * e.g. ["[disabled]"] for .btn[disabled], [":hover"] for .card:hover+ */+ states?: string[];+ /**+ * Ancestor constraints for nested selectors (e.g., .card .title).+ * Ordered from outermost to innermost ancestor.+ * Each entry's combinator describes the relationship to the next segment.+ */+ ancestors?: Array<{+ classNames: string[];+ combinator: "descendant" | "child";+ }>;+};++/**+ * Parse a selector string and determine if it's a class-based selector+ * suitable for token extraction. Uses css-tree to handle the full CSS+ * selector spec.+ *+ * Supports simple selectors, compound selectors, and nested selectors+ * using descendant (" ") and child (">") combinators where ALL segments+ * are class-based.+ *+ * Supported patterns:+ * .card → { tokenName: "card", classNames: ["card"] }+ * .card.active → { tokenName: "card.active", classNames: ["card", "active"] }+ * .btn[disabled] → { tokenName: "btn", ..., states: ["[disabled]"] }+ * .card:hover → { tokenName: "card", ..., states: [":hover"] }+ * .card .title → { tokenName: "card__title", ..., ancestors: [{classNames:["card"], combinator:"descendant"}] }+ * .card > .title → { tokenName: "card__title", ..., ancestors: [{classNames:["card"], combinator:"child"}] }+ * .a .b .c → { tokenName: "a__b__c", ..., ancestors: [{..,"descendant"},{..,"descendant"}] }+ * .card > .title:hover → { tokenName: "card__title", ..., states: [":hover"], ancestors: [...] }+ *+ * Returns undefined for:+ * - Selectors with sibling combinators (+, ~)+ * - Selectors with non-class nodes in ancestor segments (e.g., .card h1, h1 .card)+ * - Pure element/id selectors+ */+export const parseClassBasedSelector = (+ selector: string+): ParsedClassSelector | undefined => {+ let ast: csstree.CssNode;+ try {+ ast = csstree.parse(selector, { context: "selector" });+ } catch {+ return undefined;+ }++ if (ast.type !== "Selector") {+ return undefined;+ }++ const children = ast.children.toArray();+ if (children.length === 0) {+ return undefined;+ }++ // First node must be a ClassSelector+ if (children[0].type !== "ClassSelector") {+ return undefined;+ }++ // Split children into segments at Combinator nodes+ type Segment = {+ nodes: csstree.CssNode[];+ combinator?: "descendant" | "child";+ };+ const segments: Segment[] = [];+ let currentNodes: csstree.CssNode[] = [];++ for (const child of children) {+ if (child.type === "Combinator") {+ if (child.name === " ") {+ segments.push({ nodes: currentNodes, combinator: "descendant" });+ } else if (child.name === ">") {+ segments.push({ nodes: currentNodes, combinator: "child" });+ } else {+ // Sibling combinators (+, ~) — reject+ return undefined;+ }+ currentNodes = [];+ } else {+ currentNodes.push(child);+ }+ }+ // Push the last (target) segment+ segments.push({ nodes: currentNodes });++ // Validate all segments and extract class names+ const ancestors: Array<{+ classNames: string[];+ combinator: "descendant" | "child";+ }> = [];++ // Process ancestor segments (all except the last)+ for (let i = 0; i < segments.length - 1; i++) {+ const segment = segments[i];+ const segClassNames: string[] = [];+ for (const node of segment.nodes) {+ if (node.type === "ClassSelector") {+ segClassNames.push(node.name);+ } else {+ // Non-class node in an ancestor segment — reject+ return undefined;+ }+ }+ if (segClassNames.length === 0) {+ return undefined;+ }+ ancestors.push({+ classNames: segClassNames,+ combinator: segment.combinator!,+ });+ }++ // Process the last (target) segment+ const lastSegment = segments[segments.length - 1];+ const classNames: string[] = [];+ const states: string[] = [];++ for (const node of lastSegment.nodes) {+ switch (node.type) {+ case "ClassSelector":+ classNames.push(node.name);+ break;+ case "AttributeSelector":+ case "PseudoClassSelector":+ case "PseudoElementSelector":+ states.push(csstree.generate(node));+ break;+ default:+ return undefined;+ }+ }++ if (classNames.length === 0) {+ return undefined;+ }++ // Build token name: join segment class names with "__"+ const segmentNames = [+ ...ancestors.map((a) =>+ a.classNames.length === 1 ? a.classNames[0] : a.classNames.join(".")+ ),+ classNames.length === 1 ? classNames[0] : classNames.join("."),+ ];+ const tokenName = segmentNames.join("__");++ return {+ tokenName,+ classNames,+ ...(states.length > 0 ? { states } : {}),+ ...(ancestors.length > 0 ? { ancestors } : {}),+ };+};+type ParsedBreakpoint = {minWidth?: number;maxWidth?: number;@@ -307,17 +471,19 @@ export const parseMediaQuery = (mediaQuery: string): undefined | ParsedBreakpoint => {const ast = csstree.parse(mediaQuery, { context: "mediaQuery" });- let property: undefined | "minWidth" | "maxWidth";- let value: undefined | number;+ let minWidth: undefined | number;+ let maxWidth: undefined | number;+ let currentWidthProperty: undefined | "minWidth" | "maxWidth";const otherFeatures: string[] = [];csstree.walk(ast, (node) => {if (node.type === "Feature") {if (node.name === "min-width") {- property = "minWidth";+ currentWidthProperty = "minWidth";} else if (node.name === "max-width") {- property = "maxWidth";+ currentWidthProperty = "maxWidth";} else {+ currentWidthProperty = undefined;// Capture any other media feature as custom conditionconst generated = csstree.generate(node);// Remove outer parentheses if present@@ -331,23 +497,33 @@ export const parseMediaQuery = (}}if (node.type === "Dimension" && node.unit === "px") {- value = Number(node.value);+ const value = Number(node.value);+ if (currentWidthProperty === "minWidth") {+ minWidth = value;+ } else if (currentWidthProperty === "maxWidth") {+ maxWidth = value;+ }+ currentWidthProperty = undefined;}});const condition =otherFeatures.length > 0 ? otherFeatures.join(" and ") : undefined;+ const hasWidth = minWidth !== undefined || maxWidth !== undefined;+// If there's a custom condition and no width, return only condition- if (condition !== undefined && property === undefined) {+ if (condition !== undefined && !hasWidth) {return { condition };}- if (property === undefined || value === undefined) {+ if (!hasWidth && condition === undefined) {return;}+return {- [property]: value,+ ...(minWidth !== undefined ? { minWidth } : {}),+ ...(maxWidth !== undefined ? { maxWidth } : {}),...(condition !== undefined ? { condition } : {}),};};diff --git a/packages/sdk/src/schema/breakpoints.test.ts b/packages/sdk/src/schema/breakpoints.test.tsindex c6fd777b5e..1669d89cb2 100644--- a/packages/sdk/src/schema/breakpoints.test.ts+++ b/packages/sdk/src/schema/breakpoints.test.ts@@ -77,9 +77,7 @@ describe("Breakpoint schema", () => {condition: "orientation:portrait",minWidth: 1024,})- ).toThrow(- "Either minWidth, maxWidth, or condition should be defined, but not both"- );+ ).toThrow();expect(() =>Breakpoint.parse({@@ -88,9 +86,7 @@ describe("Breakpoint schema", () => {condition: "hover:hover",maxWidth: 767,})- ).toThrow(- "Either minWidth, maxWidth, or condition should be defined, but not both"- );+ ).toThrow();expect(() =>Breakpoint.parse({@@ -100,12 +96,22 @@ describe("Breakpoint schema", () => {minWidth: 1024,maxWidth: 767,})- ).toThrow(- "Either minWidth, maxWidth, or condition should be defined, but not both"- );+ ).toThrow();+ });++ test("allows breakpoint with both minWidth and maxWidth when min < max", () => {+ const result = Breakpoint.parse({+ id: "1",+ label: "Tablet range",+ minWidth: 768,+ maxWidth: 1024,+ });+ expect(result.minWidth).toBe(768);+ expect(result.maxWidth).toBe(1024);+ expect(result.condition).toBeUndefined();});- test("rejects breakpoint with both minWidth and maxWidth", () => {+ test("rejects breakpoint with minWidth >= maxWidth", () => {expect(() =>Breakpoint.parse({id: "1",@@ -114,6 +120,15 @@ describe("Breakpoint schema", () => {maxWidth: 767,})).toThrow();++ expect(() =>+ Breakpoint.parse({+ id: "2",+ label: "Invalid",+ minWidth: 768,+ maxWidth: 768,+ })+ ).toThrow();});test("preserves valid condition values", () => {diff --git a/packages/sdk/src/schema/breakpoints.ts b/packages/sdk/src/schema/breakpoints.tsindex beb5124426..4f59644c1e 100644--- a/packages/sdk/src/schema/breakpoints.ts+++ b/packages/sdk/src/schema/breakpoints.ts@@ -22,14 +22,12 @@ export const Breakpoint = zif (condition !== undefined) {return minWidth === undefined && maxWidth === undefined;}- return (- // Either min or max width have to be defined- (minWidth !== undefined && maxWidth === undefined) ||- (minWidth === undefined && maxWidth !== undefined) ||- // This is a base breakpoint- (minWidth === undefined && maxWidth === undefined)- );- }, "Either minWidth, maxWidth, or condition should be defined, but not both");+ // When both min and max width are defined, min must be less than max+ if (minWidth !== undefined && maxWidth !== undefined) {+ return minWidth < maxWidth;+ }+ return true;+ }, "Width-based (minWidth/maxWidth) and condition are mutually exclusive, and minWidth must be less than maxWidth");export type Breakpoint = z.infer<typeof Breakpoint>;