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: Support any media query condition as a breakpoint (#5547)
Oleg Isonene9a3a1ac003d
diff --git a/apps/builder/app/builder/features/breakpoints/breakpoint-editor-utils.test.ts b/apps/builder/app/builder/features/breakpoints/breakpoint-editor-utils.test.tsnew file mode 100644index 0000000000..68666206be--- /dev/null+++ b/apps/builder/app/builder/features/breakpoints/breakpoint-editor-utils.test.ts@@ -0,0 +1,232 @@+import { describe, test, expect } from "vitest";+import {+ isConditionBasedBreakpoint,+ isWidthBasedBreakpoint,+ isValidBreakpoint,+ buildBreakpointFromEditorState,+ hasUnsavedChanges,+} from "./breakpoint-editor-utils";++describe("breakpoint-editor-utils", () => {+ describe("isConditionBasedBreakpoint", () => {+ test("returns true for breakpoint with condition", () => {+ expect(+ isConditionBasedBreakpoint({ condition: "orientation:portrait" })+ ).toBe(true);+ });++ test("returns false for breakpoint with empty condition", () => {+ expect(isConditionBasedBreakpoint({ condition: "" })).toBe(false);+ expect(isConditionBasedBreakpoint({ condition: " " })).toBe(false);+ });++ test("returns false for breakpoint without condition", () => {+ expect(isConditionBasedBreakpoint({})).toBe(false);+ });+ });++ describe("isWidthBasedBreakpoint", () => {+ test("returns true for breakpoint with minWidth", () => {+ expect(isWidthBasedBreakpoint({ minWidth: 1024 })).toBe(true);+ });++ test("returns true for breakpoint with maxWidth", () => {+ expect(isWidthBasedBreakpoint({ maxWidth: 768 })).toBe(true);+ });++ test("returns false for breakpoint without width", () => {+ expect(isWidthBasedBreakpoint({})).toBe(false);+ });+ });++ describe("isValidBreakpoint", () => {+ test("returns true for condition-based breakpoint", () => {+ expect(isValidBreakpoint({ condition: "orientation:portrait" })).toBe(+ true+ );+ });++ test("returns true for width-based breakpoint", () => {+ expect(isValidBreakpoint({ minWidth: 1024 })).toBe(true);+ expect(isValidBreakpoint({ maxWidth: 768 })).toBe(true);+ });++ test("returns false for breakpoint with neither condition nor width", () => {+ expect(isValidBreakpoint({})).toBe(false);+ });+ });++ describe("buildBreakpointFromEditorState", () => {+ test("builds condition-based breakpoint", () => {+ const result = buildBreakpointFromEditorState(+ "id1",+ "Portrait",+ "orientation:portrait",+ "minWidth",+ 0,+ undefined+ );++ expect(result).toEqual({+ id: "id1",+ label: "Portrait",+ condition: "orientation:portrait",+ });+ });++ test("builds width-based breakpoint with minWidth", () => {+ const result = buildBreakpointFromEditorState(+ "id2",+ "Desktop",+ "",+ "minWidth",+ 1024,+ undefined+ );++ expect(result).toEqual({+ id: "id2",+ label: "Desktop",+ minWidth: 1024,+ });+ });++ test("builds width-based breakpoint with maxWidth", () => {+ const result = buildBreakpointFromEditorState(+ "id3",+ "Mobile",+ "",+ "maxWidth",+ 768,+ undefined+ );++ expect(result).toEqual({+ id: "id3",+ label: "Mobile",+ maxWidth: 768,+ });+ });++ test("allows zero as valid width (e.g., base breakpoint)", () => {+ const result = buildBreakpointFromEditorState(+ "id4",+ "Base",+ "",+ "minWidth",+ 0,+ undefined+ );++ expect(result).toEqual({+ id: "id4",+ label: "Base",+ minWidth: 0,+ });+ });++ test("converts to width-based when condition is cleared", () => {+ const original = {+ id: "id5",+ label: "Portrait",+ condition: "orientation:portrait",+ };++ const result = buildBreakpointFromEditorState(+ "id5",+ "Portrait",+ "", // cleared condition+ "minWidth",+ 0,+ original+ );++ // When condition is cleared with valid width (including 0), convert to width-based+ expect(result).toEqual({+ id: "id5",+ label: "Portrait",+ minWidth: 0,+ });+ });++ test("uses original label if new label is empty", () => {+ const original = {+ id: "id6",+ label: "Original",+ minWidth: 1024,+ };++ const result = buildBreakpointFromEditorState(+ "id6",+ " ", // empty label+ "",+ "minWidth",+ 1024,+ original+ );++ expect(result).toEqual({+ id: "id6",+ label: "Original",+ minWidth: 1024,+ });+ });+ });++ describe("hasUnsavedChanges", () => {+ test("returns true when label changed", () => {+ const original = { id: "1", label: "Old", minWidth: 1024 };+ expect(hasUnsavedChanges(original, "New", "", "minWidth", 1024)).toBe(+ true+ );+ });++ test("returns true when condition changed", () => {+ const original = {+ id: "1",+ label: "Test",+ condition: "orientation:portrait",+ };+ expect(+ hasUnsavedChanges(+ original,+ "Test",+ "orientation:landscape",+ "minWidth",+ 0+ )+ ).toBe(true);+ });++ test("returns true when width value changed", () => {+ const original = { id: "1", label: "Test", minWidth: 1024 };+ expect(hasUnsavedChanges(original, "Test", "", "minWidth", 768)).toBe(+ true+ );+ });++ test("returns false when nothing changed", () => {+ const original = { id: "1", label: "Test", minWidth: 1024 };+ expect(hasUnsavedChanges(original, "Test", "", "minWidth", 1024)).toBe(+ false+ );+ });++ test("returns false for condition-based breakpoint with unchanged condition", () => {+ const original = {+ id: "1",+ label: "Test",+ condition: "orientation:portrait",+ };+ expect(+ hasUnsavedChanges(+ original,+ "Test",+ "orientation:portrait",+ "minWidth",+ 0+ )+ ).toBe(false);+ });+ });+});diff --git a/apps/builder/app/builder/features/breakpoints/breakpoint-editor-utils.ts b/apps/builder/app/builder/features/breakpoints/breakpoint-editor-utils.tsnew file mode 100644index 0000000000..09385dc392--- /dev/null+++ b/apps/builder/app/builder/features/breakpoints/breakpoint-editor-utils.ts@@ -0,0 +1,102 @@+import type { Breakpoint } from "@webstudio-is/sdk";++/**+ * Determines if a breakpoint is condition-based (has a custom media query condition).+ */+export const isConditionBasedBreakpoint = (breakpoint: {+ condition?: string;+}): boolean => {+ return (+ breakpoint.condition !== undefined && breakpoint.condition.trim() !== ""+ );+};++/**+ * Determines if a breakpoint is width-based (has minWidth or maxWidth).+ */+export const isWidthBasedBreakpoint = (breakpoint: {+ minWidth?: number;+ maxWidth?: number;+}): boolean => {+ return breakpoint.minWidth !== undefined || breakpoint.maxWidth !== undefined;+};++/**+ * Validates if a breakpoint has valid data (either condition or width).+ */+export const isValidBreakpoint = (breakpoint: {+ condition?: string;+ minWidth?: number;+ maxWidth?: number;+}): boolean => {+ return (+ isConditionBasedBreakpoint(breakpoint) || isWidthBasedBreakpoint(breakpoint)+ );+};++/**+ * Builds a breakpoint from editor state, ensuring only condition OR width is set.+ * Returns undefined if the breakpoint is invalid.+ */+export const buildBreakpointFromEditorState = (+ id: string,+ label: string,+ conditionValue: string,+ widthType: "minWidth" | "maxWidth",+ widthValue: number,+ originalBreakpoint?: Breakpoint+): Breakpoint | undefined => {+ const trimmedLabel = label.trim();+ const trimmedCondition = conditionValue.trim();+ const hasCondition = trimmedCondition !== "";++ const newBreakpoint: Breakpoint = {+ id,+ label: trimmedLabel || originalBreakpoint?.label || "",+ };++ if (hasCondition) {+ // Condition-based: only set condition+ newBreakpoint.condition = trimmedCondition;+ } else if (widthValue !== undefined && widthValue >= 0) {+ // Width-based: only set width (zero is valid for base breakpoints)+ newBreakpoint[widthType] = widthValue;+ } else if (originalBreakpoint?.condition !== undefined) {+ // Preserve existing condition if input was cleared+ newBreakpoint.condition = originalBreakpoint.condition;+ } else {+ // Invalid: no condition and no valid width+ return undefined;+ }++ return newBreakpoint;+};++/**+ * Detects if there are unsaved changes in the editor state compared to original breakpoint.+ */+export const hasUnsavedChanges = (+ originalBreakpoint: Breakpoint,+ label: string,+ conditionValue: string,+ widthType: "minWidth" | "maxWidth",+ widthValue: number+): boolean => {+ if (label !== originalBreakpoint.label) {+ return true;+ }++ if (conditionValue !== (originalBreakpoint.condition ?? "")) {+ return true;+ }++ // For width-based breakpoints, check if width changed+ if (originalBreakpoint.condition === undefined) {+ const originalWidth = originalBreakpoint[widthType] ?? 0;+ if (widthValue !== originalWidth) {+ return true;+ }+ }++ return false;+};diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-container.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-container.tsxnew file mode 100644index 0000000000..08674d56d8--- /dev/null+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-container.tsx@@ -0,0 +1,105 @@+import { useState } from "react";+import { useStore } from "@nanostores/react";+import { Flex } from "@webstudio-is/design-system";+import { $breakpoints, $styles } from "~/shared/sync/data-stores";+import {+ $selectedBreakpoint,+ $selectedBreakpointId,+} from "~/shared/nano-states";+import { CanvasSettingsPopover } from "./canvas-settings-popover";+import { BreakpointsSelector } from "./breakpoints-selector";+import { BreakpointsMenu } from "./breakpoints-menu";+import { BreakpointsEditor } from "./breakpoints-editor";+import { ConfirmationDialog } from "./confirmation-dialog";+import { isBaseBreakpoint } from "~/shared/breakpoints";+import { setCanvasWidth } from "../../shared/calc-canvas-width";+import { serverSyncStore } from "~/shared/sync/sync-stores";+import type { Breakpoint } from "@webstudio-is/sdk";++const hideOnMobile = {+ "@media (max-width: 640px)": {+ display: "none",+ },+} as const;++export const BreakpointsContainer = () => {+ const breakpoints = useStore($breakpoints);+ const selectedBreakpoint = useStore($selectedBreakpoint);+ const [editorOpen, setEditorOpen] = useState(false);+ const [breakpointToDelete, setBreakpointToDelete] = useState<+ Breakpoint | undefined+ >();+ const [confirmationOpen, setConfirmationOpen] = useState(false);++ const handleDelete = () => {+ if (breakpointToDelete === undefined) {+ return;+ }+ serverSyncStore.createTransaction(+ [$breakpoints, $styles],+ (breakpoints, styles) => {+ const breakpointId = breakpointToDelete.id;+ breakpoints.delete(breakpointId);+ for (const [styleDeclKey, styleDecl] of styles) {+ if (styleDecl.breakpointId === breakpointId) {+ styles.delete(styleDeclKey);+ }+ }+ }+ );++ if (+ breakpointToDelete.id === selectedBreakpoint?.id &&+ selectedBreakpoint+ ) {+ const breakpointsArray = Array.from(breakpoints.values());+ const base =+ breakpointsArray.find(isBaseBreakpoint) ?? breakpointsArray[0];+ $selectedBreakpointId.set(base.id);+ setCanvasWidth(base.id);+ }+ setBreakpointToDelete(undefined);+ setConfirmationOpen(false);+ };++ return (+ <Flex>+ <Flex justify="end" css={hideOnMobile}>+ <CanvasSettingsPopover />+ </Flex>+ <Flex align="center" justify="center" css={hideOnMobile}>+ <BreakpointsSelector />+ </Flex>+ {selectedBreakpoint && (+ <BreakpointsMenu+ breakpoints={breakpoints}+ selectedBreakpoint={selectedBreakpoint}+ onEditClick={() => setEditorOpen(true)}+ />+ )}+ <BreakpointsEditor+ open={editorOpen}+ onOpenChange={setEditorOpen}+ onDelete={(breakpoint) => {+ setBreakpointToDelete(breakpoint);+ setEditorOpen(false);+ setConfirmationOpen(true);+ }}+ >+ <div style={{ height: "100%", width: 0 }} />+ </BreakpointsEditor>+ {breakpointToDelete && (+ <ConfirmationDialog+ open={confirmationOpen}+ breakpoint={breakpointToDelete}+ onAbort={() => {+ setBreakpointToDelete(undefined);+ setConfirmationOpen(false);+ setEditorOpen(true);+ }}+ onConfirm={handleDelete}+ />+ )}+ </Flex>+ );+};diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsxindex d41beefb2e..dc936e8cd8 100644--- a/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsx+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-editor.tsx@@ -1,5 +1,4 @@-import { z } from "zod";-import { Fragment, useEffect, useRef, useState } from "react";+import { Fragment, useState, useMemo } from "react";import { nanoid } from "nanoid";import type { Breakpoint } from "@webstudio-is/sdk";import {@@ -13,13 +12,19 @@ import {PopoverSeparator,Separator,Box,- toast,+ Popover,+ PopoverTrigger,+ PopoverContent,} from "@webstudio-is/design-system";import { MinusIcon, PlusIcon } from "@webstudio-is/icons";import { useStore } from "@nanostores/react";import { $breakpoints } from "~/shared/sync/data-stores";import { groupBreakpoints, isBaseBreakpoint } from "~/shared/breakpoints";import { serverSyncStore } from "~/shared/sync/sync-stores";+import { ConditionInput } from "./condition-input";+import { CssValueInput } from "~/builder/features/style-panel/shared/css-value-input";+import { useLocalValue } from "~/builder/features/settings-panel/shared";+import { buildBreakpointFromEditorState } from "./breakpoint-editor-utils";type BreakpointEditorItemProps = {breakpoint: Breakpoint;@@ -28,125 +33,139 @@ type BreakpointEditorItemProps = {onDelete: (breakpoint: Breakpoint) => void;};-const BreakpointFormData = z.object({- label: z.string(),- type: z.enum(["minWidth", "maxWidth"]),- value: z.string().transform(Number),-});--const useHandleChangeComplete = (- breakpoint: Breakpoint,- onChangeComplete: (breakpoint: Breakpoint) => void-) => {- const formRef = useRef<HTMLFormElement>(null);- const [formEntries, setFormEntries] =- useState<Record<string, FormDataEntryValue>>();-- /**- * Read form data using onChange event so we can access values at useEffect unsubscribe- */- const handleChange = () => {- const form = formRef.current;- if (form === null || form.reportValidity() === false) {- return;- }- setFormEntries(Object.fromEntries(new FormData(form)));- };-- const handleChangeComplete = () => {- if (formEntries === undefined) {- return;- }-- const parsed = BreakpointFormData.safeParse(formEntries);- if (parsed.success === false) {- toast.error(parsed.error.message);- return;- }-- const newBreakpoint: Breakpoint = {- id: breakpoint.id,- label: parsed.data.label,- [parsed.data.type]: parsed.data.value,- };- onChangeComplete(newBreakpoint);- };- const handleChangeCompleteRef = useRef(handleChangeComplete);- handleChangeCompleteRef.current = handleChangeComplete;-- // Handle change when unmounting (Popup close in our case)- useEffect(() => handleChangeCompleteRef.current, []);-- return { formRef, handleChangeComplete, handleChange };-};-const BreakpointEditorItem = ({breakpoint,autoFocus,onChangeComplete,onDelete,}: BreakpointEditorItemProps) => {- const { formRef, handleChangeComplete, handleChange } =- useHandleChangeComplete(breakpoint, onChangeComplete);+ const [type, setType] = useState<"minWidth" | "maxWidth">(+ breakpoint.maxWidth !== undefined ? "maxWidth" : "minWidth"+ );++ const initialValue = useMemo(+ () => ({+ label: breakpoint.label,+ condition: breakpoint.condition ?? "",+ width: breakpoint.minWidth ?? breakpoint.maxWidth ?? 0,+ }),+ [+ breakpoint.label,+ breakpoint.condition,+ breakpoint.minWidth,+ breakpoint.maxWidth,+ ]+ );++ const localValue = useLocalValue(+ initialValue,+ (value) => {+ const newBreakpoint = buildBreakpointFromEditorState(+ breakpoint.id,+ value.label,+ value.condition,+ type,+ value.width,+ breakpoint+ );++ if (newBreakpoint !== undefined) {+ onChangeComplete(newBreakpoint);+ }+ },+ { autoSave: true }+ );++ const hasCondition = localValue.value.condition.trim() !== "";return (<Flex gap="2">- <form- ref={formRef}- onKeyPress={(event) => {- if (event.key === "Enter") {- handleChangeComplete();+ <Flex direction="column" gap="1">+ <InputField+ type="text"+ value={localValue.value.label}+ onChange={(event) =>+ localValue.set({ ...localValue.value, label: event.target.value })}- }}- onSubmit={(event) => {- event.preventDefault();- handleChangeComplete();- }}- onBlur={handleChangeComplete}- onChange={handleChange}- >- <Flex direction="column" gap="1">- <InputField- type="text"- defaultValue={breakpoint.label}- placeholder="Breakpoint name"- name="label"- minLength={1}- required- autoFocus={autoFocus}+ onBlur={localValue.save}+ placeholder="Breakpoint name"+ minLength={1}+ required+ autoFocus={autoFocus}+ />+ <Flex gap="2" css={{ width: theme.spacing[26] }}>+ <Select+ css={{ width: theme.spacing[28] }}+ options={["maxWidth", "minWidth"]}+ getLabel={(option) =>+ option === "maxWidth" ? "Max Width" : "Min Width"+ }+ value={type}+ onChange={(value) => {+ setType(value as "minWidth" | "maxWidth");+ localValue.save();+ }}+ disabled={hasCondition}/>- <Flex gap="2" css={{ width: theme.spacing[26] }}>- <Select- name="type"- css={{ width: theme.spacing[28] }}- options={["maxWidth", "minWidth"]}- getLabel={(option) =>- option === "maxWidth" ? "Max Width" : "Min Width"- }- defaultValue={breakpoint.maxWidth ? "maxWidth" : "minWidth"}- onChange={handleChangeComplete}+ <Box css={{ flexShrink: 1 }}>+ <CssValueInput+ styleSource="local"+ property="width"+ value={{+ type: "unit",+ value: localValue.value.width,+ unit: "px",+ }}+ intermediateValue={undefined}+ disabled={hasCondition}+ getOptions={() => []}+ onChange={(value) => {+ if (value?.type === "unit") {+ localValue.set({+ ...localValue.value,+ width: Math.max(0, value.value),+ });+ } else if (value?.type === "intermediate") {+ const parsed = parseFloat(value.value);+ if (!isNaN(parsed)) {+ localValue.set({+ ...localValue.value,+ width: Math.max(0, parsed),+ });+ }+ }+ }}+ onChangeComplete={(event) => {+ if (event.value.type === "unit") {+ localValue.set({+ ...localValue.value,+ width: Math.max(0, event.value.value),+ });+ localValue.save();+ }+ }}+ onHighlight={() => {}}+ onAbort={() => {+ localValue.set({+ ...localValue.value,+ width: breakpoint.minWidth ?? breakpoint.maxWidth ?? 0,+ });+ }}+ onReset={() => {+ localValue.set({ ...localValue.value, width: 0 });+ localValue.save();+ }}/>- <InputField- css={{ flexShrink: 1 }}- defaultValue={breakpoint.minWidth ?? breakpoint.maxWidth ?? 0}- type="number"- name="value"- min={0}- required- suffix={- <Text- variant="unit"- color="moreSubtle"- align="center"- css={{ width: theme.spacing[10] }}- >- PX- </Text>- }- />- </Flex>+ </Box></Flex>- </form>+ <ConditionInput+ value={localValue.value.condition}+ onChange={(value) => {+ localValue.set({ ...localValue.value, condition: value });+ }}+ onBlur={localValue.save}+ />+ </Flex><IconButtononClick={() => {onDelete(breakpoint);@@ -160,22 +179,36 @@ const BreakpointEditorItem = ({type BreakpointsEditorProps = {onDelete: (breakpoint: Breakpoint) => void;+ children: React.ReactNode;+ open?: boolean;+ onOpenChange?: (open: boolean) => void;};-export const BreakpointsEditor = ({ onDelete }: BreakpointsEditorProps) => {+export const BreakpointsEditor = ({+ onDelete,+ children,+ open,+ onOpenChange,+}: BreakpointsEditorProps) => {const breakpoints = useStore($breakpoints);const [addedBreakpoints, setAddedBreakpoints] = useState<Breakpoint[]>([]);- const initialBreakpointsRef = useRef(- groupBreakpoints(Array.from(breakpoints.values()))- );++ // Use current breakpoints from store, not stale cached version+ const grouped = groupBreakpoints(Array.from(breakpoints.values()));+ const currentBreakpointsFlat = [...grouped.widthBased, ...grouped.custom];+const allBreakpoints = [...addedBreakpoints,- ...initialBreakpointsRef.current.filter(+ ...currentBreakpointsFlat.filter((breakpoint) =>addedBreakpoints.find((added) => added.id === breakpoint.id) ===undefined),- ].filter((breakpoint) => isBaseBreakpoint(breakpoint) === false);+ ].filter(+ (breakpoint) =>+ breakpoint.condition !== undefined ||+ isBaseBreakpoint(breakpoint) === false+ );const handleChangeComplete = (breakpoint: Breakpoint) => {serverSyncStore.createTransaction([$breakpoints], (breakpoints) => {@@ -183,48 +216,59 @@ export const BreakpointsEditor = ({ onDelete }: BreakpointsEditorProps) => {});};+ const handleOpenChange = (newOpen: boolean) => {+ onOpenChange?.(newOpen);+ };+return (- <Flex direction="column">- <PanelTitle- css={{ paddingInline: theme.panel.paddingInline }}- suffix={- <IconButton- onClick={() => {- const newBreakpoint: Breakpoint = {- id: nanoid(),- label: "",- minWidth: 0,- };- setAddedBreakpoints([newBreakpoint, ...addedBreakpoints]);- }}+ <Popover open={open} onOpenChange={handleOpenChange} modal>+ <PopoverTrigger asChild>{children}</PopoverTrigger>+ <PopoverContent>+ <Flex direction="column">+ <PanelTitle+ css={{ paddingInline: theme.panel.paddingInline }}+ suffix={+ <IconButton+ onClick={() => {+ const newBreakpoint: Breakpoint = {+ id: nanoid(),+ label: "",+ minWidth: 0,+ };+ setAddedBreakpoints([newBreakpoint, ...addedBreakpoints]);+ }}+ >+ <PlusIcon />+ </IconButton>+ }>- <PlusIcon />- </IconButton>- }- >- {"Breakpoints"}- </PanelTitle>- <Separator />- <Fragment>- {allBreakpoints.map((breakpoint, index, all) => {- return (- <Fragment key={breakpoint.id}>- <Box css={{ p: theme.panel.padding }}>- <BreakpointEditorItem- breakpoint={breakpoint}- onChangeComplete={handleChangeComplete}- onDelete={onDelete}- autoFocus={index === 0}- />- </Box>- {index < all.length - 1 && <PopoverSeparator />}- </Fragment>- );- })}- </Fragment>- {allBreakpoints.length === 0 && (- <Text css={{ margin: theme.spacing[10] }}>No breakpoints found</Text>- )}- </Flex>+ {"Breakpoints"}+ </PanelTitle>+ <Separator />+ <Fragment>+ {allBreakpoints.map((breakpoint, index, all) => {+ return (+ <Fragment key={breakpoint.id}>+ <Box css={{ p: theme.panel.padding }}>+ <BreakpointEditorItem+ breakpoint={breakpoint}+ onChangeComplete={handleChangeComplete}+ onDelete={onDelete}+ autoFocus={index === 0}+ />+ </Box>+ {index < all.length - 1 && <PopoverSeparator />}+ </Fragment>+ );+ })}+ </Fragment>+ {allBreakpoints.length === 0 && (+ <Text css={{ margin: theme.spacing[10] }}>+ No breakpoints found+ </Text>+ )}+ </Flex>+ </PopoverContent>+ </Popover>);};diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsxnew file mode 100644index 0000000000..2d36440a77--- /dev/null+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-menu.tsx@@ -0,0 +1,121 @@+import { useState } from "react";+import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";+import {+ Flex,+ Text,+ ToolbarButton,+ theme,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuTrigger,+ DropdownMenuCheckboxItem,+ DropdownMenuSeparator,+ Button,+} from "@webstudio-is/design-system";+import { EllipsesIcon } from "@webstudio-is/icons";+import { groupBreakpoints } from "~/shared/breakpoints";+import { $selectedBreakpointId } from "~/shared/nano-states";+import { setCanvasWidth } from "../../shared/calc-canvas-width";++type BreakpointsMenuProps = {+ breakpoints: Breakpoints;+ selectedBreakpoint: Breakpoint;+ onEditClick: () => void;+};++export const BreakpointsMenu = ({+ breakpoints,+ selectedBreakpoint,+ onEditClick,+}: BreakpointsMenuProps) => {+ const [dropdownOpen, setDropdownOpen] = useState(false);+ const grouped = groupBreakpoints(Array.from(breakpoints.values()));+ const selectedCustom = grouped.custom.find(+ (bp) => bp.id === selectedBreakpoint.id+ );++ return (+ <DropdownMenu open={dropdownOpen} onOpenChange={setDropdownOpen}>+ <DropdownMenuTrigger asChild>+ <ToolbarButton+ variant="subtle"+ aria-label="Breakpoints with custom conditions"+ data-state={selectedCustom ? "on" : "off"}+ >+ {selectedCustom ? selectedCustom.label : <EllipsesIcon />}+ </ToolbarButton>+ </DropdownMenuTrigger>+ <DropdownMenuContent css={{ width: theme.spacing[30] }}>+ {grouped.widthBased.map((breakpoint) => {+ let description = "All Sizes";+ if (breakpoint.minWidth !== undefined) {+ description = `≥ ${breakpoint.minWidth} PX`;+ } else if (breakpoint.maxWidth !== undefined) {+ description = `≤ ${breakpoint.maxWidth} PX`;+ }+ return (+ <DropdownMenuCheckboxItem+ key={breakpoint.id}+ checked={breakpoint.id === selectedBreakpoint.id}+ onSelect={() => {+ $selectedBreakpointId.set(breakpoint.id);+ setCanvasWidth(breakpoint.id);+ }}+ >+ <Flex justify="between" grow gap="2">+ <Text truncate css={{ flexBasis: "50%" }}>+ {breakpoint.label}+ </Text>+ <Text color="subtle" truncate>+ {description}+ </Text>+ </Flex>+ </DropdownMenuCheckboxItem>+ );+ })}+ {grouped.widthBased.length > 0 && grouped.custom.length > 0 && (+ <DropdownMenuSeparator />+ )}+ {grouped.custom.map((breakpoint) => (+ <DropdownMenuCheckboxItem+ key={breakpoint.id}+ checked={breakpoint.id === selectedBreakpoint.id}+ onSelect={() => {+ $selectedBreakpointId.set(breakpoint.id);+ setCanvasWidth(breakpoint.id);+ }}+ >+ <Flex justify="between" grow gap="2">+ <Text truncate css={{ flexBasis: "50%" }}>+ {breakpoint.label}+ </Text>+ <Text color="subtle" truncate>+ {breakpoint.condition}+ </Text>+ </Flex>+ </DropdownMenuCheckboxItem>+ ))}+ {(grouped.widthBased.length > 0 || grouped.custom.length > 0) && (+ <DropdownMenuSeparator />+ )}++ <Flex+ align="center"+ justify="center"+ css={{ padding: theme.panel.padding }}+ >+ <Button+ color="neutral"+ onClick={() => {+ setDropdownOpen(false);+ onEditClick();+ }}+ css={{ width: "100%" }}+ >+ Edit breakpoints+ </Button>+ </Flex>+ </DropdownMenuContent>+ </DropdownMenu>+ );+};diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-popover-toolbar-button.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-popover-toolbar-button.tsxdeleted file mode 100644index 27362110bb..0000000000--- a/apps/builder/app/builder/features/breakpoints/breakpoints-popover-toolbar-button.tsx+++ /dev/null@@ -1,51 +0,0 @@-import { forwardRef, type ComponentProps } from "react";-import { useStore } from "@nanostores/react";-import { Flex, theme, ToolbarButton } from "@webstudio-is/design-system";-import { $canvasWidth, $scale } from "~/builder/shared/nano-states";-import { $selectedBreakpoint } from "~/shared/nano-states";--const Value = ({- children,- unit,- minWidth,-}: {- children?: number;- unit: string;- minWidth: number;-}) => {- return (- <Flex gap="1" as="span" justify="end" css={{ minWidth }}>- {children}- <Flex css={{ color: theme.colors.foregroundTextMoreSubtle }} as="span">- {unit}- </Flex>- </Flex>- );-};--export const BreakpointsPopoverToolbarButton = forwardRef<- HTMLButtonElement,- ComponentProps<typeof ToolbarButton>->((props, ref) => {- const scale = useStore($scale);- const breakpoint = useStore($selectedBreakpoint);- const canvasWidth = useStore($canvasWidth);- if (breakpoint === undefined || canvasWidth === undefined) {- return null;- }- const roundedScale = Math.round(scale);- return (- <ToolbarButton ref={ref} {...props}>- <Value unit="PX" minWidth={55}>- {Math.round(canvasWidth)}- </Value>- {roundedScale !== 100 && (- <Value unit="%" minWidth={30}>- {roundedScale}- </Value>- )}- </ToolbarButton>- );-});--BreakpointsPopoverToolbarButton.displayName = "BreakpointsPopoverToolbarButton";diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-popover.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-popover.tsxdeleted file mode 100644index 664ce689b7..0000000000--- a/apps/builder/app/builder/features/breakpoints/breakpoints-popover.tsx+++ /dev/null@@ -1,219 +0,0 @@-import { useState } from "react";-import { useStore } from "@nanostores/react";-import type { Breakpoint } from "@webstudio-is/sdk";-import {- theme,- PopoverSeparator,- Flex,- Label,- Button,- Popover,- PopoverContent,- PopoverTrigger,- MenuCheckedIcon,- MenuItemIndicator,- List,- ListItem,- MenuItemButton,- Box,- PopoverMenuItemRightSlot,- Tooltip,- InputField,-} from "@webstudio-is/design-system";-import { BreakpointsEditor } from "./breakpoints-editor";-import { BreakpointsPopoverToolbarButton } from "./breakpoints-popover-toolbar-button";-import { WidthInput } from "./width-input";-import { ConfirmationDialog } from "./confirmation-dialog";-import {- $breakpoints,- $styles,- $selectedBreakpointId,- $selectedBreakpoint,- $isContentMode,-} from "~/shared/nano-states";-import {- $breakpointsMenuView,- groupBreakpoints,- isBaseBreakpoint,- minCanvasWidth,-} from "~/shared/breakpoints";-import { $scale } from "~/builder/shared/nano-states";-import { serverSyncStore } from "~/shared/sync/sync-stores";-import { setCanvasWidth } from "~/builder/shared/calc-canvas-width";--export const BreakpointsPopover = () => {- const view = useStore($breakpointsMenuView);- const [breakpointToDelete, setBreakpointToDelete] = useState<- Breakpoint | undefined- >();- const breakpoints = useStore($breakpoints);- const selectedBreakpoint = useStore($selectedBreakpoint);- const scale = useStore($scale);- const isContentMode = useStore($isContentMode);-- if (selectedBreakpoint === undefined) {- return null;- }-- const handleDelete = () => {- if (breakpointToDelete === undefined) {- return;- }- serverSyncStore.createTransaction(- [$breakpoints, $styles],- (breakpoints, styles) => {- const breakpointId = breakpointToDelete.id;- breakpoints.delete(breakpointId);- for (const [styleDeclKey, styleDecl] of styles) {- if (styleDecl.breakpointId === breakpointId) {- styles.delete(styleDeclKey);- }- }- }- );-- if (breakpointToDelete.id === selectedBreakpoint.id) {- const breakpointsArray = Array.from(breakpoints.values());- const base =- breakpointsArray.find(isBaseBreakpoint) ?? breakpointsArray[0];- $selectedBreakpointId.set(base.id);- setCanvasWidth(base.id);- }- setBreakpointToDelete(undefined);- $breakpointsMenuView.set("editor");- };-- return (- <Popover- open={view !== undefined}- onOpenChange={(isOpen) => {- $breakpointsMenuView.set(isOpen ? "initial" : undefined);- }}- >- <Tooltip content="Breakpoints">- <PopoverTrigger aria-label="Breakpoints" asChild>- <BreakpointsPopoverToolbarButton css={{ gap: theme.spacing[5] }} />- </PopoverTrigger>- </Tooltip>- <PopoverContent- sideOffset={0}- collisionPadding={4}- align="start"- css={{ width: theme.spacing[30] }}- >- {view === "confirmation" && breakpointToDelete && (- <ConfirmationDialog- breakpoint={breakpointToDelete}- onAbort={() => {- setBreakpointToDelete(undefined);- $breakpointsMenuView.set("editor");- }}- onConfirm={handleDelete}- />- )}- {view === "editor" && (- <BreakpointsEditor- onDelete={(breakpoint) => {- setBreakpointToDelete(breakpoint);- $breakpointsMenuView.set("confirmation");- }}- />- )}- {view === "initial" && (- <>- <Flex css={{ padding: theme.panel.padding }} gap="3">- <WidthInput min={minCanvasWidth} />- <Flex align="center" gap="2">- <Label>Scale</Label>- <InputField- value={`${Math.round(scale)}%`}- tabIndex={-1}- readOnly- />- </Flex>- </Flex>- <PopoverSeparator />- <List asChild>- <Flex- direction="column"- css={{ px: theme.spacing[3], py: theme.spacing[5] }}- >- {groupBreakpoints(Array.from(breakpoints.values())).map(- (breakpoint, index) => {- return (- <ListItem- asChild- onSelect={() => {- $selectedBreakpointId.set(breakpoint.id);- setCanvasWidth(breakpoint.id);- }}- index={index}- key={breakpoint.id}- >- <MenuItemButton withIndicator>- {breakpoint === selectedBreakpoint && (- <MenuItemIndicator>- <MenuCheckedIcon />- </MenuItemIndicator>- )}- <Box- css={{ flexGrow: 1, textAlign: "left" }}- as="span"- >- {breakpoint.label}- </Box>- <PopoverMenuItemRightSlot- css={{ color: theme.colors.foregroundSubtle }}- >- {breakpoint.minWidth !== undefined- ? `≥ ${breakpoint.minWidth} PX`- : breakpoint.maxWidth !== undefined- ? `≤ ${breakpoint.maxWidth} PX`- : "All Sizes"}- </PopoverMenuItemRightSlot>- </MenuItemButton>- </ListItem>- );- }- )}- </Flex>- </List>- </>- )}- {(view === "editor" || view === "initial") && (- <>- <PopoverSeparator />- <Flex- css={{- justifyContent: "center",- padding: theme.spacing[5],- }}- >- <Tooltip- content={- isContentMode- ? "Editing is not allowed in content mode"- : undefined- }- >- <Button- color="neutral"- css={{ flexGrow: 1 }}- disabled={isContentMode}- onClick={(event) => {- event.preventDefault();- $breakpointsMenuView.set(- view === "initial" ? "editor" : "initial"- );- }}- >- {view === "editor" ? "Done" : "Edit breakpoints"}- </Button>- </Tooltip>- </Flex>- </>- )}- </PopoverContent>- </Popover>- );-};diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-selector-container.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-selector-container.tsxdeleted file mode 100644index 4b14aaafde..0000000000--- a/apps/builder/app/builder/features/breakpoints/breakpoints-selector-container.tsx+++ /dev/null@@ -1,18 +0,0 @@-import { useStore } from "@nanostores/react";-import { $breakpoints } from "~/shared/sync/data-stores";-import { $selectedBreakpoint } from "~/shared/nano-states";-import { BreakpointsSelector } from "./breakpoints-selector";--export const BreakpointsSelectorContainer = () => {- const breakpoints = useStore($breakpoints);- const selectedBreakpoint = useStore($selectedBreakpoint);- if (selectedBreakpoint === undefined) {- return null;- }- return (- <BreakpointsSelector- breakpoints={breakpoints}- selectedBreakpoint={selectedBreakpoint}- />- );-};diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-selector.stories.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-selector.stories.tsxindex 6e35c4e7a0..7c117d45c4 100644--- a/apps/builder/app/builder/features/breakpoints/breakpoints-selector.stories.tsx+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-selector.stories.tsx@@ -1,85 +1,10 @@-import { nanoid } from "nanoid";-import { StorySection } from "@webstudio-is/design-system";-import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";import { BreakpointsSelector } from "./breakpoints-selector";-const createBreakpoints = (breakpoints: Array<Breakpoint>): Breakpoints => {- const breakpointsMap: [Breakpoint["id"], Breakpoint][] = breakpoints.map(- (breakpoint) => {- const id = nanoid();- return [- id,- {- ...breakpoint,- id,- },- ];- }- );- return new Map(breakpointsMap);+export const Basic = () => {+ return <BreakpointsSelector />;};-export const Story = () => {- const mixed = createBreakpoints([- { id: "placeholder", label: "Extra Large", minWidth: 1440 },- { id: "placeholder", label: "Large", minWidth: 1280 },- { id: "placeholder", label: "Base" },- { id: "placeholder", label: "Tablet", maxWidth: 991 },- { id: "placeholder", label: "Mobile landscape", maxWidth: 767 },- { id: "placeholder", label: "Mobile portrait", maxWidth: 479 },- ]);- const selectedBreakpointMixed = Array.from(mixed.values()).at(2);-- const max = createBreakpoints([- { id: "placeholder", label: "Base" },- { id: "placeholder", label: "Tablet", maxWidth: 991 },- { id: "placeholder", label: "Mobile landscape", maxWidth: 767 },- { id: "placeholder", label: "Mobile portrait", maxWidth: 479 },- ]);- const selectedBreakpointMax = Array.from(max.values()).at(0);-- const min = createBreakpoints([- { id: "placeholder", label: "Extra Large", minWidth: 1440 },- { id: "placeholder", label: "Large", minWidth: 1280 },- { id: "placeholder", label: "Base" },- ]);- const selectedBreakpointMin = Array.from(min.values()).at(2);-- if (- selectedBreakpointMixed === undefined ||- selectedBreakpointMax === undefined ||- selectedBreakpointMin === undefined- ) {- return null;- }-- return (- <>- <StorySection title="All">- <BreakpointsSelector- breakpoints={mixed}- selectedBreakpoint={selectedBreakpointMixed}- />- </StorySection>- <StorySection title="Max-width">- <BreakpointsSelector- breakpoints={max}- selectedBreakpoint={selectedBreakpointMax}- />- </StorySection>- <StorySection title="Min-width">- <BreakpointsSelector- breakpoints={min}- selectedBreakpoint={selectedBreakpointMin}- />- </StorySection>- </>- );-};--Story.storyName = "breakpoints-selector";-export default {title: "Breakpoints Selector",- component: Story,+ component: Basic,};diff --git a/apps/builder/app/builder/features/breakpoints/breakpoints-selector.tsx b/apps/builder/app/builder/features/breakpoints/breakpoints-selector.tsxindex 99bf435e45..503a0651dd 100644--- a/apps/builder/app/builder/features/breakpoints/breakpoints-selector.tsx+++ b/apps/builder/app/builder/features/breakpoints/breakpoints-selector.tsx@@ -1,5 +1,5 @@-import { useCallback, useEffect, useRef, useState } from "react";-import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";+import { useCallback, useRef } from "react";+import type { Breakpoint } from "@webstudio-is/sdk";import {Flex,Text,@@ -10,27 +10,45 @@ import {theme,} from "@webstudio-is/design-system";import { AlertIcon, AsteriskIcon } from "@webstudio-is/icons";+import { useStore } from "@nanostores/react";import { CascadeIndicator } from "./cascade-indicator";import {$selectedBreakpoint,$selectedBreakpointId,+ $breakpoints,} from "~/shared/nano-states";import { groupBreakpoints, isBaseBreakpoint } from "~/shared/breakpoints";import { setCanvasWidth } from "../../shared/calc-canvas-width";import { $canvasWidth } from "~/builder/shared/nano-states";import { useDebouncedCallback } from "use-debounce";+import { useEffect, useState } from "react";const getTooltipContent = (breakpoint: Breakpoint) => {+ const conditionText = breakpoint.condition+ ? ` (${breakpoint.condition})`+ : "";+if (isBaseBreakpoint(breakpoint)) {return (<Text>- <Text variant="regularBold">Base</Text>+ <Text variant="regularBold">Base{conditionText}</Text><br />Styles on Base apply to all viewport sizes unless overwritten by anotherbreakpoint. Start your styling here.</Text>);}++ if (breakpoint.condition) {+ return (+ <Text>+ <Text variant="regularBold">{breakpoint.condition}</Text>+ <br />+ Styles on this breakpoint apply when {breakpoint.condition}.+ </Text>+ );+ }+if (breakpoint.maxWidth !== undefined) {return (<Text>@@ -59,6 +77,13 @@ const breakpointMatchesMediaQuery = (breakpoint?: Breakpoint,canvasWidth?: number) => {+ // Custom condition breakpoints depend on runtime browser/device features (orientation, hover, color-scheme, etc.)+ // rather than canvas width, so there's no width-related zoom mismatch to detect. Returning true prevents the+ // ZoomWarning component from showing false warnings for breakpoints where canvas width is irrelevant.+ if (breakpoint?.condition !== undefined) {+ return true;+ }+if (canvasWidth === undefined ||(breakpoint?.minWidth === undefined && breakpoint?.maxWidth === undefined)@@ -124,18 +149,16 @@ const ZoomWarning = () => {);};-type BreakpointsSelector = {- breakpoints: Breakpoints;- selectedBreakpoint: Breakpoint;-};--export const BreakpointsSelector = ({- breakpoints,- selectedBreakpoint,-}: BreakpointsSelector) => {+export const BreakpointsSelector = () => {+ const breakpoints = useStore($breakpoints);+ const selectedBreakpoint = useStore($selectedBreakpoint);const refs = useRef(new Map<string, HTMLButtonElement>());const getButtonById = useCallback((id: string) => refs.current.get(id), []);+ if (selectedBreakpoint === undefined) {+ return;+ }+return (<Toolbar><ToolbarToggleGroup@@ -152,39 +175,42 @@ export const BreakpointsSelector = ({}}css={{ position: "relative" }}>- {groupBreakpoints(Array.from(breakpoints.values())).map(- (breakpoint) => {- return (- <Tooltip- key={breakpoint.id}- content={getTooltipContent(breakpoint)}- variant="wrapped"- disableHoverableContent+ {(() => {+ const grouped = groupBreakpoints(Array.from(breakpoints.values()));++ // Render width-based breakpoints+ return grouped.widthBased.map((breakpoint) => (+ <Tooltip+ key={breakpoint.id}+ content={getTooltipContent(breakpoint)}+ variant="wrapped"+ disableHoverableContent+ >+ <ToolbarToggleItem+ variant="subtle"+ ref={(node) => {+ if (node) {+ refs.current.set(breakpoint.id, node);+ return;+ }+ refs.current.delete(breakpoint.id);+ }}+ value={breakpoint.id}>- <ToolbarToggleItem- variant="subtle"- ref={(node) => {- if (node) {- refs.current.set(breakpoint.id, node);- return;- }- refs.current.delete(breakpoint.id);- }}- value={breakpoint.id}- >- {breakpoint.minWidth ?? breakpoint.maxWidth ?? (- <AsteriskIcon size={22} />- )}- </ToolbarToggleItem>- </Tooltip>- );- }+ {breakpoint.minWidth ?? breakpoint.maxWidth ?? (+ <AsteriskIcon size={22} />+ )}+ </ToolbarToggleItem>+ </Tooltip>+ ));+ })()}+ {selectedBreakpoint.condition === undefined && (+ <CascadeIndicator+ getButtonById={getButtonById}+ selectedBreakpoint={selectedBreakpoint}+ breakpoints={breakpoints}+ />)}- <CascadeIndicator- getButtonById={getButtonById}- selectedBreakpoint={selectedBreakpoint}- breakpoints={breakpoints}- /></ToolbarToggleGroup><ZoomWarning /></Toolbar>diff --git a/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsx b/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsxnew file mode 100644index 0000000000..b1619113c5--- /dev/null+++ b/apps/builder/app/builder/features/breakpoints/canvas-settings-popover.tsx@@ -0,0 +1,68 @@+import { useStore } from "@nanostores/react";+import {+ theme,+ Flex,+ Label,+ Popover,+ PopoverContent,+ PopoverTrigger,+ InputField,+ ToolbarButton,+ Text,+} from "@webstudio-is/design-system";+import { WidthInput } from "./width-input";+import { minCanvasWidth } from "~/shared/breakpoints";+import { $canvasWidth, $scale } from "~/builder/shared/nano-states";+import { $selectedBreakpoint } from "~/shared/nano-states";+import { ChevronDownIcon } from "@webstudio-is/icons";+import { useState } from "react";++export const CanvasSettingsPopover = () => {+ const selectedBreakpoint = useStore($selectedBreakpoint);+ const scale = useStore($scale);+ const canvasWidth = useStore($canvasWidth);+ const [isOpen, setIsOpen] = useState(false);+ if (selectedBreakpoint === undefined || canvasWidth === undefined) {+ return;+ }+ const roundedScale = Math.round(scale);++ return (+ <Popover open={isOpen} onOpenChange={setIsOpen}>+ <PopoverTrigger aria-label="Canvas Settings" asChild>+ <ToolbarButton>+ <Text+ css={{+ display: "flex",+ gap: "1ch",+ fontVariantNumeric: "tabular-nums",+ }}+ color={isOpen ? "contrast" : "moreSubtle"}+ >+ {Math.round(canvasWidth)}px+ {roundedScale !== 100 && <span>{`${roundedScale}%`}</span>}+ <ChevronDownIcon />+ </Text>+ </ToolbarButton>+ </PopoverTrigger>+ <PopoverContent+ sideOffset={0}+ collisionPadding={4}+ align="start"+ css={{ width: theme.spacing[30] }}+ >+ <Flex css={{ padding: theme.panel.padding }} gap="3">+ <WidthInput min={minCanvasWidth} />+ <Flex align="center" gap="2">+ <Label>Scale</Label>+ <InputField+ value={`${Math.round(scale)}%`}+ tabIndex={-1}+ readOnly+ />+ </Flex>+ </Flex>+ </PopoverContent>+ </Popover>+ );+};diff --git a/apps/builder/app/builder/features/breakpoints/condition-input.tsx b/apps/builder/app/builder/features/breakpoints/condition-input.tsxnew file mode 100644index 0000000000..1a25e73f09--- /dev/null+++ b/apps/builder/app/builder/features/breakpoints/condition-input.tsx@@ -0,0 +1,185 @@+import { useMemo } from "react";+import { Combobox } from "@webstudio-is/design-system";++const PREDEFINED_CONDITIONS = [+ {+ value: "orientation:portrait",+ label: "Orientation: Portrait",+ description: "Device is in portrait mode (height > width)",+ },+ {+ value: "orientation:landscape",+ label: "Orientation: Landscape",+ description: "Device is in landscape mode (width > height)",+ },+ {+ value: "hover:hover",+ label: "Hover: Hover",+ description: "Primary input can hover over elements",+ },+ {+ value: "hover:none",+ label: "Hover: None",+ description: "Primary input cannot hover (e.g., touch screens)",+ },+ {+ value: "prefers-color-scheme:dark",+ label: "Color Scheme: Dark",+ description: "User prefers dark color scheme",+ },+ {+ value: "prefers-color-scheme:light",+ label: "Color Scheme: Light",+ description: "User prefers light color scheme",+ },+ {+ value: "prefers-reduced-motion:reduce",+ label: "Reduced Motion: Reduce",+ description: "User prefers reduced motion/animations",+ },+ {+ value: "prefers-reduced-motion:no-preference",+ label: "Reduced Motion: No Preference",+ description: "User has no preference for reduced motion",+ },+ {+ value: "pointer:coarse",+ label: "Pointer: Coarse",+ description: "Primary input has limited accuracy (e.g., touch)",+ },+ {+ value: "pointer:fine",+ label: "Pointer: Fine",+ description: "Primary input has fine accuracy (e.g., mouse)",+ },+ {+ value: "pointer:none",+ label: "Pointer: None",+ description: "No pointing device available",+ },+ {+ value: "any-hover:hover",+ label: "Any Hover: Hover",+ description: "At least one input can hover",+ },+ {+ value: "any-hover:none",+ label: "Any Hover: None",+ description: "No inputs can hover",+ },+ {+ value: "any-pointer:coarse",+ label: "Any Pointer: Coarse",+ description: "At least one input has limited accuracy",+ },+ {+ value: "any-pointer:fine",+ label: "Any Pointer: Fine",+ description: "At least one input has fine accuracy",+ },+ {+ value: "any-pointer:none",+ label: "Any Pointer: None",+ description: "No pointing devices available",+ },+ {+ value: "prefers-contrast:more",+ label: "Contrast: More",+ description: "User prefers higher contrast",+ },+ {+ value: "prefers-contrast:less",+ label: "Contrast: Less",+ description: "User prefers lower contrast",+ },+ {+ value: "prefers-contrast:no-preference",+ label: "Contrast: No Preference",+ description: "User has no contrast preference",+ },+ {+ value: "display-mode:fullscreen",+ label: "Display Mode: Fullscreen",+ description: "App is in fullscreen mode",+ },+ {+ value: "display-mode:standalone",+ label: "Display Mode: Standalone",+ description: "App is in standalone mode (PWA)",+ },+ {+ value: "display-mode:minimal-ui",+ label: "Display Mode: Minimal UI",+ description: "App with minimal browser UI (PWA)",+ },+ {+ value: "display-mode:browser",+ label: "Display Mode: Browser",+ description: "App in regular browser tab",+ },+];++type Condition = { value: string; label: string; description?: string };++type ConditionInputProps = {+ name?: string;+ value: string;+ onChange: (value: string) => void;+ onBlur?: () => void;+ placeholder?: string;+};++export const ConditionInput = ({+ name,+ value,+ onChange,+ onBlur,+ placeholder = "e.g., orientation:portrait",+}: ConditionInputProps) => {+ // Find the matching condition item or create a custom one+ const selectedItem: Condition | null = useMemo(() => {+ const found = PREDEFINED_CONDITIONS.find((c) => c.value === value);+ if (found) {+ return found;+ }+ // If value doesn't match any predefined condition, create a custom item+ if (value) {+ return { value, label: value };+ }+ return null;+ }, [value]);++ return (+ <Combobox<Condition>+ value={selectedItem}+ itemToString={(item) => item?.value ?? ""}+ getItems={() => PREDEFINED_CONDITIONS}+ match={(search, items, itemToString) => {+ if (!search) {+ return items;+ }+ const searchLower = search.toLowerCase();+ return items.filter(+ (item) =>+ item.label.toLowerCase().includes(searchLower) ||+ itemToString(item).toLowerCase().includes(searchLower)+ );+ }}+ getItemProps={(item) => ({+ children: item.label,+ })}+ getDescription={(item) => item?.description}+ onItemSelect={(item) => {+ if (item) {+ onChange(item.value);+ }+ }}+ onChange={(value) => {+ onChange(value ?? "");+ }}+ name={name}+ onBlur={onBlur}+ placeholder={placeholder}+ />+ );+};diff --git a/apps/builder/app/builder/features/breakpoints/confirmation-dialog.tsx b/apps/builder/app/builder/features/breakpoints/confirmation-dialog.tsxindex 3e5d9a73cc..38271b6aca 100644--- a/apps/builder/app/builder/features/breakpoints/confirmation-dialog.tsx+++ b/apps/builder/app/builder/features/breakpoints/confirmation-dialog.tsx@@ -1,43 +1,48 @@import type { Breakpoint } from "@webstudio-is/sdk";-import { theme, Button, Flex, Text } from "@webstudio-is/design-system";+import {+ theme,+ Button,+ Flex,+ Text,+ Dialog,+ DialogContent,+ DialogTitle,+ DialogActions,+} from "@webstudio-is/design-system";type ConfirmationDialogProps = {onAbort: () => void;onConfirm: () => void;breakpoint: Breakpoint;+ open: boolean;};export const ConfirmationDialog = ({breakpoint,onConfirm,onAbort,+ open,}: ConfirmationDialogProps) => {return (- <Flex gap="2" direction="column" css={{ padding: theme.spacing[5] }}>- <Text>{`Are you sure you want to delete "${breakpoint.label}"?`}</Text>- <Text>- {`Deleting a breakpoint will also delete all styles associated with this+ <Dialog open={open} onOpenChange={(isOpen) => !isOpen && onAbort()}>+ <DialogContent>+ <DialogTitle>Delete Breakpoint</DialogTitle>+ <Flex gap="2" direction="column" css={{ padding: theme.spacing[5] }}>+ <Text>{`Are you sure you want to delete "${breakpoint.label}"?`}</Text>+ <Text>+ {`Deleting a breakpoint will also delete all styles associated with thisbreakpoint.`}- </Text>- <Flex justify="end" gap="2">- <Button- onClick={() => {- onConfirm();- }}- color="destructive"- >- Delete- </Button>- <Button- color="neutral"- autoFocus- onClick={() => {- onAbort();- }}- >- Abort- </Button>- </Flex>- </Flex>+ </Text>+ </Flex>+ <DialogActions>+ <Button color="neutral" onClick={onAbort}>+ Cancel+ </Button>+ <Button onClick={onConfirm} color="destructive">+ Delete+ </Button>+ </DialogActions>+ </DialogContent>+ </Dialog>);};diff --git a/apps/builder/app/builder/features/breakpoints/index.ts b/apps/builder/app/builder/features/breakpoints/index.tsindex 465cf5dabd..5cf62d7d2e 100644--- a/apps/builder/app/builder/features/breakpoints/index.ts+++ b/apps/builder/app/builder/features/breakpoints/index.ts@@ -1,2 +1 @@-export * from "./breakpoints-popover";-export * from "./breakpoints-selector-container";+export * from "./breakpoints-container";diff --git a/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx b/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsxindex 0dd3e8d484..b1bfa9c011 100644--- a/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx@@ -29,9 +29,19 @@ export const $breakpointOptions = computed(if (!isOpen) {return [];}- const sortedBreakpoints = Array.from(breakpoints.values()).sort(- compareMedia+ const allBreakpoints = Array.from(breakpoints.values());++ // Separate custom condition breakpoints from width-based+ const customBreakpoints = allBreakpoints.filter(+ (bp) => bp.condition !== undefined);+ const widthBasedBreakpoints = allBreakpoints+ .filter((bp) => bp.condition === undefined)+ .sort(compareMedia);++ // Combine with custom conditions at the end+ const sortedBreakpoints = [...widthBasedBreakpoints, ...customBreakpoints];+const breakpointOptions: BreakpointOption[] = [];for (let index = 0; index < sortedBreakpoints.length; index += 1) {const breakpoint = sortedBreakpoints[index];@@ -39,7 +49,9 @@ export const $breakpointOptions = computed(continue;}const width =- (breakpoint.minWidth ?? breakpoint.maxWidth)?.toString() ?? "";+ breakpoint.condition ??+ (breakpoint.minWidth ?? breakpoint.maxWidth)?.toString() ??+ "";breakpointOptions.push({terms: ["breakpoints", breakpoint.label, width],type: "breakpoint",@@ -52,6 +64,10 @@ export const $breakpointOptions = computed();const getBreakpointLabel = (breakpoint: Breakpoint) => {+ if (breakpoint.condition) {+ return `${breakpoint.label}: ${breakpoint.condition}`;+ }+let label = "All Sizes";if (breakpoint.minWidth !== undefined) {label = `≥ ${breakpoint.minWidth} PX`;diff --git a/apps/builder/app/builder/features/pages/page-settings.stories.tsx b/apps/builder/app/builder/features/pages/page-settings.stories.tsxindex 8378896b31..99c538c291 100644--- a/apps/builder/app/builder/features/pages/page-settings.stories.tsx+++ b/apps/builder/app/builder/features/pages/page-settings.stories.tsx@@ -1,6 +1,11 @@import { $pages } from "~/shared/nano-states/pages";import { PageSettings } from "./page-settings";-import { Grid, theme } from "@webstudio-is/design-system";+import {+ Grid,+ theme,+ Dialog,+ DialogContent,+} from "@webstudio-is/design-system";import { $assets, $project } from "~/shared/sync/data-stores";import { createDefaultPages } from "@webstudio-is/project-build";import { isRootFolder } from "@webstudio-is/sdk";@@ -83,22 +88,26 @@ $project.set({export const PageSettingsEdit = () => {return (- <Grid- css={{- width: theme.spacing[35],- margin: "auto",- border: `1px solid ${theme.colors.borderMain}`,- boxShadow: theme.shadows.menuDropShadow,- background: theme.colors.backgroundPanel,- borderRadius: theme.borderRadius[4],- }}- >- <PageSettings- onClose={() => {}}- onDuplicate={() => {}}- onDelete={() => {}}- pageId="pageId"- />- </Grid>+ <Dialog open>+ <DialogContent>+ <Grid+ css={{+ width: theme.spacing[35],+ margin: "auto",+ border: `1px solid ${theme.colors.borderMain}`,+ boxShadow: theme.shadows.menuDropShadow,+ background: theme.colors.backgroundPanel,+ borderRadius: theme.borderRadius[4],+ }}+ >+ <PageSettings+ onClose={() => {}}+ onDuplicate={() => {}}+ onDelete={() => {}}+ pageId="pageId"+ />+ </Grid>+ </DialogContent>+ </Dialog>);};diff --git a/apps/builder/app/builder/features/topbar/topbar.tsx b/apps/builder/app/builder/features/topbar/topbar.tsxindex af7297b418..bc888d54e1 100644--- a/apps/builder/app/builder/features/topbar/topbar.tsx+++ b/apps/builder/app/builder/features/topbar/topbar.tsx@@ -19,10 +19,7 @@ import { ShareButton } from "./share";import { PublishButton } from "./publish";import { SyncStatus } from "./sync-status";import { Menu } from "./menu";-import {- BreakpointsSelectorContainer,- BreakpointsPopover,-} from "../breakpoints";+import { BreakpointsContainer } from "../breakpoints";import { ViewMode } from "./view-mode";import { AddressBarPopover } from "../address-bar";import { toggleActiveSidebarPanel } from "~/builder/shared/nano-states";@@ -66,20 +63,13 @@ const PagesButton = () => {const topbarContainerStyle = css({position: "relative",display: "flex",+ justifyContent: "space-between",background: theme.colors.backgroundTopbar,height: theme.spacing[15],paddingRight: theme.panel.paddingInline,color: theme.colors.foregroundContrastMain,});-// We are hiding some elements on mobile because we want to let user-// test in preview mode with device simulators-const hideOnMobile: CSS = {- "@media (max-width: 640px)": {- display: "none",- },-};-type TopbarProps = {project: Project;hasProPlan: boolean;@@ -91,28 +81,23 @@ export const Topbar = ({ project, hasProPlan, css, loading }: TopbarProps) => {const pages = useStore($pages);return (<nav className={topbarContainerStyle({ css })}>- <Flex grow={false} shrink={false}>- <Menu />- </Flex>+ <Flex css={{ flexBasis: "20%" }}>+ <Flex grow={false} shrink={false}>+ <Menu />+ </Flex>- {/* prevent rendering when data is not loaded */}- {pages && (- <>+ {/* prevent rendering when data is not loaded */}+ {pages && (<Flex align="center"><PagesButton /><AddressBarPopover /></Flex>- <Flex css={{ minWidth: theme.spacing[23], ...hideOnMobile }}>- <BreakpointsPopover />- </Flex>- <Flex grow></Flex>- <Flex align="center" justify="center" css={hideOnMobile}>- <BreakpointsSelectorContainer />- </Flex>- </>- )}- <Flex grow></Flex>- <Toolbar>+ )}+ </Flex>+ <Flex css={{ flexBasis: "60%" }} justify="center">+ <BreakpointsContainer />+ </Flex>+ <Toolbar css={{ flexBasis: "20%" }}><ToolbarToggleGrouptype="single"css={{diff --git a/apps/builder/app/builder/shared/calc-canvas-width.test.ts b/apps/builder/app/builder/shared/calc-canvas-width.test.tsindex 5b3d4a384c..964a436a08 100644--- a/apps/builder/app/builder/shared/calc-canvas-width.test.ts+++ b/apps/builder/app/builder/shared/calc-canvas-width.test.ts@@ -263,6 +263,124 @@ describe("other breakpoints", () => {});});+describe("custom condition breakpoints", () => {+ test("returns undefined for custom condition breakpoint", () => {+ const workspaceWidth = 1200;+ const breakpoints = [+ { id: "0", label: "Base" },+ { id: "1", label: "Portrait", condition: "orientation:portrait" },+ ];+ expect(+ calcCanvasWidth({+ breakpoints,+ selectedBreakpoint: breakpoints[1],+ workspaceWidth,+ })+ ).toBeUndefined();+ });++ test("returns undefined for hover condition", () => {+ const workspaceWidth = 1200;+ const breakpoints = [+ { id: "0", label: "Base" },+ { id: "1", label: "Hover", condition: "hover:hover" },+ ];+ expect(+ calcCanvasWidth({+ breakpoints,+ selectedBreakpoint: breakpoints[1],+ workspaceWidth,+ })+ ).toBeUndefined();+ });++ test("returns undefined for prefers-color-scheme", () => {+ const workspaceWidth = 1200;+ const breakpoints = [+ { id: "0", label: "Base" },+ { id: "1", label: "Dark", condition: "prefers-color-scheme:dark" },+ ];+ expect(+ calcCanvasWidth({+ breakpoints,+ selectedBreakpoint: breakpoints[1],+ workspaceWidth,+ })+ ).toBeUndefined();+ });++ test("returns undefined regardless of custom canvasWidth for condition breakpoints", () => {+ const workspaceWidth = 1200;+ const breakpoints = [+ { id: "0", label: "Base" },+ { id: "1", label: "Portrait", condition: "orientation:portrait" },+ ];+ expect(+ calcCanvasWidth({+ breakpoints,+ selectedBreakpoint: breakpoints[1],+ workspaceWidth,+ canvasWidth: 800, // Should be ignored+ })+ ).toBeUndefined();+ });++ test("base breakpoint ignores custom condition breakpoints when calculating width", () => {+ const workspaceWidth = 1200;+ const breakpoints = [+ { id: "0", label: "Base" },+ { id: "1", label: "Tablet", minWidth: 768 },+ { id: "2", label: "Portrait", condition: "orientation:portrait" },+ { id: "3", label: "Hover", condition: "hover:hover" },+ ];+ expect(+ calcCanvasWidth({+ breakpoints,+ selectedBreakpoint: breakpoints[0],+ workspaceWidth,+ })+ ).toStrictEqual(767); // minWidth - 1, ignoring condition breakpoints+ });++ test("handles mix of width-based and condition breakpoints", () => {+ const workspaceWidth = 1200;+ const breakpoints = [+ { id: "0", label: "Base" },+ { id: "1", label: "Tablet", minWidth: 768 },+ { id: "2", label: "Portrait", condition: "orientation:portrait" },+ { id: "3", label: "Desktop", minWidth: 1024 },+ { id: "4", label: "Hover", condition: "hover:hover" },+ ];++ // Width-based breakpoint works normally+ expect(+ calcCanvasWidth({+ breakpoints,+ selectedBreakpoint: breakpoints[1],+ workspaceWidth,+ })+ ).toStrictEqual(768);++ // Condition breakpoint returns undefined+ expect(+ calcCanvasWidth({+ breakpoints,+ selectedBreakpoint: breakpoints[2],+ workspaceWidth,+ })+ ).toBeUndefined();++ // Base calculates correctly ignoring condition breakpoints+ expect(+ calcCanvasWidth({+ breakpoints,+ selectedBreakpoint: breakpoints[0],+ workspaceWidth,+ })+ ).toStrictEqual(767);+ });+});+describe("setCanvasWidth", () => {beforeEach(() => {// Reset stores before each test@@ -344,6 +462,39 @@ describe("setCanvasWidth", () => {setCanvasWidth("0");expect($canvasWidth.get()).toBe(1500);});++ test("returns undefined for custom condition breakpoint in setCanvasWidth", () => {+ $workspaceRect.set(createRect(1200, 800));+ $breakpoints.set(+ new Map([+ ["0", { id: "0", label: "Base" }],+ [+ "1",+ { id: "1", label: "Portrait", condition: "orientation:portrait" },+ ],+ ])+ );++ const result = setCanvasWidth("1");++ expect(result).toBe(true);+ expect($canvasWidth.get()).toBeUndefined(); // Undefined for condition breakpoints+ });++ test("returns undefined for hover condition breakpoint in setCanvasWidth", () => {+ $workspaceRect.set(createRect(1500, 800));+ $breakpoints.set(+ new Map([+ ["0", { id: "0", label: "Base" }],+ ["1", { id: "1", label: "Hover", condition: "hover:hover" }],+ ])+ );++ const result = setCanvasWidth("1");++ expect(result).toBe(true);+ expect($canvasWidth.get()).toBeUndefined();+ });});// Note: useSetCanvasWidth is a React hook with complex side effects (multiple store subscriptionsdiff --git a/apps/builder/app/builder/shared/calc-canvas-width.ts b/apps/builder/app/builder/shared/calc-canvas-width.tsindex 617e7f4848..e1576e0cab 100644--- a/apps/builder/app/builder/shared/calc-canvas-width.ts+++ b/apps/builder/app/builder/shared/calc-canvas-width.ts@@ -65,6 +65,12 @@ export const calcCanvasWidth = ({workspaceWidth: number;canvasWidth?: number;}) => {+ // Condition-based breakpoints (e.g., orientation:portrait, hover:hover) don't have width ranges+ // Return undefined so the width will be defined by current canvas width+ if (selectedBreakpoint.condition !== undefined) {+ return;+ }+// When user has resized the canvas to a custom value, we want to keep it.if (isCustomCanvasWidth(breakpoints, selectedBreakpoint, canvasWidth)) {return canvasWidth;@@ -79,26 +85,26 @@ export const calcCanvasWidth = ({return workspaceWidth;}- const grouped = groupBreakpoints(breakpoints).filter(- ({ minWidth, maxWidth }) => {- // We don't want to grow the canvas beyond the workspace width.- if (minWidth && minWidth < workspaceWidth) {- return true;- }- // Max width can not be smaller than the minimum canvas width.- if (maxWidth && maxWidth > minCanvasWidth) {- return true;- }+ const grouped = groupBreakpoints(breakpoints);+ // Only consider width-based breakpoints for canvas sizing+ const filtered = grouped.widthBased.filter(({ minWidth, maxWidth }) => {+ // We don't want to grow the canvas beyond the workspace width.+ if (minWidth && minWidth < workspaceWidth) {+ return true;}- );- let lowestMinWidth = grouped+ // Max width can not be smaller than the minimum canvas width.+ if (maxWidth && maxWidth > minCanvasWidth) {+ return true;+ }+ });+ let lowestMinWidth = filtered.filter(({ minWidth }) => minWidth !== undefined).at(-1)?.minWidth;lowestMinWidth =lowestMinWidth === undefined ? workspaceWidth : lowestMinWidth - 1;- let highestMaxWidth = grouped+ let highestMaxWidth = filtered.filter(({ maxWidth }) => maxWidth !== undefined).at(0)?.maxWidth;diff --git a/apps/builder/app/shared/breakpoints-utils.test.ts b/apps/builder/app/shared/breakpoints-utils.test.tsindex 6dacf0d43b..1a81bbf619 100644--- a/apps/builder/app/shared/breakpoints-utils.test.ts+++ b/apps/builder/app/shared/breakpoints-utils.test.ts@@ -38,7 +38,8 @@ describe("groupBreakpoints", () => {{ maxWidth: 767 },{ maxWidth: 479 },];- const grouped = [+ const result = groupBreakpoints(initial);+ expect(result.widthBased).toStrictEqual([{ minWidth: 1920 },{ minWidth: 1440 },{ minWidth: 1280 },@@ -46,8 +47,8 @@ describe("groupBreakpoints", () => {{ maxWidth: 991 },{ maxWidth: 767 },{ maxWidth: 479 },- ];- expect(groupBreakpoints(initial)).toStrictEqual(grouped);+ ]);+ expect(result.custom).toStrictEqual([]);});test("handles unsorted input", () => {@@ -58,36 +59,70 @@ describe("groupBreakpoints", () => {{ maxWidth: 991 },{ minWidth: 1280 },];- const grouped = [+ const result = groupBreakpoints(initial);+ expect(result.widthBased).toStrictEqual([{ minWidth: 1920 },{ minWidth: 1280 },{},{ maxWidth: 991 },{ maxWidth: 479 },- ];- expect(groupBreakpoints(initial)).toStrictEqual(grouped);+ ]);+ expect(result.custom).toStrictEqual([]);});test("handles only min-width breakpoints", () => {const initial = [{ minWidth: 768 }, { minWidth: 1024 }];- const grouped = [{ minWidth: 1024 }, { minWidth: 768 }];- expect(groupBreakpoints(initial)).toStrictEqual(grouped);+ const result = groupBreakpoints(initial);+ expect(result.widthBased).toStrictEqual([+ { minWidth: 1024 },+ { minWidth: 768 },+ ]);+ expect(result.custom).toStrictEqual([]);});test("handles only max-width breakpoints", () => {const initial = [{ maxWidth: 991 }, { maxWidth: 479 }];- const grouped = [{ maxWidth: 991 }, { maxWidth: 479 }];- expect(groupBreakpoints(initial)).toStrictEqual(grouped);+ const result = groupBreakpoints(initial);+ expect(result.widthBased).toStrictEqual([+ { maxWidth: 991 },+ { maxWidth: 479 },+ ]);+ expect(result.custom).toStrictEqual([]);});test("handles only base breakpoint", () => {const initial = [{}];- const grouped = [{}];- expect(groupBreakpoints(initial)).toStrictEqual(grouped);+ const result = groupBreakpoints(initial);+ expect(result.widthBased).toStrictEqual([{}]);+ expect(result.custom).toStrictEqual([]);});test("handles empty array", () => {- expect(groupBreakpoints([])).toStrictEqual([]);+ const result = groupBreakpoints([]);+ expect(result.widthBased).toStrictEqual([]);+ expect(result.custom).toStrictEqual([]);+ });++ test("separates custom condition breakpoints from width-based", () => {+ const initial = [+ { minWidth: 1920 },+ { condition: "orientation: portrait" },+ { minWidth: 1280 },+ {},+ { condition: "hover: hover" },+ { maxWidth: 991 },+ ];+ const result = groupBreakpoints(initial);+ expect(result.widthBased).toStrictEqual([+ { minWidth: 1920 },+ { minWidth: 1280 },+ {},+ { maxWidth: 991 },+ ]);+ expect(result.custom).toStrictEqual([+ { condition: "orientation: portrait" },+ { condition: "hover: hover" },+ ]);});});diff --git a/apps/builder/app/shared/breakpoints-utils.ts b/apps/builder/app/shared/breakpoints-utils.tsindex 44c54fe990..ccbb6312b7 100644--- a/apps/builder/app/shared/breakpoints-utils.ts+++ b/apps/builder/app/shared/breakpoints-utils.ts@@ -3,6 +3,7 @@ import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";/*** Check if a breakpoint is the base breakpoint (no min or max width).+ * Note: Does not check for custom conditions.*/export const isBaseBreakpoint = (breakpoint: {minWidth?: number;@@ -10,26 +11,42 @@ export const isBaseBreakpoint = (breakpoint: {}) => breakpoint.minWidth === undefined && breakpoint.maxWidth === undefined;/**- * Group breakpoints into three categories: min-width, base (no min/max), and max-width.- * Returns them in UI display order: min-width (largest to smallest), base, max-width (largest to smallest).+ * Group breakpoints into width-based and custom condition categories.+ * Width-based breakpoints are ordered: min-width (largest to smallest), base, max-width (largest to smallest).+ * Custom condition breakpoints are kept separate and not sorted.+ *+ * Note: minWidth/maxWidth and condition are mutually exclusive - a breakpoint has either+ * width-based properties OR a custom condition, never both.*/export const groupBreakpoints = <- T extends { minWidth?: number; maxWidth?: number },+ T extends { minWidth?: number; maxWidth?: number; condition?: string },>(breakpoints: Array<T>-): Array<T> => {- const sorted = [...breakpoints].sort(compareMedia);+): { widthBased: Array<T>; custom: Array<T> } => {+ const custom = breakpoints.filter(+ (breakpoint) => breakpoint.condition !== undefined+ );+ const widthBased = breakpoints.filter(+ (breakpoint) => breakpoint.condition === undefined+ );++ const sorted = [...widthBased].sort(compareMedia);const maxs = sorted.filter((breakpoint) => breakpoint.maxWidth !== undefined);const mins = sorted.filter((breakpoint) => breakpoint.minWidth !== undefined).reverse();const base = sorted.filter(isBaseBreakpoint);- return [...mins, ...base, ...maxs];++ return {+ widthBased: [...mins, ...base, ...maxs],+ custom,+ };};/*** Build a map of merged breakpoint IDs from fragment breakpoints to existing breakpoints.- * Breakpoints are merged when they have matching minWidth, maxWidth, and label.+ * Breakpoints are merged when they have matching minWidth, maxWidth, condition, and label.+ * Note: minWidth/maxWidth and condition are mutually exclusive.** @param fragmentBreakpoints - Breakpoints from the fragment being inserted* @param existingBreakpoints - Existing breakpoints in the projectdiff --git a/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.ts b/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.tsindex ff5af737b2..d4eda0a64e 100644--- a/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.ts+++ b/apps/builder/app/shared/breakpoints/select-breakpoint-by-order.ts@@ -8,9 +8,9 @@ import { setCanvasWidth } from "~/builder/shared/calc-canvas-width";export const selectBreakpointByOrder = (orderNumber: number) => {const breakpoints = $breakpoints.get();const index = orderNumber - 1;- const breakpoint = groupBreakpoints(Array.from(breakpoints.values())).at(- index- );+ const grouped = groupBreakpoints(Array.from(breakpoints.values()));+ const allBreakpoints = [...grouped.widthBased, ...grouped.custom];+ const breakpoint = allBreakpoints.at(index);if (breakpoint) {$selectedBreakpointId.set(breakpoint.id);setCanvasWidth(breakpoint.id);diff --git a/packages/css-data/src/parse-css.test.ts b/packages/css-data/src/parse-css.test.tsindex 3b82ed04f5..6e83058bf8 100644--- a/packages/css-data/src/parse-css.test.ts+++ b/packages/css-data/src/parse-css.test.ts@@ -869,7 +869,35 @@ test("parse media query", () => {expect(parseMediaQuery(`(max-width: 768px)`)).toEqual({maxWidth: 768,});- expect(parseMediaQuery(`(hover: hover)`)).toEqual(undefined);+ expect(parseMediaQuery(`(orientation: portrait)`)).toEqual({+ condition: "orientation:portrait",+ });+ expect(parseMediaQuery(`(orientation: landscape)`)).toEqual({+ condition: "orientation:landscape",+ });+ expect(parseMediaQuery(`(hover: hover)`)).toEqual({+ condition: "hover:hover",+ });+ // 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(+ {+ condition: "orientation:portrait and hover:hover",+ }+ );+ // Test other media features+ expect(parseMediaQuery(`(prefers-color-scheme: dark)`)).toEqual({+ condition: "prefers-color-scheme:dark",+ });+ expect(parseMediaQuery(`(pointer: coarse)`)).toEqual({+ condition: "pointer:coarse",+ });});test("camel case css property", () => {diff --git a/packages/css-data/src/parse-css.ts b/packages/css-data/src/parse-css.tsindex 6147001b16..5d519ed334 100644--- a/packages/css-data/src/parse-css.ts+++ b/packages/css-data/src/parse-css.ts@@ -297,6 +297,7 @@ export const parseCss = (css: string): ParsedStyleDecl[] => {type ParsedBreakpoint = {minWidth?: number;maxWidth?: number;+ condition?: string;};export const parseMediaQuery = (@@ -305,23 +306,45 @@ export const parseMediaQuery = (const ast = csstree.parse(mediaQuery, { context: "mediaQuery" });let property: undefined | "minWidth" | "maxWidth";let value: undefined | number;+ const otherFeatures: string[] = [];+csstree.walk(ast, (node) => {if (node.type === "Feature") {if (node.name === "min-width") {property = "minWidth";- }- if (node.name === "max-width") {+ } else if (node.name === "max-width") {property = "maxWidth";+ } else {+ // Capture any other media feature as custom condition+ const generated = csstree.generate(node);+ // Remove outer parentheses if present+ let cleaned =+ generated.startsWith("(") && generated.endsWith(")")+ ? generated.slice(1, -1)+ : generated;+ // Normalize whitespace: remove spaces around colons for consistency+ cleaned = cleaned.replace(/\s*:\s*/g, ":");+ otherFeatures.push(cleaned);}}if (node.type === "Dimension" && node.unit === "px") {value = Number(node.value);}});++ const condition =+ otherFeatures.length > 0 ? otherFeatures.join(" and ") : undefined;++ // If there's a custom condition and no width, return only condition+ if (condition !== undefined && property === undefined) {+ return { condition };+ }+if (property === undefined || value === undefined) {return;}return {[property]: value,+ ...(condition !== undefined ? { condition } : {}),};};diff --git a/packages/css-engine/src/core/compare-media.test.ts b/packages/css-engine/src/core/compare-media.test.tsindex f9ca5f832e..166b2d0526 100644--- a/packages/css-engine/src/core/compare-media.test.ts+++ b/packages/css-engine/src/core/compare-media.test.ts@@ -62,4 +62,61 @@ describe("Compare media", () => {const sorted = initial.sort(compareMedia);expect(sorted).toStrictEqual(expected);});++ test("custom conditions sorted alphabetically after base", () => {+ const initial = [+ {},+ { condition: "orientation:portrait" },+ { condition: "hover:hover" },+ { condition: "prefers-color-scheme:dark" },+ ];+ const expected = [+ {},+ { condition: "hover:hover" },+ { condition: "orientation:portrait" },+ { condition: "prefers-color-scheme:dark" },+ ];+ const sorted = initial.sort(compareMedia);+ expect(sorted).toStrictEqual(expected);+ });++ test("custom conditions before width-based", () => {+ const initial = [+ {},+ { minWidth: 1024 },+ { condition: "orientation:portrait" },+ { maxWidth: 768 },+ ];+ const expected = [+ {},+ { condition: "orientation:portrait" },+ { maxWidth: 768 },+ { minWidth: 1024 },+ ];+ const sorted = initial.sort(compareMedia);+ expect(sorted).toStrictEqual(expected);+ });++ test("mixed custom conditions and width-based", () => {+ const initial = [+ {},+ { maxWidth: 991 },+ { condition: "hover:hover" },+ { minWidth: 1280 },+ { condition: "orientation:landscape" },+ { maxWidth: 767 },+ { condition: "prefers-color-scheme:dark" },+ ];+ const expected = [+ {},+ { condition: "hover:hover" },+ { condition: "orientation:landscape" },+ { condition: "prefers-color-scheme:dark" },+ { maxWidth: 991 },+ { maxWidth: 767 },+ { minWidth: 1280 },+ ];+ const sorted = initial.sort(compareMedia);+ expect(sorted).toStrictEqual(expected);+ });});diff --git a/packages/css-engine/src/core/compare-media.ts b/packages/css-engine/src/core/compare-media.tsindex fa6aad791d..352a7ace7f 100644--- a/packages/css-engine/src/core/compare-media.ts+++ b/packages/css-engine/src/core/compare-media.ts@@ -1,13 +1,35 @@import type { MediaRuleOptions } from "./rules";/**- * Sort by minWidth descending or maxWidth ascending- * We want media querries with bigger minWidth to override the smaller once, but the smaller maxWidth to override the bigger once.+ * Sort media queries for CSS cascade order.+ * Width-based: minWidth descending, then maxWidth ascending+ * Custom conditions: sorted alphabetically, placed between base and width-based+ *+ * Note: minWidth/maxWidth and condition are mutually exclusive in MediaRuleOptions.*/export const compareMedia = (optionA: MediaRuleOptions,optionB: MediaRuleOptions) => {+ // If both have custom conditions, sort alphabetically+ if (optionA.condition !== undefined && optionB.condition !== undefined) {+ return optionA.condition.localeCompare(optionB.condition);+ }++ // Custom condition comes after base but before width-based+ if (optionA.condition !== undefined) {+ if (optionB.minWidth === undefined && optionB.maxWidth === undefined) {+ return 1; // optionA (condition) after optionB (base)+ }+ return -1; // optionA (condition) before optionB (width)+ }+ if (optionB.condition !== undefined) {+ if (optionA.minWidth === undefined && optionA.maxWidth === undefined) {+ return -1; // optionA (base) before optionB (condition)+ }+ return 1; // optionA (width) after optionB (condition)+ }+// Ensures a media with no min/max is always firstif (optionA.minWidth === undefined && optionA.maxWidth === undefined) {return -1;diff --git a/packages/css-engine/src/core/equal-media.test.ts b/packages/css-engine/src/core/equal-media.test.tsindex 1ad4a0cef5..1f1d96d289 100644--- a/packages/css-engine/src/core/equal-media.test.ts+++ b/packages/css-engine/src/core/equal-media.test.ts@@ -28,4 +28,35 @@ describe("equalMedia", () => {)).toBe(true);});++ test("custom condition", () => {+ expect(+ equalMedia(+ { condition: "orientation:portrait" },+ { condition: "orientation:portrait" }+ )+ ).toBe(true);+ expect(+ equalMedia(+ { condition: "orientation:portrait" },+ { condition: "orientation:landscape" }+ )+ ).toBe(false);+ expect(equalMedia({ condition: "orientation:portrait" }, {})).toBe(false);+ expect(equalMedia({}, { condition: "orientation:portrait" })).toBe(false);+ });++ test("condition with width should not be equal", () => {+ // Note: In practice, condition and minWidth/maxWidth are mutually exclusive+ // (enforced by schema validation). This test verifies the comparison logic only.+ expect(+ equalMedia(+ { condition: "hover:hover", minWidth: 100 },+ { condition: "hover:hover", minWidth: 100 }+ )+ ).toBe(true);+ expect(equalMedia({ condition: "hover:hover" }, { minWidth: 100 })).toBe(+ false+ );+ });});diff --git a/packages/css-engine/src/core/equal-media.ts b/packages/css-engine/src/core/equal-media.tsindex 2691d6b6ce..acecedb7e3 100644--- a/packages/css-engine/src/core/equal-media.ts+++ b/packages/css-engine/src/core/equal-media.ts@@ -1,5 +1,13 @@import type { MediaRuleOptions } from "./rules";+/**+ * Compare two media query options for equality.+ * Note: minWidth/maxWidth and condition are mutually exclusive.+ */export const equalMedia = (left: MediaRuleOptions, right: MediaRuleOptions) => {- return left.minWidth === right.minWidth && left.maxWidth === right.maxWidth;+ return (+ left.minWidth === right.minWidth &&+ left.maxWidth === right.maxWidth &&+ left.condition === right.condition+ );};diff --git a/packages/css-engine/src/core/find-applicable-media.ts b/packages/css-engine/src/core/find-applicable-media.tsindex bd9240364e..58395d2649 100644--- a/packages/css-engine/src/core/find-applicable-media.ts+++ b/packages/css-engine/src/core/find-applicable-media.ts@@ -2,7 +2,11 @@ import { compareMedia } from "./compare-media";import { matchMedia } from "./match-media";import type { MediaRuleOptions } from "./rules";-// Find media rule that matches the given width when rendered.+/**+ * Find the applicable media rule that matches the given width.+ * Only matches width-based breakpoints (minWidth/maxWidth).+ * Custom condition breakpoints are not matched by this function.+ */export const findApplicableMedia = <Media extends MediaRuleOptions>(media: Array<Media>,width: numberdiff --git a/packages/css-engine/src/core/match-media.ts b/packages/css-engine/src/core/match-media.tsindex ba06934849..4c01fe86fe 100644--- a/packages/css-engine/src/core/match-media.ts+++ b/packages/css-engine/src/core/match-media.ts@@ -1,6 +1,10 @@import type { MediaRuleOptions } from "./rules";-// This will match a breakpoint that has no min/max.+/**+ * Check if a media query matches a given width.+ * Only applies to width-based breakpoints (minWidth/maxWidth).+ * Custom condition breakpoints are not matched by this function.+ */export const matchMedia = (options: MediaRuleOptions, width: number) => {const minWidth = options.minWidth ?? Number.MIN_SAFE_INTEGER;const maxWidth = options.maxWidth ?? Number.MAX_SAFE_INTEGER;diff --git a/packages/css-engine/src/core/rules.test.ts b/packages/css-engine/src/core/rules.test.tsnew file mode 100644index 0000000000..ca799f4db8--- /dev/null+++ b/packages/css-engine/src/core/rules.test.ts@@ -0,0 +1,104 @@+import { describe, expect, test } from "vitest";+import { MediaRule, PlaintextRule } from "./rules";++describe("MediaRule with custom conditions", () => {+ test("generates media query with custom condition only", () => {+ const mediaRule = new MediaRule("breakpoint1", {+ condition: "orientation:portrait",+ });+ const plainRule = new PlaintextRule(" .test { color: red; }");+ mediaRule.insertRule(plainRule);++ const css = mediaRule.cssText;+ expect(css).toContain("@media all and (orientation:portrait)");+ expect(css).toContain("color: red");+ });++ test("generates media query with multiple conditions", () => {+ const mediaRule = new MediaRule("breakpoint2", {+ condition: "orientation:portrait and hover:hover",+ });+ const plainRule = new PlaintextRule(" .test { color: blue; }");+ mediaRule.insertRule(plainRule);++ const css = mediaRule.cssText;+ expect(css).toContain(+ "@media all and (orientation:portrait and hover:hover)"+ );+ expect(css).toContain("color: blue");+ });++ test("generates media query with hover condition", () => {+ const mediaRule = new MediaRule("breakpoint3", {+ condition: "hover:hover",+ });+ const plainRule = new PlaintextRule(" .test { cursor: pointer; }");+ mediaRule.insertRule(plainRule);++ const css = mediaRule.cssText;+ expect(css).toContain("@media all and (hover:hover)");+ expect(css).toContain("cursor: pointer");+ });++ test("generates media query with prefers-color-scheme condition", () => {+ const mediaRule = new MediaRule("breakpoint4", {+ condition: "prefers-color-scheme:dark",+ });+ const plainRule = new PlaintextRule(" .test { background: black; }");+ mediaRule.insertRule(plainRule);++ const css = mediaRule.cssText;+ expect(css).toContain("@media all and (prefers-color-scheme:dark)");+ expect(css).toContain("background: black");+ });++ test("prefers condition over width when both present", () => {+ // Note: In practice, condition and minWidth/maxWidth are mutually exclusive+ // (enforced by schema validation). This test verifies the precedence logic only.+ const mediaRule = new MediaRule("breakpoint5", {+ condition: "orientation:portrait",+ minWidth: 768,+ });+ const plainRule = new PlaintextRule(" .test { color: red; }");+ mediaRule.insertRule(plainRule);++ const css = mediaRule.cssText;+ expect(css).toContain("@media all and (orientation:portrait)");+ expect(css).not.toContain("min-width");+ });++ test("generates media query with minWidth when no condition", () => {+ const mediaRule = new MediaRule("breakpoint6", {+ minWidth: 768,+ });+ const plainRule = new PlaintextRule(" .test { color: red; }");+ mediaRule.insertRule(plainRule);++ const css = mediaRule.cssText;+ expect(css).toContain("@media all and (min-width: 768px)");+ expect(css).not.toContain("orientation");+ });++ test("generates media query with maxWidth when no condition", () => {+ const mediaRule = new MediaRule("breakpoint7", {+ maxWidth: 1024,+ });+ const plainRule = new PlaintextRule(" .test { color: green; }");+ mediaRule.insertRule(plainRule);++ const css = mediaRule.cssText;+ expect(css).toContain("@media all and (max-width: 1024px)");+ });++ test("generates base media query when no condition or width", () => {+ const mediaRule = new MediaRule("breakpoint8", {});+ const plainRule = new PlaintextRule(" .test { color: black; }");+ mediaRule.insertRule(plainRule);++ const css = mediaRule.cssText;+ expect(css).toContain("@media all");+ expect(css).not.toContain("min-width");+ expect(css).not.toContain("max-width");+ expect(css).not.toContain("orientation");+ });+});diff --git a/packages/css-engine/src/core/rules.ts b/packages/css-engine/src/core/rules.tsindex bf42fba9dc..be935c88b4 100644--- a/packages/css-engine/src/core/rules.ts+++ b/packages/css-engine/src/core/rules.ts@@ -291,9 +291,16 @@ export class NestingRule {}}+/**+ * Options for media queries.+ * Note: minWidth/maxWidth and condition are mutually exclusive.+ * If condition is set, minWidth and maxWidth must be undefined.+ * If minWidth or maxWidth is set, condition must be undefined.+ */export type MediaRuleOptions = {minWidth?: number;maxWidth?: number;+ condition?: string;mediaType?: "all" | "screen" | "print";};@@ -347,13 +354,22 @@ export class MediaRule {return "";}let conditionText = "";- const { minWidth, maxWidth } = this.options;- if (minWidth !== undefined) {- conditionText = ` and (min-width: ${minWidth}px)`;- }- if (maxWidth !== undefined) {- conditionText += ` and (max-width: ${maxWidth}px)`;+ const { minWidth, maxWidth, condition } = this.options;++ // condition and minWidth/maxWidth are mutually exclusive+ // If condition is set, use it exclusively (minWidth/maxWidth must be undefined)+ if (condition !== undefined) {+ conditionText = ` and (${condition})`;+ } else {+ // Otherwise use width-based conditions (condition must be undefined)+ if (minWidth !== undefined) {+ conditionText = ` and (min-width: ${minWidth}px)`;+ }+ if (maxWidth !== undefined) {+ conditionText += ` and (max-width: ${maxWidth}px)`;+ }}+return `@media ${this.#mediaType}${conditionText} {\n${rules.join("\n")}\n}`;diff --git a/packages/sdk/src/schema/breakpoints.test.ts b/packages/sdk/src/schema/breakpoints.test.tsnew file mode 100644index 0000000000..c6fd777b5e--- /dev/null+++ b/packages/sdk/src/schema/breakpoints.test.ts@@ -0,0 +1,138 @@+import { describe, expect, test } from "vitest";+import { Breakpoint } from "./breakpoints";++describe("Breakpoint schema", () => {+ test("accepts valid width-based breakpoints", () => {+ expect(() =>+ Breakpoint.parse({+ id: "1",+ label: "Desktop",+ minWidth: 1024,+ })+ ).not.toThrow();++ expect(() =>+ Breakpoint.parse({+ id: "2",+ label: "Mobile",+ maxWidth: 767,+ })+ ).not.toThrow();++ expect(() =>+ Breakpoint.parse({+ id: "3",+ label: "Base",+ })+ ).not.toThrow();+ });++ test("accepts valid custom condition breakpoints", () => {+ expect(() =>+ Breakpoint.parse({+ id: "1",+ label: "Portrait",+ condition: "orientation:portrait",+ })+ ).not.toThrow();++ expect(() =>+ Breakpoint.parse({+ id: "2",+ label: "Hover",+ condition: "hover:hover",+ })+ ).not.toThrow();++ expect(() =>+ Breakpoint.parse({+ id: "3",+ label: "Dark Mode",+ condition: "prefers-color-scheme:dark",+ })+ ).not.toThrow();+ });++ test("normalizes empty condition to undefined", () => {+ const result = Breakpoint.parse({+ id: "1",+ label: "Test",+ condition: "",+ });+ expect(result.condition).toBeUndefined();++ const result2 = Breakpoint.parse({+ id: "2",+ label: "Test",+ condition: " ",+ });+ expect(result2.condition).toBeUndefined();+ });++ test("rejects breakpoint with both condition and width", () => {+ expect(() =>+ Breakpoint.parse({+ id: "1",+ label: "Invalid",+ condition: "orientation:portrait",+ minWidth: 1024,+ })+ ).toThrow(+ "Either minWidth, maxWidth, or condition should be defined, but not both"+ );++ expect(() =>+ Breakpoint.parse({+ id: "2",+ label: "Invalid",+ condition: "hover:hover",+ maxWidth: 767,+ })+ ).toThrow(+ "Either minWidth, maxWidth, or condition should be defined, but not both"+ );++ expect(() =>+ Breakpoint.parse({+ id: "3",+ label: "Invalid",+ condition: "hover:hover",+ minWidth: 1024,+ maxWidth: 767,+ })+ ).toThrow(+ "Either minWidth, maxWidth, or condition should be defined, but not both"+ );+ });++ test("rejects breakpoint with both minWidth and maxWidth", () => {+ expect(() =>+ Breakpoint.parse({+ id: "1",+ label: "Invalid",+ minWidth: 1024,+ maxWidth: 767,+ })+ ).toThrow();+ });++ test("preserves valid condition values", () => {+ const result = Breakpoint.parse({+ id: "1",+ label: "Portrait",+ condition: "orientation:portrait",+ });+ expect(result.condition).toBe("orientation:portrait");+ expect(result.minWidth).toBeUndefined();+ expect(result.maxWidth).toBeUndefined();+ });++ test("handles complex conditions", () => {+ const result = Breakpoint.parse({+ id: "1",+ label: "Complex",+ condition: "orientation:portrait and hover:hover",+ });+ expect(result.condition).toBe("orientation:portrait and hover:hover");+ });+});diff --git a/packages/sdk/src/schema/breakpoints.ts b/packages/sdk/src/schema/breakpoints.tsindex c684b7437d..beb5124426 100644--- a/packages/sdk/src/schema/breakpoints.ts+++ b/packages/sdk/src/schema/breakpoints.ts@@ -8,8 +8,20 @@ export const Breakpoint = zlabel: z.string(),minWidth: z.number().optional(),maxWidth: z.number().optional(),+ condition: z.string().optional(),})- .refine(({ minWidth, maxWidth }) => {+ .transform((data) => {+ // Normalize empty condition strings to undefined+ if (data.condition !== undefined && data.condition.trim() === "") {+ return { ...data, condition: undefined };+ }+ return data;+ })+ .refine(({ minWidth, maxWidth, condition }) => {+ // If condition is set, minWidth and maxWidth should not be set+ if (condition !== undefined) {+ return minWidth === undefined && maxWidth === undefined;+ }return (// Either min or max width have to be defined(minWidth !== undefined && maxWidth === undefined) ||@@ -17,7 +29,7 @@ export const Breakpoint = z// This is a base breakpoint(minWidth === undefined && maxWidth === undefined));- }, "Either minWidth or maxWidth should be defined");+ }, "Either minWidth, maxWidth, or condition should be defined, but not both");export type Breakpoint = z.infer<typeof Breakpoint>;