Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
fix: Add tests for breakpoint creation in tailwind conversion (#5582)
Oleg Isonen3e715e9b7c5b
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.mdindex ff8da2f133..e3f94fe80b 100644--- a/.github/copilot-instructions.md+++ b/.github/copilot-instructions.md@@ -55,6 +55,19 @@- `pnpm typecheck` is slow - avoid running it unnecessarily during development- Fix all eslint and TypeScript errors before considering work complete+### Git Commits++- **When user says "push"**: Always `git add -A` to stage ALL changes, not just the current file+- Write comprehensive commit messages covering ALL changes in the commit+- Commit message format:+ - First line: `type: short description` (fix/feat/refactor/test/chore)+ - Blank line+ - Body: Explain the problem being solved and why the change was made+ - List all significant changes with bullet points+ - If tests were added, list them+- Never write commit messages that only describe one file when multiple files changed+- The commit message should make sense to someone reviewing the PR without seeing the code+### Test Failures- If tests fail with "Host system is missing dependencies to run browsers" error, run `pnpm playwright` to install Playwright dependenciesdiff --git a/apps/builder/app/shared/tailwind/tailwind.test.tsx b/apps/builder/app/shared/tailwind/tailwind.test.tsxindex 02cb38c962..dd0a3b7575 100644--- a/apps/builder/app/shared/tailwind/tailwind.test.tsx+++ b/apps/builder/app/shared/tailwind/tailwind.test.tsx@@ -368,7 +368,9 @@ describe("extract breakpoints", () => {);});- test("extract container class", async () => {+ test("container class without user min-width breakpoints", async () => {+ // container class should only create max-width breakpoints, not min-width+ // this prevents unwanted 1280/1440 breakpoints from being createdexpect(await generateFragmentFromTailwind(renderTemplate(<ws.element ws:tag="div" class="container"></ws.element>)@@ -378,6 +380,47 @@ describe("extract breakpoints", () => {<ws.elementws:tag="div"ws:style={css`+ @media (max-width: 479px) {+ max-width: none;+ }+ @media (max-width: 767px) {+ max-width: 640px;+ }+ @media (max-width: 991px) {+ max-width: 768px;+ }+ max-width: 1024px;+ width: 100%;+ `}+ ></ws.element>+ )+ );+ });++ test("container class with user min-width breakpoints", async () => {+ // when user already has min-width breakpoints, container should use them+ expect(+ await generateFragmentFromTailwind(+ renderTemplate(+ <ws.element+ ws:tag="div"+ ws:style={css`+ @media (min-width: 1280px) {+ color: red;+ }+ `}+ class="container"+ ></ws.element>+ )+ )+ ).toEqual(+ renderTemplate(+ <ws.element+ ws:tag="div"+ ws:style={css`+ @media (min-width: 1280px) {+ color: red;+ }@media (max-width: 479px) {max-width: none;}@@ -401,6 +444,73 @@ describe("extract breakpoints", () => {);});+ test("explicit xl class creates min-width breakpoint", async () => {+ // explicit xl: classes should create min-width breakpoints+ // unlike container which is special-cased+ expect(+ await generateFragmentFromTailwind(+ renderTemplate(+ <ws.element ws:tag="div" class="text-sm xl:text-lg"></ws.element>+ )+ )+ ).toEqual(+ renderTemplate(+ <ws.element+ ws:tag="div"+ ws:style={css`+ font-size: 0.875rem;+ @media (min-width: 1280px) {+ font-size: 1.125rem;+ }+ line-height: 1.25rem;+ @media (min-width: 1280px) {+ line-height: 1.75rem;+ }+ `}+ ></ws.element>+ )+ );+ });++ test("container combined with explicit xl class", async () => {+ // container shouldn't create min-width breakpoints+ // but explicit xl: class should+ expect(+ await generateFragmentFromTailwind(+ renderTemplate(+ <ws.element ws:tag="div" class="container xl:text-lg"></ws.element>+ )+ )+ ).toEqual(+ renderTemplate(+ <ws.element+ ws:tag="div"+ ws:style={css`+ @media (max-width: 479px) {+ max-width: none;+ }+ @media (max-width: 767px) {+ max-width: 640px;+ }+ @media (max-width: 991px) {+ max-width: 768px;+ }+ max-width: 1024px;+ width: 100%;+ font-size: unset;+ @media (min-width: 1280px) {+ font-size: 1.125rem;+ }+ line-height: unset;+ @media (min-width: 1280px) {+ line-height: 1.75rem;+ }+ `}+ ></ws.element>+ )+ );+ });+test("merge tailwind breakpoints with already defined ones", async () => {expect(await generateFragmentFromTailwind(@@ -577,6 +687,41 @@ describe("extract breakpoints", () => {));});++ test("non-responsive classes create only base breakpoint", async () => {+ const fragment = await generateFragmentFromTailwind(+ renderTemplate(+ <ws.element ws:tag="div" class="m-2 p-4 text-red-500"></ws.element>+ )+ );+ expect(fragment.breakpoints).toEqual([{ id: "base", label: "" }]);+ });++ test("container class creates only needed breakpoints", async () => {+ const fragment = await generateFragmentFromTailwind(+ renderTemplate(<ws.element ws:tag="div" class="container"></ws.element>)+ );+ // container should only create max-width breakpoints, not 1280/1440/1920 min-width ones+ expect(fragment.breakpoints).toEqual([+ { id: "0", label: "479", maxWidth: 479 },+ { id: "1", label: "767", maxWidth: 767 },+ { id: "2", label: "991", maxWidth: 991 },+ { id: "base", label: "" },+ ]);+ });++ test("sm:class creates only needed breakpoints", async () => {+ const fragment = await generateFragmentFromTailwind(+ renderTemplate(+ <ws.element ws:tag="div" class="opacity-50 sm:opacity-100"></ws.element>+ )+ );+ // sm: should only create 479 max-width and base, not all breakpoints+ expect(fragment.breakpoints).toEqual([+ { id: "0", label: "479", maxWidth: 479 },+ { id: "base", label: "" },+ ]);+ });});test("generate space without display property", async () => {diff --git a/apps/builder/app/shared/tailwind/tailwind.ts b/apps/builder/app/shared/tailwind/tailwind.tsindex 5ffa3d9a37..3d364ec2c7 100644--- a/apps/builder/app/shared/tailwind/tailwind.ts+++ b/apps/builder/app/shared/tailwind/tailwind.ts@@ -9,6 +9,7 @@ import {} from "@webstudio-is/css-data";import {getStyleDeclKey,+ type Breakpoint,type Instance,type Prop,type WebstudioFragment,@@ -16,14 +17,16 @@ import {import { isBaseBreakpoint } from "../nano-states";import { preflight } from "./__generated__/preflight";-const availableBreakpoints = [- { id: "1920", minWidth: 1920 },- { id: "1440", minWidth: 1440 },- { id: "1280", minWidth: 1280 },- { id: "base" },- { id: "991", maxWidth: 991 },- { id: "767", maxWidth: 767 },- { id: "479", maxWidth: 479 },+// breakpoints used to map tailwind classes to webstudio breakpoints+// includes both min-width (desktop-first) and max-width (mobile-first) breakpoints+const tailwindBreakpoints: Breakpoint[] = [+ { id: "1920", label: "1920", minWidth: 1920 },+ { id: "1440", label: "1440", minWidth: 1440 },+ { id: "1280", label: "1280", minWidth: 1280 },+ { id: "base", label: "" },+ { id: "991", label: "991", maxWidth: 991 },+ { id: "767", label: "767", maxWidth: 767 },+ { id: "479", label: "479", maxWidth: 479 },];const tailwindToWebstudioMappings: Record<number, undefined | number> = {@@ -39,7 +42,7 @@ const tailwindToWebstudioMappings: Record<number, undefined | number> = {type StyleDecl = Omit<ParsedStyleDecl, "selector">;-type Breakpoint = {+type StyleBreakpoint = {styleDecl: StyleDecl;minWidth?: number;maxWidth?: number;@@ -51,7 +54,7 @@ type Range = {end: number;};-const serializeBreakpoint = (breakpoint: Breakpoint) => {+const serializeStyleBreakpoint = (breakpoint: StyleBreakpoint) => {if (breakpoint?.minWidth !== undefined) {return `(min-width: ${breakpoint.minWidth}px)`;}@@ -62,7 +65,7 @@ const serializeBreakpoint = (breakpoint: Breakpoint) => {const UPPER_BOUND = Number.MAX_SAFE_INTEGER;-const breakpointsToRanges = (breakpoints: Breakpoint[]) => {+const breakpointsToRanges = (breakpoints: StyleBreakpoint[]) => {// collect lower bounds and idsconst values = new Set<number>([0]);const styles = new Map<undefined | number, StyleDecl>();@@ -111,11 +114,14 @@ const breakpointsToRanges = (breakpoints: Breakpoint[]) => {return ranges;};-const rangesToBreakpoints = (ranges: Range[]) => {- const breakpoints: Breakpoint[] = [];+const rangesToBreakpoints = (+ ranges: Range[],+ userBreakpoints: Breakpoint[]+) => {+ const breakpoints: StyleBreakpoint[] = [];for (const { styleDecl, start, end } of ranges) {let matchedBreakpoint;- for (const breakpoint of availableBreakpoints) {+ for (const breakpoint of userBreakpoints) {if (breakpoint.minWidth === start) {matchedBreakpoint = { styleDecl, minWidth: start };}@@ -130,15 +136,18 @@ const rangesToBreakpoints = (ranges: Range[]) => {}}if (matchedBreakpoint) {- styleDecl.breakpoint = serializeBreakpoint(matchedBreakpoint);+ styleDecl.breakpoint = serializeStyleBreakpoint(matchedBreakpoint);breakpoints.push(matchedBreakpoint);}}return breakpoints;};-const adaptBreakpoints = (parsedStyles: StyleDecl[]) => {- const breakpointGroups = new Map<string, Breakpoint[]>();+const adaptBreakpoints = (+ parsedStyles: StyleDecl[],+ userBreakpoints: Breakpoint[]+) => {+ const breakpointGroups = new Map<string, StyleBreakpoint[]>();for (const styleDecl of parsedStyles) {const mediaQuery = styleDecl.breakpoint? parseMediaQuery(styleDecl.breakpoint)@@ -162,7 +171,7 @@ const adaptBreakpoints = (parsedStyles: StyleDecl[]) => {const newStyles: typeof parsedStyles = [];for (const group of breakpointGroups.values()) {const ranges = breakpointsToRanges(group);- const newGroup = rangesToBreakpoints(ranges);+ const newGroup = rangesToBreakpoints(ranges, userBreakpoints);for (const { styleDecl } of newGroup) {newStyles.push(styleDecl);}@@ -174,7 +183,7 @@ const createUnoGenerator = async () => {return await createGenerator({presets: [presetWind3({- // css variables are defined on the same element as style+ // css variables are defined on the same element as styleDeclpreflight: "on-demand",// dark mode will be ignored by parserdark: "media",@@ -185,7 +194,11 @@ const createUnoGenerator = async () => {});};-const parseTailwindClasses = async (classes: string) => {+const parseTailwindClasses = async (+ classes: string,+ userBreakpoints: Breakpoint[],+ fragmentBreakpoints: Breakpoint[]+) => {// avoid caching uno generator instance// to prevent bloating css with preflights from previous callsconst generator = await createUnoGenerator();@@ -231,8 +244,7 @@ const parseTailwindClasses = async (classes: string) => {parsedStyles = parsedStyles.filter((styleDecl) => !styleDecl.state?.startsWith("::"));- // setup base breakpoint for container class- // to avoid hole in ranges+ // setup base breakpoint for container class to avoid hole in rangesif (hasContainer) {parsedStyles.unshift({property: "max-width",@@ -263,12 +275,24 @@ const parseTailwindClasses = async (classes: string) => {});}- parsedStyles = adaptBreakpoints(parsedStyles);+ parsedStyles = adaptBreakpoints(parsedStyles, userBreakpoints);+ // container class generates max-width styles for all Tailwind breakpoints+ // filter out min-width ones only if user doesn't have min-width breakpoints+ const hasUserMinWidthBreakpoints = fragmentBreakpoints.some(+ (bp) => bp.minWidth !== undefined+ );+ if (hasContainer && !hasUserMinWidthBreakpoints) {+ parsedStyles = parsedStyles.filter(+ (styleDecl) =>+ styleDecl.property !== "max-width" ||+ !styleDecl.breakpoint?.includes("min-width")+ );+ }const newClasses = classes.split(" ").filter((item) => !generated.matched.has(item)).join(" ");- return { newClasses: newClasses, parsedStyles };+ return { newClasses, parsedStyles };};const getUniqueIdForList = <List extends Array<{ id: string }>>(list: List) => {@@ -343,7 +367,7 @@ export const generateFragmentFromTailwind = async (styleSourceSelections.get(instanceId));if (styleSourceSelection === undefined) {- styleSourceSelection = { instanceId: instanceId, values: [] };+ styleSourceSelection = { instanceId, values: [] };styleSourceSelections.set(instanceId, styleSourceSelection);}styleSources.set(localStyleSource.id, localStyleSource);@@ -369,9 +393,9 @@ export const generateFragmentFromTailwind = async (property: camelCaseProperty(parsedStyleDecl.property),value: parsedStyleDecl.value,};- const styleDeckKey = getStyleDeclKey(styleDecl);- styles.delete(styleDeckKey);- styles.set(styleDeckKey, styleDecl);+ const styleDeclKey = getStyleDeclKey(styleDecl);+ styles.delete(styleDeclKey);+ styles.set(styleDeclKey, styleDecl);}};@@ -386,8 +410,12 @@ export const generateFragmentFromTailwind = async (await Promise.all(fragment.props.map(async (prop) => {if (prop.name === "class" && prop.type === "string") {+ // always use tailwindBreakpoints for parsing to support all Tailwind classes+ // new breakpoints will be created as needed via getBreakpointIdconst { newClasses, parsedStyles } = await parseTailwindClasses(- prop.value+ prop.value,+ tailwindBreakpoints,+ fragment.breakpoints);if (parsedStyles.length > 0) {createOrMergeLocalStyles(prop.instanceId, parsedStyles);