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: CSS Grid UI (#5614)
Oleg Isonen04188dbbf4e4
diff --git a/apps/builder/app/builder/features/navigator/css-preview.tsx b/apps/builder/app/builder/features/navigator/css-preview.tsxindex fd206d3853..1afe573927 100644--- a/apps/builder/app/builder/features/navigator/css-preview.tsx+++ b/apps/builder/app/builder/features/navigator/css-preview.tsx@@ -63,7 +63,7 @@ const getCssText = (result.push(generateStyleMap(mergeStyles(style)));};- add("Style Sources", sourceStyles);+ add("Style sources", sourceStyles);add("Cascaded", cascadedStyles);add("Preset", presetStyles);diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.tsx b/apps/builder/app/builder/features/navigator/navigator-tree.tsxindex 7e01d86bf5..9545eebe84 100644--- a/apps/builder/app/builder/features/navigator/navigator-tree.tsx+++ b/apps/builder/app/builder/features/navigator/navigator-tree.tsx@@ -637,7 +637,7 @@ export const NavigatorTree = () => {disableHoverableContent={true}content={<Text>- Variables defined on Global Root are available on every+ Variables defined on Global root are available on everyinstance on every page.</Text>}diff --git a/apps/builder/app/builder/features/style-panel/controls/menu/menu-control.tsx b/apps/builder/app/builder/features/style-panel/controls/menu/menu-control.tsxindex 22c563ccfc..08ec0b1318 100644--- a/apps/builder/app/builder/features/style-panel/controls/menu/menu-control.tsx+++ b/apps/builder/app/builder/features/style-panel/controls/menu/menu-control.tsx@@ -122,7 +122,12 @@ export const MenuControl = ({</DropdownMenuRadioGroup><DropdownMenuSeparator /><DropdownMenuItem hint>- <Box css={{ width: theme.spacing[25] }}>{description}</Box>+ <Box css={{ width: theme.spacing[26] }}>+ <Box css={{ fontFamily: theme.fonts.mono, mb: theme.spacing[5] }}>+ {property}: {descriptionValue ?? currentValue}+ </Box>+ {description}+ </Box></DropdownMenuItem></DropdownMenuContent></DropdownMenu>diff --git a/apps/builder/app/builder/features/style-panel/sections/flex-child/flex-child.tsx b/apps/builder/app/builder/features/style-panel/sections/flex-child/flex-child.tsxindex 945af2a9e6..05857a3cb7 100644--- a/apps/builder/app/builder/features/style-panel/sections/flex-child/flex-child.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/flex-child/flex-child.tsx@@ -5,26 +5,19 @@ import {ToggleGroup,ToggleGroupButton,FloatingPanel,+ SectionTitleButton,+ Tooltip,} from "@webstudio-is/design-system";import { toValue } from "@webstudio-is/css-engine";import type { CssProperty } from "@webstudio-is/css-engine";-import {- ToggleGroupControl,- ToggleGroupTooltip,-} from "../../controls/toggle-group/toggle-group-control";+import { ToggleGroupTooltip } from "../../controls/toggle-group/toggle-group-control";import { TextControl } from "../../controls";import {XSmallIcon,- AlignSelfStartIcon,- AlignSelfEndIcon,- AlignSelfCenterIcon,- AlignSelfBaselineIcon,- AlignSelfStretchIcon,ShrinkIcon,GrowIcon,- OrderFirstIcon,- OrderLastIcon,EllipsesIcon,+ ExternalLinkIcon,} from "@webstudio-is/icons";import { StyleSection } from "../../shared/style-section";import {@@ -33,8 +26,12 @@ import {} from "../../property-label";import { propertyDescriptions } from "@webstudio-is/css-data";import { useState } from "react";-import { useComputedStyleDecl, useComputedStyles } from "../../shared/model";-import { createBatchUpdate, setProperty } from "../../shared/use-style-data";+import { useStore } from "@nanostores/react";+import { useComputedStyles } from "../../shared/model";+import { createBatchUpdate } from "../../shared/use-style-data";+import { AlignSelfControl } from "../shared/align-self";+import { OrderControl } from "../shared/order";+import { $selectedInstancePath, selectInstance } from "~/shared/awareness";export const properties = ["flex-shrink",@@ -45,67 +42,36 @@ export const properties = [] satisfies [CssProperty, ...CssProperty[]];export const Section = () => {+ const instancePath = useStore($selectedInstancePath);+ // Get the parent instance (second item in the path, index 1)+ const parentInstance = instancePath?.[1];+return (- <StyleSection label="Flex Child" properties={properties}>+ <StyleSection+ label="Flex child"+ properties={properties}+ suffix={+ parentInstance && (+ <Tooltip content="Select flex container">+ <SectionTitleButton+ prefix={<ExternalLinkIcon />}+ onClick={() => selectInstance(parentInstance.instanceSelector)}+ />+ </Tooltip>+ )+ }+ ><Flex css={{ flexDirection: "column", gap: theme.spacing[5] }}><FlexChildSectionAlign /><FlexChildSectionSizing />- <FlexChildSectionOrder />+ <OrderControl /></Flex></StyleSection>);};const FlexChildSectionAlign = () => {- return (- <Grid css={{ gridTemplateColumns: "4fr auto" }}>- <PropertyLabel- label="Align"- description={propertyDescriptions.alignSelf}- properties={["align-self"]}- />- <ToggleGroupControl- label="Align"- properties={["align-self"]}- items={[- {- child: <XSmallIcon />,- description:- "The element's alignment is determined by its parent's align-items property.",- value: "auto",- },- {- child: <AlignSelfStartIcon />,- description:- "The element is aligned at the start of the cross axis.",- value: "flex-start",- },- {- child: <AlignSelfEndIcon />,- description: "The element is aligned at the end of the cross axis.",- value: "flex-end",- },- {- child: <AlignSelfCenterIcon />,- description: "The element is centered along the cross axis.",- value: "center",- },- {- child: <AlignSelfStretchIcon />,- description:- "The element is stretched to fill the entire cross axis.",- value: "stretch",- },- {- child: <AlignSelfBaselineIcon />,- description:- "The element is aligned to the baseline of the parent.",- value: "baseline",- },- ]}- />- </Grid>- );+ return <AlignSelfControl variant="flex" />;};const getSizingValue = (flexGrow: string, flexShrink: string) => {@@ -172,7 +138,7 @@ const FlexChildSectionSizing = () => {// onMouseEnter used to preserve default hovering behavior on tooltip.const [activeTooltip, setActiveTooltip] = useState<undefined | string>();return (- <Grid css={{ gridTemplateColumns: "4fr auto" }}>+ <Grid css={{ gridTemplateColumns: "3fr 8fr" }}><PropertyLabellabel="Sizing"description="Specifies the ability of a flex item to grow, shrink, or set its initial size within a flex container."@@ -294,129 +260,3 @@ const FlexChildSectionSizingPopover = () => {</FloatingPanel>);};--const FlexChildSectionOrder = () => {- const order = useComputedStyleDecl("order");- const selectedValue = toValue(order.cascadedValue);- const items = [- {- child: <XSmallIcon />,- description: "Don't change",- value: "0",- code: "order: 0;",- },- {- child: <OrderFirstIcon />,- description: "Make first",- value: "-1",- code: "order: -1;",- },- {- child: <OrderLastIcon />,- description: "Make last",- value: "1",- code: "order: 1;",- },- {- child: <FlexChildSectionOrderPopover />,- description: "Customize order",- value: "",- code: `order: ${selectedValue};`,- },- ];- // Issue: The tooltip's grace area is too big and overlaps with nearby buttons,- // preventing the tooltip from changing when the buttons are hovered over in certain cases.- // To solve issue and allow tooltips to change on button hover,- // we close the button tooltip in the ToggleGroupButton.onMouseEnter handler.- // onMouseEnter used to preserve default hovering behavior on tooltip.- const [activeTooltip, setActiveTooltip] = useState<undefined | string>();- return (- <Grid css={{ gridTemplateColumns: "4fr auto" }}>- <PropertyLabel- label="Order"- description={propertyDescriptions.order}- properties={["order"]}- />- <ToggleGroup- color={order.source.name}- type="single"- value={selectedValue}- onValueChange={(value) => {- switch (value) {- case "0":- case "1":- case "-1": {- setProperty("order")({- type: "unit",- value: Number(value),- unit: "number",- });- break;- }- }- }}- >- {items.map((item) => (- <ToggleGroupTooltip- key={item.value}- isOpen={item.value === activeTooltip}- onOpenChange={(isOpen) =>- setActiveTooltip(isOpen ? item.value : undefined)- }- isSelected={item.value === selectedValue}- label="Sizing"- code={item.code}- description={item.description}- properties={["flex-grow", "flex-shrink", "flex-basis"]}- >- <ToggleGroupButton- aria-checked={- item.value === selectedValue ||- // flex-order takes integer value, so the value can be anything from +- 0-9- // And we already have toggle buttons for -1, 0, 1- // https://developer.mozilla.org/en-US/docs/Web/CSS/order#formal_syntax- (item.value === "" &&- (Number.parseFloat(selectedValue) > 1 ||- Number.parseFloat(selectedValue) < -1))- }- value={item.value}- onMouseEnter={() =>- // reset only when highlighted is not active- setActiveTooltip((prevValue) =>- prevValue === item.value ? prevValue : undefined- )- }- >- {item.child}- </ToggleGroupButton>- </ToggleGroupTooltip>- ))}- </ToggleGroup>- </Grid>- );-};--const FlexChildSectionOrderPopover = () => {- return (- <FloatingPanel- title="Order"- placement="bottom-within"- content={- <Grid css={{ padding: theme.panel.padding }}>- <Grid css={{ gridTemplateColumns: "4fr 6fr" }} gap={2}>- <PropertyLabel- label="Order"- description={propertyDescriptions.order}- properties={["order"]}- />- <TextControl property="order" />- </Grid>- </Grid>- }- >- <Flex>- <EllipsesIcon />- </Flex>- </FloatingPanel>- );-};diff --git a/apps/builder/app/builder/features/style-panel/sections/grid-child/grid-child.test.ts b/apps/builder/app/builder/features/style-panel/sections/grid-child/grid-child.test.tsnew file mode 100644index 0000000000..ed885ec1ac--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/grid-child/grid-child.test.ts@@ -0,0 +1,109 @@+import { describe, test, expect } from "vitest";+import type { StyleValue } from "@webstudio-is/css-engine";+import { __testing__ } from "./grid-child";++const { derivePositionMode } = __testing__;++describe("derivePositionMode", () => {+ const auto: StyleValue = { type: "keyword", value: "auto" };++ describe("returns 'auto' mode", () => {+ test("when all values are 'auto'", () => {+ expect(derivePositionMode(auto, auto, auto, auto)).toBe("auto");+ });++ test("when values are 'auto' with span tuples", () => {+ const spanValue: StyleValue = {+ type: "tuple",+ value: [+ { type: "keyword", value: "span" },+ { type: "unit", value: 2, unit: "number" },+ ],+ };+ expect(derivePositionMode(auto, spanValue, auto, spanValue)).toBe("auto");+ });++ test("when all values are span tuples", () => {+ const span2: StyleValue = {+ type: "tuple",+ value: [+ { type: "keyword", value: "span" },+ { type: "unit", value: 2, unit: "number" },+ ],+ };+ const span3: StyleValue = {+ type: "tuple",+ value: [+ { type: "keyword", value: "span" },+ { type: "unit", value: 3, unit: "number" },+ ],+ };+ expect(derivePositionMode(auto, span2, auto, span3)).toBe("auto");+ });+ });++ describe("returns 'manual' mode", () => {+ test("when any value is numeric", () => {+ const numeric: StyleValue = { type: "unit", value: 1, unit: "number" };+ expect(derivePositionMode(numeric, auto, auto, auto)).toBe("manual");+ });++ test("when all values are numeric", () => {+ const val1: StyleValue = { type: "unit", value: 1, unit: "number" };+ const val2: StyleValue = { type: "unit", value: 2, unit: "number" };+ const val3: StyleValue = { type: "unit", value: 1, unit: "number" };+ const val4: StyleValue = { type: "unit", value: 3, unit: "number" };+ expect(derivePositionMode(val1, val2, val3, val4)).toBe("manual");+ });++ test("when some values are numeric and some auto", () => {+ const numeric: StyleValue = { type: "unit", value: 2, unit: "number" };+ expect(derivePositionMode(auto, numeric, auto, auto)).toBe("manual");+ });+ });++ describe("returns 'area' mode", () => {+ test("when values contain named area keywords", () => {+ const areaName: StyleValue = { type: "keyword", value: "header" };+ expect(derivePositionMode(areaName, areaName, areaName, areaName)).toBe(+ "area"+ );+ });++ test("when some values are named areas and some auto", () => {+ const areaName: StyleValue = { type: "keyword", value: "sidebar" };+ // In practice, when using grid-area shorthand, all 4 values get the same area name+ expect(derivePositionMode(areaName, areaName, areaName, areaName)).toBe(+ "area"+ );+ });++ test("when start values are named areas", () => {+ const areaName: StyleValue = { type: "keyword", value: "main" };+ expect(derivePositionMode(areaName, auto, areaName, auto)).toBe("area");+ });+ });++ describe("edge cases", () => {+ test("prioritizes 'manual' over 'area' when mixed", () => {+ // If there's any numeric value, it's manual mode+ const numeric: StyleValue = { type: "unit", value: 1, unit: "number" };+ const areaName: StyleValue = { type: "keyword", value: "header" };+ expect(derivePositionMode(numeric, areaName, auto, auto)).toBe("manual");+ });++ test("handles guaranteedInvalid value by defaulting to auto", () => {+ const invalid: StyleValue = { type: "guaranteedInvalid" };+ expect(derivePositionMode(invalid, invalid, invalid, invalid)).toBe(+ "auto"+ );+ });++ test("handles unparsed values by defaulting to auto", () => {+ const unparsed: StyleValue = { type: "unparsed", value: "something" };+ expect(derivePositionMode(unparsed, unparsed, unparsed, unparsed)).toBe(+ "auto"+ );+ });+ });+});diff --git a/apps/builder/app/builder/features/style-panel/sections/grid-child/grid-child.tsx b/apps/builder/app/builder/features/style-panel/sections/grid-child/grid-child.tsxnew file mode 100644index 0000000000..a68eb59bfc--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/grid-child/grid-child.tsx@@ -0,0 +1,682 @@+import { useState, useMemo, useEffect } from "react";+import {+ Box,+ Flex,+ Grid,+ Select,+ Text,+ theme,+ ToggleGroup,+ ToggleGroupButton,+ SectionTitleButton,+ Tooltip,+} from "@webstudio-is/design-system";+import type { CssProperty, StyleValue } from "@webstudio-is/css-engine";+import { toValue } from "@webstudio-is/css-engine";+import { StyleSection } from "../../shared/style-section";+import { PropertyLabel } from "../../property-label";+import { ToggleGroupTooltip } from "../../controls/toggle-group/toggle-group-control";+import {+ CssValueInput,+ type IntermediateStyleValue,+} from "../../shared/css-value-input";+import {+ useComputedStyleDecl,+ useComputedStyles,+ useParentComputedStyleDecl,+} from "../../shared/model";+import {+ createBatchUpdate,+ deleteProperty,+ resetEphemeralStyles,+} from "../../shared/use-style-data";+import { parseGridAreas } from "@webstudio-is/css-data";+import { getGridDimensions } from "../layout/shared/grid-areas";+import {+ GridPositionInputs,+ type GridPosition,+} from "../layout/shared/grid-position-inputs";+import { useLocalValue } from "../../../settings-panel/shared";+import { AlignSelfControl, JustifySelfControl } from "../shared/align-self";+import { OrderControl } from "../shared/order";+import { useStore } from "@nanostores/react";+import { $selectedInstancePath, selectInstance } from "~/shared/awareness";+import { ExternalLinkIcon } from "@webstudio-is/icons";++export const properties = [+ "grid-column-start",+ "grid-column-end",+ "grid-row-start",+ "grid-row-end",+ "align-self",+ "justify-self",+ "order",+] satisfies [CssProperty, ...CssProperty[]];++type PositionMode = "auto" | "area" | "manual";++/**+ * Derives the position mode from the current CSS values.+ * - "auto": All values are "auto" or span values (auto placement)+ * - "area": Values contain named grid areas (keywords that are not "auto")+ * - "manual": Values are numeric line positions+ */+const derivePositionMode = (+ columnStart: StyleValue,+ columnEnd: StyleValue,+ rowStart: StyleValue,+ rowEnd: StyleValue+): PositionMode => {+ const values = [columnStart, columnEnd, rowStart, rowEnd];++ // Check if any value is numeric (manual mode)+ const hasNumericValues = values.some(+ (value) => value.type === "unit" && value.unit === "number"+ );++ if (hasNumericValues) {+ return "manual";+ }++ // Check if all values are "auto" or span tuples (auto mode)+ const isAutoOrSpan = (value: StyleValue): boolean => {+ if (value.type === "keyword" && value.value === "auto") {+ return true;+ }+ // Span values like "span 2" are tuples+ if (value.type === "tuple" && value.value.length === 2) {+ const [first] = value.value;+ if (first.type === "keyword" && first.value === "span") {+ return true;+ }+ }+ return false;+ };++ const allAutoOrSpan = values.every(isAutoOrSpan);++ if (allAutoOrSpan) {+ return "auto";+ }++ // If we have non-auto keyword values, it's likely a named area+ const hasNamedArea = values.some(+ (value) => value.type === "keyword" && value.value !== "auto"+ );++ if (hasNamedArea) {+ return "area";+ }++ // Default to auto+ return "auto";+};++export const Section = () => {+ const [columnStart, columnEnd, rowStart, rowEnd] = useComputedStyles([+ "grid-column-start",+ "grid-column-end",+ "grid-row-start",+ "grid-row-end",+ ]);++ // Derive position mode from CSS values - this ensures the correct tab is shown+ // when selecting different instances with different grid positioning+ const derivedPositionMode = useMemo(+ () =>+ derivePositionMode(+ columnStart.cascadedValue,+ columnEnd.cascadedValue,+ rowStart.cascadedValue,+ rowEnd.cascadedValue+ ),+ [columnStart, columnEnd, rowStart, rowEnd]+ );++ // Track user override - when user explicitly changes mode, use that until CSS values match+ const [userOverrideMode, setUserOverrideMode] = useState<PositionMode | null>(+ null+ );++ // Use user override if set, otherwise use derived mode+ const positionMode = userOverrideMode ?? derivedPositionMode;++ const handleModeChange = (newMode: PositionMode) => {+ const hasKeywordValues =+ columnStart.cascadedValue.type === "keyword" &&+ columnEnd.cascadedValue.type === "keyword" &&+ rowStart.cascadedValue.type === "keyword" &&+ rowEnd.cascadedValue.type === "keyword";++ const batch = createBatchUpdate();++ if (newMode === "auto") {+ // Reset to span 1 on all axes for auto placement+ const span1: StyleValue = {+ type: "tuple",+ value: [+ { type: "keyword", value: "span" },+ { type: "unit", value: 1, unit: "number" },+ ],+ };+ batch.setProperty("grid-column-start")(span1);+ batch.setProperty("grid-column-end")(span1);+ batch.setProperty("grid-row-start")(span1);+ batch.setProperty("grid-row-end")(span1);+ batch.publish();+ } else if (newMode === "manual" && hasKeywordValues) {+ // Convert keywords to numeric positions when switching to manual+ batch.setProperty("grid-column-start")({+ type: "unit",+ value: 1,+ unit: "number",+ });+ batch.setProperty("grid-column-end")({+ type: "unit",+ value: 2,+ unit: "number",+ });+ batch.setProperty("grid-row-start")({+ type: "unit",+ value: 1,+ unit: "number",+ });+ batch.setProperty("grid-row-end")({+ type: "unit",+ value: 2,+ unit: "number",+ });+ batch.publish();+ }++ // Set user override - this will be cleared when CSS values change+ // to match the new mode (since derivePositionMode will return newMode)+ setUserOverrideMode(newMode);+ };++ // Clear user override when derived mode matches (CSS was updated to match the mode)+ // This allows the component to correctly derive mode for new instances+ useEffect(() => {+ if (userOverrideMode !== null && derivedPositionMode === userOverrideMode) {+ setUserOverrideMode(null);+ }+ }, [derivedPositionMode, userOverrideMode]);++ const instancePath = useStore($selectedInstancePath);+ // Get the parent instance (second item in the path, index 1)+ const parentInstance = instancePath?.[1];++ return (+ <StyleSection+ label="Grid child"+ properties={properties}+ suffix={+ parentInstance && (+ <Tooltip content="Select grid container">+ <SectionTitleButton+ prefix={<ExternalLinkIcon />}+ onClick={() => selectInstance(parentInstance.instanceSelector)}+ />+ </Tooltip>+ )+ }+ >+ <Flex css={{ flexDirection: "column", gap: theme.spacing[5] }}>+ <GridChildPositionMode+ value={positionMode}+ onChange={handleModeChange}+ />+ {positionMode === "auto" && <GridChildPositionAuto />}+ {positionMode === "area" && <GridChildPositionArea />}+ {positionMode === "manual" && <GridChildPositionManual />}+ <GridChildAlign />+ </Flex>+ </StyleSection>+ );+};++const GridChildPositionMode = ({+ value,+ onChange,+}: {+ value: PositionMode;+ onChange: (value: PositionMode) => void;+}) => {+ const [activeTooltip, setActiveTooltip] = useState<string | undefined>();++ const items = [+ {+ value: "auto" as const,+ label: "Auto",+ description: "Let the grid automatically place this item.",+ code: "grid-column: auto;\ngrid-row: auto;",+ },+ {+ value: "area" as const,+ label: "Area",+ description: "Place the item in a named grid area.",+ code: "grid-area: <area-name>;",+ },+ {+ value: "manual" as const,+ label: "Manual",+ description: "Manually specify the item's position using grid lines.",+ code: "grid-column: <start> / <end>;\ngrid-row: <start> / <end>;",+ },+ ];++ return (+ <Grid css={{ gridTemplateColumns: "3fr 8fr" }}>+ <PropertyLabel+ label="Position"+ description="How the grid item is positioned within the grid"+ properties={[+ "grid-column-start",+ "grid-column-end",+ "grid-row-start",+ "grid-row-end",+ ]}+ />+ <ToggleGroup+ type="single"+ value={value}+ onValueChange={(newValue) => {+ if (newValue) {+ onChange(newValue as PositionMode);+ }+ }}+ >+ {items.map((item) => (+ <ToggleGroupTooltip+ key={item.value}+ isOpen={item.value === activeTooltip}+ onOpenChange={(isOpen) =>+ setActiveTooltip(isOpen ? item.value : undefined)+ }+ isSelected={item.value === value}+ label={item.label}+ code={item.code}+ description={item.description}+ properties={["grid-column-start", "grid-row-start"]}+ >+ <ToggleGroupButton+ value={item.value}+ onMouseEnter={() =>+ setActiveTooltip((prevValue) =>+ prevValue === item.value ? prevValue : undefined+ )+ }+ >+ <Box css={{ paddingInline: theme.spacing[4] }}>{item.label}</Box>+ </ToggleGroupButton>+ </ToggleGroupTooltip>+ ))}+ </ToggleGroup>+ </Grid>+ );+};++const GridChildPositionAuto = () => {+ return (+ <Grid css={{ gridTemplateColumns: "3fr 8fr" }}>+ <div />+ <Grid css={{ gridTemplateColumns: "1fr 1fr", gap: theme.spacing[5] }}>+ <Grid css={{ gap: theme.spacing[3] }}>+ <SpanInput+ property="grid-column-end"+ startProperty="grid-column-start"+ />+ <Text variant="small" color="subtle">+ Column span+ </Text>+ </Grid>+ <Grid css={{ gap: theme.spacing[3] }}>+ <SpanInput property="grid-row-end" startProperty="grid-row-start" />+ <Text variant="small" color="subtle">+ Row span+ </Text>+ </Grid>+ </Grid>+ </Grid>+ );+};++/**+ * A specialized input for grid span values.+ * Handles conversion between span values and the number displayed.+ * When span is 1, grid uses "auto". For span > 1, uses "span N".+ */+const SpanInput = ({+ property,+ startProperty,+}: {+ property: "grid-column-end" | "grid-row-end";+ startProperty: "grid-column-start" | "grid-row-start";+}) => {+ const computedStyleDecl = useComputedStyleDecl(property);+ const value = computedStyleDecl.cascadedValue;+ const [intermediateValue, setIntermediateValue] = useState<+ StyleValue | IntermediateStyleValue+ >();++ // Extract span number from value+ // "auto" = 1, "span 2" = 2, etc.+ const getSpanNumber = (styleValue: StyleValue): number => {+ if (styleValue.type === "keyword" && styleValue.value === "auto") {+ return 1;+ }+ if (styleValue.type === "tuple" && styleValue.value.length === 2) {+ const spanKeyword = styleValue.value[0];+ const spanNumber = styleValue.value[1];+ if (+ spanKeyword.type === "keyword" &&+ spanKeyword.value === "span" &&+ spanNumber.type === "unit" &&+ spanNumber.unit === "number"+ ) {+ return spanNumber.value;+ }+ }+ if (styleValue.type === "unit" && styleValue.unit === "number") {+ return styleValue.value;+ }+ return 1;+ };++ // Create span StyleValue from number+ const createSpanValue = (num: number): StyleValue => ({+ type: "tuple",+ value: [+ { type: "keyword", value: "span" },+ { type: "unit", value: num, unit: "number" },+ ],+ });++ const currentSpan = getSpanNumber(value);++ // Display the span number as a simple unit value for the input+ const displayValue: StyleValue = {+ type: "unit",+ value: currentSpan,+ unit: "number",+ };++ const handleChange = (styleValue: StyleValue | undefined) => {+ if (styleValue === undefined) {+ deleteProperty(property, { isEphemeral: true });+ // Also ensure start is auto for auto placement+ const batch = createBatchUpdate();+ batch.deleteProperty(startProperty);+ batch.publish({ isEphemeral: true });+ return;+ }++ if (styleValue.type === "unit" && styleValue.unit === "number") {+ const spanValue = createSpanValue(+ Math.max(1, Math.round(styleValue.value))+ );+ const batch = createBatchUpdate();+ batch.setProperty(startProperty)(spanValue);+ batch.setProperty(property)(spanValue);+ batch.publish({ isEphemeral: true });+ }+ };++ const handleChangeComplete = (styleValue: StyleValue) => {+ setIntermediateValue(undefined);+ if (styleValue.type === "unit" && styleValue.unit === "number") {+ const spanValue = createSpanValue(+ Math.max(1, Math.round(styleValue.value))+ );+ const batch = createBatchUpdate();+ batch.setProperty(startProperty)(spanValue);+ batch.setProperty(property)(spanValue);+ batch.publish();+ }+ };++ return (+ <CssValueInput+ styleSource={computedStyleDecl.source.name}+ property={property}+ value={displayValue}+ intermediateValue={intermediateValue}+ getOptions={() => []}+ onChange={(styleValue) => {+ setIntermediateValue(styleValue);+ if (styleValue === undefined) {+ handleChange(undefined);+ return;+ }+ if (styleValue.type !== "intermediate") {+ handleChange(styleValue);+ }+ }}+ onHighlight={(styleValue) => {+ if (styleValue !== undefined) {+ handleChange(styleValue);+ } else {+ deleteProperty(property, { isEphemeral: true });+ }+ }}+ onChangeComplete={({ value }) => {+ handleChangeComplete(value);+ resetEphemeralStyles();+ }}+ onAbort={() => {+ resetEphemeralStyles();+ }}+ onReset={() => {+ setIntermediateValue(undefined);+ const batch = createBatchUpdate();+ batch.deleteProperty(startProperty);+ batch.deleteProperty(property);+ batch.publish();+ }}+ />+ );+};++const GridChildPositionArea = () => {+ const parentGridTemplateAreas = useParentComputedStyleDecl(+ "grid-template-areas"+ );+ const gridRowStart = useComputedStyleDecl("grid-row-start");++ // Parse area names from parent's grid-template-areas+ const areasValue = toValue(parentGridTemplateAreas.computedValue);+ const areas = parseGridAreas(areasValue);+ const areaNames = areas.map((area) => area.name);++ // Get current area name from grid-row-start+ // When using named areas, grid-row-start contains the area name+ const currentValue = toValue(gridRowStart.cascadedValue);+ const selectedArea = areaNames.includes(currentValue) ? currentValue : "";++ const handleAreaChange = (areaName: string) => {+ const batch = createBatchUpdate();+ // Setting all four properties to the same area name places the item in that area+ const areaValue: StyleValue = { type: "keyword", value: areaName };+ batch.setProperty("grid-row-start")(areaValue);+ batch.setProperty("grid-column-start")(areaValue);+ batch.setProperty("grid-row-end")(areaValue);+ batch.setProperty("grid-column-end")(areaValue);+ batch.publish();+ };++ if (areaNames.length === 0) {+ return (+ <Text color="moreSubtle">+ No named areas defined. Add areas in the parent grid's template.+ </Text>+ );+ }++ return (+ <Grid css={{ gridTemplateColumns: "3fr 8fr" }}>+ <div />+ <Select+ options={areaNames}+ value={selectedArea}+ onChange={handleAreaChange}+ placeholder="Select area"+ />+ </Grid>+ );+};++const GridChildPositionManual = () => {+ const parentGridTemplateColumns = useParentComputedStyleDecl(+ "grid-template-columns"+ );+ const parentGridTemplateRows =+ useParentComputedStyleDecl("grid-template-rows");+ const [columnStart, columnEnd, rowStart, rowEnd] = useComputedStyles([+ "grid-column-start",+ "grid-column-end",+ "grid-row-start",+ "grid-row-end",+ ]);++ // Get grid dimensions from parent+ const { columns: gridColumns, rows: gridRows } = getGridDimensions(+ toValue(parentGridTemplateColumns.computedValue),+ toValue(parentGridTemplateRows.computedValue)+ );++ // Extract numeric values from CSS values+ // For "auto" or non-numeric values, use sensible defaults based on position type+ const getNumericValue = (+ styleValue: StyleValue,+ defaultValue: number+ ): number => {+ if (styleValue.type === "unit" && styleValue.unit === "number") {+ return styleValue.value;+ }+ return defaultValue;+ };++ // Get values with defaults, ensuring they form a valid position+ const colStart = getNumericValue(columnStart.cascadedValue, 1);+ const colEnd = getNumericValue(columnEnd.cascadedValue, 2);+ const rStart = getNumericValue(rowStart.cascadedValue, 1);+ const rEnd = getNumericValue(rowEnd.cascadedValue, 2);++ // Validate and fix invalid positions (end must be greater than start)+ // Use useMemo to stabilize the position object so it doesn't change on every render+ const position: GridPosition = useMemo(+ () => ({+ columnStart: colStart,+ columnEnd: colEnd > colStart ? colEnd : colStart + 1,+ rowStart: rStart,+ rowEnd: rEnd > rStart ? rEnd : rStart + 1,+ }),+ [colStart, colEnd, rStart, rEnd]+ );++ const localValue = useLocalValue(+ position,+ (newPosition) => {+ // Validate and fix the position before saving+ const validPosition = {+ columnStart: Math.max(1, Math.round(newPosition.columnStart)),+ columnEnd: Math.max(1, Math.round(newPosition.columnEnd)),+ rowStart: Math.max(1, Math.round(newPosition.rowStart)),+ rowEnd: Math.max(1, Math.round(newPosition.rowEnd)),+ };++ // Ensure end is greater than start+ if (validPosition.columnEnd <= validPosition.columnStart) {+ validPosition.columnEnd = validPosition.columnStart + 1;+ }+ if (validPosition.rowEnd <= validPosition.rowStart) {+ validPosition.rowEnd = validPosition.rowStart + 1;+ }++ const batch = createBatchUpdate();+ batch.setProperty("grid-column-start")({+ type: "unit",+ value: validPosition.columnStart,+ unit: "number",+ });+ batch.setProperty("grid-column-end")({+ type: "unit",+ value: validPosition.columnEnd,+ unit: "number",+ });+ batch.setProperty("grid-row-start")({+ type: "unit",+ value: validPosition.rowStart,+ unit: "number",+ });+ batch.setProperty("grid-row-end")({+ type: "unit",+ value: validPosition.rowEnd,+ unit: "number",+ });+ batch.publish();+ },+ { autoSave: false }+ );++ const handleChange = (newPosition: GridPosition) => {+ localValue.set(newPosition);+ const batch = createBatchUpdate();+ batch.setProperty("grid-column-start")({+ type: "unit",+ value: newPosition.columnStart,+ unit: "number",+ });+ batch.setProperty("grid-column-end")({+ type: "unit",+ value: newPosition.columnEnd,+ unit: "number",+ });+ batch.setProperty("grid-row-start")({+ type: "unit",+ value: newPosition.rowStart,+ unit: "number",+ });+ batch.setProperty("grid-row-end")({+ type: "unit",+ value: newPosition.rowEnd,+ unit: "number",+ });+ batch.publish({ isEphemeral: true });+ };++ return (+ <Grid+ css={{+ gridTemplateColumns: "3fr 8fr",+ alignItems: "start",+ }}+ >+ <div />+ <GridPositionInputs+ value={localValue.value}+ onChange={handleChange}+ onBlur={() => {+ localValue.save();+ resetEphemeralStyles();+ }}+ gridColumns={gridColumns}+ gridRows={gridRows}+ />+ </Grid>+ );+};++const GridChildAlign = () => {+ return (+ <Flex direction="column" gap="1">+ <AlignSelfControl variant="grid" />+ <JustifySelfControl />+ <OrderControl />+ </Flex>+ );+};++export const __testing__ = {+ derivePositionMode,+};diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/layout.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/layout.tsxindex 4bbb32523c..edfcfdd696 100644--- a/apps/builder/app/builder/features/style-panel/sections/layout/layout.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/layout/layout.tsx@@ -1,4 +1,6 @@-import { useState, type JSX, type ReactNode } from "react";+import { useEffect, useRef, useState, type JSX, type ReactNode } from "react";+import { useStore } from "@nanostores/react";+import { $selectedInstanceKey } from "~/shared/awareness";import {theme,Box,@@ -38,6 +40,7 @@ import {AlignContentSpaceAroundIcon,AlignContentSpaceBetweenIcon,AlignContentStretchIcon,+ RepeatGridIcon,} from "@webstudio-is/icons";import { MenuControl, SelectControl } from "../../controls";import { createBatchUpdate, deleteProperty } from "../../shared/use-style-data";@@ -54,8 +57,13 @@ import {$availableUnitVariables,} from "../../shared/model";import type { ComputedStyleDecl } from "~/shared/style-object-model";-import { FlexGrid } from "./shared/flex-grid";+import { FlexAlignment } from "./shared/flex-alignment";+import { GridGenerator } from "./shared/grid-generator";+import { GridSettings } from "./shared/grid-settings";+import { GridAlignment } from "./shared/grid-alignment";+import { $openGridEditorPanel } from "~/builder/shared/nano-states";import { humanizeString } from "~/shared/string-utils";+import { DEFAULT_GRID_TRACK_COUNT, DEFAULT_GRID_GAP } from "./shared/constants";const GapLinked = ({isLinked,@@ -195,7 +203,7 @@ const GapInput = ({);};-const FlexGap = () => {+const Gap = () => {const [columnGap, rowGap] = useComputedStyles(["column-gap", "row-gap"]);const [isLinked, setIsLinked] = useState(() => toValue(columnGap.cascadedValue) === toValue(rowGap.cascadedValue)@@ -365,38 +373,274 @@ const FlexGap = () => {);};+// Shared alignment controls for both Flex and Grid+const AlignmentControls = ({+ showAlignContent = true,+}: {+ showAlignContent?: boolean;+}) => {+ return (+ <Grid+ css={{+ gridTemplateColumns: "1fr 1fr 1fr",+ gap: theme.spacing[7],+ }}+ >+ <MenuControl+ property="align-items"+ items={[+ {+ name: "start",+ label: "Start",+ icon: AlignStartHorizontalIcon,+ },+ {+ name: "center",+ label: "Center",+ icon: AlignCenterHorizontalIcon,+ },+ { name: "end", label: "End", icon: AlignEndHorizontalIcon },+ {+ name: "stretch",+ label: "Stretch",+ icon: StretchVerticalIcon,+ },+ {+ name: "baseline",+ label: "Baseline",+ icon: AlignBaselineIcon,+ },+ ]}+ />+ <MenuControl+ property="justify-content"+ items={[+ {+ name: "start",+ label: "Start",+ icon: AlignHorizontalJustifyStartIcon,+ },+ {+ name: "center",+ label: "Center",+ icon: AlignHorizontalJustifyCenterIcon,+ },+ {+ name: "end",+ label: "End",+ icon: AlignHorizontalJustifyEndIcon,+ },+ {+ name: "space-between",+ label: "Space Between",+ icon: AlignHorizontalSpaceBetweenIcon,+ },+ {+ name: "space-around",+ label: "Space Around",+ icon: AlignHorizontalSpaceAroundIcon,+ },+ ]}+ />+ {showAlignContent && (+ <MenuControl+ property="align-content"+ items={[+ {+ name: "start",+ label: "Start",+ icon: AlignContentStartIcon,+ },+ {+ name: "center",+ label: "Center",+ icon: AlignContentCenterIcon,+ },+ { name: "end", label: "End", icon: AlignContentEndIcon },+ {+ name: "stretch",+ label: "Stretch",+ icon: AlignContentStretchIcon,+ },+ {+ name: "space-between",+ label: "Space Between",+ icon: AlignContentSpaceBetweenIcon,+ },+ {+ name: "space-around",+ label: "Space Around",+ icon: AlignContentSpaceAroundIcon,+ },+ ]}+ />+ )}+ </Grid>+ );+};+const LayoutSectionFlex = () => {const flexWrap = useComputedStyleDecl("flex-wrap");const flexWrapValue = toValue(flexWrap.cascadedValue);return (- <Flex css={{ flexDirection: "column", gap: theme.spacing[5] }}>- <Flex css={{ gap: theme.spacing[7] }} align="stretch">- <FlexGrid />+ <Flex direction="column" gap="2">+ <Grid+ css={{+ gridTemplateColumns: `1fr 1fr 1fr`,+ gap: theme.spacing[7],+ alignItems: "start",+ }}+ >+ <FlexAlignment />+ <Grid+ css={{+ gridTemplateColumns: "1fr 1fr",+ gap: theme.spacing[7],+ }}+ >+ <MenuControl+ property="flex-direction"+ items={[+ { name: "row", label: "Row", icon: ArrowRightIcon },+ {+ name: "row-reverse",+ label: "Row Reverse",+ icon: ArrowLeftIcon,+ },+ { name: "column", label: "Column", icon: ArrowDownIcon },+ {+ name: "column-reverse",+ label: "Column Reverse",+ icon: ArrowUpIcon,+ },+ ]}+ />+ <ToggleControl+ property="flex-wrap"+ items={[+ { name: "nowrap", label: "No Wrap", icon: NoWrapIcon },+ { name: "wrap", label: "Wrap", icon: WrapIcon },+ ]}+ />+ <Box css={{ gridColumn: "1 / -1" }}>+ <AlignmentControls+ showAlignContent={+ flexWrapValue === "wrap" || flexWrapValue === "wrap-reverse"+ }+ />+ </Box>+ </Grid>+ </Grid>+ <Gap />+ </Flex>+ );+};++const applyDefaultGridStyles = (columnsValue: string, rowsValue: string) => {+ const isColumnsEmpty = !columnsValue || columnsValue === "none";+ const isRowsEmpty = !rowsValue || rowsValue === "none";+ if (isColumnsEmpty === false || isRowsEmpty === false) {+ return;+ }+ const defaultColumns = Array(DEFAULT_GRID_TRACK_COUNT).fill("1fr").join(" ");+ const defaultRows = Array(DEFAULT_GRID_TRACK_COUNT).fill("auto").join(" ");+ const batch = createBatchUpdate();+ batch.setProperty("grid-template-columns")({+ type: "unparsed",+ value: defaultColumns,+ });+ batch.setProperty("grid-template-rows")({+ type: "unparsed",+ value: defaultRows,+ });+ batch.setProperty("grid-auto-columns")({+ type: "unit",+ value: 1,+ unit: "fr",+ });+ batch.setProperty("column-gap")({+ type: "unit",+ value: DEFAULT_GRID_GAP,+ unit: "px",+ });+ batch.setProperty("row-gap")({+ type: "unit",+ value: DEFAULT_GRID_GAP,+ unit: "px",+ });+ batch.publish();+};++const LayoutSectionGrid = () => {+ const openPanel = useStore($openGridEditorPanel);++ return (+ <Flex direction="column" gap="2">+ <GridGenerator+ open={openPanel.generator}+ onOpenChange={(open) =>+ $openGridEditorPanel.set({ ...openPanel, generator: open })+ }+ />+ <GridSettings+ open={openPanel.settings}+ onOpenChange={(open) =>+ $openGridEditorPanel.set({ ...openPanel, settings: open })+ }+ />+ <Grid+ css={{+ gridTemplateColumns: "1fr 1fr 1fr",+ gap: theme.spacing[7],+ alignItems: "stretch",+ }}+ >+ <GridAlignment /><Flex direction="column" justify="between"><Flex css={{ gap: theme.spacing[7] }}><MenuControl- property="flex-direction"+ property="grid-auto-flow"items={[{ name: "row", label: "Row", icon: ArrowRightIcon },- {- name: "row-reverse",- label: "Row Reverse",- icon: ArrowLeftIcon,- },{ name: "column", label: "Column", icon: ArrowDownIcon },+ { name: "row dense", label: "Row Dense", icon: RepeatGridIcon },{- name: "column-reverse",- label: "Column Reverse",- icon: ArrowUpIcon,+ name: "column dense",+ label: "Column Dense",+ icon: RepeatGridIcon,},]}/>- <ToggleControl- property="flex-wrap"+ <MenuControl+ property="align-content"items={[- { name: "nowrap", label: "No Wrap", icon: NoWrapIcon },- { name: "wrap", label: "Wrap", icon: WrapIcon },+ {+ name: "start",+ label: "Start",+ icon: AlignContentStartIcon,+ },+ {+ name: "center",+ label: "Center",+ icon: AlignContentCenterIcon,+ },+ { name: "end", label: "End", icon: AlignContentEndIcon },+ {+ name: "stretch",+ label: "Stretch",+ icon: AlignContentStretchIcon,+ },+ {+ name: "space-between",+ label: "Space Between",+ icon: AlignContentSpaceBetweenIcon,+ },+ {+ name: "space-around",+ label: "Space Around",+ icon: AlignContentSpaceAroundIcon,+ },]}/></Flex>@@ -404,6 +648,17 @@ const LayoutSectionFlex = () => {<MenuControlproperty="align-items"items={[+ {+ name: "start",+ label: "Start",+ icon: AlignStartHorizontalIcon,+ },+ {+ name: "center",+ label: "Center",+ icon: AlignCenterHorizontalIcon,+ },+ { name: "end", label: "End", icon: AlignEndHorizontalIcon },{name: "stretch",label: "Stretch",@@ -414,87 +669,69 @@ const LayoutSectionFlex = () => {label: "Baseline",icon: AlignBaselineIcon,},+ ]}+ />+ <MenuControl+ property="justify-items"+ items={[+ {+ name: "start",+ label: "Start",+ icon: AlignStartHorizontalIcon,+ },{name: "center",label: "Center",icon: AlignCenterHorizontalIcon,},+ { name: "end", label: "End", icon: AlignEndHorizontalIcon },{- name: "start",- label: "Start",- icon: AlignStartHorizontalIcon,+ name: "stretch",+ label: "Stretch",+ icon: StretchVerticalIcon,+ },+ {+ name: "baseline",+ label: "Baseline",+ icon: AlignBaselineIcon,},- { name: "end", label: "End", icon: AlignEndHorizontalIcon },]}/><MenuControlproperty="justify-content"items={[{- name: "space-between",- label: "Space Between",- icon: AlignHorizontalSpaceBetweenIcon,- },- {- name: "space-around",- label: "Space Around",- icon: AlignHorizontalSpaceAroundIcon,+ name: "start",+ label: "Start",+ icon: AlignHorizontalJustifyStartIcon,},{name: "center",label: "Center",icon: AlignHorizontalJustifyCenterIcon,},- {- name: "start",- label: "Start",- icon: AlignHorizontalJustifyStartIcon,- },{name: "end",label: "End",icon: AlignHorizontalJustifyEndIcon,},+ {+ name: "space-between",+ label: "Space Between",+ icon: AlignHorizontalSpaceBetweenIcon,+ },+ {+ name: "space-around",+ label: "Space Around",+ icon: AlignHorizontalSpaceAroundIcon,+ },]}/>- {(flexWrapValue === "wrap" || flexWrapValue === "wrap-reverse") && (- <MenuControl- property="align-content"- items={[- {- name: "space-between",- label: "Space Between",- icon: AlignContentSpaceBetweenIcon,- },- {- name: "space-around",- label: "Space Around",- icon: AlignContentSpaceAroundIcon,- },- {- name: "stretch",- label: "Stretch",- icon: AlignContentStretchIcon,- },- {- name: "center",- label: "Center",- icon: AlignContentCenterIcon,- },- {- name: "start",- label: "Start",- icon: AlignContentStartIcon,- },- { name: "end", label: "End", icon: AlignContentEndIcon },- ]}- />- )}</Flex></Flex>- </Flex>+ </Grid>- <FlexGap />+ <Gap /></Flex>);};@@ -502,8 +739,10 @@ const LayoutSectionFlex = () => {const orderedDisplayValues = ["block","flex",+ "grid","inline-block","inline-flex",+ "inline-grid","inline","none",];@@ -513,22 +752,58 @@ export const properties = ["flex-direction","flex-wrap","align-items",+ "justify-items","justify-content","align-content","row-gap","column-gap",+ "grid-auto-flow",+ "grid-auto-columns",+ "grid-auto-rows",+ "grid-template-columns",+ "grid-template-rows",] satisfies Array<CssProperty>;+const isGridDisplay = (value: string) =>+ value === "grid" || value === "inline-grid";+export const Section = () => {const display = useComputedStyleDecl("display");const displayValue = toValue(display.cascadedValue);+ const instanceKey = useStore($selectedInstanceKey);+ const gridTemplateColumns = useComputedStyleDecl("grid-template-columns");+ const gridTemplateRows = useComputedStyleDecl("grid-template-rows");+ const columnsValue = toValue(gridTemplateColumns.cascadedValue);+ const rowsValue = toValue(gridTemplateRows.cascadedValue);++ const prevRef = useRef<{+ displayValue: string;+ instanceKey: string | undefined;+ }>();++ useEffect(() => {+ const prev = prevRef.current;+ prevRef.current = { displayValue, instanceKey };+ // Apply defaults only when display transitions from non-grid to grid+ // on the same instance (not on initial render or instance switch)+ if (+ prev === undefined ||+ prev.instanceKey !== instanceKey ||+ isGridDisplay(prev.displayValue) ||+ isGridDisplay(displayValue) === false+ ) {+ return;+ }+ applyDefaultGridStyles(columnsValue, rowsValue);+ }, [displayValue, instanceKey, columnsValue, rowsValue]);+return (<StyleSection label="Layout" properties={properties}><Flex direction="column" gap="2"><Gridcss={{- gridTemplateColumns: `1fr ${theme.spacing[24]}`,- alignItems: "center",+ gridTemplateColumns: `1fr 2fr`,+ gap: theme.spacing[4],}}><PropertyLabel@@ -544,6 +819,9 @@ export const Section = () => {{(displayValue === "flex" || displayValue === "inline-flex") && (<LayoutSectionFlex />)}+ {(displayValue === "grid" || displayValue === "inline-grid") && (+ <LayoutSectionGrid />+ )}</Flex></StyleSection>);diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-grid.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/alignment-ui.tsxsimilarity index 51%rename from apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-grid.tsxrename to apps/builder/app/builder/features/style-panel/sections/layout/shared/alignment-ui.tsxindex 32499660a4..5dfc4269b7 100644--- a/apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-grid.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/alignment-ui.tsx@@ -1,11 +1,6 @@-import type { CSSProperties } from "react";import { Box, Flex, Grid, IconButton } from "@webstudio-is/design-system";-import { toValue } from "@webstudio-is/css-engine";import { DotIcon } from "@webstudio-is/icons";import { theme } from "@webstudio-is/design-system";-import { useComputedStyles } from "../../../shared/model";-import { getPriorityStyleValueSource } from "../../../property-label";-import { createBatchUpdate } from "../../../shared/use-style-data";// Sometimes we need to hide a dot that ends up at an end// of a line and visually extends it@@ -28,46 +23,33 @@ const shouldHideDot = ({return x === 2 && y === 2;}}-return false;};-export const FlexGrid = () => {- const styles = useComputedStyles([- "flex-direction",- "justify-content",- "align-items",- ]);- const styleValueSourceColor = getPriorityStyleValueSource(styles);- const [flexDirection, justifyContent, alignItems] = styles;- const flexDirectionValue = toValue(flexDirection.cascadedValue);- const justifyContentValue = toValue(justifyContent.cascadedValue);- const alignItemsValue = toValue(alignItems.cascadedValue);+type AlignmentVisualProps = {+ // Visual state+ justifyContent: string;+ alignItems: string;+ isColumnDirection: boolean;+ color: string;+ // Item sizing for stretch behavior+ itemStretchWidth: boolean;+ itemStretchHeight: boolean;+ // Click handler for grid buttons+ onSelect: (position: { x: number; y: number }) => void;+};++export const AlignmentUi = ({+ justifyContent,+ alignItems,+ isColumnDirection,+ color,+ itemStretchWidth,+ itemStretchHeight,+ onSelect,+}: AlignmentVisualProps) => {const alignment = ["start", "center", "end"];const gridSize = alignment.length;- const isFlexDirectionColumn =- flexDirectionValue === "column" || flexDirectionValue === "column-reverse";-- let color = theme.colors.foregroundFlexUiMain;-- if (styleValueSourceColor === "local") {- color = theme.colors.foregroundLocalFlexUi;- }- if (styleValueSourceColor === "overwritten") {- color = theme.colors.foregroundOverwrittenFlexUi;- }- if (styleValueSourceColor === "remote") {- color = theme.colors.foregroundRemoteFlexUi;- }-- const addjustLinesPadding = (padding: number | undefined) => {- if (padding === undefined) {- return {};- }- return isFlexDirectionColumn- ? { paddingTop: padding, paddingBottom: padding }- : { paddingLeft: padding, paddingRight: padding };- };return (<Grid@@ -82,17 +64,16 @@ export const FlexGrid = () => {gridTemplateRows: "repeat(3, 1fr)",color,"&:focus-within": {- outlineColor: theme.colors.borderLocalFlexUi,+ outline: `1px solid ${theme.colors.borderLocalFlexUi}`,},}}>{Array.from(Array(gridSize * gridSize), (_, index) => {const x = index % gridSize;const y = Math.floor(index / gridSize);- // grid edges starts with 1let gridColumn = `${x + 1} / ${x + 2}`;let gridRow = `${y + 1} / ${y + 2}`;- if (isFlexDirectionColumn) {+ if (isColumnDirection) {[gridColumn, gridRow] = [gridRow, gridColumn];}return (@@ -123,26 +104,13 @@ export const FlexGrid = () => {outline: "none",},}}- onClick={() => {- const justifyContent = alignment[x];- const alignItems = alignment[y];- const batch = createBatchUpdate();- batch.setProperty("align-items")({- type: "keyword",- value: alignItems,- });- batch.setProperty("justify-content")({- type: "keyword",- value: justifyContent,- });- batch.publish();- }}+ onClick={() => onSelect({ x, y })}>{shouldHideDot({x,y,- justifyContent: justifyContentValue,- alignItems: alignItemsValue,+ justifyContent,+ alignItems,}) === false && (<Box css={{ size: 16 }}><DotIcon size={8} />@@ -163,28 +131,39 @@ export const FlexGrid = () => {pointerEvents: "none",}}style={{- flexDirection: flexDirectionValue as CSSProperties["flexDirection"],- justifyContent: justifyContentValue,- alignItems: alignItemsValue,- ...addjustLinesPadding(- justifyContentValue === "space-between"- ? 8- : justifyContentValue === "space-around"- ? 14.5- : undefined- ),+ flexDirection: isColumnDirection ? "column" : "row",+ justifyContent,+ alignItems,+ ...(justifyContent === "space-between"+ ? isColumnDirection+ ? { paddingTop: 8, paddingBottom: 8 }+ : { paddingLeft: 8, paddingRight: 8 }+ : justifyContent === "space-around"+ ? isColumnDirection+ ? { paddingTop: 14.5, paddingBottom: 14.5 }+ : { paddingLeft: 14.5, paddingRight: 14.5 }+ : {}),}}>- {[7, 12, 5].map((size) => (+ {[9, 14, 7].map((size) => (<Boxkey={size}css={{borderRadius: theme.borderRadius[1],backgroundColor: "currentColor",- ...(isFlexDirectionColumn- ? { minWidth: size, minHeight: 3 }- : { minWidth: 3, minHeight: size }),+ flexShrink: 0,}}+ style={+ isColumnDirection+ ? {+ minWidth: itemStretchWidth ? "100%" : size,+ minHeight: 3,+ }+ : {+ minWidth: 3,+ minHeight: itemStretchHeight ? "100%" : size,+ }+ }/>))}</Flex>diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/constants.ts b/apps/builder/app/builder/features/style-panel/sections/layout/shared/constants.tsnew file mode 100644index 0000000000..0e4846b2af--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/constants.ts@@ -0,0 +1,9 @@+/**+ * Default number of tracks (columns and rows) when a grid is first created.+ */+export const DEFAULT_GRID_TRACK_COUNT = 2;++/**+ * Default gap (in px) applied to both column-gap and row-gap when a grid is first created.+ */+export const DEFAULT_GRID_GAP = 16;diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-grid.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-alignment.stories.tsxsimilarity index 89%rename from apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-grid.stories.tsxrename to apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-alignment.stories.tsxindex eb3916c7e4..8906f9f7d4 100644--- a/apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-grid.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-alignment.stories.tsx@@ -1,9 +1,9 @@import { Box, Flex } from "@webstudio-is/design-system";-import { FlexGrid as FlexGridComponent } from "./flex-grid";+import { FlexAlignment as FlexAlignmentComponent } from "./flex-alignment";export default {- title: "Style Panel/Layout/Flex Grid",- component: FlexGridComponent,+ title: "Style Panel/Layout/Flex Alignment",+ component: FlexAlignmentComponent,};const alignItems = ["normal", "stretch", "baseline", "center", "start", "end"];@@ -57,7 +57,7 @@ export const FlexGrid = () => {</Box>{justifyContent.map((justifyContent) => (<Box key={justifyContent} css={{ position: "relative" }}>- <FlexGridComponent />+ <FlexAlignmentComponent /></Box>))}</Flex>diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-alignment.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-alignment.tsxnew file mode 100644index 0000000000..ae1df3611f--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/flex-alignment.tsx@@ -0,0 +1,61 @@+import { toValue } from "@webstudio-is/css-engine";+import { theme } from "@webstudio-is/design-system";+import { useComputedStyles } from "../../../shared/model";+import { getPriorityStyleValueSource } from "../../../property-label";+import { createBatchUpdate } from "../../../shared/use-style-data";+import { AlignmentUi } from "./alignment-ui";++export const FlexAlignment = () => {+ const styles = useComputedStyles([+ "flex-direction",+ "justify-content",+ "align-items",+ ]);+ const styleValueSourceColor = getPriorityStyleValueSource(styles);+ const [flexDirection, justifyContent, alignItems] = styles;++ const flexDirectionValue = toValue(flexDirection.cascadedValue);+ const justifyContentValue = toValue(justifyContent.cascadedValue);+ const alignItemsValue = toValue(alignItems.cascadedValue);++ const isColumnDirection =+ flexDirectionValue === "column" || flexDirectionValue === "column-reverse";++ let color = theme.colors.foregroundFlexUiMain;+ if (styleValueSourceColor === "local") {+ color = theme.colors.foregroundLocalFlexUi;+ }+ if (styleValueSourceColor === "overwritten") {+ color = theme.colors.foregroundOverwrittenFlexUi;+ }+ if (styleValueSourceColor === "remote") {+ color = theme.colors.foregroundRemoteFlexUi;+ }++ const alignment = ["start", "center", "end"];++ return (+ <AlignmentUi+ justifyContent={justifyContentValue}+ alignItems={alignItemsValue}+ isColumnDirection={isColumnDirection}+ color={color}+ itemStretchWidth={false}+ itemStretchHeight={false}+ onSelect={({ x, y }) => {+ const justifyContent = alignment[x];+ const alignItems = alignment[y];+ const batch = createBatchUpdate();+ batch.setProperty("align-items")({+ type: "keyword",+ value: alignItems,+ });+ batch.setProperty("justify-content")({+ type: "keyword",+ value: justifyContent,+ });+ batch.publish();+ }}+ />+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-alignment.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-alignment.tsxnew file mode 100644index 0000000000..978eb0c253--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-alignment.tsx@@ -0,0 +1,69 @@+import { theme } from "@webstudio-is/design-system";+import { toValue } from "@webstudio-is/css-engine";+import { useComputedStyles } from "../../../shared/model";+import { getPriorityStyleValueSource } from "../../../property-label";+import { createBatchUpdate } from "../../../shared/use-style-data";+import { AlignmentUi } from "./alignment-ui";++export const GridAlignment = () => {+ const styles = useComputedStyles([+ "grid-auto-flow",+ "justify-content",+ "justify-items",+ "align-items",+ ]);+ const styleValueSourceColor = getPriorityStyleValueSource(styles);+ const [gridAutoFlow, justifyContent, justifyItems, alignItems] = styles;++ const gridAutoFlowValue = toValue(gridAutoFlow.cascadedValue);+ const justifyContentValue = toValue(justifyContent.cascadedValue);+ const justifyItemsValue = toValue(justifyItems.cascadedValue);+ const alignItemsValue = toValue(alignItems.cascadedValue);++ const isColumnDirection = gridAutoFlowValue.includes("column");++ // For grid, justify-items controls item alignment within cells+ // When stretch, items fill the track width (row) or height (column)+ const itemStretchWidth =+ !isColumnDirection && justifyItemsValue === "stretch";+ const itemStretchHeight =+ isColumnDirection && justifyItemsValue === "stretch";++ let color = theme.colors.foregroundFlexUiMain;+ if (styleValueSourceColor === "local") {+ color = theme.colors.foregroundLocalFlexUi;+ }+ if (styleValueSourceColor === "overwritten") {+ color = theme.colors.foregroundOverwrittenFlexUi;+ }+ if (styleValueSourceColor === "remote") {+ color = theme.colors.foregroundRemoteFlexUi;+ }++ const alignment = ["start", "center", "end"];++ return (+ <AlignmentUi+ justifyContent={justifyContentValue}+ alignItems={alignItemsValue}+ isColumnDirection={isColumnDirection}+ color={color}+ itemStretchWidth={itemStretchWidth}+ itemStretchHeight={itemStretchHeight}+ onSelect={({ x, y }) => {+ const justifyContent = alignment[x];+ const alignItems = alignment[y];+ const batch = createBatchUpdate();+ batch.setProperty("align-items")({+ type: "keyword",+ value: alignItems,+ });+ batch.setProperty("justify-content")({+ type: "keyword",+ value: justifyContent,+ });+ batch.publish();+ }}+ />+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-area-picker.test.ts b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-area-picker.test.tsnew file mode 100644index 0000000000..60235dbc75--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-area-picker.test.ts@@ -0,0 +1,303 @@+import { describe, test, expect } from "vitest";+import { __testing__ } from "./grid-area-picker";+import type { AreaInfo } from "@webstudio-is/css-data";++const { buildOccupiedCellMap, clampRectangle, computeCellClick } = __testing__;++describe("buildOccupiedCellMap", () => {+ test("returns empty map when no areas", () => {+ const map = buildOccupiedCellMap([], 3, 3);+ expect(map.size).toBe(0);+ });++ test("maps single 1×1 area", () => {+ const areas: AreaInfo[] = [+ { name: "a", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ ];+ const map = buildOccupiedCellMap(areas, 3, 3);+ expect(map.get("1,1")).toBe("a");+ expect(map.has("2,1")).toBe(false);+ });++ test("maps multi-cell area", () => {+ const areas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ ];+ const map = buildOccupiedCellMap(areas, 3, 3);+ expect(map.get("1,1")).toBe("header");+ expect(map.get("2,1")).toBe("header");+ expect(map.has("3,1")).toBe(false);+ });++ test("maps multiple areas", () => {+ const areas: AreaInfo[] = [+ { name: "a", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ { name: "b", columnStart: 2, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ ];+ const map = buildOccupiedCellMap(areas, 3, 3);+ expect(map.get("1,1")).toBe("a");+ expect(map.get("2,1")).toBe("b");+ });++ test("clamps to grid bounds", () => {+ const areas: AreaInfo[] = [+ { name: "big", columnStart: 1, columnEnd: 10, rowStart: 1, rowEnd: 10 },+ ];+ const map = buildOccupiedCellMap(areas, 2, 2);+ expect(map.get("1,1")).toBe("big");+ expect(map.get("2,2")).toBe("big");+ expect(map.has("3,1")).toBe(false);+ });+});++describe("clampRectangle", () => {+ test("returns single cell when no obstacles", () => {+ const result = clampRectangle(+ { col: 1, row: 1 },+ { col: 1, row: 1 },+ new Map()+ );+ expect(result).toEqual({+ colStart: 1,+ colEnd: 1,+ rowStart: 1,+ rowEnd: 1,+ });+ });++ test("returns full rectangle when no obstacles", () => {+ const result = clampRectangle(+ { col: 1, row: 1 },+ { col: 3, row: 2 },+ new Map()+ );+ expect(result).toEqual({+ colStart: 1,+ colEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ });+ });++ test("shrinks from target side to avoid occupied cell", () => {+ const occupied = new Map([["3,1", "other"]]);+ const result = clampRectangle(+ { col: 1, row: 1 },+ { col: 3, row: 1 },+ occupied+ );+ expect(result).toEqual({+ colStart: 1,+ colEnd: 2,+ rowStart: 1,+ rowEnd: 1,+ });+ });++ test("works when target is before anchor", () => {+ const result = clampRectangle(+ { col: 3, row: 3 },+ { col: 1, row: 1 },+ new Map()+ );+ expect(result).toEqual({+ colStart: 1,+ colEnd: 3,+ rowStart: 1,+ rowEnd: 3,+ });+ });++ test("shrinks columns first, then rows to avoid occupied cell", () => {+ // Occupied cell at col 1, row 3 — columns shrink first (colEnd 2→1),+ // then rows shrink (rowEnd 3→2) to clear "1,3"+ const occupied = new Map([["1,3", "other"]]);+ const result = clampRectangle(+ { col: 1, row: 1 },+ { col: 2, row: 3 },+ occupied+ );+ expect(result).toEqual({+ colStart: 1,+ colEnd: 1,+ rowStart: 1,+ rowEnd: 2,+ });+ });+});++describe("computeCellClick", () => {+ const baseArea: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };++ test("ignores click on occupied cell", () => {+ const occupied = new Map([["2,1", "other"]]);+ const result = computeCellClick(+ 2,+ 1,+ baseArea,+ { col: 1, row: 1 },+ occupied+ );+ expect(result).toBeUndefined();+ });++ test("clicking selected cell resets to 1×1 at that cell", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 3,+ };+ const result = computeCellClick(2, 2, area, { col: 1, row: 1 }, new Map());+ expect(result).toEqual({+ area: {+ name: "test",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ },+ anchor: { col: 2, row: 2 },+ });+ });++ test("clicking unselected cell extends from anchor", () => {+ const result = computeCellClick(+ 3,+ 3,+ baseArea,+ { col: 1, row: 1 },+ new Map()+ );+ expect(result).toEqual({+ area: {+ name: "test",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 4,+ },+ anchor: { col: 1, row: 1 },+ });+ });++ test("extending to diagonal cell forms full rectangle", () => {+ // click (1,1) then (6,6) — should select 1-6 × 1-6+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ const result = computeCellClick(6, 6, area, { col: 1, row: 1 }, new Map());+ expect(result).toEqual({+ area: {+ name: "test",+ columnStart: 1,+ columnEnd: 7,+ rowStart: 1,+ rowEnd: 7,+ },+ anchor: { col: 1, row: 1 },+ });+ });++ test("extending after reset forms new rectangle from new anchor", () => {+ // After resetting to (2,2), clicking (7,7) should select 2-7 × 2-7+ const area: AreaInfo = {+ name: "test",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ };+ const result = computeCellClick(7, 7, area, { col: 2, row: 2 }, new Map());+ expect(result).toEqual({+ area: {+ name: "test",+ columnStart: 2,+ columnEnd: 8,+ rowStart: 2,+ rowEnd: 8,+ },+ anchor: { col: 2, row: 2 },+ });+ });++ test("extending clamps around occupied cells", () => {+ const occupied = new Map([["3,1", "other"]]);+ const result = computeCellClick(+ 4,+ 1,+ baseArea,+ { col: 1, row: 1 },+ occupied+ );+ // Can't include col 3, so clamps to col 1-2+ expect(result).toEqual({+ area: {+ name: "test",+ columnStart: 1,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ },+ anchor: { col: 1, row: 1 },+ });+ });++ test("clicking the only selected cell (1×1) still resets anchor", () => {+ const result = computeCellClick(+ 1,+ 1,+ baseArea,+ { col: 1, row: 1 },+ new Map()+ );+ expect(result).toEqual({+ area: {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ anchor: { col: 1, row: 1 },+ });+ });++ test("clicking selected cell in square selection resets to 1×1", () => {+ const squareArea: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 4,+ };+ const result = computeCellClick(+ 2,+ 2,+ squareArea,+ { col: 1, row: 1 },+ new Map()+ );+ expect(result).toEqual({+ area: {+ name: "test",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ },+ anchor: { col: 2, row: 2 },+ });+ });+});diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-area-picker.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-area-picker.tsxnew file mode 100644index 0000000000..f967ad195c--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-area-picker.tsx@@ -0,0 +1,338 @@+import { useRef, useMemo } from "react";+import { theme, Grid, Tooltip, css } from "@webstudio-is/design-system";+import type { AreaInfo } from "@webstudio-is/css-data";++/**+ * Build a map from "col,row" keys to area names for cells occupied by other areas.+ */+const buildOccupiedCellMap = (+ otherAreas: AreaInfo[],+ gridColumns: number,+ gridRows: number+): Map<string, string> => {+ const map = new Map<string, string>();+ for (const area of otherAreas) {+ for (let r = area.rowStart; r < area.rowEnd; r++) {+ for (let c = area.columnStart; c < area.columnEnd; c++) {+ if (c >= 1 && c <= gridColumns && r >= 1 && r <= gridRows) {+ map.set(`${c},${r}`, area.name);+ }+ }+ }+ }+ return map;+};++/**+ * Clamp a rectangle so it does not include any occupied cells.+ * Shrinks the rectangle edge-by-edge from the extension side.+ */+const clampRectangle = (+ anchor: { col: number; row: number },+ target: { col: number; row: number },+ occupied: Map<string, string>+): { colStart: number; colEnd: number; rowStart: number; rowEnd: number } => {+ let colStart = Math.min(anchor.col, target.col);+ let colEnd = Math.max(anchor.col, target.col);+ let rowStart = Math.min(anchor.row, target.row);+ let rowEnd = Math.max(anchor.row, target.row);++ const hasOccupied = (+ cs: number,+ ce: number,+ rs: number,+ re: number+ ): boolean => {+ for (let r = rs; r <= re; r++) {+ for (let c = cs; c <= ce; c++) {+ if (occupied.has(`${c},${r}`)) {+ return true;+ }+ }+ }+ return false;+ };++ // Shrink from the side opposite to anchor until no occupied cells remain+ while (hasOccupied(colStart, colEnd, rowStart, rowEnd)) {+ const shrunk =+ // Try shrinking column range from the side away from anchor+ (colEnd > anchor.col && colEnd > colStart && ((colEnd -= 1), true)) ||+ (colStart < anchor.col && colStart < colEnd && ((colStart += 1), true)) ||+ // Try shrinking row range from the side away from anchor+ (rowEnd > anchor.row && rowEnd > rowStart && ((rowEnd -= 1), true)) ||+ (rowStart < anchor.row && rowStart < rowEnd && ((rowStart += 1), true));++ if (!shrunk) {+ break;+ }+ }++ return { colStart, colEnd, rowStart, rowEnd };+};++/**+ * Compute the result of clicking a cell in the area picker.+ *+ * Returns `undefined` when the click should be ignored (occupied cell).+ * Otherwise returns `{ area, anchor }` with the new area bounds and anchor point.+ *+ * - Clicking an occupied cell → ignored+ * - Clicking a selected cell → resets to 1×1 at that cell (new anchor)+ * - Clicking an unselected cell → extends from anchor, clamped around obstacles+ */+const computeCellClick = (+ col: number,+ row: number,+ value: AreaInfo,+ anchor: { col: number; row: number },+ occupied: Map<string, string>+): { area: AreaInfo; anchor: { col: number; row: number } } | undefined => {+ if (occupied.has(`${col},${row}`)) {+ return undefined;+ }++ const isSelected =+ col >= value.columnStart &&+ col < value.columnEnd &&+ row >= value.rowStart &&+ row < value.rowEnd;++ // Click a selected cell → deselect all, set this cell as the new anchor+ if (isSelected) {+ return {+ area: {+ ...value,+ columnStart: col,+ columnEnd: col + 1,+ rowStart: row,+ rowEnd: row + 1,+ },+ anchor: { col, row },+ };+ }++ // Click an unselected cell → extend from anchor to form a rectangle+ const rect = clampRectangle(anchor, { col, row }, occupied);+ return {+ area: {+ ...value,+ columnStart: rect.colStart,+ columnEnd: rect.colEnd + 1,+ rowStart: rect.rowStart,+ rowEnd: rect.rowEnd + 1,+ },+ anchor,+ };+};++// Export for testing only+export const __testing__ = {+ buildOccupiedCellMap,+ clampRectangle,+ computeCellClick,+};++const freeCellStyle = css({+ minHeight: 20,+ border: "none",+ padding: 0,+ backgroundColor: theme.colors.backgroundControls,+ transition: "background-color 0.1s ease",+ cursor: "pointer",+ "&:hover": {+ backgroundColor: theme.colors.backgroundPrimary,+ },+});++const selectedCellStyle = css({+ minHeight: 20,+ border: "none",+ padding: 0,+ backgroundColor: "transparent",+ cursor: "pointer",+ "&:hover": {+ backgroundColor: "rgba(255, 255, 255, 0.15)",+ },+});++const occupiedAreaStyle = css({+ minHeight: 20,+ border: "none",+ padding: 0,+ borderRadius: theme.borderRadius[3],+ backgroundColor: theme.colors.backgroundDestructiveMain,+ cursor: "not-allowed",+ opacity: 0.6,+});++const selectedAreaBgStyle = css({+ border: "none",+ borderRadius: theme.borderRadius[3],+ backgroundColor: theme.colors.backgroundPrimary,+ pointerEvents: "none",+});++type GridAreaPickerProps = {+ value: AreaInfo;+ onChange: (value: AreaInfo) => void;+ onHoverChange?: (area: AreaInfo | undefined) => void;+ gridColumns: number;+ gridRows: number;+ otherAreas: AreaInfo[];+};++export const GridAreaPicker = ({+ value,+ onChange,+ onHoverChange,+ gridColumns,+ gridRows,+ otherAreas,+}: GridAreaPickerProps) => {+ const anchorRef = useRef<{ col: number; row: number }>({+ col: value.columnStart,+ row: value.rowStart,+ });++ const occupied = useMemo(+ () => buildOccupiedCellMap(otherAreas, gridColumns, gridRows),+ [otherAreas, gridColumns, gridRows]+ );++ const handleCellClick = (col: number, row: number) => {+ const result = computeCellClick(+ col,+ row,+ value,+ anchorRef.current,+ occupied+ );+ if (result === undefined) {+ return;+ }+ anchorRef.current = result.anchor;+ onChange(result.area);+ };++ // Deduplicate areas for rendering as single spanning elements+ const visibleAreas = useMemo(() => {+ const seen = new Set<string>();+ return otherAreas.filter((area) => {+ if (seen.has(area.name)) {+ return false;+ }+ if (area.columnStart > gridColumns || area.rowStart > gridRows) {+ return false;+ }+ if (area.columnEnd <= 1 || area.rowEnd <= 1) {+ return false;+ }+ seen.add(area.name);+ return true;+ });+ }, [otherAreas, gridColumns, gridRows]);++ const hasSelection =+ value.columnEnd > value.columnStart && value.rowEnd > value.rowStart;++ // Individual buttons for free and selected cells+ const cells = useMemo(() => {+ const result: React.ReactNode[] = [];+ for (let row = 1; row <= gridRows; row++) {+ for (let col = 1; col <= gridColumns; col++) {+ if (occupied.has(`${col},${row}`)) {+ continue;+ }+ const isSelected =+ col >= value.columnStart &&+ col < value.columnEnd &&+ row >= value.rowStart &&+ row < value.rowEnd;+ result.push(+ <button+ key={`${col},${row}`}+ className={isSelected ? selectedCellStyle() : freeCellStyle()}+ style={{+ gridColumn: `${col} / ${col + 1}`,+ gridRow: `${row} / ${row + 1}`,+ }}+ onClick={() => handleCellClick(col, row)}+ onMouseEnter={() => {+ onHoverChange?.({+ name: "",+ columnStart: col,+ columnEnd: col + 1,+ rowStart: row,+ rowEnd: row + 1,+ });+ }}+ onMouseLeave={() => onHoverChange?.(undefined)}+ aria-label={`Cell ${col}, ${row}`}+ />+ );+ }+ }+ return result;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [+ gridColumns,+ gridRows,+ occupied,+ value.columnStart,+ value.columnEnd,+ value.rowStart,+ value.rowEnd,+ ]);++ return (+ <Grid+ onMouseLeave={() => onHoverChange?.(undefined)}+ css={{+ width: "100%",+ gridTemplateColumns: `repeat(${gridColumns}, minmax(20px, 1fr))`,+ gridTemplateRows: `repeat(${gridRows}, 20px)`,+ gap: 1,+ backgroundColor: theme.colors.borderMain,+ borderRadius: theme.borderRadius[4],+ overflow: "hidden",+ }}+ >+ {/* Selected area background: single element spanning the whole selection */}+ {hasSelection && (+ <div+ className={selectedAreaBgStyle()}+ style={{+ gridColumn: `${value.columnStart} / ${value.columnEnd}`,+ gridRow: `${value.rowStart} / ${value.rowEnd}`,+ }}+ />+ )}++ {/* Occupied areas: one spanning element per area */}+ {visibleAreas.map((area) => {+ const colStart = Math.max(1, area.columnStart);+ const colEnd = Math.min(gridColumns + 1, area.columnEnd);+ const rowStart = Math.max(1, area.rowStart);+ const rowEnd = Math.min(gridRows + 1, area.rowEnd);+ return (+ <Tooltip key={area.name} content={area.name}>+ <button+ disabled+ className={occupiedAreaStyle()}+ style={{+ gridColumn: `${colStart} / ${colEnd}`,+ gridRow: `${rowStart} / ${rowEnd}`,+ }}+ onMouseEnter={() => onHoverChange?.(area)}+ onMouseLeave={() => onHoverChange?.(undefined)}+ aria-label={`Area ${area.name}`}+ />+ </Tooltip>+ );+ })}++ {cells}+ </Grid>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.test.ts b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.test.tsnew file mode 100644index 0000000000..66ac7b3f4d--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.test.ts@@ -0,0 +1,668 @@+import { describe, test, expect } from "vitest";+import {+ parseGridAreas,+ getGridDimensions,+ __testing__,+ type AreaInfo,+} from "./grid-areas";++const {+ generateGridTemplate,+ checkOverlap,+ generateUniqueAreaName,+ findNonOverlappingPosition,+ isAreaWithinBounds,+ filterAreasWithinBounds,+ toAreaName,+} = __testing__;++describe("parseGridAreas", () => {+ test("parses empty or none value", () => {+ expect(parseGridAreas("")).toEqual([]);+ expect(parseGridAreas("none")).toEqual([]);+ });++ test("parses single area", () => {+ const result = parseGridAreas('"header"');+ expect(result).toEqual([+ {+ name: "header",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ ]);+ });++ test("parses area spanning multiple columns", () => {+ const result = parseGridAreas('"header header header"');+ expect(result).toEqual([+ {+ name: "header",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 2,+ },+ ]);+ });++ test("parses multiple areas in one row", () => {+ const result = parseGridAreas('"sidebar main"');+ expect(result).toHaveLength(2);+ expect(result).toContainEqual({+ name: "sidebar",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ });+ expect(result).toContainEqual({+ name: "main",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ });+ });++ test("parses area spanning multiple rows", () => {+ const result = parseGridAreas('"sidebar main" "sidebar footer"');+ expect(result).toHaveLength(3);+ expect(result).toContainEqual({+ name: "sidebar",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 3,+ });+ });++ test("parses complex layout with multiple rows and columns", () => {+ const result = parseGridAreas(+ '"header header" "sidebar main" "footer footer"'+ );+ expect(result).toHaveLength(4);+ expect(result).toContainEqual({+ name: "header",+ columnStart: 1,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ });+ expect(result).toContainEqual({+ name: "sidebar",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 2,+ rowEnd: 3,+ });+ expect(result).toContainEqual({+ name: "main",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ });+ expect(result).toContainEqual({+ name: "footer",+ columnStart: 1,+ columnEnd: 3,+ rowStart: 3,+ rowEnd: 4,+ });+ });++ test("ignores dots (empty cells)", () => {+ const result = parseGridAreas('"header ." ". main"');+ expect(result).toHaveLength(2);+ expect(result).toContainEqual({+ name: "header",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ });+ expect(result).toContainEqual({+ name: "main",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ });+ });+});++describe("generateGridTemplate", () => {+ test("generates template for single area", () => {+ const areas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ ];+ expect(generateGridTemplate(areas, 2, 2)).toBe('"header ." ". ."');+ });++ test("generates template for area spanning columns", () => {+ const areas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ ];+ expect(generateGridTemplate(areas, 2, 2)).toBe('"header header" ". ."');+ });++ test("generates template for complex layout", () => {+ const areas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ { name: "sidebar", columnStart: 1, columnEnd: 2, rowStart: 2, rowEnd: 3 },+ { name: "main", columnStart: 2, columnEnd: 3, rowStart: 2, rowEnd: 3 },+ ];+ expect(generateGridTemplate(areas, 2, 2)).toBe(+ '"header header" "sidebar main"'+ );+ });++ test("fills empty cells with dots", () => {+ const areas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ { name: "footer", columnStart: 2, columnEnd: 3, rowStart: 2, rowEnd: 3 },+ ];+ expect(generateGridTemplate(areas, 2, 2)).toBe('"header ." ". footer"');+ });++ test("handles area out of bounds gracefully", () => {+ const areas: AreaInfo[] = [+ {+ name: "header",+ columnStart: 1,+ columnEnd: 10,+ rowStart: 1,+ rowEnd: 10,+ },+ ];+ // Should only fill within the grid bounds+ expect(generateGridTemplate(areas, 2, 2)).toBe(+ '"header header" "header header"'+ );+ });+});++describe("getGridDimensions", () => {+ test("parses column and row counts", () => {+ expect(getGridDimensions("1fr 2fr", "100px 200px")).toEqual({+ columns: 2,+ rows: 2,+ });+ });++ test("handles complex track definitions", () => {+ expect(+ getGridDimensions("repeat(3, 1fr)", "minmax(100px, 1fr) auto 200px")+ ).toEqual({+ columns: 3, // repeat(3, 1fr) = 3 columns+ rows: 3, // minmax(100px, 1fr), auto, 200px = 3 rows+ });+ });++ test("defaults to 2 when none", () => {+ expect(getGridDimensions("none", "none")).toEqual({+ columns: 2,+ rows: 2,+ });+ });++ test("defaults to 2 when empty", () => {+ expect(getGridDimensions("", "")).toEqual({+ columns: 2,+ rows: 2,+ });+ });+});++describe("checkOverlap", () => {+ test("detects overlapping areas", () => {+ const area1: AreaInfo = {+ name: "a",+ columnStart: 1,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 3,+ };+ const area2: AreaInfo = {+ name: "b",+ columnStart: 2,+ columnEnd: 4,+ rowStart: 2,+ rowEnd: 4,+ };+ expect(checkOverlap(area1, area2)).toBe(true);+ });++ test("detects non-overlapping areas horizontally", () => {+ const area1: AreaInfo = {+ name: "a",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ const area2: AreaInfo = {+ name: "b",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ };+ expect(checkOverlap(area1, area2)).toBe(false);+ });++ test("detects non-overlapping areas vertically", () => {+ const area1: AreaInfo = {+ name: "a",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ const area2: AreaInfo = {+ name: "b",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 2,+ rowEnd: 3,+ };+ expect(checkOverlap(area1, area2)).toBe(false);+ });++ test("detects complete containment as overlap", () => {+ const area1: AreaInfo = {+ name: "a",+ columnStart: 1,+ columnEnd: 5,+ rowStart: 1,+ rowEnd: 5,+ };+ const area2: AreaInfo = {+ name: "b",+ columnStart: 2,+ columnEnd: 4,+ rowStart: 2,+ rowEnd: 4,+ };+ expect(checkOverlap(area1, area2)).toBe(true);+ });++ test("detects edge adjacency as non-overlapping", () => {+ const area1: AreaInfo = {+ name: "a",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ const area2: AreaInfo = {+ name: "b",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ };+ expect(checkOverlap(area1, area2)).toBe(false);+ });+});++describe("generateUniqueAreaName", () => {+ test("returns 'Area' when no existing names", () => {+ expect(generateUniqueAreaName([])).toBe("Area");+ });++ test("returns 'Area' when it doesn't exist", () => {+ expect(generateUniqueAreaName(["Header", "Footer"])).toBe("Area");+ });++ test("returns 'Area-1' when 'Area' exists", () => {+ expect(generateUniqueAreaName(["Area"])).toBe("Area-1");+ });++ test("returns next available number", () => {+ expect(generateUniqueAreaName(["Area", "Area-1", "Area-2"])).toBe("Area-3");+ });++ test("handles gaps in numbering", () => {+ expect(generateUniqueAreaName(["Area", "Area-2", "Area-5"])).toBe("Area-1");+ });+});++describe("findNonOverlappingPosition", () => {+ test("finds first cell when grid is empty", () => {+ const result = findNonOverlappingPosition([], 2, 2);+ expect(result.needsNewRow).toBe(false);+ expect(result.area).toMatchObject({+ name: "Area",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ });+ });++ test("finds next available cell", () => {+ const existingAreas: AreaInfo[] = [+ { name: "Area", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ ];+ const result = findNonOverlappingPosition(existingAreas, 2, 2);+ expect(result.needsNewRow).toBe(false);+ expect(result.area).toMatchObject({+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ });+ });++ test("generates unique name for new area", () => {+ const existingAreas: AreaInfo[] = [+ { name: "Area", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ ];+ const result = findNonOverlappingPosition(existingAreas, 2, 2);+ expect(result.area.name).toBe("Area-1");+ });++ test("adds new row when grid is full", () => {+ const existingAreas: AreaInfo[] = [+ { name: "Area", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ { name: "Area-1", columnStart: 2, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ { name: "Area-2", columnStart: 1, columnEnd: 2, rowStart: 2, rowEnd: 3 },+ { name: "Area-3", columnStart: 2, columnEnd: 3, rowStart: 2, rowEnd: 3 },+ ];+ const result = findNonOverlappingPosition(existingAreas, 2, 2);+ expect(result.needsNewRow).toBe(true);+ expect(result.area).toMatchObject({+ columnStart: 1,+ columnEnd: 3,+ rowStart: 3,+ rowEnd: 4,+ });+ });++ test("finds cell when area spans multiple cells", () => {+ const existingAreas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ ];+ const result = findNonOverlappingPosition(existingAreas, 2, 2);+ expect(result.needsNewRow).toBe(false);+ expect(result.area).toMatchObject({+ columnStart: 1,+ columnEnd: 2,+ rowStart: 2,+ rowEnd: 3,+ });+ });+});++describe("isAreaWithinBounds", () => {+ test("validates area within bounds", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(true);+ });++ test("rejects area with invalid column start", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 0,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("rejects area with column start >= column end", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 2,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("rejects area with column end beyond grid", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("rejects area with invalid row start", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 0,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("rejects area with row start >= row end", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 2,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("rejects area with row end beyond grid", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 4,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("allows area at grid boundary", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(true);+ });+});++describe("filterAreasWithinBounds", () => {+ test("returns all areas when all are valid", () => {+ const areas: AreaInfo[] = [+ {+ name: "area1",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "area2",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ },+ ];+ const result = filterAreasWithinBounds(areas, 3, 2);+ expect(result).toEqual(areas);+ expect(result).toHaveLength(2);+ });++ test("filters out single area that exceeds column bounds", () => {+ const areas: AreaInfo[] = [+ {+ name: "valid",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 2,+ },+ ];+ const result = filterAreasWithinBounds(areas, 2, 2);+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe("valid");+ });++ test("filters out single area that exceeds row bounds", () => {+ const areas: AreaInfo[] = [+ {+ name: "valid",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 4,+ },+ ];+ const result = filterAreasWithinBounds(areas, 2, 2);+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe("valid");+ });++ test("filters out multiple invalid areas", () => {+ const areas: AreaInfo[] = [+ {+ name: "valid",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid1",+ columnStart: 1,+ columnEnd: 5,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid2",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 5,+ },+ ];+ const result = filterAreasWithinBounds(areas, 2, 2);+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe("valid");+ });++ test("returns empty array when all areas are invalid", () => {+ const areas: AreaInfo[] = [+ {+ name: "invalid1",+ columnStart: 1,+ columnEnd: 5,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid2",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 5,+ },+ ];+ const result = filterAreasWithinBounds(areas, 2, 2);+ expect(result).toEqual([]);+ });++ test("returns empty array for empty input", () => {+ const result = filterAreasWithinBounds([], 3, 3);+ expect(result).toEqual([]);+ });++ test("preserves order of valid areas", () => {+ const areas: AreaInfo[] = [+ {+ name: "first",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid",+ columnStart: 1,+ columnEnd: 5,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "second",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ },+ ];+ const result = filterAreasWithinBounds(areas, 3, 2);+ expect(result).toHaveLength(2);+ expect(result[0].name).toBe("first");+ expect(result[1].name).toBe("second");+ });+});++describe("toAreaName", () => {+ test("replaces spaces with dashes", () => {+ expect(toAreaName("Area 1")).toBe("Area-1");+ });++ test("replaces multiple consecutive spaces with a single dash", () => {+ expect(toAreaName("my area")).toBe("my-area");+ });++ test("replaces leading and trailing spaces", () => {+ expect(toAreaName(" header ")).toBe("-header-");+ });++ test("returns single word unchanged", () => {+ expect(toAreaName("sidebar")).toBe("sidebar");+ });++ test("handles empty string", () => {+ expect(toAreaName("")).toBe("");+ });++ test("handles tabs and mixed whitespace", () => {+ expect(toAreaName("a\tb")).toBe("a-b");+ });+});diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.tsxnew file mode 100644index 0000000000..754e7497b5--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.tsx@@ -0,0 +1,686 @@+import { useState, useCallback, useEffect } from "react";+import {+ theme,+ Flex,+ Text,+ IconButton,+ FloatingPanel,+ Label,+ InputField,+ Grid,+ CssValueListItem,+ CssValueListArrowFocus,+ SmallIconButton,+} from "@webstudio-is/design-system";+import { PlusIcon, MinusIcon } from "@webstudio-is/icons";+import { toValue } from "@webstudio-is/css-engine";+import { lexer } from "css-tree";+import {+ parseGridTemplateTrackList,+ parseGridAreas,+ type AreaInfo,+} from "@webstudio-is/css-data";+import {+ CollapsibleSectionRoot,+ useOpenState,+} from "~/builder/shared/collapsible-section";+import { useComputedStyleDecl } from "../../../shared/model";+import { createBatchUpdate } from "../../../shared/use-style-data";+import { GridPositionInputs } from "./grid-position-inputs";+import { GridAreaPicker } from "./grid-area-picker";+import { $gridEditingArea } from "~/builder/shared/nano-states";++export { parseGridAreas, type AreaInfo } from "@webstudio-is/css-data";++/**+ * Convert a user-typed area name into a valid CSS <custom-ident>.+ * Replaces whitespace runs with a single dash.+ */+const toAreaName = (input: string): string => input.replace(/\s+/g, "-");++/**+ * Generate grid-template-areas CSS string from area information+ * @example+ * generateGridTemplate([+ * { name: 'header', columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 }+ * ], 2, 2)+ * // Returns: '"header header" ". ."'+ */+const generateGridTemplate = (+ areas: AreaInfo[],+ columns: number,+ rows: number+): string => {+ // Create a 2D grid filled with dots+ const grid: string[][] = Array.from({ length: rows }, () =>+ Array(columns).fill(".")+ );++ // Fill in each area+ areas.forEach((area) => {+ for (let r = area.rowStart - 1; r < area.rowEnd - 1; r++) {+ for (let c = area.columnStart - 1; c < area.columnEnd - 1; c++) {+ if (r >= 0 && r < rows && c >= 0 && c < columns) {+ grid[r][c] = area.name;+ }+ }+ }+ });++ // Convert to CSS string format+ return grid.map((row) => `"${row.join(" ")}"`).join(" ");+};++/**+ * Get grid dimensions from template columns/rows CSS values+ * @example+ * getGridDimensions('1fr 2fr', '100px 200px 300px')+ * // Returns: { columns: 2, rows: 3 }+ */+export const getGridDimensions = (+ columnsValue: string,+ rowsValue: string+): { columns: number; rows: number } => {+ const columnTracks = parseGridTemplateTrackList(columnsValue);+ const rowTracks = parseGridTemplateTrackList(rowsValue);+ // Default to 2 if no tracks (for "none" or empty values)+ const columns = columnTracks.length || 2;+ const rows = rowTracks.length || 2;+ return { columns, rows };+};++/**+ * Check if two grid areas overlap+ * @example+ * checkOverlap(+ * { name: 'a', columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ * { name: 'b', columnStart: 2, columnEnd: 4, rowStart: 1, rowEnd: 2 }+ * )+ * // Returns: true (they overlap in columns 2)+ */+const checkOverlap = (area1: AreaInfo, area2: AreaInfo): boolean => {+ return (+ area1.columnStart < area2.columnEnd &&+ area1.columnEnd > area2.columnStart &&+ area1.rowStart < area2.rowEnd &&+ area1.rowEnd > area2.rowStart+ );+};++/**+ * Generate a unique area name based on existing names+ * @example+ * generateUniqueAreaName(['Area', 'Area-1'])+ * // Returns: 'Area-2'+ */+const generateUniqueAreaName = (existingNames: string[]): string => {+ const baseName = "Area";+ const existingNamesSet = new Set(existingNames);++ if (!existingNamesSet.has(baseName)) {+ return baseName;+ }++ let counter = 1;+ while (existingNamesSet.has(`${baseName}-${counter}`)) {+ counter++;+ }+ return `${baseName}-${counter}`;+};++/**+ * Find a non-overlapping position for a new area in the grid+ * Returns the area with a unique name and whether a new row is needed+ * @example+ * findNonOverlappingPosition([], 2, 2)+ * // Returns: { area: { name: 'Area', columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 }, needsNewRow: false }+ */+const findNonOverlappingPosition = (+ existingAreas: AreaInfo[],+ gridColumns: number,+ gridRows: number+): { area: AreaInfo; needsNewRow: boolean } => {+ const uniqueName = generateUniqueAreaName(existingAreas.map((a) => a.name));++ // Try to find an empty cell in the existing grid+ for (let row = 1; row <= gridRows; row++) {+ for (let col = 1; col <= gridColumns; col++) {+ const testArea: AreaInfo = {+ name: uniqueName,+ columnStart: col,+ columnEnd: col + 1,+ rowStart: row,+ rowEnd: row + 1,+ };++ const hasOverlap = existingAreas.some((existing) =>+ checkOverlap(testArea, existing)+ );++ if (!hasOverlap) {+ return { area: testArea, needsNewRow: false };+ }+ }+ }++ // No empty cell found, need to add a new row+ return {+ area: {+ name: uniqueName,+ columnStart: 1,+ columnEnd: gridColumns + 1,+ rowStart: gridRows + 1,+ rowEnd: gridRows + 2,+ },+ needsNewRow: true,+ };+};++/**+ * Validate area bounds are within grid dimensions+ */+const isAreaWithinBounds = (+ area: AreaInfo,+ gridColumns: number,+ gridRows: number+): boolean => {+ return (+ area.columnStart >= 1 &&+ area.columnStart < area.columnEnd &&+ area.columnEnd <= gridColumns + 1 &&+ area.rowStart >= 1 &&+ area.rowStart < area.rowEnd &&+ area.rowEnd <= gridRows + 1+ );+};++/**+ * Filter out areas that don't fit within the grid dimensions+ * Used when grid dimensions change (rows/columns deleted)+ */+const filterAreasWithinBounds = (+ areas: AreaInfo[],+ gridColumns: number,+ gridRows: number+): AreaInfo[] => {+ return areas.filter((area) =>+ isAreaWithinBounds(area, gridColumns, gridRows)+ );+};++// Export for testing only+export const __testing__ = {+ generateGridTemplate,+ checkOverlap,+ generateUniqueAreaName,+ findNonOverlappingPosition,+ isAreaWithinBounds,+ filterAreasWithinBounds,+ toAreaName,+};++type AreaEditorProps = {+ area: AreaInfo | undefined;+ editingIndex: number | undefined;+ gridColumns: number;+ gridRows: number;+ existingAreas: AreaInfo[];+ onSave: (area: AreaInfo, oldName?: string) => void;+ onClose: () => void;+};++const AreaEditor = ({+ area,+ editingIndex,+ gridColumns,+ gridRows,+ existingAreas,+ onSave,+ onClose,+}: AreaEditorProps) => {+ const [value, setValue] = useState<AreaInfo>(+ area || {+ name: "Area",+ columnStart: 1,+ columnEnd: gridColumns + 1,+ rowStart: 1,+ rowEnd: gridRows + 1,+ }+ );++ const handleSave = useCallback(+ (overrideValue?: AreaInfo) => {+ const current = overrideValue ?? value;+ const trimmedName = toAreaName(current.name.trim()) || "Area";++ // Validate CSS identifier using css-tree lexer+ if (!lexer.match("<custom-ident>", trimmedName).matched) {+ return;+ }++ // Filter out the area being edited from validation using index+ const otherAreas =+ editingIndex !== undefined+ ? existingAreas.filter((_, index) => index !== editingIndex)+ : existingAreas;++ // Check for duplicate names+ const hasDuplicateName = otherAreas.some(+ (existingArea) => existingArea.name === trimmedName+ );++ if (hasDuplicateName) {+ return;+ }++ // Validate bounds+ if (!isAreaWithinBounds(current, gridColumns, gridRows)) {+ return;+ }++ // Check for overlaps with other areas+ const hasOverlap = otherAreas.some((existingArea) =>+ checkOverlap(current, existingArea)+ );++ if (hasOverlap) {+ return;+ }++ onSave(+ {+ ...current,+ name: trimmedName,+ },+ area?.name+ );+ },+ [value, area, existingAreas, onSave, editingIndex, gridColumns, gridRows]+ );++ // Validation is now handled by GridPositionInputs component++ // Check for duplicate names+ const trimmedName = toAreaName(value.name.trim());+ // Filter out the area being edited from the comparison using index+ const otherAreas =+ editingIndex !== undefined+ ? existingAreas.filter((_, index) => index !== editingIndex)+ : existingAreas;++ const hasDuplicateName =+ trimmedName !== "" &&+ trimmedName !== area?.name && // Don't show error if name hasn't changed+ otherAreas.some((existingArea) => existingArea.name === trimmedName);++ // Check for overlaps with other areas+ const hasOverlap = otherAreas.some((existingArea) =>+ checkOverlap(value, existingArea)+ );++ return (+ <Flex direction="column" gap="2" css={{ padding: theme.panel.padding }}>+ <Grid+ css={{+ gridTemplateColumns: "60px 1fr 1fr",+ gap: theme.spacing[3],+ alignItems: "center",+ }}+ >+ <Label>Name</Label>+ <InputField+ css={{ gridColumn: "span 2" }}+ value={value.name}+ onChange={(event) => setValue({ ...value, name: event.target.value })}+ onBlur={() => handleSave()}+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ onClose();+ } else if (event.key === "Enter") {+ handleSave();+ }+ }}+ color={hasDuplicateName ? "error" : undefined}+ placeholder="Area"+ autoFocus+ />+ </Grid>++ <Grid+ css={{+ gridTemplateColumns: "60px 1fr",+ gap: theme.spacing[3],+ alignItems: "start",+ }}+ >+ <Label css={{ paddingTop: theme.spacing[3] }}>Position</Label>+ <GridPositionInputs+ value={{+ ...value,+ columnEnd: value.columnEnd - 1,+ rowEnd: value.rowEnd - 1,+ }}+ onChange={(position) =>+ setValue({+ ...value,+ ...position,+ columnEnd: position.columnEnd + 1,+ rowEnd: position.rowEnd + 1,+ })+ }+ onBlur={() => handleSave()}+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ onClose();+ } else if (event.key === "Enter") {+ handleSave();+ }+ }}+ gridColumns={gridColumns}+ gridRows={gridRows}+ checkBounds+ inclusiveEnd+ />+ </Grid>++ <GridAreaPicker+ value={value}+ onChange={(picked) => {+ setValue(picked);+ handleSave(picked);+ }}+ onHoverChange={(hovered) => {+ if (hovered) {+ $gridEditingArea.set({+ columnStart: hovered.columnStart,+ columnEnd: hovered.columnEnd,+ rowStart: hovered.rowStart,+ rowEnd: hovered.rowEnd,+ });+ } else {+ // Restore current value highlight+ $gridEditingArea.set({+ columnStart: value.columnStart,+ columnEnd: value.columnEnd,+ rowStart: value.rowStart,+ rowEnd: value.rowEnd,+ });+ }+ }}+ gridColumns={gridColumns}+ gridRows={gridRows}+ otherAreas={otherAreas}+ />++ {hasDuplicateName && (+ <Text variant="labels" color="destructive">+ Area name already exists+ </Text>+ )}+ {hasOverlap && (+ <Text variant="labels" color="destructive">+ Area overlaps with another area+ </Text>+ )}+ </Flex>+ );+};++export const GridAreas = () => {+ const [isOpen, setIsOpen] = useOpenState("Areas");+ const [editingAreaIndex, setEditingAreaIndex] = useState<number | undefined>(+ undefined+ );+ const [hoveredAreaIndex, setHoveredAreaIndex] = useState<number | undefined>(+ undefined+ );++ const gridTemplateAreas = useComputedStyleDecl("grid-template-areas");+ const gridTemplateColumns = useComputedStyleDecl("grid-template-columns");+ const gridTemplateRows = useComputedStyleDecl("grid-template-rows");++ const areasValue = toValue(gridTemplateAreas.cascadedValue);+ const columnsValue = toValue(gridTemplateColumns.cascadedValue);+ const rowsValue = toValue(gridTemplateRows.cascadedValue);++ const areas = parseGridAreas(areasValue);+ const { columns, rows } = getGridDimensions(columnsValue, rowsValue);++ // Update grid editing area highlight when editing or hovering an area+ // Editing takes priority over hovering+ const highlightIndex = editingAreaIndex ?? hoveredAreaIndex;+ useEffect(() => {+ if (highlightIndex !== undefined && areas[highlightIndex]) {+ const area = areas[highlightIndex];+ $gridEditingArea.set({+ columnStart: area.columnStart,+ columnEnd: area.columnEnd,+ rowStart: area.rowStart,+ rowEnd: area.rowEnd,+ });+ } else {+ $gridEditingArea.set(undefined);+ }+ return () => {+ $gridEditingArea.set(undefined);+ };+ }, [highlightIndex, areas]);++ const saveArea = useCallback(+ (newArea: AreaInfo, oldName?: string) => {+ const batch = createBatchUpdate();++ let updatedAreas = [...areas];++ // Check if oldName exists in current areas+ const isUpdate = oldName && areas.some((a) => a.name === oldName);++ if (isUpdate) {+ // Update existing area+ updatedAreas = updatedAreas.map((a) =>+ a.name === oldName ? newArea : a+ );+ } else {+ // Add new area+ updatedAreas.push(newArea);+ }++ // Filter out areas that are out of bounds+ const validAreas = filterAreasWithinBounds(updatedAreas, columns, rows);++ const template = generateGridTemplate(validAreas, columns, rows);+ batch.setProperty("grid-template-areas")({+ type: "unparsed",+ value: template,+ });+ batch.publish();+ },+ [areas, columns, rows]+ );++ const removeArea = useCallback(+ (areaName: string) => {+ const batch = createBatchUpdate();+ const remainingAreas = areas.filter((a) => a.name !== areaName);++ if (remainingAreas.length === 0) {+ batch.setProperty("grid-template-areas")({+ type: "keyword",+ value: "none",+ });+ } else {+ const template = generateGridTemplate(remainingAreas, columns, rows);+ batch.setProperty("grid-template-areas")({+ type: "unparsed",+ value: template,+ });+ }+ batch.publish();+ },+ [areas, columns, rows]+ );++ // Clean up areas that are out of bounds when grid dimensions change+ useEffect(() => {+ // Only run if there are areas and dimensions are valid+ if (areas.length === 0 || columns === 0 || rows === 0) {+ return;+ }++ const validAreas = filterAreasWithinBounds(areas, columns, rows);++ // If some areas are invalid, update the grid-template-areas+ if (validAreas.length < areas.length) {+ const batch = createBatchUpdate();++ if (validAreas.length === 0) {+ batch.setProperty("grid-template-areas")({+ type: "keyword",+ value: "none",+ });+ } else {+ const template = generateGridTemplate(validAreas, columns, rows);+ batch.setProperty("grid-template-areas")({+ type: "unparsed",+ value: template,+ });+ }++ batch.publish();+ }+ }, [columns, rows, areas]);++ const addArea = useCallback(() => {+ const { area: newArea, needsNewRow } = findNonOverlappingPosition(+ areas,+ columns,+ rows+ );++ const batch = createBatchUpdate();++ // Calculate actual dimensions after potential row addition+ let actualRows = rows;++ // If we need a new row, add it to the grid+ if (needsNewRow) {+ const currentRowTracks = parseGridTemplateTrackList(rowsValue);+ const lastRowSize =+ currentRowTracks[currentRowTracks.length - 1]?.value || "1fr";+ const updatedRows = [+ ...currentRowTracks.map((t) => t.value),+ lastRowSize,+ ].join(" ");+ batch.setProperty("grid-template-rows")({+ type: "unparsed",+ value: updatedRows,+ });+ actualRows = rows + 1; // Use the new row count+ }++ // Add the new area to the grid+ const updatedAreas = [...areas, newArea];+ const template = generateGridTemplate(+ updatedAreas,+ columns,+ actualRows // Use actualRows instead of stale rows+ );+ batch.setProperty("grid-template-areas")({+ type: "unparsed",+ value: template,+ });+ batch.publish();+ }, [areas, columns, rows, rowsValue]);++ return (+ <CollapsibleSectionRoot+ label={`Areas (${areas.length})`}+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ fullWidth+ trigger={+ <Flex+ align="center"+ justify="between"+ css={{ padding: theme.spacing[5] }}+ >+ <Text variant="labels" color="subtle">+ Areas ({areas.length})+ </Text>+ <IconButton+ onClick={(e) => {+ e.stopPropagation();+ addArea();+ }}+ >+ <PlusIcon />+ </IconButton>+ </Flex>+ }+ >+ <CssValueListArrowFocus>+ <Flex direction="column">+ {areas.length === 0 && (+ <Text+ color="subtle"+ align="center"+ css={{ padding: theme.panel.padding }}+ >+ No Areas+ </Text>+ )}+ {areas.map((area, index) => (+ <FloatingPanel+ key={area.name}+ placement="left-start"+ title="Edit area"+ content={+ <AreaEditor+ area={area}+ editingIndex={index}+ gridColumns={columns}+ gridRows={rows}+ existingAreas={areas}+ onSave={saveArea}+ onClose={() => setEditingAreaIndex(undefined)}+ />+ }+ open={editingAreaIndex === index}+ onOpenChange={(open) => {+ if (open) {+ setEditingAreaIndex(index);+ } else {+ setEditingAreaIndex(undefined);+ }+ }}+ >+ <CssValueListItem+ id={String(index)}+ index={index}+ onMouseEnter={() => setHoveredAreaIndex(index)}+ onMouseLeave={() => setHoveredAreaIndex(undefined)}+ label={+ <Label truncate>+ {area.name} ({area.columnStart}-{area.columnEnd - 1} /{" "}+ {area.rowStart}-{area.rowEnd - 1})+ </Label>+ }+ buttons={+ <SmallIconButton+ variant="destructive"+ tabIndex={-1}+ icon={<MinusIcon />}+ onClick={(e) => {+ e.stopPropagation();+ removeArea(area.name);+ }}+ />+ }+ />+ </FloatingPanel>+ ))}+ </Flex>+ </CssValueListArrowFocus>+ </CollapsibleSectionRoot>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.utils.test.ts b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.utils.test.tsnew file mode 100644index 0000000000..89c806f33e--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-areas.utils.test.ts@@ -0,0 +1,641 @@+import { describe, test, expect } from "vitest";+import {+ parseGridAreas,+ getGridDimensions,+ __testing__,+ type AreaInfo,+} from "./grid-areas";++const {+ generateGridTemplate,+ checkOverlap,+ generateUniqueAreaName,+ findNonOverlappingPosition,+ isAreaWithinBounds,+ filterAreasWithinBounds,+} = __testing__;++describe("parseGridAreas", () => {+ test("parses empty or none value", () => {+ expect(parseGridAreas("")).toEqual([]);+ expect(parseGridAreas("none")).toEqual([]);+ });++ test("parses single area", () => {+ const result = parseGridAreas('"header"');+ expect(result).toEqual([+ {+ name: "header",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ ]);+ });++ test("parses area spanning multiple columns", () => {+ const result = parseGridAreas('"header header header"');+ expect(result).toEqual([+ {+ name: "header",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 2,+ },+ ]);+ });++ test("parses multiple areas in one row", () => {+ const result = parseGridAreas('"sidebar main"');+ expect(result).toHaveLength(2);+ expect(result).toContainEqual({+ name: "sidebar",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ });+ expect(result).toContainEqual({+ name: "main",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ });+ });++ test("parses area spanning multiple rows", () => {+ const result = parseGridAreas('"sidebar main" "sidebar footer"');+ expect(result).toHaveLength(3);+ expect(result).toContainEqual({+ name: "sidebar",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 3,+ });+ });++ test("parses complex layout with multiple rows and columns", () => {+ const result = parseGridAreas(+ '"header header" "sidebar main" "footer footer"'+ );+ expect(result).toHaveLength(4);+ expect(result).toContainEqual({+ name: "header",+ columnStart: 1,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ });+ expect(result).toContainEqual({+ name: "sidebar",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 2,+ rowEnd: 3,+ });+ expect(result).toContainEqual({+ name: "main",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ });+ expect(result).toContainEqual({+ name: "footer",+ columnStart: 1,+ columnEnd: 3,+ rowStart: 3,+ rowEnd: 4,+ });+ });++ test("ignores dots (empty cells)", () => {+ const result = parseGridAreas('"header ." ". main"');+ expect(result).toHaveLength(2);+ expect(result).toContainEqual({+ name: "header",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ });+ expect(result).toContainEqual({+ name: "main",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ });+ });+});++describe("generateGridTemplate", () => {+ test("generates template for single area", () => {+ const areas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ ];+ expect(generateGridTemplate(areas, 2, 2)).toBe('"header ." ". ."');+ });++ test("generates template for area spanning columns", () => {+ const areas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ ];+ expect(generateGridTemplate(areas, 2, 2)).toBe('"header header" ". ."');+ });++ test("generates template for complex layout", () => {+ const areas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ { name: "sidebar", columnStart: 1, columnEnd: 2, rowStart: 2, rowEnd: 3 },+ { name: "main", columnStart: 2, columnEnd: 3, rowStart: 2, rowEnd: 3 },+ ];+ expect(generateGridTemplate(areas, 2, 2)).toBe(+ '"header header" "sidebar main"'+ );+ });++ test("fills empty cells with dots", () => {+ const areas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ { name: "footer", columnStart: 2, columnEnd: 3, rowStart: 2, rowEnd: 3 },+ ];+ expect(generateGridTemplate(areas, 2, 2)).toBe('"header ." ". footer"');+ });++ test("handles area out of bounds gracefully", () => {+ const areas: AreaInfo[] = [+ {+ name: "header",+ columnStart: 1,+ columnEnd: 10,+ rowStart: 1,+ rowEnd: 10,+ },+ ];+ // Should only fill within the grid bounds+ expect(generateGridTemplate(areas, 2, 2)).toBe(+ '"header header" "header header"'+ );+ });+});++describe("getGridDimensions", () => {+ test("parses column and row counts", () => {+ expect(getGridDimensions("1fr 2fr", "100px 200px")).toEqual({+ columns: 2,+ rows: 2,+ });+ });++ test("handles complex track definitions", () => {+ expect(+ getGridDimensions("repeat(3, 1fr)", "minmax(100px, 1fr) auto 200px")+ ).toEqual({+ columns: 3, // repeat(3, 1fr) expands to 3 tracks+ rows: 3, // minmax(100px, 1fr), auto, 200px = 3 tracks+ });+ });++ test("defaults to 2 when none", () => {+ expect(getGridDimensions("none", "none")).toEqual({+ columns: 2,+ rows: 2,+ });+ });++ test("defaults to 2 when empty", () => {+ expect(getGridDimensions("", "")).toEqual({+ columns: 2,+ rows: 2,+ });+ });+});++describe("checkOverlap", () => {+ test("detects overlapping areas", () => {+ const area1: AreaInfo = {+ name: "a",+ columnStart: 1,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 3,+ };+ const area2: AreaInfo = {+ name: "b",+ columnStart: 2,+ columnEnd: 4,+ rowStart: 2,+ rowEnd: 4,+ };+ expect(checkOverlap(area1, area2)).toBe(true);+ });++ test("detects non-overlapping areas horizontally", () => {+ const area1: AreaInfo = {+ name: "a",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ const area2: AreaInfo = {+ name: "b",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ };+ expect(checkOverlap(area1, area2)).toBe(false);+ });++ test("detects non-overlapping areas vertically", () => {+ const area1: AreaInfo = {+ name: "a",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ const area2: AreaInfo = {+ name: "b",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 2,+ rowEnd: 3,+ };+ expect(checkOverlap(area1, area2)).toBe(false);+ });++ test("detects complete containment as overlap", () => {+ const area1: AreaInfo = {+ name: "a",+ columnStart: 1,+ columnEnd: 5,+ rowStart: 1,+ rowEnd: 5,+ };+ const area2: AreaInfo = {+ name: "b",+ columnStart: 2,+ columnEnd: 4,+ rowStart: 2,+ rowEnd: 4,+ };+ expect(checkOverlap(area1, area2)).toBe(true);+ });++ test("detects edge adjacency as non-overlapping", () => {+ const area1: AreaInfo = {+ name: "a",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ const area2: AreaInfo = {+ name: "b",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ };+ expect(checkOverlap(area1, area2)).toBe(false);+ });+});++describe("generateUniqueAreaName", () => {+ test("returns 'Area' when no existing names", () => {+ expect(generateUniqueAreaName([])).toBe("Area");+ });++ test("returns 'Area' when it doesn't exist", () => {+ expect(generateUniqueAreaName(["Header", "Footer"])).toBe("Area");+ });++ test("returns 'Area-1' when 'Area' exists", () => {+ expect(generateUniqueAreaName(["Area"])).toBe("Area-1");+ });++ test("returns next available number", () => {+ expect(generateUniqueAreaName(["Area", "Area-1", "Area-2"])).toBe("Area-3");+ });++ test("handles gaps in numbering", () => {+ expect(generateUniqueAreaName(["Area", "Area-2", "Area-5"])).toBe("Area-1");+ });+});++describe("findNonOverlappingPosition", () => {+ test("finds first cell when grid is empty", () => {+ const result = findNonOverlappingPosition([], 2, 2);+ expect(result.needsNewRow).toBe(false);+ expect(result.area).toMatchObject({+ name: "Area",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ });+ });++ test("finds next available cell", () => {+ const existingAreas: AreaInfo[] = [+ { name: "Area", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ ];+ const result = findNonOverlappingPosition(existingAreas, 2, 2);+ expect(result.needsNewRow).toBe(false);+ expect(result.area).toMatchObject({+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ });+ });++ test("generates unique name for new area", () => {+ const existingAreas: AreaInfo[] = [+ { name: "Area", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ ];+ const result = findNonOverlappingPosition(existingAreas, 2, 2);+ expect(result.area.name).toBe("Area-1");+ });++ test("adds new row when grid is full", () => {+ const existingAreas: AreaInfo[] = [+ { name: "Area", columnStart: 1, columnEnd: 2, rowStart: 1, rowEnd: 2 },+ { name: "Area-1", columnStart: 2, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ { name: "Area-2", columnStart: 1, columnEnd: 2, rowStart: 2, rowEnd: 3 },+ { name: "Area-3", columnStart: 2, columnEnd: 3, rowStart: 2, rowEnd: 3 },+ ];+ const result = findNonOverlappingPosition(existingAreas, 2, 2);+ expect(result.needsNewRow).toBe(true);+ expect(result.area).toMatchObject({+ columnStart: 1,+ columnEnd: 3,+ rowStart: 3,+ rowEnd: 4,+ });+ });++ test("finds cell when area spans multiple cells", () => {+ const existingAreas: AreaInfo[] = [+ { name: "header", columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ ];+ const result = findNonOverlappingPosition(existingAreas, 2, 2);+ expect(result.needsNewRow).toBe(false);+ expect(result.area).toMatchObject({+ columnStart: 1,+ columnEnd: 2,+ rowStart: 2,+ rowEnd: 3,+ });+ });+});++describe("isAreaWithinBounds", () => {+ test("validates area within bounds", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(true);+ });++ test("rejects area with invalid column start", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 0,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("rejects area with column start >= column end", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 2,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("rejects area with column end beyond grid", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("rejects area with invalid row start", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 0,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("rejects area with row start >= row end", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 2,+ rowEnd: 2,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("rejects area with row end beyond grid", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 4,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(false);+ });++ test("allows area at grid boundary", () => {+ const area: AreaInfo = {+ name: "test",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ };+ expect(isAreaWithinBounds(area, 2, 2)).toBe(true);+ });+});++describe("filterAreasWithinBounds", () => {+ test("returns all areas when all are valid", () => {+ const areas: AreaInfo[] = [+ {+ name: "area1",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "area2",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ },+ ];+ const result = filterAreasWithinBounds(areas, 3, 2);+ expect(result).toEqual(areas);+ expect(result).toHaveLength(2);+ });++ test("filters out single area that exceeds column bounds", () => {+ const areas: AreaInfo[] = [+ {+ name: "valid",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 2,+ },+ ];+ const result = filterAreasWithinBounds(areas, 2, 2);+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe("valid");+ });++ test("filters out single area that exceeds row bounds", () => {+ const areas: AreaInfo[] = [+ {+ name: "valid",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 4,+ },+ ];+ const result = filterAreasWithinBounds(areas, 2, 2);+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe("valid");+ });++ test("filters out multiple invalid areas", () => {+ const areas: AreaInfo[] = [+ {+ name: "valid",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid1",+ columnStart: 1,+ columnEnd: 5,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid2",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 5,+ },+ ];+ const result = filterAreasWithinBounds(areas, 2, 2);+ expect(result).toHaveLength(1);+ expect(result[0].name).toBe("valid");+ });++ test("returns empty array when all areas are invalid", () => {+ const areas: AreaInfo[] = [+ {+ name: "invalid1",+ columnStart: 1,+ columnEnd: 5,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid2",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 5,+ },+ ];+ const result = filterAreasWithinBounds(areas, 2, 2);+ expect(result).toEqual([]);+ });++ test("returns empty array for empty input", () => {+ const result = filterAreasWithinBounds([], 3, 3);+ expect(result).toEqual([]);+ });++ test("preserves order of valid areas", () => {+ const areas: AreaInfo[] = [+ {+ name: "first",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "invalid",+ columnStart: 1,+ columnEnd: 5,+ rowStart: 1,+ rowEnd: 2,+ },+ {+ name: "second",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ },+ ];+ const result = filterAreasWithinBounds(areas, 3, 2);+ expect(result).toHaveLength(2);+ expect(result[0].name).toBe("first");+ expect(result[1].name).toBe("second");+ });+});diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.test.ts b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.test.tsnew file mode 100644index 0000000000..9f437c11ab--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.test.ts@@ -0,0 +1,323 @@+import { describe, test, expect } from "vitest";+import type { StyleDecl } from "@webstudio-is/sdk";+import { __testing__ } from "./grid-generator";++const { gridPresets, computeFillGridData, applyFillGridItems } = __testing__;++const makeIdGenerator = () => {+ let counter = 0;+ return () => `id-${++counter}`;+};++const createEmptyData = (parentId: string) => ({+ instances: new Map([+ [+ parentId,+ {+ type: "instance" as const,+ id: parentId,+ component: "Box",+ children: [] as Array<{ type: "id"; value: string }>,+ },+ ],+ ]),+ styleSources: new Map<string, { type: "local"; id: string }>(),+ styleSourceSelections: new Map<+ string,+ { instanceId: string; values: string[] }+ >(),+ styles: new Map<string, StyleDecl>(),+});++describe("gridPresets", () => {+ test("each preset has required fields", () => {+ for (const preset of gridPresets) {+ expect(preset.label).toBeTruthy();+ expect(preset.columns).toBeTruthy();+ expect(preset.rows).toBeTruthy();+ expect(preset.previewColumns).toBeTruthy();+ expect(preset.previewRows).toBeTruthy();+ }+ });++ test("no preset duplicates what the NxM picker does", () => {+ const equalFrPattern = /^(1fr\s*)+$/;+ for (const preset of gridPresets) {+ const trivialCols = equalFrPattern.test(preset.columns);+ const trivialRows = equalFrPattern.test(preset.rows);+ // At least one axis must go beyond equal 1fr tracks+ expect(trivialCols && trivialRows).toBe(false);+ }+ });++ test("fluid sidebar uses fit-content", () => {+ const sidebar = gridPresets.find((p) => p.label === "Fluid sidebar");+ expect(sidebar).toBeDefined();+ expect(sidebar?.columns).toContain("fit-content");+ });++ test("page stack has auto-sized header and footer rows", () => {+ const stack = gridPresets.find((p) => p.label === "Page stack");+ expect(stack).toBeDefined();+ expect(stack?.rows).toBe("auto 1fr auto");+ });++ test("holy grail preset has named areas", () => {+ const holyGrail = gridPresets.find((p) => p.label === "Holy grail");+ expect(holyGrail).toBeDefined();+ expect(holyGrail?.areas).toBeDefined();+ expect(holyGrail?.areas).toContain("header");+ expect(holyGrail?.areas).toContain("sidebar");+ expect(holyGrail?.areas).toContain("main");+ expect(holyGrail?.areas).toContain("footer");+ });++ test("responsive cards uses auto-fit with 250px minimum", () => {+ const cards = gridPresets.find((p) => p.label === "Responsive cards");+ expect(cards).toBeDefined();+ expect(cards?.columns).toContain("auto-fit");+ expect(cards?.columns).toContain("250px");+ });++ test("feature section uses auto-fit with 350px minimum", () => {+ const feature = gridPresets.find((p) => p.label === "Feature section");+ expect(feature).toBeDefined();+ expect(feature?.columns).toContain("auto-fit");+ expect(feature?.columns).toContain("350px");+ });++ test("footer columns uses auto-fit with 150px minimum", () => {+ const footer = gridPresets.find((p) => p.label === "Footer columns");+ expect(footer).toBeDefined();+ expect(footer?.columns).toContain("auto-fit");+ expect(footer?.columns).toContain("150px");+ });++ test("all auto-fit presets have distinct minmax thresholds", () => {+ const autoFitPresets = gridPresets.filter((p) =>+ p.columns.includes("auto-fit")+ );+ const thresholds = autoFitPresets.map((p) => {+ const match = p.columns.match(/minmax\((\d+)px/);+ return match?.[1];+ });+ expect(new Set(thresholds).size).toBe(thresholds.length);+ });++ test("preview thumbnails visually distinguish each preset", () => {+ const previews = gridPresets.map(+ (p) => `${p.previewColumns}|${p.previewRows}`+ );+ expect(new Set(previews).size).toBe(previews.length);+ });+});++describe("computeFillGridData", () => {+ test("returns items for each empty cell", () => {+ const items = computeFillGridData({+ totalCells: 6,+ existingChildCount: 0,+ generateId: makeIdGenerator(),+ });+ expect(items.length).toBe(6);+ });++ test("subtracts existing children", () => {+ const items = computeFillGridData({+ totalCells: 6,+ existingChildCount: 4,+ generateId: makeIdGenerator(),+ });+ expect(items.length).toBe(2);+ });++ test("returns empty array when grid is already full", () => {+ const items = computeFillGridData({+ totalCells: 4,+ existingChildCount: 4,+ generateId: makeIdGenerator(),+ });+ expect(items.length).toBe(0);+ });++ test("returns empty array when grid has more children than cells", () => {+ const items = computeFillGridData({+ totalCells: 4,+ existingChildCount: 7,+ generateId: makeIdGenerator(),+ });+ expect(items.length).toBe(0);+ });++ test("each item has unique instanceId and styleSourceId", () => {+ const items = computeFillGridData({+ totalCells: 9,+ existingChildCount: 0,+ generateId: makeIdGenerator(),+ });+ const instanceIds = items.map((item) => item.instanceId);+ const styleSourceIds = items.map((item) => item.styleSourceId);+ const allIds = [...instanceIds, ...styleSourceIds];+ expect(new Set(allIds).size).toBe(allIds.length);+ });++ test("single cell grid with no children returns one item", () => {+ const items = computeFillGridData({+ totalCells: 1,+ existingChildCount: 0,+ generateId: makeIdGenerator(),+ });+ expect(items.length).toBe(1);+ });+});++describe("applyFillGridItems", () => {+ test("creates Box instances in the data", () => {+ const data = createEmptyData("grid-1");+ const items = computeFillGridData({+ totalCells: 3,+ existingChildCount: 0,+ generateId: makeIdGenerator(),+ });+ applyFillGridItems(data, items, "bp-1", "grid-1");++ expect(data.instances.size).toBe(4); // parent + 3 children+ for (const item of items) {+ const instance = data.instances.get(item.instanceId);+ expect(instance).toBeDefined();+ expect(instance?.component).toBe("Box");+ expect(instance?.children).toEqual([]);+ }+ });++ test("appends children to parent instance", () => {+ const data = createEmptyData("grid-1");+ const items = computeFillGridData({+ totalCells: 2,+ existingChildCount: 0,+ generateId: makeIdGenerator(),+ });+ applyFillGridItems(data, items, "bp-1", "grid-1");++ const parent = data.instances.get("grid-1");+ expect(parent?.children.length).toBe(2);+ expect(parent?.children[0]).toEqual({+ type: "id",+ value: items[0].instanceId,+ });+ expect(parent?.children[1]).toEqual({+ type: "id",+ value: items[1].instanceId,+ });+ });++ test("preserves existing children when appending", () => {+ const data = createEmptyData("grid-1");+ const parent = data.instances.get("grid-1")!;+ parent.children.push({ type: "id", value: "existing-child" });++ const items = computeFillGridData({+ totalCells: 3,+ existingChildCount: 1,+ generateId: makeIdGenerator(),+ });+ applyFillGridItems(data, items, "bp-1", "grid-1");++ expect(parent.children.length).toBe(3);+ expect(parent.children[0]).toEqual({+ type: "id",+ value: "existing-child",+ });+ });++ test("creates local style sources for each item", () => {+ const data = createEmptyData("grid-1");+ const items = computeFillGridData({+ totalCells: 2,+ existingChildCount: 0,+ generateId: makeIdGenerator(),+ });+ applyFillGridItems(data, items, "bp-1", "grid-1");++ expect(data.styleSources.size).toBe(2);+ for (const item of items) {+ const source = data.styleSources.get(item.styleSourceId);+ expect(source).toEqual({ type: "local", id: item.styleSourceId });+ }+ });++ test("links style sources to instances via selections", () => {+ const data = createEmptyData("grid-1");+ const items = computeFillGridData({+ totalCells: 2,+ existingChildCount: 0,+ generateId: makeIdGenerator(),+ });+ applyFillGridItems(data, items, "bp-1", "grid-1");++ expect(data.styleSourceSelections.size).toBe(2);+ for (const item of items) {+ const selection = data.styleSourceSelections.get(item.instanceId);+ expect(selection).toEqual({+ instanceId: item.instanceId,+ values: [item.styleSourceId],+ });+ }+ });++ test("sets display flex and flex-direction column on each item", () => {+ const data = createEmptyData("grid-1");+ const items = computeFillGridData({+ totalCells: 2,+ existingChildCount: 0,+ generateId: makeIdGenerator(),+ });+ applyFillGridItems(data, items, "bp-1", "grid-1");++ expect(data.styles.size).toBe(4);+ const styleValues = Array.from(data.styles.values()) as Array<{+ breakpointId: string;+ property: string;+ value: { type: string; value: string };+ }>;+ for (const style of styleValues) {+ expect(style.breakpointId).toBe("bp-1");+ }+ const displayStyles = styleValues.filter((s) => s.property === "display");+ const directionStyles = styleValues.filter(+ (s) => s.property === "flexDirection"+ );+ expect(displayStyles).toHaveLength(2);+ expect(directionStyles).toHaveLength(2);+ for (const style of displayStyles) {+ expect(style.value).toEqual({ type: "keyword", value: "flex" });+ }+ for (const style of directionStyles) {+ expect(style.value).toEqual({ type: "keyword", value: "column" });+ }+ });++ test("does nothing when parent instance is missing", () => {+ const data = createEmptyData("grid-1");+ const items = computeFillGridData({+ totalCells: 2,+ existingChildCount: 0,+ generateId: makeIdGenerator(),+ });+ applyFillGridItems(data, items, "bp-1", "nonexistent");++ // No new instances or styles should be created+ expect(data.instances.size).toBe(1); // only original parent+ expect(data.styleSources.size).toBe(0);+ expect(data.styles.size).toBe(0);+ });++ test("handles empty items array", () => {+ const data = createEmptyData("grid-1");+ applyFillGridItems(data, [], "bp-1", "grid-1");++ const parent = data.instances.get("grid-1");+ expect(parent?.children.length).toBe(0);+ expect(data.styleSources.size).toBe(0);+ });+});diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsxnew file mode 100644index 0000000000..d12b222366--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-generator.tsx@@ -0,0 +1,627 @@+import { useMemo, useState } from "react";+import { useStore } from "@nanostores/react";+import { nanoid } from "nanoid";+import {+ Box,+ Button,+ Flex,+ Grid,+ theme,+ Text,+ FloatingPanel,+ Tooltip,+ css,+ Separator,+} from "@webstudio-is/design-system";+import { toValue } from "@webstudio-is/css-engine";+import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";+import {+ parseGridTemplateTrackList,+ parseGridAreas,+ getGridAxisMode,+ getGridAxisLabel,+ isImplicitGridMode,+ type GridAxisMode,+} from "@webstudio-is/css-data";+import { useComputedStyleDecl } from "../../../shared/model";+import { createBatchUpdate } from "../../../shared/use-style-data";+import {+ $breakpoints,+ $gridCellData,+ $instances,+ $selectedInstanceSelector,+} from "~/shared/nano-states";+import { updateWebstudioData } from "~/shared/instance-utils";+import { DEFAULT_GRID_TRACK_COUNT } from "./constants";++/**+ * Parse track count from a computed CSS value.+ * Returns DEFAULT_GRID_TRACK_COUNT for empty/none values.+ */+const parseTrackCount = (value: string): number => {+ if (!value || value === "none") {+ return DEFAULT_GRID_TRACK_COUNT;+ }+ const tracks = parseGridTemplateTrackList(value);+ return tracks.length || DEFAULT_GRID_TRACK_COUNT;+};++/**+ * Calculate the actual track count for an axis.+ * Uses DOM-probed count for implicit modes, parsed count for explicit.+ */+const getAxisTrackCount = (+ mode: GridAxisMode,+ computedValue: string,+ domCount: number | undefined+): number => {+ const parsedCount = parseTrackCount(computedValue);+ if (isImplicitGridMode(mode)) {+ return domCount ?? parsedCount;+ }+ return parsedCount;+};++const selectorCellStyle = css({+ width: 16,+ height: 16,+ borderRadius: theme.borderRadius[3],+ backgroundColor: theme.colors.backgroundControls,+ border: `1px solid ${theme.colors.borderMain}`,+ transition: "all 0.1s ease",+ "&:hover": {+ borderColor: theme.colors.borderFocus,+ },+ variants: {+ highlighted: {+ true: {+ backgroundColor: theme.colors.backgroundHover,+ borderColor: theme.colors.borderFocus,+ },+ },+ },+});++type GridGeneratorSelectorProps = {+ onSelect: (columns: number, rows: number) => void;+ initialColumns: number;+ initialRows: number;+};++const GridGeneratorSelector = ({+ onSelect,+ initialColumns,+ initialRows,+}: GridGeneratorSelectorProps) => {+ const [hoveredCell, setHoveredCell] = useState<{+ col: number;+ row: number;+ } | null>(null);++ const maxCols = 12;+ const maxRows = 8;++ const cells = useMemo(() => {+ return Array.from({ length: maxRows * maxCols }).map((_, i) => {+ const col = i % maxCols;+ const row = Math.floor(i / maxCols);+ const isSelected =+ col < initialColumns && row < initialRows && !hoveredCell;+ const isHighlighted =+ hoveredCell && col <= hoveredCell.col && row <= hoveredCell.row;++ return (+ <Tooltip+ key={i}+ content={+ hoveredCell && col === hoveredCell.col && row === hoveredCell.row+ ? `${hoveredCell.col + 1}×${hoveredCell.row + 1}`+ : ""+ }+ open={+ hoveredCell+ ? col === hoveredCell.col && row === hoveredCell.row+ : false+ }+ >+ <button+ onMouseEnter={() => setHoveredCell({ col, row })}+ onClick={() => onSelect(col + 1, row + 1)}+ className={selectorCellStyle({+ highlighted: isHighlighted || isSelected || undefined,+ })}+ />+ </Tooltip>+ );+ });+ }, [hoveredCell, onSelect, maxCols, maxRows, initialColumns, initialRows]);++ return (+ <Grid+ onMouseLeave={() => setHoveredCell(null)}+ css={{+ gridTemplateColumns: `repeat(${maxCols}, 1fr)`,+ gridTemplateRows: `repeat(${maxRows}, 1fr)`,+ gap: 2,+ }}+ >+ {cells}+ </Grid>+ );+};++type GridPreset = {+ label: string;+ columns: string;+ rows: string;+ areas?: string;+ // Mini-preview dimensions for the button thumbnail+ previewColumns: string;+ previewRows: string;+};++const gridPresets: GridPreset[] = [+ {+ label: "Fluid sidebar",+ columns: "fit-content(300px) 1fr",+ rows: "1fr",+ previewColumns: "1fr 3fr",+ previewRows: "1fr",+ },+ {+ label: "Page stack",+ columns: "1fr",+ rows: "auto 1fr auto",+ previewColumns: "1fr",+ previewRows: "1fr 4fr 1fr",+ },+ {+ label: "Holy grail",+ columns: "1fr 3fr 1fr",+ rows: "auto 1fr auto",+ areas: `"header header header" "sidebar main aside" "footer footer footer"`,+ previewColumns: "1fr 3fr 1fr",+ previewRows: "1fr 3fr 1fr",+ },+ {+ label: "Responsive cards",+ columns: "repeat(auto-fit, minmax(250px, 1fr))",+ rows: "auto",+ previewColumns: "1fr 1fr 1fr",+ previewRows: "1fr 1fr",+ },+ {+ label: "Feature section",+ columns: "repeat(auto-fit, minmax(350px, 1fr))",+ rows: "auto",+ previewColumns: "1fr 1fr",+ previewRows: "1fr",+ },+ {+ label: "Footer columns",+ columns: "repeat(auto-fit, minmax(150px, 1fr))",+ rows: "auto",+ previewColumns: "1fr 1fr 1fr 1fr",+ previewRows: "1fr",+ },+];++const presetButtonStyle = css({+ all: "unset",+ display: "flex",+ flexDirection: "column",+ alignItems: "center",+ gap: theme.spacing[2],+ cursor: "pointer",+ borderRadius: theme.borderRadius[3],+ padding: theme.spacing[3],+ boxSizing: "border-box",+ "&:hover": {+ backgroundColor: theme.colors.backgroundHover,+ },+ "&:focus-visible": {+ outline: `2px solid ${theme.colors.borderFocus}`,+ },+});++const presetPreviewStyle = css({+ width: "100%",+ aspectRatio: "3 / 2",+ borderRadius: theme.borderRadius[2],+ border: `1px solid ${theme.colors.borderMain}`,+ overflow: "hidden",+});++type GridPresetsPickerProps = {+ onSelect: (preset: GridPreset) => void;+};++const GridPresetsPicker = ({ onSelect }: GridPresetsPickerProps) => {+ return (+ <Grid+ css={{+ gridTemplateColumns: "repeat(3, 1fr)",+ gap: theme.spacing[3],+ }}+ >+ {gridPresets.map((preset) => (+ <Tooltip key={preset.label} content={preset.label}>+ <button+ className={presetButtonStyle()}+ onClick={() => onSelect(preset)}+ >+ <Grid+ className={presetPreviewStyle()}+ css={{+ gridTemplateColumns: preset.previewColumns,+ gridTemplateRows: preset.previewRows,+ gap: 1,+ padding: 2,+ }}+ >+ {Array.from({+ length:+ preset.previewColumns.split(" ").length *+ preset.previewRows.split(" ").length,+ }).map((_, i) => (+ <Box+ key={i}+ css={{+ backgroundColor: theme.colors.backgroundControls,+ borderRadius: theme.borderRadius[1],+ border: `1px solid ${theme.colors.borderMain}`,+ }}+ />+ ))}+ </Grid>+ <Text+ variant="tiny"+ align="center"+ css={{+ display: "-webkit-box",+ WebkitLineClamp: 2,+ WebkitBoxOrient: "vertical",+ overflow: "hidden",+ wordBreak: "break-word",+ }}+ >+ {preset.label}+ </Text>+ </button>+ </Tooltip>+ ))}+ </Grid>+ );+};++type FillGridInput = {+ totalCells: number;+ existingChildCount: number;+ generateId: () => string;+};++type FillGridItem = {+ instanceId: string;+ styleSourceId: string;+};++const computeFillGridData = ({+ totalCells,+ existingChildCount,+ generateId,+}: FillGridInput): FillGridItem[] => {+ const cellsToAdd = totalCells - existingChildCount;+ if (cellsToAdd <= 0) {+ return [];+ }+ return Array.from({ length: cellsToAdd }, () => ({+ instanceId: generateId(),+ styleSourceId: generateId(),+ }));+};++const applyFillGridItems = (+ data: Pick<+ Parameters<Parameters<typeof updateWebstudioData>[0]>[0],+ "instances" | "styleSources" | "styleSourceSelections" | "styles"+ >,+ items: FillGridItem[],+ breakpointId: string,+ parentInstanceId: string+) => {+ const parentInstance = data.instances.get(parentInstanceId);+ if (parentInstance === undefined) {+ return;+ }+ for (const { instanceId, styleSourceId } of items) {+ data.instances.set(instanceId, {+ type: "instance",+ id: instanceId,+ component: "Box",+ children: [],+ });+ data.styleSources.set(styleSourceId, {+ type: "local",+ id: styleSourceId,+ });+ data.styleSourceSelections.set(instanceId, {+ instanceId,+ values: [styleSourceId],+ });+ const displayStyleDecl: StyleDecl = {+ breakpointId,+ styleSourceId,+ property: "display",+ value: { type: "keyword", value: "flex" },+ };+ data.styles.set(getStyleDeclKey(displayStyleDecl), displayStyleDecl);+ const directionStyleDecl: StyleDecl = {+ breakpointId,+ styleSourceId,+ property: "flexDirection",+ value: { type: "keyword", value: "column" },+ };+ data.styles.set(getStyleDeclKey(directionStyleDecl), directionStyleDecl);+ parentInstance.children.push({ type: "id", value: instanceId });+ }+};++const gridGeneratorButtonStyle = css({+ all: "unset",+ position: "relative",+ display: "grid",+ width: "100%",+ height: 60,+ outline: `1px solid ${theme.colors.borderMain}`,+ borderRadius: theme.borderRadius[3],+ overflow: "hidden",+ cursor: "pointer",+ "&:focus-within, &[data-state=open]": {+ outline: `1px solid ${theme.colors.borderLocalFlexUi}`,+ },+ "&:hover": {+ backgroundColor: theme.colors.backgroundHover,+ },+});++type GridGeneratorProps = {+ open: boolean;+ onOpenChange: (open: boolean) => void;+};++export const GridGenerator = ({ open, onOpenChange }: GridGeneratorProps) => {+ const gridTemplateColumns = useComputedStyleDecl("grid-template-columns");+ const gridTemplateRows = useComputedStyleDecl("grid-template-rows");+ const gridTemplateAreas = useComputedStyleDecl("grid-template-areas");+ const gridCellData = useStore($gridCellData);++ // Analyze both axes using pure functions+ const columnsValueCascaded = toValue(gridTemplateColumns.cascadedValue);+ const rowsValueCascaded = toValue(gridTemplateRows.cascadedValue);+ const columnsMode = getGridAxisMode(columnsValueCascaded);+ const rowsMode = getGridAxisMode(rowsValueCascaded);++ // Calculate track counts+ // For unknown modes (subgrid, masonry, line-names), we use defaults+ const columnsValueComputed = toValue(gridTemplateColumns.computedValue);+ const rowsValueComputed = toValue(gridTemplateRows.computedValue);+ const columnCount = getAxisTrackCount(+ columnsMode,+ columnsValueComputed,+ gridCellData?.columnCount+ );+ const rowCount = getAxisTrackCount(+ rowsMode,+ rowsValueComputed,+ gridCellData?.rowCount+ );++ const displayColumnCount = Math.min(columnCount, 8);+ const displayRowCount = Math.min(rowCount, 8);++ const handleChange = (columns: number, rows: number) => {+ const batch = createBatchUpdate();++ batch.setProperty("grid-template-columns")({+ type: "unparsed",+ value: Array(columns).fill("1fr").join(" "),+ });++ batch.setProperty("grid-template-rows")({+ type: "unparsed",+ value: Array(rows).fill("1fr").join(" "),+ });++ batch.publish();+ };++ const handleSelectorSelect = (columns: number, rows: number) => {+ handleChange(columns, rows);+ };++ const handlePresetSelect = (preset: GridPreset) => {+ const batch = createBatchUpdate();+ batch.setProperty("grid-template-columns")({+ type: "unparsed",+ value: preset.columns,+ });+ batch.setProperty("grid-template-rows")({+ type: "unparsed",+ value: preset.rows,+ });+ if (preset.areas) {+ batch.setProperty("grid-template-areas")({+ type: "unparsed",+ value: preset.areas,+ });+ } else {+ batch.deleteProperty("grid-template-areas");+ }+ batch.publish();+ };++ const handleFillGrid = () => {+ const instanceSelector = $selectedInstanceSelector.get();+ if (instanceSelector === undefined) {+ return;+ }+ const instances = $instances.get();+ const parentInstance = instances.get(instanceSelector[0]);+ if (parentInstance === undefined) {+ return;+ }+ const existingChildCount = parentInstance.children.filter(+ (child) => child.type === "id"+ ).length;+ const baseBreakpoint = Array.from($breakpoints.get().values()).find(+ (bp) => bp.minWidth === undefined && bp.maxWidth === undefined+ );+ if (baseBreakpoint === undefined) {+ return;+ }+ const items = computeFillGridData({+ totalCells: columnCount * rowCount,+ existingChildCount,+ generateId: nanoid,+ });+ if (items.length === 0) {+ return;+ }+ updateWebstudioData((data) => {+ applyFillGridItems(data, items, baseBreakpoint.id, instanceSelector[0]);+ });+ };++ // Build a map from "col,row" (0-based) to area name for the preview+ const areasValue = toValue(gridTemplateAreas.cascadedValue);+ const areas = useMemo(() => parseGridAreas(areasValue), [areasValue]);++ const areaMap = useMemo(() => {+ const map = new Map<string, string>();+ for (const area of areas) {+ for (let r = area.rowStart; r < area.rowEnd; r++) {+ for (let c = area.columnStart; c < area.columnEnd; c++) {+ const displayCol = c - 1;+ const displayRow = r - 1;+ if (displayCol < displayColumnCount && displayRow < displayRowCount) {+ map.set(`${displayCol},${displayRow}`, area.name);+ }+ }+ }+ }+ return map;+ }, [areas, displayColumnCount, displayRowCount]);++ // Memoize grid cells to avoid recreating on each render+ const gridCells = useMemo(() => {+ return Array.from({ length: displayColumnCount * displayRowCount }).map(+ (_, i) => {+ const col = i % displayColumnCount;+ const row = Math.floor(i / displayColumnCount);+ const areaName = areaMap.get(`${col},${row}`);+ const rightNeighbor = areaMap.get(`${col + 1},${row}`);+ const bottomNeighbor = areaMap.get(`${col},${row + 1}`);+ // Hide border when both sides belong to the same named area+ const mergedRight =+ areaName !== undefined && areaName === rightNeighbor;+ const mergedBottom =+ areaName !== undefined && areaName === bottomNeighbor;++ return (+ <Box+ key={i}+ css={{+ width: "100%",+ height: "100%",+ borderRight:+ col < displayColumnCount - 1 && !mergedRight+ ? `1px solid ${theme.colors.borderMain}`+ : undefined,+ borderBottom:+ row < displayRowCount - 1 && !mergedBottom+ ? `1px solid ${theme.colors.borderMain}`+ : undefined,+ }}+ />+ );+ }+ );+ }, [displayColumnCount, displayRowCount, areaMap]);++ return (+ <FloatingPanel+ title="Grid generator"+ placement="left-start"+ content={+ <Flex direction="column">+ <Flex+ direction="column"+ gap="3"+ css={{ padding: theme.panel.padding }}+ >+ <GridGeneratorSelector+ onSelect={handleSelectorSelect}+ initialColumns={columnCount}+ initialRows={rowCount}+ />+ </Flex>+ <Separator />+ <Flex+ direction="column"+ gap="3"+ css={{ padding: theme.panel.padding }}+ >+ <GridPresetsPicker onSelect={handlePresetSelect} />+ </Flex>+ <Separator />+ <Flex css={{ padding: theme.panel.padding }}>+ <Button+ color="neutral"+ css={{ width: "100%" }}+ onClick={handleFillGrid}+ >+ Fill grid+ </Button>+ </Flex>+ </Flex>+ }+ open={open}+ onOpenChange={onOpenChange}+ closeOnInteractOutside={false}+ >+ {/* Visual grid preview - similar to Figma's style */}+ <button+ aria-label={`Grid layout: ${columnCount} columns by ${rowCount} rows`}+ className={gridGeneratorButtonStyle()}+ style={{+ gridTemplateColumns: `repeat(${displayColumnCount}, 1fr)`,+ gridTemplateRows: `repeat(${displayRowCount}, 1fr)`,+ }}+ >+ {gridCells}+ <Text+ variant="mono"+ css={{+ position: "absolute",+ inset: 0,+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+ pointerEvents: "none",+ whiteSpace: "nowrap",+ }}+ >+ {getGridAxisLabel(columnsMode, columnCount) ++ "×" ++ getGridAxisLabel(rowsMode, rowCount)}+ </Text>+ </button>+ </FloatingPanel>+ );+};++export const __testing__ = {+ gridPresets,+ computeFillGridData,+ applyFillGridItems,+};diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-position-inputs.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-position-inputs.tsxnew file mode 100644index 0000000000..00030ccec4--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-position-inputs.tsx@@ -0,0 +1,190 @@+import {+ Flex,+ Grid,+ InputField,+ Text,+ theme,+} from "@webstudio-is/design-system";++export type GridPosition = {+ columnStart: number;+ columnEnd: number;+ rowStart: number;+ rowEnd: number;+};++export type GridPositionValidation = {+ isColumnStartValid: boolean;+ isColumnEndValid: boolean;+ isRowStartValid: boolean;+ isRowEndValid: boolean;+};++export const validateGridPosition = (+ position: GridPosition,+ gridColumns: number,+ gridRows: number,+ options: { checkBounds?: boolean; inclusiveEnd?: boolean } = {}+): GridPositionValidation => {+ const { checkBounds = false, inclusiveEnd = false } = options;+ // With inclusiveEnd, end is a track index (end >= start is valid).+ // Without, end is a grid-line number (end > start is required).+ const endOp = inclusiveEnd+ ? (end: number, start: number) => end >= start+ : (end: number, start: number) => end > start;+ const maxCol = inclusiveEnd ? gridColumns : gridColumns + 1;+ const maxRow = inclusiveEnd ? gridRows : gridRows + 1;+ const result = {+ isColumnStartValid:+ position.columnStart >= 1 &&+ endOp(position.columnEnd, position.columnStart),+ isColumnEndValid:+ endOp(position.columnEnd, position.columnStart) &&+ (!checkBounds || position.columnEnd <= maxCol),+ isRowStartValid:+ position.rowStart >= 1 && endOp(position.rowEnd, position.rowStart),+ isRowEndValid:+ endOp(position.rowEnd, position.rowStart) &&+ (!checkBounds || position.rowEnd <= maxRow),+ };+ return result;+};++type GridPositionInputsProps = {+ value: GridPosition;+ onChange: (value: GridPosition) => void;+ onBlur?: () => void;+ onKeyDown?: (event: React.KeyboardEvent) => void;+ gridColumns: number;+ gridRows: number;+ checkBounds?: boolean;+ /**+ * When true, "end" values are inclusive track indices (1-based)+ * instead of exclusive grid-line numbers.+ * Validation uses end >= start instead of end > start.+ */+ inclusiveEnd?: boolean;+};++const PositionInputGroup = ({+ startValue,+ endValue,+ onStartChange,+ onEndChange,+ onBlur,+ onKeyDown,+ isStartValid,+ isEndValid,+ minStart,+ maxStart,+ minEnd,+ maxEnd,+ label,+}: {+ startValue: number;+ endValue: number;+ onStartChange: (value: number) => void;+ onEndChange: (value: number) => void;+ onBlur?: () => void;+ isStartValid: boolean;+ isEndValid: boolean;+ minStart: number;+ maxStart: number;+ minEnd: number;+ maxEnd: number;+ label: string;+ onKeyDown?: (event: React.KeyboardEvent) => void;+}) => (+ <Flex direction="column" gap="1" css={{ flex: 1 }}>+ <Grid css={{ gridTemplateColumns: "1fr 1fr", gap: theme.spacing[3] }}>+ <InputField+ type="number"+ value={String(startValue)}+ onChange={(event) => {+ const num = Number(event.target.value);+ if (!isNaN(num)) {+ onStartChange(num);+ }+ }}+ onBlur={onBlur}+ onKeyDown={onKeyDown}+ color={isStartValid ? undefined : "error"}+ min={minStart}+ max={maxStart}+ />+ <InputField+ type="number"+ value={String(endValue)}+ onChange={(event) => {+ const num = Number(event.target.value);+ if (!isNaN(num)) {+ onEndChange(num);+ }+ }}+ onBlur={onBlur}+ onKeyDown={onKeyDown}+ color={isEndValid ? undefined : "error"}+ min={minEnd}+ max={maxEnd}+ />+ </Grid>+ <Text variant="small" color="subtle">+ {label}+ </Text>+ </Flex>+);++export const GridPositionInputs = ({+ value,+ onChange,+ onBlur,+ onKeyDown,+ gridColumns,+ gridRows,+ checkBounds = false,+ inclusiveEnd = false,+}: GridPositionInputsProps) => {+ const validation = validateGridPosition(value, gridColumns, gridRows, {+ checkBounds,+ inclusiveEnd,+ });++ const colMaxEnd = inclusiveEnd ? gridColumns : gridColumns + 1;+ const rowMaxEnd = inclusiveEnd ? gridRows : gridRows + 1;+ const minEnd = inclusiveEnd ? 1 : 2;++ return (+ <Flex gap="2">+ <PositionInputGroup+ startValue={value.columnStart}+ endValue={value.columnEnd}+ onStartChange={(columnStart) => onChange({ ...value, columnStart })}+ onEndChange={(columnEnd) => onChange({ ...value, columnEnd })}+ onBlur={onBlur}+ onKeyDown={onKeyDown}+ isStartValid={validation.isColumnStartValid}+ isEndValid={validation.isColumnEndValid}+ minStart={1}+ maxStart={gridColumns}+ minEnd={minEnd}+ maxEnd={colMaxEnd}+ label="Column: start/end"+ />+ <PositionInputGroup+ startValue={value.rowStart}+ endValue={value.rowEnd}+ onStartChange={(rowStart) => onChange({ ...value, rowStart })}+ onEndChange={(rowEnd) => onChange({ ...value, rowEnd })}+ onBlur={onBlur}+ onKeyDown={onKeyDown}+ isStartValid={validation.isRowStartValid}+ isEndValid={validation.isRowEndValid}+ minStart={1}+ maxStart={gridRows}+ minEnd={minEnd}+ maxEnd={rowMaxEnd}+ label="Row: start/end"+ />+ </Flex>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.tsx b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.tsxnew file mode 100644index 0000000000..4942219af7--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-settings.tsx@@ -0,0 +1,531 @@+import { useMemo, useState, useCallback, useEffect } from "react";+import {+ theme,+ Flex,+ Text,+ FloatingPanel,+ IconButton,+ Label,+ CssValueListItem,+ CssValueListArrowFocus,+ SmallIconButton,+ useSortable,+ Button,+ Checkbox,+ Grid,+} from "@webstudio-is/design-system";+import { toValue, type StyleValue } from "@webstudio-is/css-engine";+import {+ parseGridTemplateTrackList,+ serializeGridTemplateTrackList,+ parseMinmax,+ serializeMinmax,+ isEditableGridMode,+ getGridAxisMode,+ type GridTrack,+} from "@webstudio-is/css-data";+import { PlusIcon, MinusIcon } from "@webstudio-is/icons";+import { useStore } from "@nanostores/react";+import { $selectedInstance } from "~/shared/awareness";+import { useComputedStyleDecl } from "../../../shared/model";+import { CssValueInputContainer } from "../../../shared/css-value-input";+import { createBatchUpdate } from "../../../shared/use-style-data";+import {+ CollapsibleSectionRoot,+ useOpenState,+} from "~/builder/shared/collapsible-section";+import { GridAreas } from "./grid-areas";+import { $gridEditingTrack } from "~/builder/shared/nano-states";++/**+ * Compute how many auto tracks are created when children exceed+ * the defined template tracks along the flow axis.+ * e.g. a 2×2 grid with 5 children in row flow → ceil(5/2) - 2 = 1 auto row.+ */+const computeAutoTrackCount = (+ childCount: number,+ crossAxisTrackCount: number,+ flowAxisTrackCount: number+) =>+ Math.max(+ 0,+ Math.ceil(childCount / Math.max(1, crossAxisTrackCount)) -+ flowAxisTrackCount+ );++const trackTypeLabels = {+ column: { singular: "Column", plural: "Columns" },+ row: { singular: "Row", plural: "Rows" },+} as const;++const serializeTrackList = (tracks: GridTrack[]): StyleValue => {+ const value = serializeGridTemplateTrackList(tracks);+ if (value === "none") {+ return { type: "keyword", value: "none" };+ }+ return { type: "unparsed", value };+};++type GridTrackProperty =+ | "grid-template-columns"+ | "grid-template-rows"+ | "grid-auto-columns"+ | "grid-auto-rows";++type TrackItemProps = {+ property: GridTrackProperty;+ trackType: "column" | "row";+ track: string;+ index: number;+ id: string;+ dragItemId: string | undefined;+ isEditing: boolean;+ isAuto?: boolean;+ canRemove: boolean;+ onEditingChange: (open: boolean) => void;+ onUpdate: (index: number, newValue: string) => void;+ onRemove: (index: number) => void;+ onHoverStart: () => void;+ onHoverEnd: () => void;+};++const TrackItem = ({+ property,+ trackType,+ track,+ index,+ id,+ dragItemId,+ isEditing,+ isAuto,+ canRemove,+ onEditingChange,+ onUpdate,+ onRemove,+ onHoverStart,+ onHoverEnd,+}: TrackItemProps) => {+ const minmaxParts = parseMinmax(track);+ const [isMinmax, setIsMinmax] = useState(minmaxParts !== undefined);+ const [minValue, setMinValue] = useState(minmaxParts?.min ?? "0");+ const [maxValue, setMaxValue] = useState(minmaxParts?.max ?? "1fr");++ // Sync state when track prop changes (e.g., external edits, undo/redo)+ useEffect(() => {+ const parsed = parseMinmax(track);+ setIsMinmax(parsed !== undefined);+ if (parsed) {+ setMinValue(parsed.min);+ setMaxValue(parsed.max);+ }+ }, [track]);++ const handleMinmaxToggle = (checked: boolean) => {+ setIsMinmax(checked);+ if (checked) {+ // Convert single value to minmax with reasonable defaults+ const newMin = "0";+ const newMax = track === "auto" ? "1fr" : track;+ setMinValue(newMin);+ setMaxValue(newMax);+ onUpdate(index, serializeMinmax({ min: newMin, max: newMax }));+ } else {+ // Convert minmax to single value (use max value)+ onUpdate(index, maxValue);+ }+ };++ const handleMinUpdate = (value: string) => {+ setMinValue(value);+ onUpdate(index, serializeMinmax({ min: value, max: maxValue }));+ };++ const handleMaxUpdate = (value: string) => {+ setMaxValue(value);+ onUpdate(index, serializeMinmax({ min: minValue, max: value }));+ };++ return (+ <FloatingPanel+ placement="bottom-within"+ title={`Edit ${trackType}`}+ content={+ <Flex direction="column" gap="2" css={{ padding: theme.panel.padding }}>+ {isMinmax ? (+ <Grid columns={2} gap="2">+ <Flex direction="column" gap="1">+ <Label>Min</Label>+ <CssValueInputContainer+ styleSource="local"+ property={property}+ value={{+ type: "unparsed",+ value: minValue,+ }}+ onUpdate={(styleValue) => {+ const stringValue =+ styleValue.type === "unparsed"+ ? styleValue.value+ : toValue(styleValue);+ handleMinUpdate(stringValue);+ }}+ onDelete={() => {}}+ />+ </Flex>+ <Flex direction="column" gap="1">+ <Label>Max</Label>+ <CssValueInputContainer+ styleSource="local"+ property={property}+ value={{+ type: "unparsed",+ value: maxValue,+ }}+ onUpdate={(styleValue) => {+ const stringValue =+ styleValue.type === "unparsed"+ ? styleValue.value+ : toValue(styleValue);+ handleMaxUpdate(stringValue);+ }}+ onDelete={() => {}}+ />+ </Flex>+ </Grid>+ ) : (+ <Flex direction="column" gap="1">+ <Label>Value</Label>+ <CssValueInputContainer+ styleSource="local"+ property={property}+ value={{+ type: "unparsed",+ value: track,+ }}+ onUpdate={(styleValue) => {+ const stringValue =+ styleValue.type === "unparsed"+ ? styleValue.value+ : toValue(styleValue);+ onUpdate(index, stringValue);+ }}+ onDelete={() => {}}+ />+ </Flex>+ )}+ <Flex align="center" gap="2">+ <Checkbox+ id={`minmax-${id}`}+ checked={isMinmax}+ onCheckedChange={handleMinmaxToggle}+ />+ <Label htmlFor={`minmax-${id}`}>Use min/max</Label>+ </Flex>+ </Flex>+ }+ open={isEditing}+ onOpenChange={onEditingChange}+ >+ <CssValueListItem+ id={id}+ draggable={!isAuto}+ active={dragItemId === id}+ index={index}+ onMouseEnter={onHoverStart}+ onMouseLeave={onHoverEnd}+ label={+ <Label truncate title={track}>+ {track}+ </Label>+ }+ buttons={+ isAuto ? undefined : (+ <SmallIconButton+ variant="destructive"+ tabIndex={-1}+ disabled={canRemove === false}+ icon={<MinusIcon />}+ onClick={(e) => {+ e.stopPropagation();+ onRemove(index);+ }}+ />+ )+ }+ />+ </FloatingPanel>+ );+};++type TrackEditorProps = {+ property: GridTrackProperty;+ trackType: keyof typeof trackTypeLabels;+ label?: string;+ defaultTrackValue?: string;+ autoTrackCount?: number;+ disabled?: boolean;+};++const TrackEditor = ({+ property,+ trackType,+ label: labelOverride,+ defaultTrackValue = "1fr",+ autoTrackCount,+ disabled = false,+}: TrackEditorProps) => {+ const { plural } = trackTypeLabels[trackType];+ const isAuto =+ property === "grid-auto-columns" || property === "grid-auto-rows";+ const label = labelOverride ?? plural;+ const displayCount = isAuto ? (autoTrackCount ?? 0) : undefined;+ const openStateKey = isAuto ? `auto-${trackType}` : trackType;+ const styleDecl = useComputedStyleDecl(property);+ const value = toValue(styleDecl.cascadedValue);+ const tracks = parseGridTemplateTrackList(value);+ const [isOpen, setIsOpen] = useOpenState(openStateKey);+ const [editingIndex, setEditingIndex] = useState<number | undefined>(+ undefined+ );+ const [hoveredIndex, setHoveredIndex] = useState<number | undefined>(+ undefined+ );++ // Update grid editing track highlight when editing or hovering a track+ // Only for template tracks since auto tracks aren't shown in the grid guides+ const highlightIndex = editingIndex ?? hoveredIndex;+ useEffect(() => {+ if (isAuto) {+ return;+ }+ if (highlightIndex !== undefined) {+ $gridEditingTrack.set({ type: trackType, index: highlightIndex });+ } else {+ // Only clear if this track type was being edited+ const current = $gridEditingTrack.get();+ if (current?.type === trackType) {+ $gridEditingTrack.set(undefined);+ }+ }+ return () => {+ const current = $gridEditingTrack.get();+ if (current?.type === trackType) {+ $gridEditingTrack.set(undefined);+ }+ };+ }, [isAuto, highlightIndex, trackType]);++ const updateTracks = useCallback(+ (newTracks: GridTrack[]) => {+ const batch = createBatchUpdate();+ batch.setProperty(property)(serializeTrackList(newTracks));+ batch.publish();+ },+ [property]+ );++ const addTrack = useCallback(() => {+ const newTracks = [...tracks, { value: defaultTrackValue }];+ updateTracks(newTracks);+ }, [tracks, updateTracks, defaultTrackValue]);++ const removeTrack = useCallback(+ (index: number) => {+ if (tracks.length > 1) {+ updateTracks(tracks.filter((_, i) => i !== index));+ if (editingIndex === index) {+ setEditingIndex(undefined);+ }+ }+ },+ [tracks, updateTracks, editingIndex]+ );++ const updateTrack = useCallback(+ (index: number, newValue: string) => {+ const newTracks = [...tracks];+ newTracks[index] = { value: newValue };+ updateTracks(newTracks);+ },+ [tracks, updateTracks]+ );++ const sortableItems = useMemo(+ () => tracks.map((_, index) => ({ id: String(index) })),+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [tracks.length]+ );++ const { dragItemId, placementIndicator, sortableRefCallback } = useSortable({+ items: sortableItems,+ onSort: (newIndex, oldIndex) => {+ if (oldIndex === newIndex) {+ return;+ }+ const newTracks = [...tracks];+ const [removed] = newTracks.splice(oldIndex, 1);+ newTracks.splice(newIndex, 0, removed);+ updateTracks(newTracks);+ },+ });++ return (+ <CollapsibleSectionRoot+ label={`${label} (${displayCount ?? tracks.length})`}+ isOpen={isOpen}+ onOpenChange={setIsOpen}+ fullWidth+ trigger={+ <Flex+ align="center"+ justify="between"+ css={{ padding: theme.spacing[5] }}+ >+ <Text variant="labels" color="subtle">+ {label} ({displayCount ?? tracks.length})+ </Text>+ {!isAuto && (+ <IconButton+ disabled={disabled}+ onClick={(e) => {+ e.stopPropagation();+ addTrack();+ }}+ >+ <PlusIcon />+ </IconButton>+ )}+ </Flex>+ }+ >+ <CssValueListArrowFocus dragItemId={dragItemId}>+ <Flex direction="column" ref={sortableRefCallback}>+ {tracks.length === 0 && (+ <Text+ color="subtle"+ align="center"+ css={{ padding: theme.panel.padding }}+ >+ No {trackType}+ </Text>+ )}+ {tracks.map((track, index) => {+ const id = String(index);+ return (+ <TrackItem+ key={id}+ property={property}+ trackType={trackType}+ track={track.value}+ index={index}+ id={id}+ dragItemId={dragItemId}+ isEditing={editingIndex === index}+ isAuto={isAuto}+ canRemove={tracks.length > 1}+ onEditingChange={(open) => {+ if (open) {+ setEditingIndex(index);+ } else {+ setEditingIndex(undefined);+ }+ }}+ onUpdate={updateTrack}+ onRemove={removeTrack}+ onHoverStart={() => setHoveredIndex(index)}+ onHoverEnd={() => setHoveredIndex(undefined)}+ />+ );+ })}+ {placementIndicator}+ </Flex>+ </CssValueListArrowFocus>+ </CollapsibleSectionRoot>+ );+};++type GridSettingsProps = {+ open: boolean;+ onOpenChange: (open: boolean) => void;+};++export const GridSettings = ({ open, onOpenChange }: GridSettingsProps) => {+ const selectedInstance = useStore($selectedInstance);+ const gridTemplateColumns = useComputedStyleDecl("grid-template-columns");+ const gridTemplateRows = useComputedStyleDecl("grid-template-rows");+ const gridAutoFlow = useComputedStyleDecl("grid-auto-flow");++ const columnsValue = toValue(gridTemplateColumns.cascadedValue);+ const rowsValue = toValue(gridTemplateRows.cascadedValue);+ const autoFlowValue = toValue(gridAutoFlow.cascadedValue);++ const childCount =+ selectedInstance?.children.filter((child) => child.type === "id").length ??+ 0;+ const templateColumnCount = parseGridTemplateTrackList(columnsValue).length;+ const templateRowCount = parseGridTemplateTrackList(rowsValue).length;+ const isColumnFlow = autoFlowValue.startsWith("column");++ const autoRowCount = isColumnFlow+ ? 0+ : computeAutoTrackCount(childCount, templateColumnCount, templateRowCount);+ const autoColumnCount = isColumnFlow+ ? computeAutoTrackCount(childCount, templateRowCount, templateColumnCount)+ : 0;++ // Check if each axis can be edited visually+ const columnsMode = getGridAxisMode(columnsValue);+ const rowsMode = getGridAxisMode(rowsValue);+ const isColumnsEditable = isEditableGridMode(columnsMode);+ const isRowsEditable = isEditableGridMode(rowsMode);++ const editGridButton = (+ <Button color="neutral" css={{ width: "100%" }}>+ Configure grid+ </Button>+ );++ return (+ <FloatingPanel+ title="Grid settings"+ placement="bottom-within"+ content={+ <Flex+ direction="column"+ css={{ width: theme.spacing[30], overflow: "auto" }}+ data-floating-panel-container+ >+ <TrackEditor+ property="grid-template-columns"+ trackType="column"+ disabled={!isColumnsEditable}+ />+ <TrackEditor+ property="grid-auto-columns"+ trackType="column"+ label="Auto columns"+ autoTrackCount={autoColumnCount}+ />+ <TrackEditor+ property="grid-template-rows"+ trackType="row"+ disabled={!isRowsEditable}+ />+ <TrackEditor+ property="grid-auto-rows"+ trackType="row"+ label="Auto rows"+ defaultTrackValue="auto"+ autoTrackCount={autoRowCount}+ />+ <GridAreas />+ </Flex>+ }+ open={open}+ onOpenChange={onOpenChange}+ closeOnInteractOutside={false}+ >+ {editGridButton}+ </FloatingPanel>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-utils.test.ts b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-utils.test.tsnew file mode 100644index 0000000000..f9ab7a2d11--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-utils.test.ts@@ -0,0 +1,239 @@+import { describe, test, expect } from "vitest";+import type {+ StyleDecl,+ StyleDeclKey,+ StyleSource,+ StyleSourceSelection,+} from "@webstudio-is/sdk";+import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";+import { isAutoGridPlacement, resetGridChildPlacement } from "./grid-utils";++const createStyleDecl = (+ styleSourceId: string,+ breakpointId: string,+ property: StyleProperty,+ value: StyleValue+): StyleDecl => ({+ styleSourceId,+ breakpointId,+ property,+ value,+});++const createStyleDeclEntry = (+ styleDecl: StyleDecl+): [StyleDeclKey, StyleDecl] => [+ `${styleDecl.styleSourceId}:${styleDecl.breakpointId}:${styleDecl.property}:`,+ styleDecl,+];++const createData = ({+ styleSourcesList = [],+ selectionsList = [],+ styleDeclsList = [],+}: {+ styleSourcesList?: StyleSource[];+ selectionsList?: StyleSourceSelection[];+ styleDeclsList?: StyleDecl[];+}) => ({+ styleSources: new Map(styleSourcesList.map((s) => [s.id, s])),+ styleSourceSelections: new Map(selectionsList.map((s) => [s.instanceId, s])),+ styles: new Map(styleDeclsList.map((d) => createStyleDeclEntry(d))),+});++const auto: StyleValue = { type: "keyword", value: "auto" };+const numeric = (n: number): StyleValue => ({+ type: "unit",+ value: n,+ unit: "number",+});+const keyword = (v: string): StyleValue => ({ type: "keyword", value: v });++describe("isAutoGridPlacement", () => {+ test("returns true when instance has no style source selection", () => {+ const data = createData({});+ expect(isAutoGridPlacement({ ...data, instanceId: "child" })).toBe(true);+ });++ test("returns true when instance has no local style sources", () => {+ const data = createData({+ styleSourcesList: [{ id: "token1", type: "token", name: "Token" }],+ selectionsList: [{ instanceId: "child", values: ["token1"] }],+ });+ expect(isAutoGridPlacement({ ...data, instanceId: "child" })).toBe(true);+ });++ test("returns true when no grid placement styles exist", () => {+ const data = createData({+ styleSourcesList: [{ id: "local1", type: "local" }],+ selectionsList: [{ instanceId: "child", values: ["local1"] }],+ styleDeclsList: [+ createStyleDecl("local1", "bp1", "alignSelf", keyword("center")),+ ],+ });+ expect(isAutoGridPlacement({ ...data, instanceId: "child" })).toBe(true);+ });++ test("returns true when all grid placement values are auto", () => {+ const data = createData({+ styleSourcesList: [{ id: "local1", type: "local" }],+ selectionsList: [{ instanceId: "child", values: ["local1"] }],+ styleDeclsList: [+ createStyleDecl("local1", "bp1", "gridColumnStart", auto),+ createStyleDecl("local1", "bp1", "gridColumnEnd", auto),+ createStyleDecl("local1", "bp1", "gridRowStart", auto),+ createStyleDecl("local1", "bp1", "gridRowEnd", auto),+ ],+ });+ expect(isAutoGridPlacement({ ...data, instanceId: "child" })).toBe(true);+ });++ test("returns false when grid placement has numeric values", () => {+ const data = createData({+ styleSourcesList: [{ id: "local1", type: "local" }],+ selectionsList: [{ instanceId: "child", values: ["local1"] }],+ styleDeclsList: [+ createStyleDecl("local1", "bp1", "gridColumnStart", numeric(2)),+ createStyleDecl("local1", "bp1", "gridColumnEnd", numeric(3)),+ createStyleDecl("local1", "bp1", "gridRowStart", numeric(1)),+ createStyleDecl("local1", "bp1", "gridRowEnd", numeric(2)),+ ],+ });+ expect(isAutoGridPlacement({ ...data, instanceId: "child" })).toBe(false);+ });++ test("returns false when any single property is numeric", () => {+ const data = createData({+ styleSourcesList: [{ id: "local1", type: "local" }],+ selectionsList: [{ instanceId: "child", values: ["local1"] }],+ styleDeclsList: [+ createStyleDecl("local1", "bp1", "gridColumnStart", numeric(2)),+ ],+ });+ expect(isAutoGridPlacement({ ...data, instanceId: "child" })).toBe(false);+ });++ test("returns false when grid placement uses named areas", () => {+ const data = createData({+ styleSourcesList: [{ id: "local1", type: "local" }],+ selectionsList: [{ instanceId: "child", values: ["local1"] }],+ styleDeclsList: [+ createStyleDecl("local1", "bp1", "gridColumnStart", keyword("main")),+ createStyleDecl("local1", "bp1", "gridColumnEnd", keyword("main")),+ createStyleDecl("local1", "bp1", "gridRowStart", keyword("main")),+ createStyleDecl("local1", "bp1", "gridRowEnd", keyword("main")),+ ],+ });+ expect(isAutoGridPlacement({ ...data, instanceId: "child" })).toBe(false);+ });++ test("ignores grid placement styles from token style sources", () => {+ const data = createData({+ styleSourcesList: [+ { id: "token1", type: "token", name: "Token" },+ { id: "local1", type: "local" },+ ],+ selectionsList: [{ instanceId: "child", values: ["token1", "local1"] }],+ styleDeclsList: [+ // Token has grid placement — should be ignored+ createStyleDecl("token1", "bp1", "gridColumnStart", numeric(2)),+ // Local has no grid placement+ createStyleDecl("local1", "bp1", "alignSelf", keyword("center")),+ ],+ });+ expect(isAutoGridPlacement({ ...data, instanceId: "child" })).toBe(true);+ });+});++describe("resetGridChildPlacement", () => {+ test("removes grid placement styles from local style source", () => {+ const data = createData({+ styleSourcesList: [{ id: "local1", type: "local" }],+ selectionsList: [{ instanceId: "child", values: ["local1"] }],+ styleDeclsList: [+ createStyleDecl("local1", "bp1", "gridColumnStart", numeric(2)),+ createStyleDecl("local1", "bp1", "gridColumnEnd", numeric(3)),+ createStyleDecl("local1", "bp1", "gridRowStart", numeric(1)),+ createStyleDecl("local1", "bp1", "gridRowEnd", numeric(2)),+ createStyleDecl("local1", "bp1", "alignSelf", keyword("center")),+ ],+ });++ resetGridChildPlacement({ ...data, instanceId: "child" });++ // Grid placement styles should be removed+ expect(data.styles.size).toBe(1);+ const remaining = [...data.styles.values()][0];+ expect(remaining.property).toBe("alignSelf");+ });++ test("keeps non-grid styles intact", () => {+ const data = createData({+ styleSourcesList: [{ id: "local1", type: "local" }],+ selectionsList: [{ instanceId: "child", values: ["local1"] }],+ styleDeclsList: [+ createStyleDecl("local1", "bp1", "alignSelf", keyword("center")),+ createStyleDecl("local1", "bp1", "justifySelf", keyword("start")),+ createStyleDecl("local1", "bp1", "order", numeric(1)),+ ],+ });++ resetGridChildPlacement({ ...data, instanceId: "child" });++ expect(data.styles.size).toBe(3);+ });++ test("does nothing when instance has no style source selection", () => {+ const data = createData({});+ resetGridChildPlacement({ ...data, instanceId: "child" });+ expect(data.styles.size).toBe(0);+ });++ test("does nothing when instance has no local style sources", () => {+ const data = createData({+ styleSourcesList: [{ id: "token1", type: "token", name: "Token" }],+ selectionsList: [{ instanceId: "child", values: ["token1"] }],+ styleDeclsList: [+ createStyleDecl("token1", "bp1", "gridColumnStart", numeric(2)),+ ],+ });++ resetGridChildPlacement({ ...data, instanceId: "child" });++ // Token styles should not be touched+ expect(data.styles.size).toBe(1);+ });++ test("removes auto-valued grid placement styles", () => {+ const data = createData({+ styleSourcesList: [{ id: "local1", type: "local" }],+ selectionsList: [{ instanceId: "child", values: ["local1"] }],+ styleDeclsList: [+ createStyleDecl("local1", "bp1", "gridColumnStart", auto),+ createStyleDecl("local1", "bp1", "gridColumnEnd", auto),+ ],+ });++ resetGridChildPlacement({ ...data, instanceId: "child" });++ expect(data.styles.size).toBe(0);+ });++ test("removes grid placement across multiple breakpoints", () => {+ const data = createData({+ styleSourcesList: [{ id: "local1", type: "local" }],+ selectionsList: [{ instanceId: "child", values: ["local1"] }],+ styleDeclsList: [+ createStyleDecl("local1", "bp1", "gridColumnStart", numeric(1)),+ createStyleDecl("local1", "bp2", "gridColumnStart", numeric(3)),+ createStyleDecl("local1", "bp1", "alignSelf", keyword("center")),+ ],+ });++ resetGridChildPlacement({ ...data, instanceId: "child" });++ expect(data.styles.size).toBe(1);+ const remaining = [...data.styles.values()][0];+ expect(remaining.property).toBe("alignSelf");+ });+});diff --git a/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-utils.ts b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-utils.tsnew file mode 100644index 0000000000..dd4be81479--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/layout/shared/grid-utils.ts@@ -0,0 +1,96 @@+import type {+ Instance,+ StyleSource,+ StyleSourceSelections,+ StyleSources,+ Styles,+} from "@webstudio-is/sdk";+import type { StyleProperty } from "@webstudio-is/css-engine";++const gridPlacementProperties: ReadonlySet<StyleProperty> = new Set([+ "gridColumnStart",+ "gridColumnEnd",+ "gridRowStart",+ "gridRowEnd",+]);++/**+ * Check if an instance is auto-placed in a grid by examining its local styles.+ * Returns true when no grid placement property has a non-auto value.+ */+export const isAutoGridPlacement = ({+ styles,+ styleSources,+ styleSourceSelections,+ instanceId,+}: {+ styles: Styles;+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ instanceId: Instance["id"];+}): boolean => {+ const selection = styleSourceSelections.get(instanceId);+ if (selection === undefined) {+ return true;+ }+ const localIds = new Set<StyleSource["id"]>();+ for (const id of selection.values) {+ if (styleSources.get(id)?.type === "local") {+ localIds.add(id);+ }+ }+ if (localIds.size === 0) {+ return true;+ }+ for (const styleDecl of styles.values()) {+ if (localIds.has(styleDecl.styleSourceId) === false) {+ continue;+ }+ if (gridPlacementProperties.has(styleDecl.property) === false) {+ continue;+ }+ if (+ styleDecl.value.type === "keyword" &&+ styleDecl.value.value === "auto"+ ) {+ continue;+ }+ return false;+ }+ return true;+};++/**+ * Remove grid placement styles from an instance's local style sources.+ * Used after duplication to prevent overlapping grid children.+ */+export const resetGridChildPlacement = ({+ styles,+ styleSources,+ styleSourceSelections,+ instanceId,+}: {+ styles: Styles;+ styleSources: StyleSources;+ styleSourceSelections: StyleSourceSelections;+ instanceId: Instance["id"];+}) => {+ const selection = styleSourceSelections.get(instanceId);+ if (selection === undefined) {+ return;+ }+ const localIds = new Set<StyleSource["id"]>();+ for (const id of selection.values) {+ if (styleSources.get(id)?.type === "local") {+ localIds.add(id);+ }+ }+ for (const [key, styleDecl] of styles) {+ if (localIds.has(styleDecl.styleSourceId) === false) {+ continue;+ }+ if (gridPlacementProperties.has(styleDecl.property)) {+ styles.delete(key);+ }+ }+};diff --git a/apps/builder/app/builder/features/style-panel/sections/sections.ts b/apps/builder/app/builder/features/style-panel/sections/sections.tsindex 2a2071a622..692ba3adde 100644--- a/apps/builder/app/builder/features/style-panel/sections/sections.ts+++ b/apps/builder/app/builder/features/style-panel/sections/sections.ts@@ -1,6 +1,7 @@import type { ReactNode } from "react";import * as layout from "./layout/layout";import * as flexChild from "./flex-child/flex-child";+import * as gridChild from "./grid-child/grid-child";import * as listItem from "./list-item";import * as space from "./space/space";import * as size from "./size/size";@@ -27,6 +28,7 @@ export const sections = new Map<>([["layout", layout],["flexChild", flexChild],+ ["gridChild", gridChild],["listItem", listItem],["space", space],["size", size],diff --git a/apps/builder/app/builder/features/style-panel/sections/shared/align-self.tsx b/apps/builder/app/builder/features/style-panel/sections/shared/align-self.tsxnew file mode 100644index 0000000000..f3cec33933--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/shared/align-self.tsx@@ -0,0 +1,135 @@+import { Grid } from "@webstudio-is/design-system";+import {+ XSmallIcon,+ AlignSelfStartIcon,+ AlignSelfEndIcon,+ AlignSelfCenterIcon,+ AlignSelfBaselineIcon,+ AlignSelfStretchIcon,+} from "@webstudio-is/icons";+import { PropertyLabel } from "../../property-label";+import { ToggleGroupControl } from "../../controls/toggle-group/toggle-group-control";+import { propertyDescriptions } from "@webstudio-is/css-data";++type AlignSelfControlProps = {+ /**+ * "flex" uses flex-start/flex-end values+ * "grid" uses start/end values+ */+ variant: "flex" | "grid";+};++export const AlignSelfControl = ({ variant }: AlignSelfControlProps) => {+ const startValue = variant === "flex" ? "flex-start" : "start";+ const endValue = variant === "flex" ? "flex-end" : "end";+ const axisName = variant === "flex" ? "cross axis" : "block axis";+ const parentProperty =+ variant === "flex" ? "align-items" : "align-items or align-content";++ return (+ <Grid css={{ gridTemplateColumns: "3fr 8fr" }}>+ <PropertyLabel+ label="Align"+ description={propertyDescriptions.alignSelf}+ properties={["align-self"]}+ />+ <ToggleGroupControl+ label="Align"+ properties={["align-self"]}+ items={[+ {+ child: <XSmallIcon />,+ description: `The element's alignment is determined by its parent's ${parentProperty} property.`,+ value: "auto",+ },+ {+ child: <AlignSelfStartIcon />,+ description: `The element is aligned at the start of the ${axisName}.`,+ value: startValue,+ },+ {+ child: <AlignSelfCenterIcon />,+ description: `The element is centered along the ${axisName}.`,+ value: "center",+ },+ {+ child: <AlignSelfEndIcon />,+ description: `The element is aligned at the end of the ${axisName}.`,+ value: endValue,+ },+ {+ child: <AlignSelfStretchIcon />,+ description: `The element is stretched to fill the entire ${axisName}.`,+ value: "stretch",+ },+ {+ child: <AlignSelfBaselineIcon />,+ description: `The element is aligned to the baseline along the ${axisName}.`,+ value: "baseline",+ },+ ]}+ />+ </Grid>+ );+};++export const JustifySelfControl = () => {+ return (+ <Grid css={{ gridTemplateColumns: "3fr 8fr" }}>+ <PropertyLabel+ label="Justify"+ description={propertyDescriptions.justifySelf}+ properties={["justify-self"]}+ />+ <ToggleGroupControl+ label="Justify"+ properties={["justify-self"]}+ items={[+ {+ child: <XSmallIcon />,+ description:+ "The element's justification is determined by its parent's justify-items property.",+ value: "auto",+ },+ {+ child: (+ <AlignSelfStartIcon style={{ transform: "rotate(-90deg)" }} />+ ),+ description:+ "The element is aligned at the start of the inline axis.",+ value: "start",+ },+ {+ child: (+ <AlignSelfCenterIcon style={{ transform: "rotate(-90deg)" }} />+ ),+ description: "The element is centered along the inline axis.",+ value: "center",+ },+ {+ child: <AlignSelfEndIcon style={{ transform: "rotate(-90deg)" }} />,+ description:+ "The element is aligned at the end of the inline axis.",+ value: "end",+ },+ {+ child: (+ <AlignSelfStretchIcon style={{ transform: "rotate(-90deg)" }} />+ ),+ description:+ "The element is stretched to fill the entire inline axis.",+ value: "stretch",+ },+ {+ child: (+ <AlignSelfBaselineIcon style={{ transform: "rotate(-90deg)" }} />+ ),+ description:+ "The element is aligned to the baseline of the parent.",+ value: "baseline",+ },+ ]}+ />+ </Grid>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/shared/order.tsx b/apps/builder/app/builder/features/style-panel/sections/shared/order.tsxnew file mode 100644index 0000000000..e8556a777d--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/shared/order.tsx@@ -0,0 +1,152 @@+import { useState } from "react";+import {+ Flex,+ FloatingPanel,+ Grid,+ theme,+ ToggleGroup,+ ToggleGroupButton,+} from "@webstudio-is/design-system";+import { toValue } from "@webstudio-is/css-engine";+import {+ XSmallIcon,+ OrderFirstIcon,+ OrderLastIcon,+ EllipsesIcon,+} from "@webstudio-is/icons";+import { TextControl } from "../../controls";+import { ToggleGroupTooltip } from "../../controls/toggle-group/toggle-group-control";+import { PropertyLabel } from "../../property-label";+import { propertyDescriptions } from "@webstudio-is/css-data";+import { useComputedStyleDecl } from "../../shared/model";+import { setProperty } from "../../shared/use-style-data";++const OrderPopover = () => {+ return (+ <FloatingPanel+ title="Order"+ placement="bottom-within"+ content={+ <Grid+ css={{+ gridTemplateColumns: "4fr 6fr",+ padding: theme.panel.padding,+ }}+ gap={2}+ >+ <PropertyLabel+ label="Order"+ description={propertyDescriptions.order}+ properties={["order"]}+ />+ <TextControl property="order" />+ </Grid>+ }+ >+ <Flex>+ <EllipsesIcon />+ </Flex>+ </FloatingPanel>+ );+};++export const OrderControl = () => {+ const order = useComputedStyleDecl("order");+ const selectedValue = toValue(order.cascadedValue);+ const items = [+ {+ child: <XSmallIcon />,+ description: "Don't change",+ value: "0",+ code: "order: 0;",+ },+ {+ child: <OrderFirstIcon />,+ description: "Make first",+ value: "-1",+ code: "order: -1;",+ },+ {+ child: <OrderLastIcon />,+ description: "Make last",+ value: "1",+ code: "order: 1;",+ },+ {+ child: <OrderPopover />,+ description: "Customize order",+ value: "",+ code: `order: ${selectedValue};`,+ },+ ];+ // Issue: The tooltip's grace area is too big and overlaps with nearby buttons,+ // preventing the tooltip from changing when the buttons are hovered over in certain cases.+ // To solve issue and allow tooltips to change on button hover,+ // we close the button tooltip in the ToggleGroupButton.onMouseEnter handler.+ // onMouseEnter used to preserve default hovering behavior on tooltip.+ const [activeTooltip, setActiveTooltip] = useState<undefined | string>();+ return (+ <Grid css={{ gridTemplateColumns: "3fr 8fr" }}>+ <PropertyLabel+ label="Order"+ description={propertyDescriptions.order}+ properties={["order"]}+ />+ <ToggleGroup+ color={order.source.name}+ type="single"+ value={selectedValue}+ onValueChange={(value) => {+ switch (value) {+ case "0":+ case "1":+ case "-1": {+ setProperty("order")({+ type: "unit",+ value: Number(value),+ unit: "number",+ });+ break;+ }+ }+ }}+ >+ {items.map((item) => (+ <ToggleGroupTooltip+ key={item.value}+ isOpen={item.value === activeTooltip}+ onOpenChange={(isOpen) =>+ setActiveTooltip(isOpen ? item.value : undefined)+ }+ isSelected={item.value === selectedValue}+ label="Order"+ code={item.code}+ description={item.description}+ properties={["order"]}+ >+ <ToggleGroupButton+ aria-checked={+ item.value === selectedValue ||+ // order takes integer value, so the value can be anything from +- 0-9+ // And we already have toggle buttons for -1, 0, 1+ // https://developer.mozilla.org/en-US/docs/Web/CSS/order#formal_syntax+ (item.value === "" &&+ (Number.parseFloat(selectedValue) > 1 ||+ Number.parseFloat(selectedValue) < -1))+ }+ value={item.value}+ onMouseEnter={() =>+ // reset only when highlighted is not active+ setActiveTooltip((prevValue) =>+ prevValue === item.value ? prevValue : undefined+ )+ }+ >+ {item.child}+ </ToggleGroupButton>+ </ToggleGroupTooltip>+ ))}+ </ToggleGroup>+ </Grid>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/transforms/transform-extractors.ts b/apps/builder/app/builder/features/style-panel/sections/transforms/transform-extractors.tsindex 8633e840b6..0b4b15c99b 100644--- a/apps/builder/app/builder/features/style-panel/sections/transforms/transform-extractors.ts+++ b/apps/builder/app/builder/features/style-panel/sections/transforms/transform-extractors.ts@@ -1,6 +1,7 @@import type {FunctionValue,KeywordValue,+ LayersValue,StyleValue,TupleValue,UnitValue,@@ -33,8 +34,9 @@ export const extractRotatePropertiesFromTransform = (transform: StyleValue) => {};export const extractSkewPropertiesFromTransform = (skew: StyleValue) => {- let skewX: FunctionValue | undefined = undefined;- let skewY: FunctionValue | undefined = undefined;+ type SkewFunction = FunctionValue & { args: LayersValue };+ let skewX: SkewFunction | undefined = undefined;+ let skewY: SkewFunction | undefined = undefined;if (skew.type !== "tuple") {return { skewX, skewY };@@ -42,11 +44,11 @@ export const extractSkewPropertiesFromTransform = (skew: StyleValue) => {for (const item of skew.value) {if (item.type === "function" && item.name === "skewX") {- skewX = item;+ skewX = item as SkewFunction;}if (item.type === "function" && item.name === "skewY") {- skewY = item;+ skewY = item as SkewFunction;}}diff --git a/apps/builder/app/builder/features/style-panel/sections/transforms/transform-skew.tsx b/apps/builder/app/builder/features/style-panel/sections/transforms/transform-skew.tsxindex b00fe5a67e..6209643b74 100644--- a/apps/builder/app/builder/features/style-panel/sections/transforms/transform-skew.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/transforms/transform-skew.tsx@@ -6,34 +6,23 @@ import { CssValueInputContainer } from "../../shared/css-value-input";import { PropertyInlineLabel } from "../../property-label";import { useComputedStyleDecl } from "../../shared/model";import { updateTransformFunction } from "./transform-utils";+import { extractSkewPropertiesFromTransform } from "./transform-extractors";// We use fakeProperty to pass for the CssValueInputContainer.// https://developer.mozilla.org/en-US/docs/Web/CSS/rotate#formal_syntax// angleconst fakeProperty = "rotate";+const defaultAngle: StyleValue = { type: "unit", value: 0, unit: "deg" };+export const SkewPanelContent = () => {const styleDecl = useComputedStyleDecl("transform");- const tuple =- styleDecl.cascadedValue.type === "tuple"- ? styleDecl.cascadedValue- : undefined;- let skewX: StyleValue = { type: "unit", value: 0, unit: "deg" };- let skewY: StyleValue = { type: "unit", value: 0, unit: "deg" };- for (const item of tuple?.value ?? []) {- if (- item.type === "function" &&- item.args.type === "layers" &&- item.args.value[0].type === "unit"- ) {- if (item.name === "skewx") {- skewX = item.args.value[0];- }- if (item.name === "skewY") {- skewY = item.args.value[0];- }- }- }+ const { skewX: skewXFn, skewY: skewYFn } = extractSkewPropertiesFromTransform(+ styleDecl.cascadedValue+ );++ const skewX: StyleValue = skewXFn?.args.value[0] ?? defaultAngle;+ const skewY: StyleValue = skewYFn?.args.value[0] ?? defaultAngle;return (<Flex direction="column" gap={2}>diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts b/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.tsindex 0bd3924ea1..12c6311c90 100644--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/parse-intermediate-or-invalid-value.ts@@ -49,6 +49,14 @@ export const parseIntermediateOrInvalidValue = (value = value.slice(0, -1);}+ // Round values for properties that require integers when unit is "number"+ if ("unit" in styleValue && styleValue.unit === "number") {+ const numericValue = Number(value);+ if (!Number.isNaN(numericValue) && !Number.isInteger(numericValue)) {+ value = String(Math.round(numericValue));+ }+ }+// When user enters a number, we don't know if its a valid unit value,// so we are going to parse it with a unit and if its not invalid - we take it.const ast = cssTryParseValue(value);@@ -94,7 +102,7 @@ export const parseIntermediateOrInvalidValue = (if ("unit" in styleValue && styleValue.unit === "number") {// when unit is number some properties supports only integer// for example z-index- styleInput = parseCssValue(property, `${Math.round(Number(value))}`);+ styleInput = parseCssValue(property, value);if (styleInput.type !== "invalid") {return styleInput;}diff --git a/apps/builder/app/builder/features/style-panel/shared/style-section.tsx b/apps/builder/app/builder/features/style-panel/shared/style-section.tsxindex a97ebd1ba3..c9c5809cc4 100644--- a/apps/builder/app/builder/features/style-panel/shared/style-section.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/style-section.tsx@@ -37,9 +37,10 @@ export const StyleSection = (props: {properties: CssProperty[];// @todo remove to keep sections consistentfullWidth?: boolean;+ suffix?: ReactNode;children: ReactNode;}) => {- const { label, children, properties, fullWidth } = props;+ const { label, children, properties, fullWidth, suffix } = props;const [isOpen, setIsOpen] = useOpenState(label);const styles = useComputedStyles(properties);return (@@ -48,7 +49,7 @@ export const StyleSection = (props: {isOpen={isOpen}onOpenChange={setIsOpen}trigger={- <SectionTitle dots={getDots(styles)}>+ <SectionTitle dots={getDots(styles)} suffix={suffix}><SectionTitleLabel>{label}</SectionTitleLabel></SectionTitle>}diff --git a/apps/builder/app/builder/features/style-panel/style-panel.tsx b/apps/builder/app/builder/features/style-panel/style-panel.tsxindex 71fbf49c20..7ec7b05e41 100644--- a/apps/builder/app/builder/features/style-panel/style-panel.tsx+++ b/apps/builder/app/builder/features/style-panel/style-panel.tsx@@ -152,6 +152,10 @@ export const StylePanel = () => {if (category === "flexChild" && parentDisplay.includes("flex") === false) {continue;}+ // show grid child UI only when parent is grid or inline-grid+ if (category === "gridChild" && parentDisplay.includes("grid") === false) {+ continue;+ }// allow customizing list item type only for list and list itemif (category === "listItem" &&@@ -178,7 +182,7 @@ export const StylePanel = () => {<><Box css={{ padding: theme.panel.padding }}><Text variant="titles" css={{ paddingBlock: theme.panel.paddingBlock }}>- Style Sources+ Style sources</Text><StyleSourcesSection /></Box>diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsxindex 0e547a8459..6dfb2f40ab 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-tools.tsx@@ -12,12 +12,17 @@ import {HoveredInstanceOutline,SelectedInstanceOutline,} from "./outline";+import { GridGuides } from "./grid-guides";import { Label } from "./outline/label";import { Outline } from "./outline/outline";import { useSubscribeDragAndDropState } from "./use-subscribe-drag-drop-state";import { applyScale } from "./outline";-import { $clampingRect, $scale } from "~/builder/shared/nano-states";+import {+ $clampingRect,+ $scale,+ $openGridEditorPanel,+} from "~/builder/shared/nano-states";import { BlockChildHoveredInstanceOutline } from "./outline/block-instance-outline";import { TextEditorContextMenu } from "./block-editor-context-menu";import { CanvasInstanceContextMenu } from "./canvas-instance-context-menu";@@ -44,6 +49,7 @@ export const CanvasTools = () => {const instances = useStore($instances);const scale = useStore($scale);const clampingRect = useStore($clampingRect);+ const openGridEditorPanel = useStore($openGridEditorPanel);if (!canvasToolsVisible) {return;@@ -80,6 +86,9 @@ export const CanvasTools = () => {<>{isPreviewMode === false && (<>+ {(openGridEditorPanel.generator || openGridEditorPanel.settings) && (+ <GridGuides />+ )}<SelectedInstanceOutline /><HoveredInstanceOutline /><CollaborativeInstanceOutline />diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/grid-guides.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/grid-guides.tsxnew file mode 100644index 0000000000..2b834f8997--- /dev/null+++ b/apps/builder/app/builder/features/workspace/canvas-tools/grid-guides.tsx@@ -0,0 +1,280 @@+import { useMemo, useLayoutEffect, useRef } from "react";+import { useStore } from "@nanostores/react";+import { css } from "@webstudio-is/design-system";+import { theme, textVariants } from "@webstudio-is/design-system";+import { $gridCellData } from "~/shared/nano-states";+import {+ $scale,+ $gridEditingTrack,+ $gridEditingArea,+} from "~/builder/shared/nano-states";+import { $ephemeralStyles } from "~/canvas/stores";+import { parseGridAreas } from "@webstudio-is/css-data";++// Compute the AABB offset that CSS transforms cause, by letting the browser+// do all parsing and matrix composition via a hidden probe element.+// No manual parsing of translate/rotate/scale values — works with any CSS,+// including variables already resolved to computed values on the canvas.+const getTransformOffset = (cssText: string): { dx: number; dy: number } => {+ const probe = document.createElement("div");+ // Apply the same CSS as the canvas element (width, height, transform,+ // transform-origin, translate, rotate, scale, etc.)+ probe.style.cssText = cssText;+ // Override layout: fixed at viewport origin, invisible+ probe.style.position = "fixed";+ probe.style.left = "0px";+ probe.style.top = "0px";+ probe.style.visibility = "hidden";+ probe.style.pointerEvents = "none";+ document.body.appendChild(probe);+ const bcr = probe.getBoundingClientRect();+ document.body.removeChild(probe);+ // Without transforms the probe sits at (0, 0).+ // The delta is the displacement caused by CSS transforms.+ return { dx: bcr.left, dy: bcr.top };+};++const containerStyle = css({+ position: "absolute",+ inset: 0,+ pointerEvents: "none",+ overflow: "hidden",+ // contain: strict must live here, not on the grid mirror div.+ // The mirror applies the user's CSS transform, so placing contain+ // on it would clip cells relative to the transformed box instead+ // of the viewport-aligned overlay boundary.+ contain: "strict",+});++// Use the browser's CSS parser to extract a single property from cssText.+// Never write ad-hoc regex/string parsers for CSS values.+const probe = document.createElement("div");+const getPropertyFromCssText = (cssText: string, property: string): string => {+ probe.style.cssText = cssText;+ return probe.style.getPropertyValue(property);+};++// Build a map of "col,row" → area name from cssText.+// Only the top-left cell of each named area gets an entry so the+// label appears once, not in every spanned cell.+const getAreaNamesByCell = (cssText: string): Map<string, string> => {+ const areas = getPropertyFromCssText(cssText, "grid-template-areas");+ const result = new Map<string, string>();+ for (const { name, columnStart, rowStart } of parseGridAreas(areas)) {+ result.set(`${columnStart},${rowStart}`, name);+ }+ return result;+};++// Build a set of all "col,row" keys that belong to any named area.+// Used to suppress per-cell outlines inside areas.+const getAreaCells = (cssText: string): Set<string> => {+ const areas = getPropertyFromCssText(cssText, "grid-template-areas");+ const result = new Set<string>();+ for (const { columnStart, columnEnd, rowStart, rowEnd } of parseGridAreas(+ areas+ )) {+ for (let row = rowStart; row < rowEnd; row++) {+ for (let col = columnStart; col < columnEnd; col++) {+ result.add(`${col},${row}`);+ }+ }+ }+ return result;+};++// Return the full parsed area spans for rendering merged area outlines.+const getAreaSpans = (cssText: string) => {+ const areas = getPropertyFromCssText(cssText, "grid-template-areas");+ return parseGridAreas(areas);+};++const cellStyle = css({+ pointerEvents: "none",+ outline: `1px dashed ${theme.colors.borderMain}`,+ outlineOffset: "-0.5px",+ // Area cells suppress their per-cell outline; a merged area outline+ // div renders a single border around the whole area instead.+ "&[data-area]": {+ outline: "none",+ },+});++const areaOutlineStyle = css({+ pointerEvents: "none",+ outline: `1px solid ${theme.colors.borderMain}`,+ outlineOffset: "-0.5px",+});++const areaLabelStyle = css(textVariants.regular, {+ position: "absolute",+ top: 2,+ left: 4,+ color: theme.colors.foregroundSubtle,+ pointerEvents: "none",+ whiteSpace: "nowrap",+ overflow: "hidden",+ textOverflow: "ellipsis",+ maxWidth: "calc(100% - 8px)",+});++const highlightStyle = css({+ pointerEvents: "none",+ backgroundColor: "oklch(94.8% 0.027 246.4 / 0.6)",+});++export const GridGuides = () => {+ const gridCellData = useStore($gridCellData);+ const gridEditingTrack = useStore($gridEditingTrack);+ const gridEditingArea = useStore($gridEditingArea);+ const scale = useStore($scale);+ const ephemeralStyles = useStore($ephemeralStyles);+ const mirrorRef = useRef<HTMLDivElement>(null);++ const resolvedCssText = gridCellData?.resolvedCssText;++ // Compute the transform-induced offset so we can position the wrapper at+ // the untransformed layout origin. The mirror div then re-applies the CSS+ // transforms, landing the overlay at the correct visual position.+ // Uses a hidden probe element — the browser handles all CSS parsing.+ const transformOffset = useMemo(+ () =>+ resolvedCssText ? getTransformOffset(resolvedCssText) : { dx: 0, dy: 0 },+ [resolvedCssText]+ );++ // Parse area names from the cssText — only the top-left cell gets a label+ const areaNames = useMemo(+ () => getAreaNamesByCell(resolvedCssText ?? ""),+ [resolvedCssText]+ );++ // Set of all cells covered by any named area — for outline styling+ const areaCells = useMemo(+ () => getAreaCells(resolvedCssText ?? ""),+ [resolvedCssText]+ );++ // Full area spans for rendering merged outlines+ const areaSpans = useMemo(+ () => getAreaSpans(resolvedCssText ?? ""),+ [resolvedCssText]+ );++ // Apply canvas CSS to the mirror div via cssText — bypasses React's+ // style system so we can sync any property without type gymnastics.+ // useLayoutEffect (not useEffect) to apply styles synchronously before+ // paint, avoiding a one-frame flash of unstyled content.+ useLayoutEffect(() => {+ if (mirrorRef.current && resolvedCssText !== undefined) {+ mirrorRef.current.style.cssText = resolvedCssText;+ }+ }, [resolvedCssText]);++ if (!gridCellData || ephemeralStyles.length !== 0) {+ return null;+ }++ const {+ bcr,+ untransformedWidth,+ untransformedHeight,+ columnCount,+ rowCount,+ } = gridCellData;++ const scaleFactor = scale / 100;++ // Recover untransformed position: BCR includes transforms, subtract them.+ const untransformedLeft = bcr.left - transformOffset.dx;+ const untransformedTop = bcr.top - transformOffset.dy;++ // Generate one cell per grid slot+ const cells: Array<{ col: number; row: number }> = [];+ for (let row = 1; row <= rowCount; row++) {+ for (let col = 1; col <= columnCount; col++) {+ cells.push({ col, row });+ }+ }++ return (+ <div className={containerStyle()}>+ {/* Positioning wrapper: our scale + translate to place the overlay */}+ <div+ style={{+ position: "absolute",+ left: 0,+ top: 0,+ transform: `scale(${scaleFactor}) translate3d(${untransformedLeft}px, ${untransformedTop}px, 0)`,+ transformOrigin: "0 0",+ width: untransformedWidth,+ height: untransformedHeight,+ pointerEvents: "none",+ }}+ >+ {/* Grid mirror: faithfully reproduces the canvas element's CSS.+ Styles applied via cssText in useEffect — adding a new synced+ property only requires a one-line change in grid-guide-utils. */}+ <div ref={mirrorRef}>+ {cells.map(({ col, row }) => {+ const areaName = areaNames.get(`${col},${row}`);+ const isArea = areaCells.has(`${col},${row}`);+ return (+ <div+ key={`${col}-${row}`}+ className={cellStyle()}+ data-area={isArea ? "" : undefined}+ style={{+ gridColumn: col,+ gridRow: row,+ position: "relative",+ }}+ >+ {areaName && (+ <span className={areaLabelStyle()}>{areaName}</span>+ )}+ </div>+ );+ })}+ {/* Merged area outlines: one div per named area spanning its+ full grid region, rendered after cells so it paints on top. */}+ {areaSpans.map((area) => (+ <div+ key={`area-outline-${area.name}`}+ className={areaOutlineStyle()}+ style={{+ gridColumn: `${area.columnStart} / ${area.columnEnd}`,+ gridRow: `${area.rowStart} / ${area.rowEnd}`,+ }}+ />+ ))}+ {gridEditingTrack && (+ <div+ className={highlightStyle()}+ style={+ gridEditingTrack.type === "column"+ ? {+ gridColumn: gridEditingTrack.index + 1,+ gridRow: "1 / -1",+ }+ : {+ gridColumn: "1 / -1",+ gridRow: gridEditingTrack.index + 1,+ }+ }+ />+ )}+ {gridEditingArea && (+ <div+ className={highlightStyle()}+ style={{+ gridColumn: `${gridEditingArea.columnStart} / ${gridEditingArea.columnEnd}`,+ gridRow: `${gridEditingArea.rowStart} / ${gridEditingArea.rowEnd}`,+ }}+ />+ )}+ </div>+ </div>+ </div>+ );+};diff --git a/apps/builder/app/builder/shared/collapsible-section.tsx b/apps/builder/app/builder/shared/collapsible-section.tsxindex 2401f7d0c0..6d1376bf38 100644--- a/apps/builder/app/builder/shared/collapsible-section.tsx+++ b/apps/builder/app/builder/shared/collapsible-section.tsx@@ -20,7 +20,6 @@ import {} from "react";import { PlusIcon } from "@webstudio-is/icons";import type { Simplify } from "type-fest";-import { capitalCase } from "change-case";type Label = string;@@ -136,7 +135,7 @@ export const CollapsibleSectionRoot = ({<Collapsible.Trigger asChild>{trigger ?? (<SectionTitle>- <SectionTitleLabel>{capitalCase(label ?? "")}</SectionTitleLabel>+ <SectionTitleLabel>{label ?? ""}</SectionTitleLabel></SectionTitle>)}</Collapsible.Trigger>@@ -232,7 +231,7 @@ export const CollapsibleSectionWithAddButton = ({) : undefined}>- <SectionTitleLabel>{capitalCase(props.label)}</SectionTitleLabel>+ <SectionTitleLabel>{props.label}</SectionTitleLabel></SectionTitle>}>diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex a5564a3aa3..08b28ed117 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -1,4 +1,8 @@import { toast } from "@webstudio-is/design-system";+import {+ isAutoGridPlacement,+ resetGridChildPlacement,+} from "~/builder/features/style-panel/sections/layout/shared/grid-utils";import { createCommandsEmitter, type Command } from "~/shared/commands-emitter";import {$editingItemSelector,@@ -363,6 +367,26 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({if (newRootInstanceId === undefined) {return;}++ // When the original child is auto-placed in a grid, ensure the+ // duplicate is also auto-placed to prevent overlapping items.+ // Manually positioned children keep their exact grid position.+ if (+ isAutoGridPlacement({+ styles: data.styles,+ styleSources: data.styleSources,+ styleSourceSelections: data.styleSourceSelections,+ instanceId: selectedItem.instance.id,+ })+ ) {+ resetGridChildPlacement({+ styles: data.styles,+ styleSources: data.styleSources,+ styleSourceSelections: data.styleSourceSelections,+ instanceId: newRootInstanceId,+ });+ }+const parentInstance = data.instances.get(parentItem.instance.id);if (parentInstance === undefined) {return;diff --git a/apps/builder/app/builder/shared/css-editor/css-editor.tsx b/apps/builder/app/builder/shared/css-editor/css-editor.tsxindex c0e732f52c..9a0a3c4d1c 100644--- a/apps/builder/app/builder/shared/css-editor/css-editor.tsx+++ b/apps/builder/app/builder/shared/css-editor/css-editor.tsx@@ -198,7 +198,7 @@ const AdvancedPropertyValue = ({};/**- * The Advanced section in the Style Panel on </> Global Root has performance issues.+ * The Advanced section in the Style Panel on </> Global root has performance issues.* To fix this, we skip rendering properties not visible in the viewport using the contentvisibilityautostatechange event,* and the contentVisibility and containIntrinsicSize CSS properties.*/diff --git a/apps/builder/app/builder/shared/nano-states/index.ts b/apps/builder/app/builder/shared/nano-states.tssimilarity index 85%rename from apps/builder/app/builder/shared/nano-states/index.tsrename to apps/builder/app/builder/shared/nano-states.tsindex 2454009c10..f59312ae81 100644--- a/apps/builder/app/builder/shared/nano-states/index.ts+++ b/apps/builder/app/builder/shared/nano-states.ts@@ -4,8 +4,8 @@ import {$selectedInstanceRenderState,} from "~/shared/nano-states/misc";import { $canvasIframeState } from "~/shared/nano-states/canvas";-import { $settings, getSetting } from "../client-settings";import type { SidebarPanelName } from "~/builder/sidebar-left/types";+import { $settings, getSetting } from "./client-settings";export const $isShareDialogOpen = atom<boolean>(false);@@ -149,3 +149,31 @@ export const toggleActiveSidebarPanel = (panel: SidebarPanelName) => {};export const $remoteDialog = atom<{ title: string; url: string } | undefined>();++// Track which grid track (column/row) is being edited in the style panel+export type GridEditingTrack = {+ type: "column" | "row";+ index: number;+};++export const $gridEditingTrack = atom<GridEditingTrack | undefined>(undefined);++// Track which grid area is being edited in the style panel+export type GridEditingArea = {+ columnStart: number;+ columnEnd: number;+ rowStart: number;+ rowEnd: number;+};++export const $gridEditingArea = atom<GridEditingArea | undefined>(undefined);++// Which grid editor panels are open.+// Used to conditionally show grid guides on the canvas.+export const $openGridEditorPanel = atom<{+ generator: boolean;+ settings: boolean;+}>({+ generator: false,+ settings: false,+});diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex 888edba39f..484ffa31db 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -55,7 +55,7 @@ import {initCopyPaste,initCopyPasteForContentEditMode,} from "~/shared/copy-paste/init-copy-paste";-import { setDataCollapsed, subscribeCollapsed } from "./collapsed";+import { inflateInstance, subscribeInflator } from "./inflator";import { useWindowResizeDebounced } from "~/shared/dom-hooks";import { subscribeInstanceSelection } from "./instance-selection";import { subscribeInstanceHovering } from "./instance-hovering";@@ -67,6 +67,7 @@ import { updateCollaborativeInstanceRect } from "./collaborative-instance";import { initCanvasApi } from "~/shared/canvas-api";import { subscribeFontLoadingDone } from "./shared/font-weight-support";import { subscribeSelected } from "./instance-selected";+import { subscribeGridGuidesOnSelected } from "./grid-guide-utils";import { subscribeScrollNewInstanceIntoView } from "./shared/scroll-new-instance-into-view";import { $selectedPage } from "~/shared/awareness";import { createInstanceElement } from "./elements";@@ -178,8 +179,10 @@ const DesignMode = () => {abortController.signal);const unsubscribeSelected = subscribeSelected(debounceEffect);+ const unsubscribeGridGuides = subscribeGridGuidesOnSelected();return () => {unsubscribeSelected();+ unsubscribeGridGuides();abortController.abort();};}, [debounceEffect]);@@ -218,8 +221,10 @@ const ContentEditMode = () => {abortController.signal);const unsubscribeSelected = subscribeSelected(debounceEffect);+ const unsubscribeGridGuides = subscribeGridGuidesOnSelected();return () => {unsubscribeSelected();+ unsubscribeGridGuides();abortController.abort();};}, [debounceEffect]);@@ -295,18 +300,18 @@ export const Canvas = () => {useEffect(() => {const rootInstanceId = selectedPage?.rootInstanceId;if (rootInstanceId !== undefined) {- setDataCollapsed(rootInstanceId);+ inflateInstance(rootInstanceId);}});useWindowResizeDebounced(() => {const rootInstanceId = selectedPage?.rootInstanceId;if (rootInstanceId !== undefined) {- setDataCollapsed(rootInstanceId);+ inflateInstance(rootInstanceId);}});- useEffect(subscribeCollapsed, []);+ useEffect(subscribeInflator, []);useHashLinkSync();diff --git a/apps/builder/app/canvas/collapsed.ts b/apps/builder/app/canvas/collapsed.tsdeleted file mode 100644index ee7a9aa9c2..0000000000--- a/apps/builder/app/canvas/collapsed.ts+++ /dev/null@@ -1,342 +0,0 @@-import htmlTags, { voidHtmlTags, type HtmlTags } from "html-tags";-import { collapsedAttribute, idAttribute } from "@webstudio-is/react-sdk";-import { compareMedia, StyleValue } from "@webstudio-is/css-engine";-import {- $breakpoints,- $instances,- $registeredComponentMetas,- $stylesIndex,-} from "~/shared/nano-states";-import { $selectedBreakpoint } from "~/shared/nano-states";-import { $selectedPage } from "~/shared/awareness";-import { serverSyncStore } from "~/shared/sync/sync-stores";-import { doNotTrackMutation } from "~/shared/dom-utils";--const isHtmlTag = (tag: string): tag is HtmlTags =>- htmlTags.includes(tag as HtmlTags);--const instanceIdSet = new Set<string>();--let rafHandle: number;--// Do not add collapsed paddings for replaced elements as at the moment we add them they don't have real size-// https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element-const replacedHtmlElements = ["iframe", "video", "embed", "img"];--// Do not add collapsed paddings for void elements-// https://developer.mozilla.org/en-US/docs/Glossary/Void_element-const skipElementsSet = new Set([...voidHtmlTags, ...replacedHtmlElements]);--const isSelectorSupported = (selector: string) => {- try {- return Boolean(document.querySelector(selector));- } catch {- return false;- }-};--const getInstanceSize = (instanceId: string, tagName: HtmlTags | undefined) => {- const metas = $registeredComponentMetas.get();- const breakpoints = $breakpoints.get();- const selectedBreakpoint = $selectedBreakpoint.get();- const { stylesByInstanceId } = $stylesIndex.get();- const instances = $instances.get();- const selectedBreakpointId = selectedBreakpoint?.id;-- if (selectedBreakpointId === undefined) {- return {- width: undefined,- height: undefined,- };- }-- let widthValue: undefined | StyleValue;- let heightValue: undefined | StyleValue;-- const component =- instanceId === undefined ? undefined : instances.get(instanceId)?.component;- if (component && tagName) {- const presetStyles = metas.get(component)?.presetStyle?.[tagName] ?? [];- for (const styleDecl of presetStyles) {- if (styleDecl.state === undefined) {- if (styleDecl.property === "width") {- widthValue = styleDecl.value;- }- if (styleDecl.property === "height") {- heightValue = styleDecl.value;- }- }- }- }-- const sortedBreakpoints = Array.from(breakpoints.values()).sort(compareMedia);- const matchingBreakpoints: string[] = [];- for (const breakpoint of sortedBreakpoints) {- matchingBreakpoints.push(breakpoint.id);- if (breakpoint.id === selectedBreakpointId) {- break;- }- }-- const instanceStyles = stylesByInstanceId.get(instanceId);- if (instanceStyles) {- for (const breakpointId of matchingBreakpoints) {- for (const styleDecl of instanceStyles) {- if (- styleDecl.breakpointId === breakpointId &&- styleDecl.state === undefined- ) {- if (styleDecl.property === "width") {- widthValue = styleDecl.value;- }- if (styleDecl.property === "height") {- heightValue = styleDecl.value;- }- }- }- }- }-- return {- width: widthValue?.type === "unit" ? widthValue.value : undefined,- height: heightValue?.type === "unit" ? heightValue.value : undefined,- };-};--const MAX_SIZE_TO_USE_OPTIMIZATION = 50;--const findFirstNonContentsParent = (element: Element) => {- // Start with the element's parent- let parent = element.parentElement;-- // Continue traversing up until we find a non-contents parent or reach the top- while (parent) {- // Get the computed style of the parent- const computedStyle = window.getComputedStyle(parent);-- const isHidden = parent.getAttribute("hidden") !== null;-- // Check if the display is not 'contents'- if (computedStyle.display !== "contents" && !isHidden) {- return parent;- }-- // Move up to the next parent- parent = parent.parentElement;- }-- // Return null if no non-contents parent is found- return null;-};--const recalculate = () => {- const rootInstanceId = $selectedPage.get()?.rootInstanceId;-- // Below algorithm quickly finds the common ancestor of all elements with an instanceId.- // However, for a large number of elements, it's more efficient to calculate from the root.- // In almost all cases, if instanceIdsSet >= MAX_SIZE_TO_USE_OPTIMIZATION, it likely includes all elements.- const instanceIds =- instanceIdSet.size < MAX_SIZE_TO_USE_OPTIMIZATION- ? Array.from(instanceIdSet)- : rootInstanceId !== undefined- ? [rootInstanceId]- : [];-- instanceIdSet.clear();- if (instanceIds.length === 0) {- return;- }-- /**- * Selector to find elements common ancestors, in case of no :has selector support select body- **/- const elementSelector = isSelectorSupported(":has(body)")- ? `[${idAttribute}]${instanceIds- .map((instanceId) => `:has([${idAttribute}="${instanceId}"])`)- .join("")}`- : "body";-- const elements: Element[] = [];-- // Element itself or last common ancestor or body- const baseElement =- Array.from(document.querySelectorAll(elementSelector)).pop() ??- document.body;- elements.push(baseElement);-- const descendants = baseElement.querySelectorAll(`[${idAttribute}]`);- elements.push(...descendants);-- const elementsToRecalculate: HTMLElement[] = [];- const parentsWithAbsoluteChildren = new Map<HTMLElement, number>();-- for (const element of elements) {- if (!(element instanceof HTMLElement)) {- continue;- }-- if (skipElementsSet.has(element.tagName.toLowerCase())) {- // Images should not collapse, and have a fallback.- // The issue that unloaded image has 0 width and height until explicitly set,- // so at the moment new Image added we detect it as collapsed.- // Skip it for now.- continue;- }-- const elementStyle = window.getComputedStyle(element);-- // Find all Leaf like elements- // Leaf like elements are elements that have no children or all children are absolute or fixed- // Excluding hidden elements without size- if (element.childElementCount === 0) {- if (element.offsetParent !== null) {- elementsToRecalculate.push(element);- }-- if (elementStyle.position === "fixed") {- elementsToRecalculate.push(element);- }- }-- const parentElement = findFirstNonContentsParent(element);-- if (parentElement) {- if (- elementStyle.position === "absolute" ||- elementStyle.position === "fixed" ||- element.offsetParent == null // collapsed or none- ) {- parentsWithAbsoluteChildren.set(- parentElement,- parentsWithAbsoluteChildren.get(parentElement) ?? 0- );- } else {- parentsWithAbsoluteChildren.set(parentElement, 1);- }- }- }-- for (const [element, value] of parentsWithAbsoluteChildren.entries()) {- // HTML is not part of webstudio data so skip to not process- if (element.tagName === "HTML") {- continue;- }-- // All children are absolute or fixed- if (value === 0) {- elementsToRecalculate.push(element);- }- }-- // If most elements are collapsed at the next step, scrollHeight becomes equal to clientHeight,- // which resets the scroll position. To prevent this, we set the document's height to the current scrollHeight- // to preserve the scroll position.- // use nested element to avoid full page repaint and freeze on big projects- let collapsedElement = document.querySelector(- "#ws-collapsed"- ) as null | HTMLElement;- if (!collapsedElement) {- collapsedElement = document.createElement("div") as HTMLElement;- collapsedElement.style.position = "absolute";- collapsedElement.style.top = "0px";- collapsedElement.style.left = "0px";- collapsedElement.style.right = "0px";- collapsedElement.setAttribute("id", "ws-collapsed");- collapsedElement.setAttribute("hidden", "true");- // Mark that we are in the process of recalculating collapsed elements- // to avoid infinite loop of mutations- doNotTrackMutation(collapsedElement);- document.documentElement.appendChild(collapsedElement);- }- collapsedElement.removeAttribute("hidden");- collapsedElement.style.height = `${document.documentElement.scrollHeight}px`;-- // Now combine all operations in batches.-- // 1. Remove all collapsed attributes- baseElement.parentElement?.removeAttribute(collapsedAttribute);- baseElement.removeAttribute(collapsedAttribute);- for (const element of baseElement.querySelectorAll(- `[${collapsedAttribute}]`- )) {- element.removeAttribute(collapsedAttribute);- }-- // 2. Calculate collapsed state- const collapsedElements = new Map<HTMLElement, string>();-- for (const element of elementsToRecalculate) {- const elementInstanceId = element.getAttribute(idAttribute);-- if (elementInstanceId === null) {- // Not a webstudio controlled element, like popover portal- continue;- }-- const tagName = element.tagName.toLowerCase();-- const elementSize = getInstanceSize(- elementInstanceId,- isHtmlTag(tagName) ? tagName : undefined- );-- const collapsedWidth =- element.offsetWidth === 0 && elementSize.width === undefined ? "w" : "";- const collapsedHeight =- element.offsetHeight === 0 && elementSize.height === undefined ? "h" : "";-- if (collapsedHeight || collapsedWidth) {- collapsedElements.set(element, collapsedWidth + collapsedHeight);- }- }-- // 3. Add collapsed attributes- for (const [element, value] of collapsedElements.entries()) {- element.setAttribute(collapsedAttribute, value);- }-- collapsedElement.setAttribute("hidden", "true");-};--/**- * When we add elements or edit element styles, a situation arises where an element can collapse.- * I.e. get either 0 width or 0 height or both.- * We need the user to be able to select such elements anyway.- * We try to find the minimum set of elements that will prevent any of the canvas elements from collapsing.- * For such elements we set collapsedAttribute and then style helpers add padding to- * prevent collapsing.- **/-export const setDataCollapsed = (instanceId: string, syncExec = false) => {- instanceIdSet.add(instanceId);-- cancelAnimationFrame(rafHandle);-- if (syncExec) {- recalculate();- return;- }-- rafHandle = requestAnimationFrame(() => {- recalculate();- });-};--/**- * For optimisation reasons try to extract instanceId of changed elements from pubsub- * In that case we just check the subtree of parent/common ancestor of changed elements to find collapsed elements- **/-export const subscribeCollapsed = () => {- return serverSyncStore.subscribe((_transactionId, changes) => {- for (const change of changes) {- if (change.namespace === "styleSourceSelections") {- for (const patch of change.patches) {- const instanceId = patch.value?.instanceId;-- if (typeof instanceId === "string") {- setDataCollapsed(instanceId);- }- }- }- }- });-};diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsxindex c0c4fcff53..7febd3a05c 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx@@ -54,7 +54,7 @@ import { nanoid } from "nanoid";import { createRegularStyleSheet } from "@webstudio-is/css-engine";import type { Instance, Instances, Props } from "@webstudio-is/sdk";import {- collapsedAttribute,+ inflatedAttribute,idAttribute,selectorIdAttribute,} from "@webstudio-is/react-sdk";@@ -85,7 +85,7 @@ import {getVisibleElementsByInstanceSelector,} from "~/shared/dom-utils";import deepEqual from "fast-deep-equal";-import { setDataCollapsed } from "~/canvas/collapsed";+import { inflateInstance } from "~/canvas/inflator";import {$selectedPage,addTemporaryInstance,@@ -1546,7 +1546,7 @@ export const TextEditor = ({if (treeRootInstance) {const jsonState = editorState.toJSON();if (deepEqual(jsonState, lastSavedStateJsonRef.current)) {- setDataCollapsed(rootInstanceSelector[0], false);+ inflateInstance(rootInstanceSelector[0], false);return;}@@ -1557,7 +1557,7 @@ export const TextEditor = ({lastSavedStateJsonRef.current = jsonState;}- setDataCollapsed(rootInstanceSelector[0], false);+ inflateInstance(rootInstanceSelector[0], false);});const textEditingSelector = $textEditingInstanceSelector.get()?.selector;@@ -1699,7 +1699,7 @@ export const TextEditor = ({continue;}- if (!elt.hasAttribute(collapsedAttribute)) {+ if (!elt.hasAttribute(inflatedAttribute)) {continue;}}diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsxindex 7a168ecd4b..d00e47ea94 100644--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx@@ -71,7 +71,7 @@ import {type InstanceSelector,areInstanceSelectorsEqual,} from "~/shared/tree-utils";-import { setDataCollapsed } from "~/canvas/collapsed";+import { inflateInstance } from "~/canvas/inflator";import { getIsVisuallyHidden } from "~/shared/visually-hidden";import { serverSyncStore } from "~/shared/sync/sync-stores";import { TextEditor } from "../text-editor";@@ -348,12 +348,12 @@ const useInstanceProps = (instanceSelector: InstanceSelector) => {const existingElements = new Set<string>();/**- * We are identifying newly created instances like Tooltips and ensuring the calculation of 'collapsed' elements.+ * We are identifying newly created instances like Tooltips and ensuring the calculation of 'inflated' elements.*/-const useCollapsedOnNewElement = (instanceId: Instance["id"]) => {+const useInflateOnNewElement = (instanceId: Instance["id"]) => {useEffect(() => {if (existingElements.has(instanceId) === false) {- setDataCollapsed(instanceId);+ inflateInstance(instanceId);}existingElements.add(instanceId);@@ -466,7 +466,7 @@ export const WebstudioComponentCanvas = forwardRef<*/const initialContentEditableContent = useRef(children);- useCollapsedOnNewElement(instanceId);+ useInflateOnNewElement(instanceId);// this assumes presence of `useStore($selectedInstanceSelector)` above// we rely on root re-rendering after selected instance changesdiff --git a/apps/builder/app/canvas/grid-guide-utils.test.ts b/apps/builder/app/canvas/grid-guide-utils.test.tsnew file mode 100644index 0000000000..2abbd44847--- /dev/null+++ b/apps/builder/app/canvas/grid-guide-utils.test.ts@@ -0,0 +1,42 @@+import { describe, test, expect } from "vitest";+import { __testing__ } from "./grid-guide-utils";++const { findImplicitStart } = __testing__;++describe("findImplicitStart", () => {+ test("returns trackCount when all tracks are explicit", () => {+ // All tracks are regular sizes, no 1.25px+ expect(findImplicitStart("100px 200px 300px", 3)).toBe(3);+ });++ test("detects implicit tracks at the end", () => {+ // Two explicit tracks followed by one implicit (1.25px)+ expect(findImplicitStart("100px 200px 1.25px", 3)).toBe(2);+ });++ test("detects implicit tracks at the start", () => {+ // Negative line numbers can push implicit tracks before explicit ones+ expect(findImplicitStart("1.25px 100px 200px", 3)).toBe(0);+ });++ test("detects multiple implicit tracks", () => {+ expect(findImplicitStart("100px 1.25px 1.25px", 3)).toBe(1);+ });++ test("returns trackCount for empty template", () => {+ expect(findImplicitStart("none", 0)).toBe(0);+ });++ test("returns trackCount for single explicit track", () => {+ expect(findImplicitStart("100px", 1)).toBe(1);+ });++ test("handles fractional explicit sizes near probe value", () => {+ // 1.5px should not trigger implicit detection+ expect(findImplicitStart("1.5px 100px", 2)).toBe(2);+ });++ test("handles exact probe value", () => {+ expect(findImplicitStart("1.25px", 1)).toBe(0);+ });+});diff --git a/apps/builder/app/canvas/grid-guide-utils.ts b/apps/builder/app/canvas/grid-guide-utils.tsnew file mode 100644index 0000000000..8196618549--- /dev/null+++ b/apps/builder/app/canvas/grid-guide-utils.ts@@ -0,0 +1,331 @@+import {+ $instances,+ $isResizingCanvas,+ $stylesIndex,+ $propValuesByInstanceSelectorWithMemoryProps,+} from "~/shared/nano-states";+import { $gridCellData, type GridCellData } from "~/shared/nano-states";+import { subscribeScrollState } from "~/canvas/shared/scroll-state";+import { subscribeWindowResize } from "~/shared/dom-hooks";+import type { InstanceSelector } from "~/shared/tree-utils";+import { $awareness } from "~/shared/awareness";+import { getElementByInstanceSelector } from "~/shared/dom-utils";+import { parseGridTemplateTrackList } from "@webstudio-is/css-data";+import { doNotTrackMutation } from "~/shared/dom-utils";++const hideGridGuides = () => {+ $gridCellData.set(undefined);+};++const MAX_TRACKS = 20;++// Read resolved CSS strings from getComputedStyle. No DOM probing needed —+// the builder grid guides mirror the grid via a child div that faithfully+// reproduces the canvas element's CSS (including user transforms).+// A parent wrapper handles our scale + translate positioning.+// Inflation is handled at the track level (minmax in inflator.ts), so+// resolved templates are always non-zero for inflated grids.++// CSS properties synced to the builder overlay mirror div.+// To support a new property, add it here — no type or builder changes needed.+const mirrorProperties = [+ // Grid layout+ "display",+ "grid-template-columns",+ "grid-template-rows",+ "grid-template-areas",+ "column-gap",+ "row-gap",+ "justify-content",+ "justify-items",+ "align-content",+ "align-items",+ // Box model+ "width",+ "height",+ "box-sizing",+ "padding-top",+ "padding-right",+ "padding-bottom",+ "padding-left",+ "border-top-width",+ "border-right-width",+ "border-bottom-width",+ "border-left-width",+ "border-top-style",+ "border-right-style",+ "border-bottom-style",+ "border-left-style",+ // Direction+ "direction",+ // Transforms+ "transform",+ "transform-origin",+ "scale",+ "rotate",+ "translate",+];++// Sentinel value for the implicit track probe. Implicit (auto-generated)+// tracks will resolve to this size while explicit tracks keep their original+// resolved size. 1.25px is unlikely to appear in authored CSS.+const IMPLICIT_PROBE_SIZE = 1.25;++/**+ * Find the index where implicit tracks begin for one axis.+ * Parses the resolved template track list from a clone where+ * grid-auto-columns/rows are set to IMPLICIT_PROBE_SIZE px.+ * Returns the 0-based index of the first implicit track, or+ * trackCount when all tracks are explicit.+ */+const findImplicitStart = (+ resolvedTemplate: string,+ trackCount: number+): number => {+ const tracks = parseGridTemplateTrackList(resolvedTemplate);+ for (let i = 0; i < tracks.length; i++) {+ const size = parseFloat(tracks[i].value);+ if (Math.abs(size - IMPLICIT_PROBE_SIZE) < 0.01) {+ return i;+ }+ }+ return trackCount;+};++/**+ * Probe implicit track boundaries by creating a hidden clone of the grid+ * with grid-auto-columns/rows set to 1.25px. Implicit tracks resolve to+ * 1.25px while explicit tracks retain their authored size.+ */+const probeImplicitTracks = (+ gridElement: HTMLElement,+ columnCount: number,+ rowCount: number+): { implicitColumnStart: number; implicitRowStart: number } => {+ const clone = gridElement.cloneNode(false) as HTMLElement;+ doNotTrackMutation(clone);+ clone.style.cssText = window.getComputedStyle(gridElement).cssText;+ clone.style.position = "fixed";+ clone.style.visibility = "hidden";+ clone.style.pointerEvents = "none";+ clone.style.gridAutoColumns = `${IMPLICIT_PROBE_SIZE}px`;+ clone.style.gridAutoRows = `${IMPLICIT_PROBE_SIZE}px`;++ // Copy child placeholders so the browser generates the same implicit tracks+ for (const child of gridElement.children) {+ const placeholder = document.createElement("div");+ const childStyle = window.getComputedStyle(child);+ placeholder.style.gridColumnStart = childStyle.gridColumnStart;+ placeholder.style.gridColumnEnd = childStyle.gridColumnEnd;+ placeholder.style.gridRowStart = childStyle.gridRowStart;+ placeholder.style.gridRowEnd = childStyle.gridRowEnd;+ placeholder.style.order = childStyle.order;+ doNotTrackMutation(placeholder);+ clone.appendChild(placeholder);+ }++ document.body.appendChild(clone);+ const probeStyle = window.getComputedStyle(clone);+ const implicitColumnStart = findImplicitStart(+ probeStyle.gridTemplateColumns,+ columnCount+ );+ const implicitRowStart = findImplicitStart(+ probeStyle.gridTemplateRows,+ rowCount+ );+ document.body.removeChild(clone);++ return { implicitColumnStart, implicitRowStart };+};++const computeGridCells = (+ gridElement: HTMLElement,+ instanceId: string+): GridCellData | undefined => {+ const computedStyle = window.getComputedStyle(gridElement);+ const display = computedStyle.display;++ if (display !== "grid" && display !== "inline-grid") {+ return;+ }++ const columnTracks = parseGridTemplateTrackList(+ computedStyle.gridTemplateColumns+ );+ const rowTracks = parseGridTemplateTrackList(computedStyle.gridTemplateRows);++ const columnCount = Math.min(Math.max(1, columnTracks.length), MAX_TRACKS);+ const rowCount = Math.min(Math.max(1, rowTracks.length), MAX_TRACKS);++ const untransformedWidth = gridElement.offsetWidth;+ const untransformedHeight = gridElement.offsetHeight;++ if (untransformedWidth < 1 || untransformedHeight < 1) {+ return;+ }++ const bcr = gridElement.getBoundingClientRect();++ // Build cssText from a whitelist of properties that affect grid layout+ // and visual appearance. Adding a new property = one line here.+ const parts: string[] = [];+ for (const prop of mirrorProperties) {+ const value = computedStyle.getPropertyValue(prop);+ if (value) {+ parts.push(`${prop}:${value}`);+ }+ }+ // Override border-color to transparent — we need border space but not color+ parts.push("border-color:transparent");++ const { implicitColumnStart, implicitRowStart } = probeImplicitTracks(+ gridElement,+ columnCount,+ rowCount+ );++ return {+ instanceId,+ columnCount,+ rowCount,+ bcr: { top: bcr.top, left: bcr.left },+ untransformedWidth,+ untransformedHeight,+ resolvedCssText: parts.join(";"),+ implicitColumnStart,+ implicitRowStart,+ };+};++const findGridContainer = (+ instanceSelector: Readonly<InstanceSelector>+): { element: HTMLElement; instanceId: string } | undefined => {+ // Check each ancestor in the selector+ for (let i = 0; i < instanceSelector.length; i++) {+ const ancestorSelector = instanceSelector.slice(i);+ const element = getElementByInstanceSelector(ancestorSelector);++ if (element) {+ const computedStyle = window.getComputedStyle(element);+ const display = computedStyle.display;++ if (display === "grid" || display === "inline-grid") {+ return { element, instanceId: instanceSelector[i] };+ }+ }+ }++ return undefined;+};++const subscribeGridGuides = (+ selectedInstanceSelector: Readonly<InstanceSelector>+) => {+ if (selectedInstanceSelector.length === 0) {+ hideGridGuides();+ return;+ }++ let rafId = 0;++ // Re-evaluate findGridContainer on every update so that the overlay+ // appears as soon as an element becomes a grid (e.g. display changed+ // from block → grid) without requiring a re-selection.+ const updateGridGuides = () => {+ if ($isResizingCanvas.get()) {+ hideGridGuides();+ return;+ }++ const gridInfo = findGridContainer(selectedInstanceSelector);+ if (!gridInfo) {+ hideGridGuides();+ return;+ }++ const cellData = computeGridCells(gridInfo.element, gridInfo.instanceId);+ $gridCellData.set(cellData);+ };++ // Schedule an update after styles are applied to the DOM.+ // The stylesheet renderer uses rAF, so we need rAF→rAF to ensure+ // both the CSS is written and layout is recalculated.+ const scheduleUpdate = () => {+ cancelAnimationFrame(rafId);+ rafId = requestAnimationFrame(() => {+ rafId = requestAnimationFrame(() => {+ updateGridGuides();+ });+ });+ };++ // Initial computation+ updateGridGuides();++ const unsubscribeStylesIndex = $stylesIndex.subscribe(() => {+ scheduleUpdate();+ });++ const unsubscribeInstances = $instances.subscribe(() => {+ scheduleUpdate();+ });++ const unsubscribePropValues =+ $propValuesByInstanceSelectorWithMemoryProps.subscribe(() => {+ scheduleUpdate();+ });++ const unsubscribeIsResizing = $isResizingCanvas.subscribe((isResizing) => {+ if (isResizing) {+ hideGridGuides();+ } else {+ updateGridGuides();+ }+ });++ const unsubscribeScrollState = subscribeScrollState({+ onScrollStart: hideGridGuides,+ onScrollEnd: updateGridGuides,+ });++ const unsubscribeWindowResize = subscribeWindowResize({+ onResizeStart: hideGridGuides,+ onResizeEnd: updateGridGuides,+ });++ return () => {+ cancelAnimationFrame(rafId);+ hideGridGuides();+ unsubscribeStylesIndex();+ unsubscribeInstances();+ unsubscribePropValues();+ unsubscribeIsResizing();+ unsubscribeScrollState();+ unsubscribeWindowResize();+ };+};++export const subscribeGridGuidesOnSelected = () => {+ let previousSelectedInstance: readonly string[] | undefined = undefined;+ let unsubscribeGridGuides = () => {};++ const unsubscribe = $awareness.subscribe((awareness) => {+ const instanceSelector = awareness?.instanceSelector;+ if (instanceSelector !== previousSelectedInstance) {+ unsubscribeGridGuides();+ unsubscribeGridGuides =+ subscribeGridGuides(instanceSelector ?? []) ?? (() => {});+ previousSelectedInstance = instanceSelector;+ }+ });++ return () => {+ unsubscribe();+ unsubscribeGridGuides();+ };+};++export const __testing__ = {+ findImplicitStart,+};diff --git a/apps/builder/app/canvas/inflator.test.ts b/apps/builder/app/canvas/inflator.test.tsnew file mode 100644index 0000000000..24c9c8a164--- /dev/null+++ b/apps/builder/app/canvas/inflator.test.ts@@ -0,0 +1,405 @@+import { describe, test, expect } from "vitest";+import type { Breakpoint, StyleDecl, WsComponentMeta } from "@webstudio-is/sdk";+import type { StyleValue } from "@webstudio-is/css-engine";+import { __testing__ } from "./inflator";++const {+ getInstanceSize,+ getInflationState,+ buildAncestorSelector,+ extractInstanceIdsFromChanges,+} = __testing__;++const px = (value: number): StyleValue => ({+ type: "unit",+ value,+ unit: "px",+});++const createStyleDecl = (overrides: Partial<StyleDecl> = {}): StyleDecl => ({+ styleSourceId: "ss-1",+ breakpointId: "base",+ property: "color",+ value: { type: "keyword", value: "red" },+ ...overrides,+});++describe("getInstanceSize", () => {+ const baseBreakpoints = new Map<string, Breakpoint>([+ ["base", { id: "base", label: "Base" }],+ ]);++ const callGetInstanceSize = (+ overrides: Partial<Parameters<typeof getInstanceSize>[0]> = {}+ ) =>+ getInstanceSize({+ instanceId: "inst-1",+ tagName: "div",+ metas: new Map(),+ breakpoints: baseBreakpoints,+ selectedBreakpointId: "base",+ stylesByInstanceId: new Map(),+ instances: new Map(),+ ...overrides,+ });++ const noSize = { width: undefined, height: undefined };++ test("returns undefined when no selected breakpoint", () => {+ expect(callGetInstanceSize({ selectedBreakpointId: undefined })).toEqual(+ noSize+ );+ });++ test("returns undefined when instance has no styles or preset", () => {+ expect(callGetInstanceSize()).toEqual(noSize);+ });++ test("reads width and height from preset styles", () => {+ const metas = new Map<string, WsComponentMeta>([+ [+ "Box",+ {+ presetStyle: {+ div: [+ { property: "width", value: px(100) },+ { property: "height", value: px(50) },+ ],+ },+ },+ ],+ ]);+ expect(+ callGetInstanceSize({+ metas,+ instances: new Map([["inst-1", { component: "Box" }]]),+ })+ ).toEqual({ width: 100, height: 50 });+ });++ test("ignores preset styles with a state selector", () => {+ const metas = new Map<string, WsComponentMeta>([+ [+ "Box",+ {+ presetStyle: {+ div: [{ state: ":hover", property: "width", value: px(200) }],+ },+ },+ ],+ ]);+ expect(+ callGetInstanceSize({+ metas,+ instances: new Map([["inst-1", { component: "Box" }]]),+ })+ ).toEqual(noSize);+ });++ test("instance styles override preset styles", () => {+ const metas = new Map<string, WsComponentMeta>([+ [+ "Box",+ {+ presetStyle: {+ div: [{ property: "width", value: px(100) }],+ },+ },+ ],+ ]);+ expect(+ callGetInstanceSize({+ metas,+ instances: new Map([["inst-1", { component: "Box" }]]),+ stylesByInstanceId: new Map([+ ["inst-1", [createStyleDecl({ property: "width", value: px(250) })]],+ ]),+ })+ ).toEqual({ width: 250, height: undefined });+ });++ test("non-unit value (auto) results in undefined", () => {+ expect(+ callGetInstanceSize({+ instances: new Map([["inst-1", { component: "Box" }]]),+ stylesByInstanceId: new Map([+ [+ "inst-1",+ [+ createStyleDecl({+ property: "width",+ value: { type: "keyword", value: "auto" },+ }),+ ],+ ],+ ]),+ })+ ).toEqual(noSize);+ });++ test("cascades breakpoints from smallest to selected", () => {+ const breakpoints = new Map<string, Breakpoint>([+ ["base", { id: "base", label: "Base" }],+ ["tablet", { id: "tablet", label: "Tablet", maxWidth: 991 }],+ ["mobile", { id: "mobile", label: "Mobile", maxWidth: 479 }],+ ]);+ expect(+ callGetInstanceSize({+ breakpoints,+ selectedBreakpointId: "tablet",+ instances: new Map([["inst-1", { component: "Box" }]]),+ stylesByInstanceId: new Map([+ [+ "inst-1",+ [+ createStyleDecl({+ breakpointId: "base",+ property: "width",+ value: px(100),+ }),+ createStyleDecl({+ breakpointId: "tablet",+ property: "width",+ value: px(200),+ }),+ createStyleDecl({+ breakpointId: "mobile",+ property: "width",+ value: px(300),+ }),+ ],+ ],+ ]),+ })+ ).toEqual({ width: 200, height: undefined });+ });++ test("stops cascade at selected breakpoint", () => {+ const breakpoints = new Map<string, Breakpoint>([+ ["base", { id: "base", label: "Base" }],+ ["tablet", { id: "tablet", label: "Tablet", maxWidth: 991 }],+ ["mobile", { id: "mobile", label: "Mobile", maxWidth: 479 }],+ ]);+ expect(+ callGetInstanceSize({+ breakpoints,+ selectedBreakpointId: "base",+ instances: new Map([["inst-1", { component: "Box" }]]),+ stylesByInstanceId: new Map([+ [+ "inst-1",+ [+ createStyleDecl({+ breakpointId: "mobile",+ property: "width",+ value: px(300),+ }),+ ],+ ],+ ]),+ })+ ).toEqual(noSize);+ });++ test("skips preset when tagName is undefined", () => {+ const metas = new Map<string, WsComponentMeta>([+ [+ "Box",+ {+ presetStyle: {+ div: [{ property: "width", value: px(100) }],+ },+ },+ ],+ ]);+ expect(+ callGetInstanceSize({+ tagName: undefined,+ metas,+ instances: new Map([["inst-1", { component: "Box" }]]),+ })+ ).toEqual(noSize);+ });++ test("ignores instance styles with a state selector", () => {+ expect(+ callGetInstanceSize({+ instances: new Map([["inst-1", { component: "Box" }]]),+ stylesByInstanceId: new Map([+ [+ "inst-1",+ [+ createStyleDecl({+ state: ":hover",+ property: "width",+ value: px(999),+ }),+ ],+ ],+ ]),+ })+ ).toEqual(noSize);+ });+});++describe("getInflationState", () => {+ const call = (overrides: Partial<Parameters<typeof getInflationState>[0]>) =>+ getInflationState({+ offsetWidth: 100,+ offsetHeight: 100,+ explicitWidth: undefined,+ explicitHeight: undefined,+ ...overrides,+ });++ test("no inflation when element has size", () => {+ expect(call({})).toBe("");+ });++ test("inflate width only", () => {+ expect(call({ offsetWidth: 0 })).toBe("w");+ });++ test("inflate height only", () => {+ expect(call({ offsetHeight: 0 })).toBe("h");+ });++ test("inflate both dimensions", () => {+ expect(call({ offsetWidth: 0, offsetHeight: 0 })).toBe("wh");+ });++ test("explicit width prevents inflation", () => {+ expect(call({ offsetWidth: 0, explicitWidth: 100 })).toBe("");+ });++ test("explicit height prevents inflation", () => {+ expect(call({ offsetHeight: 0, explicitHeight: 50 })).toBe("");+ });++ test("both explicit sizes prevent inflation", () => {+ expect(+ call({+ offsetWidth: 0,+ offsetHeight: 0,+ explicitWidth: 100,+ explicitHeight: 50,+ })+ ).toBe("");+ });++ test("partial explicit: inflate only height", () => {+ expect(call({ offsetWidth: 0, offsetHeight: 0, explicitWidth: 100 })).toBe(+ "h"+ );+ });++ test("explicit 0 still prevents inflation", () => {+ expect(+ call({+ offsetWidth: 0,+ offsetHeight: 0,+ explicitWidth: 0,+ explicitHeight: 0,+ })+ ).toBe("");+ });+});++describe("buildAncestorSelector", () => {+ test("returns body when :has() is not supported", () => {+ expect(+ buildAncestorSelector({+ instanceIds: ["id-1", "id-2"],+ hasSelectorSupport: false,+ })+ ).toBe("body");+ });++ test("single instance id", () => {+ expect(+ buildAncestorSelector({ instanceIds: ["id-1"], hasSelectorSupport: true })+ ).toBe('[data-ws-id]:has([data-ws-id="id-1"])');+ });++ test("multiple instance ids", () => {+ expect(+ buildAncestorSelector({+ instanceIds: ["id-1", "id-2"],+ hasSelectorSupport: true,+ })+ ).toBe('[data-ws-id]:has([data-ws-id="id-1"]):has([data-ws-id="id-2"])');+ });++ test("empty array with :has() support", () => {+ expect(+ buildAncestorSelector({ instanceIds: [], hasSelectorSupport: true })+ ).toBe("[data-ws-id]");+ });++ test("empty array without :has() support", () => {+ expect(+ buildAncestorSelector({ instanceIds: [], hasSelectorSupport: false })+ ).toBe("body");+ });+});++describe("extractInstanceIdsFromChanges", () => {+ const sss = (patches: Array<{ value?: { instanceId?: unknown } }>) => ({+ namespace: "styleSourceSelections" as const,+ patches,+ });++ test("empty changes", () => {+ expect(extractInstanceIdsFromChanges([])).toEqual([]);+ });++ test("extracts ids from styleSourceSelections", () => {+ expect(+ extractInstanceIdsFromChanges([+ sss([{ value: { instanceId: "a" } }, { value: { instanceId: "b" } }]),+ ])+ ).toEqual(["a", "b"]);+ });++ test("ignores other namespaces", () => {+ expect(+ extractInstanceIdsFromChanges([+ { namespace: "styles", patches: [{ value: { instanceId: "a" } }] },+ ])+ ).toEqual([]);+ });++ test("skips patches without instanceId or with non-string instanceId", () => {+ expect(+ extractInstanceIdsFromChanges([+ sss([+ { value: {} },+ { value: { instanceId: undefined } },+ { value: { instanceId: 123 } },+ { value: { instanceId: "valid" } },+ ]),+ ])+ ).toEqual(["valid"]);+ });++ test("combines ids across multiple changes", () => {+ expect(+ extractInstanceIdsFromChanges([+ sss([{ value: { instanceId: "a" } }]),+ { namespace: "styles", patches: [{ value: { instanceId: "skip" } }] },+ sss([{ value: { instanceId: "b" } }]),+ ])+ ).toEqual(["a", "b"]);+ });++ test("handles patches without value property", () => {+ expect(+ extractInstanceIdsFromChanges([+ sss([+ {} as { value?: { instanceId?: unknown } },+ { value: { instanceId: "a" } },+ ]),+ ])+ ).toEqual(["a"]);+ });+});diff --git a/apps/builder/app/canvas/inflator.ts b/apps/builder/app/canvas/inflator.tsnew file mode 100644index 0000000000..7674d41728--- /dev/null+++ b/apps/builder/app/canvas/inflator.ts@@ -0,0 +1,541 @@+import htmlTags, { voidHtmlTags, type HtmlTags } from "html-tags";+import { inflatedAttribute, idAttribute } from "@webstudio-is/react-sdk";+import { compareMedia, type StyleValue } from "@webstudio-is/css-engine";+import { parseGridTemplateTrackList } from "@webstudio-is/css-data";+import type { Breakpoint, StyleDecl, WsComponentMeta } from "@webstudio-is/sdk";+import {+ $breakpoints,+ $instances,+ $registeredComponentMetas,+ $stylesIndex,+} from "~/shared/nano-states";+import { $selectedBreakpoint } from "~/shared/nano-states";+import { $selectedPage } from "~/shared/awareness";+import { serverSyncStore } from "~/shared/sync/sync-stores";+import { doNotTrackMutation } from "~/shared/dom-utils";++const isHtmlTag = (tag: string): tag is HtmlTags =>+ htmlTags.includes(tag as HtmlTags);++const instanceIdSet = new Set<string>();++let rafHandle: number;++// Padding in px added to collapsed elements to give them visible size on canvas.+// Grid containers multiply this by their track count so each virtual cell+// gets this amount of space.+export const INFLATE_PADDING = 75;++// Marker attribute for grid containers with per-track minmax wrapping.+// Separate from inflatedAttribute so dashed-outline CSS doesn't apply+// to grids that aren't fully collapsed — only their tracks are inflated.+const gridInflatedAttribute = "data-ws-grid-inflated";++// Do not add inflation paddings for replaced elements as at the moment we add them they don't have real size+// https://developer.mozilla.org/en-US/docs/Web/CSS/Replaced_element+const replacedHtmlElements = ["iframe", "video", "embed", "img"];++// Do not add inflation paddings for void elements+// https://developer.mozilla.org/en-US/docs/Glossary/Void_element+const skipElementsSet = new Set([...voidHtmlTags, ...replacedHtmlElements]);++const isSelectorSupported = (selector: string) => {+ try {+ return Boolean(document.querySelector(selector));+ } catch {+ return false;+ }+};++/**+ * Determine explicit width/height for an instance from preset + breakpoint styles.+ * Returns `{ width, height }` where each is a number if explicitly set via a unit value,+ * or `undefined` if not set or set to a non-unit value (e.g., `auto`).+ *+ * Pure function — accepts all data as parameters for testability.+ */+const getInstanceSize = ({+ instanceId,+ tagName,+ metas,+ breakpoints,+ selectedBreakpointId,+ stylesByInstanceId,+ instances,+}: {+ instanceId: string;+ tagName: HtmlTags | undefined;+ metas: Map<string, WsComponentMeta>;+ breakpoints: Map<string, Breakpoint>;+ selectedBreakpointId: string | undefined;+ stylesByInstanceId: Map<string, StyleDecl[]>;+ instances: Map<string, { component: string }>;+}): { width: number | undefined; height: number | undefined } => {+ if (selectedBreakpointId === undefined) {+ return { width: undefined, height: undefined };+ }++ let widthValue: undefined | StyleValue;+ let heightValue: undefined | StyleValue;++ const component = instances.get(instanceId)?.component;+ if (component && tagName) {+ const presetStyles = metas.get(component)?.presetStyle?.[tagName] ?? [];+ for (const styleDecl of presetStyles) {+ if (styleDecl.state === undefined) {+ if (styleDecl.property === "width") {+ widthValue = styleDecl.value;+ }+ if (styleDecl.property === "height") {+ heightValue = styleDecl.value;+ }+ }+ }+ }++ const sortedBreakpoints = Array.from(breakpoints.values()).sort(compareMedia);+ const matchingBreakpoints: string[] = [];+ for (const breakpoint of sortedBreakpoints) {+ matchingBreakpoints.push(breakpoint.id);+ if (breakpoint.id === selectedBreakpointId) {+ break;+ }+ }++ const instanceStyles = stylesByInstanceId.get(instanceId);+ if (instanceStyles) {+ for (const breakpointId of matchingBreakpoints) {+ for (const styleDecl of instanceStyles) {+ if (+ styleDecl.breakpointId === breakpointId &&+ styleDecl.state === undefined+ ) {+ if (styleDecl.property === "width") {+ widthValue = styleDecl.value;+ }+ if (styleDecl.property === "height") {+ heightValue = styleDecl.value;+ }+ }+ }+ }+ }++ return {+ width: widthValue?.type === "unit" ? widthValue.value : undefined,+ height: heightValue?.type === "unit" ? heightValue.value : undefined,+ };+};++/**+ * Determine the inflation state for an element based on its actual dimensions+ * and whether explicit sizes are set. Returns `"w"`, `"h"`, `"wh"`, or `""`.+ *+ * Pure function for testability.+ */+const getInflationState = ({+ offsetWidth,+ offsetHeight,+ explicitWidth,+ explicitHeight,+}: {+ offsetWidth: number;+ offsetHeight: number;+ explicitWidth: number | undefined;+ explicitHeight: number | undefined;+}): string => {+ const inflateWidth =+ offsetWidth === 0 && explicitWidth === undefined ? "w" : "";+ const inflateHeight =+ offsetHeight === 0 && explicitHeight === undefined ? "h" : "";+ return inflateWidth + inflateHeight;+};++/**+ * Build a CSS selector to find the common ancestor of a set of instance IDs.+ * Falls back to `"body"` when `:has()` is not supported.+ *+ * Pure function for testability.+ */+const buildAncestorSelector = ({+ instanceIds,+ hasSelectorSupport,+}: {+ instanceIds: string[];+ hasSelectorSupport: boolean;+}): string => {+ if (!hasSelectorSupport) {+ return "body";+ }+ return `[${idAttribute}]${instanceIds+ .map((instanceId) => `:has([${idAttribute}="${instanceId}"])`)+ .join("")}`;+};++/**+ * Extract instanceIds from server sync store changes that affect style source selections.+ *+ * Pure function for testability.+ */+const extractInstanceIdsFromChanges = (+ changes: Array<{+ namespace: string;+ patches: Array<{ value?: { instanceId?: unknown } }>;+ }>+): string[] => {+ const ids: string[] = [];+ for (const change of changes) {+ if (change.namespace === "styleSourceSelections") {+ for (const patch of change.patches) {+ const instanceId = patch.value?.instanceId;+ if (typeof instanceId === "string") {+ ids.push(instanceId);+ }+ }+ }+ }+ return ids;+};++const MAX_SIZE_TO_USE_OPTIMIZATION = 50;++const findFirstNonContentsParent = (element: Element) => {+ let parent = element.parentElement;++ while (parent) {+ const computedStyle = window.getComputedStyle(parent);+ const isHidden = parent.getAttribute("hidden") !== null;++ if (computedStyle.display !== "contents" && !isHidden) {+ return parent;+ }++ parent = parent.parentElement;+ }++ return undefined;+};++const applyInflation = () => {+ const rootInstanceId = $selectedPage.get()?.rootInstanceId;++ // Below algorithm quickly finds the common ancestor of all elements with an instanceId.+ // However, for a large number of elements, it's more efficient to calculate from the root.+ // In almost all cases, if instanceIdsSet >= MAX_SIZE_TO_USE_OPTIMIZATION, it likely includes all elements.+ const instanceIds =+ instanceIdSet.size < MAX_SIZE_TO_USE_OPTIMIZATION+ ? Array.from(instanceIdSet)+ : rootInstanceId !== undefined+ ? [rootInstanceId]+ : [];++ instanceIdSet.clear();+ if (instanceIds.length === 0) {+ return;+ }++ const hasSelectorSupport = isSelectorSupported(":has(body)");++ const elementSelector = buildAncestorSelector({+ instanceIds,+ hasSelectorSupport,+ });++ const elements: Element[] = [];++ // Element itself or last common ancestor or body+ const baseElement =+ Array.from(document.querySelectorAll(elementSelector)).pop() ??+ document.body;+ elements.push(baseElement);++ const descendants = baseElement.querySelectorAll(`[${idAttribute}]`);+ elements.push(...descendants);++ const elementsToRecalculate: HTMLElement[] = [];+ const gridContainers = new Set<HTMLElement>();+ const parentsWithAbsoluteChildren = new Map<HTMLElement, number>();++ for (const element of elements) {+ if (!(element instanceof HTMLElement)) {+ continue;+ }++ if (skipElementsSet.has(element.tagName.toLowerCase())) {+ // Images should not collapse, and have a fallback.+ // The issue that unloaded image has 0 width and height until explicitly set,+ // so at the moment new Image added we detect it as collapsed.+ // Skip it for now.+ continue;+ }++ const elementStyle = window.getComputedStyle(element);++ // Collect grid containers for per-track inflation (step 5).+ // Runs regardless of child count — even grids with children need+ // their tracks wrapped to prevent empty cells from collapsing.+ if (+ elementStyle.display === "grid" ||+ elementStyle.display === "inline-grid"+ ) {+ gridContainers.add(element);+ }++ // Find all Leaf like elements+ // Leaf like elements are elements that have no children or all children are absolute or fixed+ // Excluding hidden elements without size+ if (element.childElementCount === 0) {+ if (element.offsetParent !== null) {+ elementsToRecalculate.push(element);+ }++ if (elementStyle.position === "fixed") {+ elementsToRecalculate.push(element);+ }+ }++ const parentElement = findFirstNonContentsParent(element);++ if (parentElement) {+ if (+ elementStyle.position === "absolute" ||+ elementStyle.position === "fixed" ||+ element.offsetParent == null // collapsed or none+ ) {+ parentsWithAbsoluteChildren.set(+ parentElement,+ parentsWithAbsoluteChildren.get(parentElement) ?? 0+ );+ } else {+ parentsWithAbsoluteChildren.set(parentElement, 1);+ }+ }+ }++ for (const [element, value] of parentsWithAbsoluteChildren.entries()) {+ // HTML is not part of webstudio data so skip to not process+ if (element.tagName === "HTML") {+ continue;+ }++ // All children are absolute or fixed+ if (value === 0) {+ elementsToRecalculate.push(element);+ }+ }++ // If most elements are inflated at the next step, scrollHeight becomes equal to clientHeight,+ // which resets the scroll position. To prevent this, we set the document's height to the current scrollHeight+ // to preserve the scroll position.+ // use nested element to avoid full page repaint and freeze on big projects+ let inflatorElement = document.querySelector(+ "#ws-inflator"+ ) as null | HTMLElement;+ if (!inflatorElement) {+ inflatorElement = document.createElement("div") as HTMLElement;+ inflatorElement.style.position = "absolute";+ inflatorElement.style.top = "0px";+ inflatorElement.style.left = "0px";+ inflatorElement.style.right = "0px";+ inflatorElement.setAttribute("id", "ws-inflator");+ inflatorElement.setAttribute("hidden", "true");+ // Mark that we are in the process of recalculating inflated elements+ // to avoid infinite loop of mutations+ doNotTrackMutation(inflatorElement);+ document.documentElement.appendChild(inflatorElement);+ }+ inflatorElement.removeAttribute("hidden");+ inflatorElement.style.height = `${document.documentElement.scrollHeight}px`;++ // Now combine all operations in batches.++ // 1. Remove all inflated attributes and grid inflation overrides.+ const clearInflation = (el: Element) => {+ const wasInflated = el.hasAttribute(inflatedAttribute);+ const wasGridInflated = el.hasAttribute(gridInflatedAttribute);+ el.removeAttribute(inflatedAttribute);+ el.removeAttribute(gridInflatedAttribute);+ if (el instanceof HTMLElement) {+ el.style.removeProperty("--ws-inflate-h");+ el.style.removeProperty("--ws-inflate-w");+ if (wasInflated || wasGridInflated) {+ el.style.removeProperty("grid-template-columns");+ el.style.removeProperty("grid-template-rows");+ }+ }+ };+ if (baseElement.parentElement) {+ clearInflation(baseElement.parentElement);+ }+ clearInflation(baseElement);+ for (const element of baseElement.querySelectorAll(+ `[${inflatedAttribute}], [${gridInflatedAttribute}]`+ )) {+ clearInflation(element);+ }++ // 2. Read stores once for all elements+ const metas = $registeredComponentMetas.get();+ const breakpoints = $breakpoints.get();+ const selectedBreakpoint = $selectedBreakpoint.get();+ const { stylesByInstanceId } = $stylesIndex.get();+ const allInstances = $instances.get();+ const selectedBreakpointId = selectedBreakpoint?.id;++ // 3. Calculate inflation state+ const inflatedElements = new Map<HTMLElement, string>();++ for (const element of elementsToRecalculate) {+ const elementInstanceId = element.getAttribute(idAttribute);++ if (elementInstanceId === null) {+ // Not a webstudio controlled element, like popover portal+ continue;+ }++ const tagName = element.tagName.toLowerCase();++ const elementSize = getInstanceSize({+ instanceId: elementInstanceId,+ tagName: isHtmlTag(tagName) ? tagName : undefined,+ metas,+ breakpoints,+ selectedBreakpointId,+ stylesByInstanceId,+ instances: allInstances,+ });++ // Grid containers with no children may have non-zero offsetHeight/offsetWidth+ // purely from gaps even though all tracks collapsed to 0px.+ // Detect this case and treat the dimension as 0 so inflation kicks in.+ let { offsetWidth, offsetHeight } = element;+ const elementComputedStyle = window.getComputedStyle(element);+ if (+ (elementComputedStyle.display === "grid" ||+ elementComputedStyle.display === "inline-grid") &&+ element.childElementCount === 0+ ) {+ const rows = parseGridTemplateTrackList(+ elementComputedStyle.gridTemplateRows+ );+ const cols = parseGridTemplateTrackList(+ elementComputedStyle.gridTemplateColumns+ );+ if (rows.length > 0 && rows.every((t) => t.value === "0px")) {+ offsetHeight = 0;+ }+ if (cols.length > 0 && cols.every((t) => t.value === "0px")) {+ offsetWidth = 0;+ }+ }++ const state = getInflationState({+ offsetWidth,+ offsetHeight,+ explicitWidth: elementSize.width,+ explicitHeight: elementSize.height,+ });++ if (state) {+ inflatedElements.set(element, state);+ }+ }++ // 4. Add inflated attributes for collapsed elements (dashed outline + padding).+ for (const [element, value] of inflatedElements.entries()) {+ element.setAttribute(inflatedAttribute, value);+ }++ // 5. Per-track grid inflation.+ // Only inflate tracks that resolved to 0px (empty/collapsed).+ // Skip inflation on axes that use auto-fit — the browser intentionally+ // collapses unused auto-fit tracks to 0px and they should stay hidden.+ for (const element of gridContainers) {+ const instanceId = element.getAttribute(idAttribute);+ const instanceStyles = instanceId+ ? stylesByInstanceId.get(instanceId)+ : undefined;++ const hasAutoFit = (property: string) =>+ instanceStyles?.some(+ (s) =>+ s.property === property &&+ s.value.type === "unparsed" &&+ s.value.value.includes("auto-fit")+ ) ?? false;++ const computedStyle = window.getComputedStyle(element);++ const cols = parseGridTemplateTrackList(computedStyle.gridTemplateColumns);+ if (+ !hasAutoFit("gridTemplateColumns") &&+ cols.length > 0 &&+ cols.some((t) => t.value === "0px")+ ) {+ element.style.gridTemplateColumns = cols+ .map((t) =>+ t.value === "0px" ? `minmax(${INFLATE_PADDING}px, 0px)` : t.value+ )+ .join(" ");+ }++ const rows = parseGridTemplateTrackList(computedStyle.gridTemplateRows);+ if (+ !hasAutoFit("gridTemplateRows") &&+ rows.length > 0 &&+ rows.some((t) => t.value === "0px")+ ) {+ element.style.gridTemplateRows = rows+ .map((t) =>+ t.value === "0px" ? `minmax(${INFLATE_PADDING}px, 0px)` : t.value+ )+ .join(" ");+ }++ element.setAttribute(gridInflatedAttribute, "");+ }++ inflatorElement.setAttribute("hidden", "true");+};++/**+ * When we add elements or edit element styles, a situation arises where an element can collapse+ * to 0 width, 0 height, or both. We need the user to be able to select such elements anyway.+ * We find the minimum set of elements that would otherwise collapse, set the inflatedAttribute+ * on them, and style helpers add padding to prevent collapsing.+ **/+export const inflateInstance = (instanceId: string, syncExec = false) => {+ instanceIdSet.add(instanceId);++ cancelAnimationFrame(rafHandle);++ if (syncExec) {+ applyInflation();+ return;+ }++ rafHandle = requestAnimationFrame(() => {+ applyInflation();+ });+};++/**+ * For optimisation reasons try to extract instanceId of changed elements from pubsub.+ * In that case we just check the subtree of parent/common ancestor of changed elements+ * to find elements that need inflation.+ **/+export const subscribeInflator = () => {+ return serverSyncStore.subscribe((_transactionId, changes) => {+ const ids = extractInstanceIdsFromChanges(changes);+ for (const id of ids) {+ inflateInstance(id);+ }+ });+};++export const __testing__ = {+ getInstanceSize,+ getInflationState,+ buildAncestorSelector,+ extractInstanceIdsFromChanges,+};diff --git a/apps/builder/app/canvas/instance-selected.ts b/apps/builder/app/canvas/instance-selected.tsindex 67688d0ea0..0c94293558 100644--- a/apps/builder/app/canvas/instance-selected.ts+++ b/apps/builder/app/canvas/instance-selected.ts@@ -27,7 +27,7 @@ import {} from "~/shared/dom-utils";import { subscribeScrollState } from "~/canvas/shared/scroll-state";import { $selectedInstanceOutline } from "~/shared/nano-states";-import { setDataCollapsed } from "~/canvas/collapsed";+import { inflateInstance } from "~/canvas/inflator";import type { InstanceSelector } from "~/shared/tree-utils";import { $awareness } from "~/shared/awareness";@@ -128,7 +128,7 @@ const subscribeSelectedInstance = ();};- const updateDataCollapsed = () => {+ const updateInflation = () => {if (visibleElements.length === 0) {return;}@@ -144,15 +144,15 @@ const subscribeSelectedInstance = (continue;}- setDataCollapsed(instanceSelector[0], false);+ inflateInstance(instanceSelector[0], false);}- // Synchronously execute setDataCollapsed to calculate right outline- // This fixes an issue, when new element outline was calculated before collapsed elements calculations- setDataCollapsed(instanceId, true);+ // Synchronously execute inflateInstance to calculate right outline+ // This fixes an issue, when new element outline was calculated before inflation calculations+ inflateInstance(instanceId, true);};- updateDataCollapsed();+ updateInflation();const showOutline = () => {if ($isResizingCanvas.get()) {@@ -214,9 +214,13 @@ const subscribeSelectedInstance = (const update = () => {debounceEffect(() => {updateElements();+ // Disconnect before inflation so the observer doesn't see+ // the inline style changes inflation makes on the parent element.+ // updateObservers() reconnects after.+ mutationObserver.disconnect();// Having hover etc, element can have no size because of that// Newly created element can have 0 size- updateDataCollapsed();+ updateInflation();// contentRect has wrong x/y values for absolutely positioned element.// getBoundingClientRect is used instead.showOutline();diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.tsindex 731d73439a..15b36eca07 100644--- a/apps/builder/app/canvas/shared/styles.ts+++ b/apps/builder/app/canvas/shared/styles.ts@@ -13,7 +13,8 @@ import {createImageValueTransformer,addFontRules,} from "@webstudio-is/sdk";-import { collapsedAttribute, idAttribute } from "@webstudio-is/react-sdk";+import { inflatedAttribute, idAttribute } from "@webstudio-is/react-sdk";+import { INFLATE_PADDING } from "~/canvas/inflator";import { isPseudoElement, parseMediaCondition } from "@webstudio-is/css-data";import {StyleValue,@@ -74,10 +75,6 @@ export const editablePlaceholderAttribute = "data-ws-editable-placeholder";// https://developer.mozilla.org/en-US/docs/Web/CSS/attr#backwards_compatibilityexport const editingPlaceholderVariable = "--ws-editing-placeholder";-// Minimum size to prevent elements from collapsing to zero dimensions on canvas-// This value provides enough visual space to see and interact with empty elements-const collapsePadding = "50px";-const hasExpressionChildren = (instance: Instance) =>instance.children.some((child) => child.type === "expression");@@ -107,7 +104,7 @@ const helperStylesShared = [`,// Using :where allows to prevent increasing specificity, so that helper is overwritten by user styles.- `[${idAttribute}]:where([${collapsedAttribute}]:not(body)) {+ `[${idAttribute}]:where([${inflatedAttribute}]:not(body)) {outline: 1px dashed rgba(0,0,0,0.7);outline-offset: -1px;box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.7);@@ -119,17 +116,21 @@ const helperStylesShared = [// 3. We prevent this by excluding elements with `data-lexical-editor`.// 4. This rule is used here and not in collapsing detection because `data-lexical-editor` might not be set instantly.// Mistakes in collapsing will be corrected in the next cycle.- `[${idAttribute}]:where(:not(body):not([data-lexical-editor])[${collapsedAttribute}="w"]) {- padding-right: ${collapsePadding};+ // Grid containers use track-level minmax() inflation (applied inline by+ // inflator.ts) instead of padding, so we skip padding for elements that+ // have inline grid-template-columns or grid-template-rows (i.e. grids).+ // Non-grid elements fall back to the default INFLATE_PADDING.+ `[${idAttribute}]:where(:not(body):not([data-lexical-editor]):not([style*="grid-template"])[${inflatedAttribute}="w"]) {+ padding-right: ${INFLATE_PADDING}px;}`,// Has no height, will collapse- `[${idAttribute}]:where(:not(body):not([data-lexical-editor])[${collapsedAttribute}="h"]) {- padding-top: ${collapsePadding};+ `[${idAttribute}]:where(:not(body):not([data-lexical-editor]):not([style*="grid-template"])[${inflatedAttribute}="h"]) {+ padding-top: ${INFLATE_PADDING}px;}`,// Has no width or height, will collapse- `[${idAttribute}]:where(:not(body):not([data-lexical-editor])[${collapsedAttribute}="wh"]) {- padding-right: ${collapsePadding};- padding-top: ${collapsePadding};+ `[${idAttribute}]:where(:not(body):not([data-lexical-editor]):not([style*="grid-template"])[${inflatedAttribute}="wh"]) {+ padding-right: ${INFLATE_PADDING}px;+ padding-top: ${INFLATE_PADDING}px;}`,`[${idAttribute}][contenteditable], [${idAttribute}]:focus {outline: 0;diff --git a/apps/builder/app/shared/copy-paste/init-copy-paste.ts b/apps/builder/app/shared/copy-paste/init-copy-paste.tsindex cb2d3cc576..df17f49b8e 100644--- a/apps/builder/app/shared/copy-paste/init-copy-paste.ts+++ b/apps/builder/app/shared/copy-paste/init-copy-paste.ts@@ -46,7 +46,7 @@ const validateClipboardEvent = (event: ClipboardEvent) => {return false;}- // Allows native selection of text in the Builder panels, such as CSS Preview.+ // Allows native selection of text in the Builder panels, such as CSS preview.if (event.type === "copy") {const isInBuilderContext = window.self === window.top;const selection = window.getSelection();diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex 22762c9039..cc99fd6e8a 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -1693,7 +1693,7 @@ export const findClosestInsertable = (const instanceSelector = from?.parentSelector ??awareness?.instanceSelector ?? [selectedPage.rootInstanceId];if (instanceSelector[0] === ROOT_INSTANCE_ID) {- toast.error(`Cannot insert into Global Root`);+ toast.error(`Cannot insert into Global root`);return;}const metas = $registeredComponentMetas.get();diff --git a/apps/builder/app/shared/nano-states/canvas.ts b/apps/builder/app/shared/nano-states/canvas.tsindex b4758161f8..e3d962286a 100644--- a/apps/builder/app/shared/nano-states/canvas.ts+++ b/apps/builder/app/shared/nano-states/canvas.ts@@ -185,3 +185,28 @@ export const $canvasIframeState = atom<"idle" | "ready">("idle");export const $detectedFontsWeights = atom<Map<string, Array<FontWeight>>>(new Map());++export type GridCellData = {+ instanceId: Instance["id"];+ columnCount: number;+ rowCount: number;+ // Raw bounding client rect (post-transform). The builder recovers the+ // untransformed position by probing a hidden element with the same CSS.+ bcr: { top: number; left: number };+ // Untransformed border-box dimensions from offsetWidth/offsetHeight.+ untransformedWidth: number;+ untransformedHeight: number;+ // CSS text built from getComputedStyle on the canvas element.+ // Applied verbatim to the builder overlay mirror div via style.cssText.+ // Adding a new synced property = one line in the whitelist array+ // in grid-guide-utils.ts.+ resolvedCssText: string;+ // Index of the first implicit column track (0-based), or columnCount+ // when all tracks are explicit.+ implicitColumnStart: number;+ // Index of the first implicit row track (0-based), or rowCount+ // when all tracks are explicit.+ implicitRowStart: number;+};++export const $gridCellData = atom<GridCellData | undefined>(undefined);diff --git a/apps/builder/app/shared/style-object-model.ts b/apps/builder/app/shared/style-object-model.tsindex a546606db3..d4fc00bff0 100644--- a/apps/builder/app/shared/style-object-model.ts+++ b/apps/builder/app/shared/style-object-model.ts@@ -47,7 +47,7 @@ import {* invalidate model* lazily recompute all properties*- * 3. CSS Preview+ * 3. CSS preview** all properties are collected from instance selector* property are iterated with own model and computeddiff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex 74a7a1224f..21c3c7df05 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -43,6 +43,7 @@ import {$selectedInstanceOutline,$blockChildOutline,$textToolbar,+ $gridCellData,$registeredComponentMetas,$registeredTemplates,$modifierKeys,@@ -138,6 +139,7 @@ export const createObjectPool = () => {new NanostoresSyncObject("blockChildOutline", $blockChildOutline),new NanostoresSyncObject("instanceContextMenu", $instanceContextMenu),new NanostoresSyncObject("modifierKeys", $modifierKeys),+ new NanostoresSyncObject("gridCellData", $gridCellData),new NanostoresSyncObject("collaborativeInstanceSelector",$collaborativeInstanceSelectordiff --git a/apps/builder/package.json b/apps/builder/package.jsonindex 7e1d6cf1b9..8cfa0e3adc 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -11,9 +11,8 @@"build:webflow-presets": "pnpm css-to-ws ./app/shared/copy-paste/plugin-webflow/style-presets.css ./app/shared/copy-paste/plugin-webflow/__generated__/style-presets.ts","build:tailwind-preflight": "tsx --conditions=webstudio ./app/shared/tailwind/preflight-bin.ts && prettier --write ./app/shared/tailwind/__generated__/preflight.ts","start": "remix-serve build/server/index.js",- "build:http-client": "pnpm --filter=@webstudio-is/http-client build",- "dev": "pnpm build:http-client && remix vite:dev",- "dev:auth": "pnpm build:http-client && DEBUG=OAuth2Strategy,ws:* remix vite:dev",+ "dev": "remix vite:dev",+ "dev:auth": "DEBUG=OAuth2Strategy,ws:* remix vite:dev","typecheck": "tsgo --noEmit --emitDeclarationOnly false","test": "vitest run"},diff --git a/fixtures/react-router-cloudflare/app/__generated__/index.css b/fixtures/react-router-cloudflare/app/__generated__/index.cssindex cea53af775..bae88880bc 100644--- a/fixtures/react-router-cloudflare/app/__generated__/index.css+++ b/fixtures/react-router-cloudflare/app/__generated__/index.css@@ -2,6 +2,8 @@:root {display: grid;min-height: 100%;+ grid-template-rows: auto;+ grid-template-columns: 1fr;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;diff --git a/fixtures/react-router-docker/app/__generated__/index.css b/fixtures/react-router-docker/app/__generated__/index.cssindex cea53af775..bae88880bc 100644--- a/fixtures/react-router-docker/app/__generated__/index.css+++ b/fixtures/react-router-docker/app/__generated__/index.css@@ -2,6 +2,8 @@:root {display: grid;min-height: 100%;+ grid-template-rows: auto;+ grid-template-columns: 1fr;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;diff --git a/fixtures/react-router-netlify/app/__generated__/index.css b/fixtures/react-router-netlify/app/__generated__/index.cssindex cea53af775..bae88880bc 100644--- a/fixtures/react-router-netlify/app/__generated__/index.css+++ b/fixtures/react-router-netlify/app/__generated__/index.css@@ -2,6 +2,8 @@:root {display: grid;min-height: 100%;+ grid-template-rows: auto;+ grid-template-columns: 1fr;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;diff --git a/fixtures/react-router-vercel/app/__generated__/index.css b/fixtures/react-router-vercel/app/__generated__/index.cssindex cea53af775..bae88880bc 100644--- a/fixtures/react-router-vercel/app/__generated__/index.css+++ b/fixtures/react-router-vercel/app/__generated__/index.css@@ -2,6 +2,8 @@:root {display: grid;min-height: 100%;+ grid-template-rows: auto;+ grid-template-columns: 1fr;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/index.css b/fixtures/ssg-netlify-by-project-id/app/__generated__/index.cssindex 4ee35065c1..cd9e1ffa2b 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/index.css+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/index.css@@ -2,6 +2,8 @@:root {display: grid;min-height: 100%;+ grid-template-rows: auto;+ grid-template-columns: 1fr;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;diff --git a/fixtures/ssg/app/__generated__/index.css b/fixtures/ssg/app/__generated__/index.cssindex cea53af775..bae88880bc 100644--- a/fixtures/ssg/app/__generated__/index.css+++ b/fixtures/ssg/app/__generated__/index.css@@ -2,6 +2,8 @@:root {display: grid;min-height: 100%;+ grid-template-rows: auto;+ grid-template-columns: 1fr;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/index.css b/fixtures/webstudio-cloudflare-template/app/__generated__/index.cssindex cea53af775..bae88880bc 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/index.css+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/index.css@@ -2,6 +2,8 @@:root {display: grid;min-height: 100%;+ grid-template-rows: auto;+ grid-template-columns: 1fr;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;diff --git a/fixtures/webstudio-features/app/__generated__/index.css b/fixtures/webstudio-features/app/__generated__/index.cssindex dc5b37af56..9590a0d588 100644--- a/fixtures/webstudio-features/app/__generated__/index.css+++ b/fixtures/webstudio-features/app/__generated__/index.css@@ -2,6 +2,8 @@:root {display: grid;min-height: 100%;+ grid-template-rows: auto;+ grid-template-columns: 1fr;font-family: Arial, Roboto, sans-serif;font-size: 16px;line-height: 1.2;diff --git a/packages/css-data/src/__generated__/keyword-values.ts b/packages/css-data/src/__generated__/keyword-values.tsindex 569c436de3..0ccefb0230 100644--- a/packages/css-data/src/__generated__/keyword-values.ts+++ b/packages/css-data/src/__generated__/keyword-values.ts@@ -15,6 +15,16 @@ export const keywordValues: KeywordValues = {"view-timeline-name": [],"scroll-timeline-name": [],"view-timeline-inset": [],+ "grid-auto-flow": [+ "row",+ "column",+ "dense",+ "row dense",+ "column dense",+ "initial",+ "inherit",+ "unset",+ ],"list-style-type": ["disc","circle",@@ -3933,7 +3943,6 @@ export const keywordValues: KeywordValues = {"inherit","unset",],- "grid-auto-flow": ["row", "column", "dense", "initial", "inherit", "unset"],"grid-auto-rows": ["min-content","max-content",diff --git a/packages/css-data/src/__generated__/property-value-descriptions.ts b/packages/css-data/src/__generated__/property-value-descriptions.tsindex a011525459..ebf8bd5aa6 100644--- a/packages/css-data/src/__generated__/property-value-descriptions.ts+++ b/packages/css-data/src/__generated__/property-value-descriptions.ts@@ -1,9 +1,11 @@// This file was auto-generatedexport const propertiesGenerated = {accentColor: "Sets the color used for highlighting user interface controls.",- alignContent: "Aligns a flex container's lines within the flex container.",- alignItems: "Aligns items along the cross axis of a flex container.",- alignSelf: "Aligns a flex item along the cross axis of its container.",+ alignContent:+ "Aligns and distributes content along the cross/block axis of a flex or grid container.",+ alignItems:+ "Aligns items along the cross/block axis within a flex or grid container.",+ alignSelf: "Aligns an item along the cross/block axis within its container.",alignTracks: "Defines how tracks are aligned in a grid container.",animationComposition: "Specifies whether an animation is additive or not.",animationDelay: "Defines a delay for the start of an animation.",@@ -221,10 +223,11 @@ export const propertiesGenerated = {"Sets the inline-start position of an element relative to its nearest positioned ancestor.",isolation:"Determines whether an element should create a new stacking context.",- justifyContent: "Aligns flex items along the main axis of their container.",+ justifyContent:+ "Aligns and distributes content along the main/inline axis of a flex or grid container.",justifyItems:- "Aligns items inside a grid cell along both the row and column axis.",- justifySelf: "Aligns a grid item along both the row and column axis.",+ "Aligns items along the inline axis within a flex or grid container.",+ justifySelf: "Aligns an item along the inline axis within its container.",justifyTracks: "Aligns grid tracks along the row or column axis.",left: "Sets the left position of an element relative to its nearest positioned ancestor.",letterSpacing: "Controls the spacing between characters in a block of text.",@@ -297,7 +300,8 @@ export const propertiesGenerated = {offsetRotate:"Controls the rotation of an element around a fixed point in degrees.",opacity: "Controls the transparency of an element.",- order: "Controls the order in which an element appears in a flex container.",+ order:+ "Controls the order in which an element appears within its flex or grid container.",orphans: "Controls the minimum number of lines for the last line of a block.",outlineColor: "Controls the color of an element's outline.",outlineOffset:@@ -570,9 +574,9 @@ export const propertiesGenerated = {padding: "Sets the padding on all four sides of an element at once.","padding-block": "Sets the padding on the block axis of an element.","padding-inline": "Sets the padding on the inline axis of an element.",- "place-content": "Aligns a flex container's lines within it.",- "place-items": "Aligns a flex container's items within it.",- "place-self": "Allows the default alignment of a flex item to be overridden.",+ "place-content": "Shorthand for align-content and justify-content.",+ "place-items": "Shorthand for align-items and justify-items.",+ "place-self": "Shorthand for align-self and justify-self.","scroll-margin": "Controls the top and bottom sides of the scrollbar","scroll-margin-block": "Controls the top and bottom sides of the scrollbar","scroll-margin-inline": "Controls the left and right sides of the scrollbar",@@ -633,27 +637,28 @@ export const properties = {export const declarationsGenerated = {"alignContent:normal":- "Aligns and distributes grid items along the cross axis with different spacing options.",+ "Aligns and distributes items along the cross/block axis with default spacing.","alignContent:first":- "Aligns and distributes grid items along the cross axis, prioritizing the first line.",+ "Aligns and distributes items along the cross/block axis, prioritizing the first line.","alignContent:last":- "Aligns and distributes grid items along the cross axis, prioritizing the last line.",- "alignContent:baseline": "Aligns grid items with their baselines.",+ "Aligns and distributes items along the cross/block axis, prioritizing the last line.",+ "alignContent:baseline": "Aligns items with their baselines.","alignContent:space-between":- "Aligns and distributes grid items with equal space between them.",+ "Aligns and distributes items with equal space between them.","alignContent:space-around":- "Aligns and distributes grid items with equal space around them.",+ "Aligns and distributes items with equal space around them.","alignContent:space-evenly":- "Aligns and distributes grid items with equal space between them and around the edges.",- "alignContent:stretch": "Stretches grid items to fill the container.",+ "Aligns and distributes items with equal space between them and around the edges.",+ "alignContent:stretch": "Stretches items to fill the container.","alignContent:unsafe": "Enables alignment modes that are considered risky.","alignContent:safe": "Enables alignment modes that are safe to use.",- "alignContent:center": "Centers and aligns grid items to the center.",- "alignContent:start": "Aligns grid items to the start of the container.",- "alignContent:end": "Aligns grid items to the end of the container.",+ "alignContent:center": "Centers items along the cross/block axis.",+ "alignContent:start": "Aligns items to the start of the container.",+ "alignContent:end": "Aligns items to the end of the container.","alignContent:flex-start":- "Aligns grid items to the start of the first line.",- "alignContent:flex-end": "Aligns grid items to the end of the last line.",+ "Aligns items to the start of the container (same as start).",+ "alignContent:flex-end":+ "Aligns items to the end of the container (same as end).","alignContent:initial": "Sets the default alignment for align-content.","alignContent:inherit":"The element inherits the align-content value of its parent.",@@ -663,8 +668,8 @@ export const declarationsGenerated = {"The default, stretches the element vertically depending on the height of the container.","alignItems:stretch":"Stretches the element vertically to fill the container.",- "alignItems:first": "Stretches flex items from the first baseline.",- "alignItems:last": "Stretches flex items from the last baseline.",+ "alignItems:first": "Aligns items from the first baseline.",+ "alignItems:last": "Aligns items from the last baseline.","alignItems:baseline":"Aligns the element with the baseline of the parent container.","alignItems:unsafe":@@ -678,29 +683,31 @@ export const declarationsGenerated = {"alignItems:self-start": "Aligns the element at the start of itself.","alignItems:self-end": "Aligns the element at the end of itself.","alignItems:flex-start":- "Aligns the element at the start of the flex container.",- "alignItems:flex-end": "Aligns the element at the end of the flex container.",+ "Aligns items at the start of the container (same as start).",+ "alignItems:flex-end":+ "Aligns items at the end of the container (same as end).","alignItems:initial": "Items are aligned to their default position.","alignItems:inherit":"Inherits the align-items property from the parent element.","alignItems:unset": "Resets the align-items property to its default value.",- "alignSelf:auto": "Default alignment for the individual flex item.",+ "alignSelf:auto": "Uses the parent's align-items value.","alignSelf:normal":- 'Same as "stretch", but only for flex items that haven\'t specified a `flex-basis` value.',- "alignSelf:stretch": "Stretch to fill the container (the default value).",- "alignSelf:first": "Places the item at the start of the cross axis.",- "alignSelf:last": "Places the item at the end of the cross axis.",+ "Behaves as stretch or start depending on the layout mode.",+ "alignSelf:stretch": "Stretches to fill the container.",+ "alignSelf:first": "Places the item at the start of the cross/block axis.",+ "alignSelf:last": "Places the item at the end of the cross/block axis.","alignSelf:baseline":- "Aligns the baseline of the flex item with the baseline of the parent container.",+ "Aligns the item's baseline with the baseline of other items.","alignSelf:unsafe": "Enables a kind of backwards compatibility mode.","alignSelf:safe": "Applies all but potentially hazardous alignment values.",- "alignSelf:center": "Centers the flex item vertically.",- "alignSelf:start": "Places the item at the start of the cross axis.",- "alignSelf:end": "Places the item at the end of the cross axis.",- "alignSelf:self-start": "Places the item at the start of the cross axis.",- "alignSelf:self-end": "Places the item at the end of the cross axis.",- "alignSelf:flex-start": "Aligns flex items to the start of the cross axis.",- "alignSelf:flex-end": "Aligns flex items to the end of the cross axis.",+ "alignSelf:center": "Centers the item along the cross/block axis.",+ "alignSelf:start": "Places the item at the start of the cross/block axis.",+ "alignSelf:end": "Places the item at the end of the cross/block axis.",+ "alignSelf:self-start":+ "Places the item at the start of the cross/block axis.",+ "alignSelf:self-end": "Places the item at the end of the cross/block axis.",+ "alignSelf:flex-start": "Places the item at the start (same as start).",+ "alignSelf:flex-end": "Places the item at the end (same as end).","alignSelf:initial": "Sets the align-self property to its default value.","alignSelf:inherit":"Inherits the align-self property from its parent element.",@@ -729,9 +736,9 @@ export const declarationsGenerated = {"alignTracks:start": "Aligns the grid tracks to the start of the grid area.","alignTracks:end": "Aligns the grid tracks to the end of the grid area.","alignTracks:flex-start":- "Aligns the grid tracks to the start of the flex container.",+ "Aligns the grid tracks to the start of the container (same as start).","alignTracks:flex-end":- "Aligns the grid tracks to the end of the flex container.",+ "Aligns the grid tracks to the end of the container (same as end).","alignTracks:initial": "Sets the alignment to its default value.","alignTracks:inherit": "Inherits the alignment from its parent element.","alignTracks:unset": "Resets the alignment to its natural value.",@@ -2413,56 +2420,44 @@ export const declarationsGenerated = {"justifyContent:unset":"Resets the property to its default value if it has been set before, otherwise behaves like inherit.","justifyItems:normal":- "The grid items are aligned according to the default alignment for the items.",- "justifyItems:stretch": "The grid items are stretched to fill the grid area.",+ "Items are aligned according to the default alignment.",+ "justifyItems:stretch": "Items are stretched to fill the container.","justifyItems:first": "Invalid value.","justifyItems:last": "Invalid value.",- "justifyItems:baseline":- "The grid items are aligned such that their baselines align.",- "justifyItems:unsafe":- "The grid items are aligned as if `start` if values are unsafe.",- "justifyItems:safe":- "The grid items are aligned as if `center` if values are unsafe.",- "justifyItems:center": "The grid items are centered in the grid area.",- "justifyItems:start":- "The grid items are aligned to the start of the grid area.",- "justifyItems:end": "The grid items are aligned to the end of the grid area.",+ "justifyItems:baseline": "Items are aligned such that their baselines align.",+ "justifyItems:unsafe": "Allows alignment that may cause overflow.",+ "justifyItems:safe": "Prevents alignment that may cause overflow.",+ "justifyItems:center": "Items are centered along the inline axis.",+ "justifyItems:start": "Items are aligned to the start of the inline axis.",+ "justifyItems:end": "Items are aligned to the end of the inline axis.","justifyItems:self-start":- "The grid items are aligned to the start of the grid area for their respective axis.",+ "Items are aligned to the start of their respective inline axis.","justifyItems:self-end":- "The grid items are aligned to the end of the grid area for their respective axis.",- "justifyItems:flex-start":- "The grid items are aligned to the start of the axis lines.",- "justifyItems:flex-end":- "The grid items are aligned to the end of the axis lines.",- "justifyItems:left":- "The grid items are aligned to the left of the grid area container.",- "justifyItems:right":- "The grid items are aligned to the right of the grid area container.",+ "Items are aligned to the end of their respective inline axis.",+ "justifyItems:flex-start": "Items are aligned to the start (same as start).",+ "justifyItems:flex-end": "Items are aligned to the end (same as end).",+ "justifyItems:left": "Items are aligned to the left of the container.",+ "justifyItems:right": "Items are aligned to the right of the container.","justifyItems:legacy": "Aligns items according to their legacy alignment.","justifyItems:initial": "Sets the alignment to its default value.","justifyItems:inherit": "Inherits the alignment from its parent element.","justifyItems:unset": "Resets the alignment to its inherited value.",- "justifySelf:auto": "The browser selects the alignment.",+ "justifySelf:auto": "Uses the parent's justify-items value.","justifySelf:normal":- "The browser places the item according to the container's alignment rules.",+ "The item is placed according to the container's alignment rules.","justifySelf:stretch": "Stretches the item to fit the container.",- "justifySelf:first": "Places the item at the start of the grid area.",- "justifySelf:last": "Places the item at the end of the grid area.",+ "justifySelf:first": "Places the item at the start of the inline axis.",+ "justifySelf:last": "Places the item at the end of the inline axis.","justifySelf:baseline": "Aligns the item along the baseline.",- "justifySelf:unsafe": "Allows the item to be placed outside the grid area.",- "justifySelf:safe":- "Prevents the item from being placed outside the grid area.",- "justifySelf:center": "Centers the item horizontally.",- "justifySelf:start": "Places the item at the start of the row.",- "justifySelf:end": "Places the item at the end of the row.",- "justifySelf:self-start": "Aligns the item at the start of its grid area.",- "justifySelf:self-end":- "Aligns the content of a grid item to the end of its grid cell along the inline (row) axis.",- "justifySelf:flex-start":- "Aligns a flex item to the start (beginning) of the container along the main axis.",- "justifySelf:flex-end":- "Aligns a flex item to the end of the container along the main axis.",+ "justifySelf:unsafe": "Allows alignment that may cause overflow.",+ "justifySelf:safe": "Prevents alignment that may cause overflow.",+ "justifySelf:center": "Centers the item along the inline axis.",+ "justifySelf:start": "Places the item at the start of the inline axis.",+ "justifySelf:end": "Places the item at the end of the inline axis.",+ "justifySelf:self-start": "Aligns the item at the start of its inline axis.",+ "justifySelf:self-end": "Aligns the item at the end of its inline axis.",+ "justifySelf:flex-start": "Places the item at the start (same as start).",+ "justifySelf:flex-end": "Places the item at the end (same as end).","justifySelf:left":"Aligns the content of an element to the left of its container.","justifySelf:right":@@ -2494,9 +2489,9 @@ export const declarationsGenerated = {"justifyTracks:end":"Aligns justification content to the end of the grid area.","justifyTracks:flex-start":- "Aligns justification content to the start of the flex container.",+ "Aligns tracks to the start of the container (same as start).","justifyTracks:flex-end":- "Aligns justification content to the end of the flex container.",+ "Aligns tracks to the end of the container (same as end).","justifyTracks:left":"Aligns justification content to the left of the grid area.","justifyTracks:right":@@ -4455,7 +4450,12 @@ export const declarationsGenerated = {"zoom:unset": "Unsets the zoom level, allowing the browser to decide.",} as Record<string, string | undefined>;-export const declarationsOverrides = {} as Record<string, string | undefined>;+export const declarationsOverrides = {+ "gridAutoFlow:row dense":+ "Grid items are placed along rows, filling in holes earlier in the grid when smaller items appear later.",+ "gridAutoFlow:column dense":+ "Grid items are placed along columns, filling in holes earlier in the grid when smaller items appear later.",+} as Record<string, string | undefined>;export const declarations = {...declarationsGenerated,diff --git a/packages/css-data/src/custom-data.ts b/packages/css-data/src/custom-data.tsindex a55ae9c394..7b4c6a0740 100644--- a/packages/css-data/src/custom-data.ts+++ b/packages/css-data/src/custom-data.ts@@ -80,6 +80,18 @@ propertiesData["view-timeline-inset"] = {};keywordValues["view-timeline-inset"] = [];+// Add combined values for grid-auto-flow that mdn-data doesn't include+keywordValues["grid-auto-flow"] = [+ "row",+ "column",+ "dense",+ "row dense",+ "column dense",+ "initial",+ "inherit",+ "unset",+];+keywordValues["list-style-type"] = ["disc","circle",diff --git a/packages/css-data/src/property-parsers/grid-template-areas.test.ts b/packages/css-data/src/property-parsers/grid-template-areas.test.tsnew file mode 100644index 0000000000..66cfb12720--- /dev/null+++ b/packages/css-data/src/property-parsers/grid-template-areas.test.ts@@ -0,0 +1,158 @@+import { describe, test, expect } from "vitest";+import { parseGridAreas } from "./grid-template-areas";++describe("parseGridAreas", () => {+ test("parses empty or none value", () => {+ expect(parseGridAreas("")).toEqual([]);+ expect(parseGridAreas("none")).toEqual([]);+ });++ test("parses single area", () => {+ const result = parseGridAreas('"header"');+ expect(result).toEqual([+ {+ name: "header",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ },+ ]);+ });++ test("parses area spanning multiple columns", () => {+ const result = parseGridAreas('"header header header"');+ expect(result).toEqual([+ {+ name: "header",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 2,+ },+ ]);+ });++ test("parses multiple areas in one row", () => {+ const result = parseGridAreas('"sidebar main"');+ expect(result).toHaveLength(2);+ expect(result).toContainEqual({+ name: "sidebar",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ });+ expect(result).toContainEqual({+ name: "main",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ });+ });++ test("parses area spanning multiple rows", () => {+ const result = parseGridAreas('"sidebar main" "sidebar footer"');+ expect(result).toHaveLength(3);+ expect(result).toContainEqual({+ name: "sidebar",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 3,+ });+ });++ test("parses complex layout with multiple rows and columns", () => {+ const result = parseGridAreas(+ '"header header" "sidebar main" "footer footer"'+ );+ expect(result).toHaveLength(4);+ expect(result).toContainEqual({+ name: "header",+ columnStart: 1,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 2,+ });+ expect(result).toContainEqual({+ name: "sidebar",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 2,+ rowEnd: 3,+ });+ expect(result).toContainEqual({+ name: "main",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ });+ expect(result).toContainEqual({+ name: "footer",+ columnStart: 1,+ columnEnd: 3,+ rowStart: 3,+ rowEnd: 4,+ });+ });++ test("ignores dots (empty cells)", () => {+ const result = parseGridAreas('"header ." ". main"');+ expect(result).toHaveLength(2);+ expect(result).toContainEqual({+ name: "header",+ columnStart: 1,+ columnEnd: 2,+ rowStart: 1,+ rowEnd: 2,+ });+ expect(result).toContainEqual({+ name: "main",+ columnStart: 2,+ columnEnd: 3,+ rowStart: 2,+ rowEnd: 3,+ });+ });++ test("returns empty array for invalid value", () => {+ expect(parseGridAreas("not-valid-areas")).toEqual([]);+ });++ test("parses area spanning both rows and columns", () => {+ const result = parseGridAreas(+ '"logo logo nav" "logo logo content" "footer footer footer"'+ );+ expect(result).toContainEqual({+ name: "logo",+ columnStart: 1,+ columnEnd: 3,+ rowStart: 1,+ rowEnd: 3,+ });+ expect(result).toContainEqual({+ name: "nav",+ columnStart: 3,+ columnEnd: 4,+ rowStart: 1,+ rowEnd: 2,+ });+ expect(result).toContainEqual({+ name: "content",+ columnStart: 3,+ columnEnd: 4,+ rowStart: 2,+ rowEnd: 3,+ });+ expect(result).toContainEqual({+ name: "footer",+ columnStart: 1,+ columnEnd: 4,+ rowStart: 3,+ rowEnd: 4,+ });+ });+});diff --git a/packages/css-data/src/property-parsers/grid-template-areas.ts b/packages/css-data/src/property-parsers/grid-template-areas.tsnew file mode 100644index 0000000000..5b5ebb674d--- /dev/null+++ b/packages/css-data/src/property-parsers/grid-template-areas.ts@@ -0,0 +1,68 @@+import { cssTryParseValue } from "../parse-css-value";++export type AreaInfo = {+ name: string;+ columnStart: number;+ columnEnd: number;+ rowStart: number;+ rowEnd: number;+};++/**+ * Parse grid-template-areas CSS string into structured area information.+ * Uses css-tree to parse the value into String AST nodes,+ * then extracts cell names from each row string.+ *+ * @example+ * parseGridAreas('"header header" "sidebar main"')+ * // Returns: [+ * // { name: 'header', columnStart: 1, columnEnd: 3, rowStart: 1, rowEnd: 2 },+ * // { name: 'sidebar', columnStart: 1, columnEnd: 2, rowStart: 2, rowEnd: 3 },+ * // { name: 'main', columnStart: 2, columnEnd: 3, rowStart: 2, rowEnd: 3 }+ * // ]+ */+export const parseGridAreas = (value: string): AreaInfo[] => {+ if (!value || value === "none") {+ return [];+ }++ const ast = cssTryParseValue(value);+ if (ast === undefined || ast.type !== "Value") {+ return [];+ }++ const areaMap = new Map<string, AreaInfo>();+ let rowIndex = 0;++ for (const node of ast.children) {+ // Each row in grid-template-areas is a quoted string → String node+ if (node.type !== "String") {+ continue;+ }++ const names = node.value.split(/\s+/).filter(Boolean);+ for (let colIndex = 0; colIndex < names.length; colIndex++) {+ const name = names[colIndex];+ if (name === ".") {+ continue;+ }+ const existing = areaMap.get(name);+ if (existing === undefined) {+ areaMap.set(name, {+ name,+ columnStart: colIndex + 1,+ columnEnd: colIndex + 2,+ rowStart: rowIndex + 1,+ rowEnd: rowIndex + 2,+ });+ } else {+ existing.columnEnd = Math.max(existing.columnEnd, colIndex + 2);+ existing.rowEnd = Math.max(existing.rowEnd, rowIndex + 2);+ }+ }++ rowIndex++;+ }++ return Array.from(areaMap.values());+};diff --git a/packages/css-data/src/property-parsers/grid-template-tracks.test.ts b/packages/css-data/src/property-parsers/grid-template-tracks.test.tsnew file mode 100644index 0000000000..ea376ffe56--- /dev/null+++ b/packages/css-data/src/property-parsers/grid-template-tracks.test.ts@@ -0,0 +1,447 @@+import { describe, test, expect } from "vitest";+import {+ parseGridTemplateTrackList,+ serializeGridTemplateTrackList,+ parseMinmax,+ serializeMinmax,+ checkGridTemplateSupport,+ getGridAxisMode,+ isImplicitGridMode,+ isEditableGridMode,+ getGridAxisLabel,+} from "./grid-template-tracks";++describe("parseGridTemplateTrackList", () => {+ test("returns empty array for 'none'", () => {+ expect(parseGridTemplateTrackList("none")).toEqual([]);+ });++ test("returns empty array for empty string", () => {+ expect(parseGridTemplateTrackList("")).toEqual([]);+ });++ test("parses simple fr units", () => {+ expect(parseGridTemplateTrackList("1fr")).toEqual([{ value: "1fr" }]);+ expect(parseGridTemplateTrackList("1fr 2fr")).toEqual([+ { value: "1fr" },+ { value: "2fr" },+ ]);+ expect(parseGridTemplateTrackList("1fr 2fr 3fr")).toEqual([+ { value: "1fr" },+ { value: "2fr" },+ { value: "3fr" },+ ]);+ });++ test("parses pixel values", () => {+ expect(parseGridTemplateTrackList("100px")).toEqual([{ value: "100px" }]);+ expect(parseGridTemplateTrackList("100px 200px")).toEqual([+ { value: "100px" },+ { value: "200px" },+ ]);+ });++ test("parses percentage values", () => {+ expect(parseGridTemplateTrackList("50%")).toEqual([{ value: "50%" }]);+ expect(parseGridTemplateTrackList("25% 75%")).toEqual([+ { value: "25%" },+ { value: "75%" },+ ]);+ });++ test("parses mixed units", () => {+ expect(parseGridTemplateTrackList("100px 1fr 50%")).toEqual([+ { value: "100px" },+ { value: "1fr" },+ { value: "50%" },+ ]);+ });++ test("parses auto keyword", () => {+ expect(parseGridTemplateTrackList("auto")).toEqual([{ value: "auto" }]);+ expect(parseGridTemplateTrackList("auto 1fr auto")).toEqual([+ { value: "auto" },+ { value: "1fr" },+ { value: "auto" },+ ]);+ });++ test("parses min-content and max-content", () => {+ expect(parseGridTemplateTrackList("min-content")).toEqual([+ { value: "min-content" },+ ]);+ expect(parseGridTemplateTrackList("max-content")).toEqual([+ { value: "max-content" },+ ]);+ expect(parseGridTemplateTrackList("min-content 1fr max-content")).toEqual([+ { value: "min-content" },+ { value: "1fr" },+ { value: "max-content" },+ ]);+ });++ test("parses minmax() function", () => {+ expect(parseGridTemplateTrackList("minmax(100px, 1fr)")).toEqual([+ { value: "minmax(100px,1fr)" },+ ]);+ expect(+ parseGridTemplateTrackList("minmax(100px, 1fr) minmax(200px, 2fr)")+ ).toEqual([{ value: "minmax(100px,1fr)" }, { value: "minmax(200px,2fr)" }]);+ });++ test("parses fit-content() function", () => {+ expect(parseGridTemplateTrackList("fit-content(200px)")).toEqual([+ { value: "fit-content(200px)" },+ ]);+ });++ test("expands repeat() with number", () => {+ expect(parseGridTemplateTrackList("repeat(3, 1fr)")).toEqual([+ { value: "1fr" },+ { value: "1fr" },+ { value: "1fr" },+ ]);+ });++ test("expands repeat() with multiple tracks", () => {+ expect(parseGridTemplateTrackList("repeat(2, 100px 1fr)")).toEqual([+ { value: "100px" },+ { value: "1fr" },+ { value: "100px" },+ { value: "1fr" },+ ]);+ });++ test("keeps repeat(auto-fill) as single track", () => {+ const result = parseGridTemplateTrackList("repeat(auto-fill, 100px)");+ expect(result).toEqual([{ value: "repeat(auto-fill,100px)" }]);+ });++ test("keeps repeat(auto-fit) as single track", () => {+ const result = parseGridTemplateTrackList(+ "repeat(auto-fit, minmax(100px, 1fr))"+ );+ expect(result).toEqual([{ value: "repeat(auto-fit,minmax(100px,1fr))" }]);+ });++ test("handles complex mixed values", () => {+ expect(+ parseGridTemplateTrackList(+ "100px repeat(2, 1fr) minmax(100px, auto) 50px"+ )+ ).toEqual([+ { value: "100px" },+ { value: "1fr" },+ { value: "1fr" },+ { value: "minmax(100px,auto)" },+ { value: "50px" },+ ]);+ });++ test("ignores line names", () => {+ expect(+ parseGridTemplateTrackList("[header] 1fr [content] 2fr [footer]")+ ).toEqual([{ value: "1fr" }, { value: "2fr" }]);+ });++ test("ignores line names with repeat", () => {+ expect(parseGridTemplateTrackList("repeat(2, [col] 1fr)")).toEqual([+ { value: "1fr" },+ { value: "1fr" },+ ]);+ });+});++describe("serializeGridTemplateTrackList", () => {+ test("returns 'none' for empty array", () => {+ expect(serializeGridTemplateTrackList([])).toBe("none");+ });++ test("joins tracks with spaces", () => {+ expect(+ serializeGridTemplateTrackList([{ value: "1fr" }, { value: "2fr" }])+ ).toBe("1fr 2fr");+ });++ test("handles single track", () => {+ expect(serializeGridTemplateTrackList([{ value: "100px" }])).toBe("100px");+ });++ test("preserves complex values", () => {+ expect(+ serializeGridTemplateTrackList([+ { value: "100px" },+ { value: "minmax(100px,1fr)" },+ { value: "auto" },+ ])+ ).toBe("100px minmax(100px,1fr) auto");+ });+});++describe("round-trip parsing and serialization", () => {+ test("simple values round-trip correctly", () => {+ const original = "1fr 2fr 3fr";+ const parsed = parseGridTemplateTrackList(original);+ const serialized = serializeGridTemplateTrackList(parsed);+ expect(serialized).toBe(original);+ });++ test("mixed values round-trip correctly", () => {+ const original = "100px 1fr auto";+ const parsed = parseGridTemplateTrackList(original);+ const serialized = serializeGridTemplateTrackList(parsed);+ expect(serialized).toBe(original);+ });+});++describe("parseMinmax", () => {+ test("parses simple minmax", () => {+ expect(parseMinmax("minmax(100px, 1fr)")).toEqual({+ min: "100px",+ max: "1fr",+ });+ });++ test("parses minmax with auto", () => {+ expect(parseMinmax("minmax(auto, 1fr)")).toEqual({+ min: "auto",+ max: "1fr",+ });+ });++ test("parses minmax with min-content/max-content", () => {+ expect(parseMinmax("minmax(min-content, max-content)")).toEqual({+ min: "min-content",+ max: "max-content",+ });+ });++ test("parses minmax with percentage", () => {+ expect(parseMinmax("minmax(10%, 50%)")).toEqual({+ min: "10%",+ max: "50%",+ });+ });++ test("returns undefined for non-minmax values", () => {+ expect(parseMinmax("1fr")).toBeUndefined();+ expect(parseMinmax("100px")).toBeUndefined();+ expect(parseMinmax("auto")).toBeUndefined();+ });++ test("returns undefined for other functions", () => {+ expect(parseMinmax("fit-content(200px)")).toBeUndefined();+ expect(parseMinmax("repeat(3, 1fr)")).toBeUndefined();+ });++ test("returns undefined for invalid values", () => {+ expect(parseMinmax("")).toBeUndefined();+ expect(parseMinmax("minmax()")).toBeUndefined();+ expect(parseMinmax("minmax(100px)")).toBeUndefined();+ });+});++describe("serializeMinmax", () => {+ test("creates minmax string", () => {+ expect(serializeMinmax({ min: "100px", max: "1fr" })).toBe(+ "minmax(100px,1fr)"+ );+ });++ test("handles auto values", () => {+ expect(serializeMinmax({ min: "auto", max: "1fr" })).toBe(+ "minmax(auto,1fr)"+ );+ });++ test("handles content values", () => {+ expect(serializeMinmax({ min: "min-content", max: "max-content" })).toBe(+ "minmax(min-content,max-content)"+ );+ });+});++describe("parseMinmax and serializeMinmax round-trip", () => {+ test("minmax round-trips correctly", () => {+ const original = "minmax(100px,1fr)";+ const parsed = parseMinmax(original);+ expect(parsed).not.toBeUndefined();+ const serialized = serializeMinmax(parsed!);+ expect(serialized).toBe(original);+ });+});++describe("checkGridTemplateSupport", () => {+ test("supports empty and none values", () => {+ expect(checkGridTemplateSupport("")).toEqual({ supported: true });+ expect(checkGridTemplateSupport("none")).toEqual({ supported: true });+ });++ test("supports simple track values", () => {+ expect(checkGridTemplateSupport("1fr")).toEqual({ supported: true });+ expect(checkGridTemplateSupport("100px 1fr auto")).toEqual({+ supported: true,+ });+ });++ test("supports minmax()", () => {+ expect(checkGridTemplateSupport("minmax(100px, 1fr)")).toEqual({+ supported: true,+ });+ });++ test("supports repeat() with number", () => {+ expect(checkGridTemplateSupport("repeat(3, 1fr)")).toEqual({+ supported: true,+ });+ });++ test("rejects subgrid", () => {+ const result = checkGridTemplateSupport("subgrid");+ expect(result.supported).toBe(false);+ expect(result).toHaveProperty("reason");+ expect(result).toHaveProperty("type", "subgrid");+ });++ test("rejects masonry", () => {+ const result = checkGridTemplateSupport("masonry");+ expect(result.supported).toBe(false);+ expect(result).toHaveProperty("reason");+ expect(result).toHaveProperty("type", "masonry");+ });++ test("supports CSS variables (should be resolved via computedValue)", () => {+ // CSS variables are supported when using computedValue which resolves them+ const result = checkGridTemplateSupport("var(--grid-cols)");+ expect(result.supported).toBe(true);+ });++ test("rejects repeat(auto-fill)", () => {+ const result = checkGridTemplateSupport("repeat(auto-fill, 100px)");+ expect(result.supported).toBe(false);+ expect(result).toHaveProperty("reason");+ expect(result).toHaveProperty("type", "auto-fill");+ });++ test("rejects repeat(auto-fit)", () => {+ const result = checkGridTemplateSupport(+ "repeat(auto-fit, minmax(100px, 1fr))"+ );+ expect(result.supported).toBe(false);+ expect(result).toHaveProperty("reason");+ expect(result).toHaveProperty("type", "auto-fit");+ });++ test("rejects line names", () => {+ const result = checkGridTemplateSupport("[header] 1fr [content] 2fr");+ expect(result.supported).toBe(false);+ expect(result).toHaveProperty("reason");+ expect(result).toHaveProperty("type", "line-names");+ });++ test("rejects mixed auto-fill with other tracks", () => {+ const result = checkGridTemplateSupport(+ "100px repeat(auto-fill, 1fr) 100px"+ );+ expect(result.supported).toBe(false);+ expect(result).toHaveProperty("reason");+ expect(result).toHaveProperty("type", "auto-fill");+ });+});++describe("getGridAxisMode", () => {+ test("returns 'none' for empty or none values", () => {+ expect(getGridAxisMode("")).toBe("none");+ expect(getGridAxisMode("none")).toBe("none");+ });++ test("returns 'auto' for single auto keyword", () => {+ expect(getGridAxisMode("auto")).toBe("auto");+ });++ test("returns 'explicit' for regular track values", () => {+ expect(getGridAxisMode("1fr 2fr")).toBe("explicit");+ expect(getGridAxisMode("100px 200px")).toBe("explicit");+ expect(getGridAxisMode("repeat(3, 1fr)")).toBe("explicit");+ expect(getGridAxisMode("minmax(100px, 1fr)")).toBe("explicit");+ });++ test("returns 'auto-fill' for repeat(auto-fill, ...)", () => {+ expect(getGridAxisMode("repeat(auto-fill, 100px)")).toBe("auto-fill");+ expect(getGridAxisMode("repeat(auto-fill, minmax(100px, 1fr))")).toBe(+ "auto-fill"+ );+ });++ test("returns 'auto-fit' for repeat(auto-fit, ...)", () => {+ expect(getGridAxisMode("repeat(auto-fit, 100px)")).toBe("auto-fit");+ expect(getGridAxisMode("repeat(auto-fit, minmax(100px, 1fr))")).toBe(+ "auto-fit"+ );+ });++ test("returns 'subgrid' for subgrid", () => {+ expect(getGridAxisMode("subgrid")).toBe("subgrid");+ expect(getGridAxisMode("subgrid [header] [content]")).toBe("subgrid");+ });++ test("returns 'masonry' for masonry", () => {+ expect(getGridAxisMode("masonry")).toBe("masonry");+ });++ test("returns 'line-names' for values with line names", () => {+ expect(getGridAxisMode("[header] 1fr [content]")).toBe("line-names");+ });+});++describe("isImplicitGridMode", () => {+ test("returns true for implicit modes", () => {+ expect(isImplicitGridMode("auto-fill")).toBe(true);+ expect(isImplicitGridMode("auto-fit")).toBe(true);+ expect(isImplicitGridMode("auto")).toBe(true);+ expect(isImplicitGridMode("none")).toBe(true);+ });++ test("returns false for explicit modes", () => {+ expect(isImplicitGridMode("explicit")).toBe(false);+ expect(isImplicitGridMode("subgrid")).toBe(false);+ expect(isImplicitGridMode("masonry")).toBe(false);+ expect(isImplicitGridMode("line-names")).toBe(false);+ });+});++describe("isEditableGridMode", () => {+ test("returns true for editable modes", () => {+ expect(isEditableGridMode("explicit")).toBe(true);+ expect(isEditableGridMode("none")).toBe(true);+ expect(isEditableGridMode("auto")).toBe(true);+ });++ test("returns false for non-editable modes", () => {+ expect(isEditableGridMode("auto-fill")).toBe(false);+ expect(isEditableGridMode("auto-fit")).toBe(false);+ expect(isEditableGridMode("subgrid")).toBe(false);+ expect(isEditableGridMode("masonry")).toBe(false);+ expect(isEditableGridMode("line-names")).toBe(false);+ });+});++describe("getGridAxisLabel", () => {+ test("returns mode name for implicit modes", () => {+ expect(getGridAxisLabel("auto-fill", 5)).toBe("auto-fill");+ expect(getGridAxisLabel("auto-fit", 3)).toBe("auto-fit");+ expect(getGridAxisLabel("auto", 2)).toBe("auto");+ expect(getGridAxisLabel("none", 2)).toBe("none");+ });++ test("returns track count for explicit mode", () => {+ expect(getGridAxisLabel("explicit", 3)).toBe("3");+ expect(getGridAxisLabel("explicit", 5)).toBe("5");+ });++ test("returns mode name for advanced modes", () => {+ expect(getGridAxisLabel("subgrid", 4)).toBe("subgrid");+ expect(getGridAxisLabel("masonry", 3)).toBe("masonry");+ expect(getGridAxisLabel("line-names", 2)).toBe("[…]");+ });+});diff --git a/packages/css-data/src/property-parsers/grid-template-tracks.ts b/packages/css-data/src/property-parsers/grid-template-tracks.tsnew file mode 100644index 0000000000..c3ec8cad5e--- /dev/null+++ b/packages/css-data/src/property-parsers/grid-template-tracks.ts@@ -0,0 +1,448 @@+import * as csstree from "css-tree";+import { cssTryParseValue } from "../parse-css-value";++/**+ * Represents a single grid track.+ * Can be a simple value like "1fr", "100px", "auto"+ * or a complex value like "minmax(100px, 1fr)"+ */+export type GridTrack = {+ /** The raw CSS value of the track */+ value: string;+};++/**+ * Parse a grid-template-columns or grid-template-rows value into an array of tracks.+ *+ * Handles:+ * - Simple values: "1fr", "100px", "auto", "min-content", "max-content"+ * - Functions: "minmax(100px, 1fr)", "fit-content(200px)"+ * - Repeat: "repeat(3, 1fr)" -> expands to ["1fr", "1fr", "1fr"]+ * - Line names: "[header] 1fr [content] 2fr" -> ignores line names, returns ["1fr", "2fr"]+ *+ * @param value - The CSS value string for grid-template-columns/rows+ * @returns Array of track values, or empty array if value is "none" or invalid+ */+export const parseGridTemplateTrackList = (value: string): GridTrack[] => {+ if (!value || value === "none") {+ return [];+ }++ const ast = cssTryParseValue(value);+ if (ast === undefined || ast.type !== "Value") {+ return [];+ }++ const tracks: GridTrack[] = [];+ const children = ast.children.toArray();++ for (const node of children) {+ // Skip line names (bracketed identifiers like [header])+ if (node.type === "Brackets") {+ continue;+ }++ // Handle simple identifiers: auto, min-content, max-content+ if (node.type === "Identifier") {+ tracks.push({ value: node.name });+ continue;+ }++ // Handle dimensions: 100px, 1fr, 50%+ if (node.type === "Dimension") {+ tracks.push({ value: `${node.value}${node.unit}` });+ continue;+ }++ // Handle percentages+ if (node.type === "Percentage") {+ tracks.push({ value: `${node.value}%` });+ continue;+ }++ // Handle numbers (rare but valid)+ if (node.type === "Number") {+ tracks.push({ value: node.value });+ continue;+ }++ // Handle functions: minmax(), fit-content(), repeat()+ if (node.type === "Function") {+ if (node.name === "repeat") {+ // Expand repeat() function+ const repeatTracks = expandRepeat(node);+ tracks.push(...repeatTracks);+ } else {+ // For other functions (minmax, fit-content), keep as-is+ tracks.push({ value: csstree.generate(node) });+ }+ continue;+ }+ }++ return tracks;+};++/**+ * Expand a repeat() function into individual tracks.+ * e.g., repeat(3, 1fr) -> [{ value: "1fr" }, { value: "1fr" }, { value: "1fr" }]+ * e.g., repeat(2, 100px 1fr) -> [{ value: "100px" }, { value: "1fr" }, { value: "100px" }, { value: "1fr" }]+ *+ * Note: repeat(auto-fill, ...) and repeat(auto-fit, ...) cannot be expanded+ * and will return the original function as a single track.+ */+const expandRepeat = (node: csstree.FunctionNode): GridTrack[] => {+ const children = node.children.toArray();++ // First child should be the count (number or auto-fill/auto-fit)+ const countNode = children[0];++ // Handle auto-fill and auto-fit - cannot expand, return as single track+ if (countNode?.type === "Identifier") {+ if (countNode.name === "auto-fill" || countNode.name === "auto-fit") {+ return [{ value: csstree.generate(node) }];+ }+ }++ // Get the repeat count+ let count = 1;+ if (countNode?.type === "Number") {+ count = parseInt(countNode.value, 10);+ if (isNaN(count) || count < 1) {+ return [{ value: csstree.generate(node) }];+ }+ }++ // Find the comma separator and get track template after it+ const trackTemplateNodes: csstree.CssNode[] = [];+ let foundComma = false;+ for (const child of children) {+ if (child.type === "Operator" && child.value === ",") {+ foundComma = true;+ continue;+ }+ if (foundComma) {+ trackTemplateNodes.push(child);+ }+ }++ if (trackTemplateNodes.length === 0) {+ return [{ value: csstree.generate(node) }];+ }++ // Parse the track template+ const templateTracks: GridTrack[] = [];+ for (const templateNode of trackTemplateNodes) {+ // Skip line names+ if (templateNode.type === "Brackets") {+ continue;+ }++ if (templateNode.type === "Identifier") {+ templateTracks.push({ value: templateNode.name });+ } else if (templateNode.type === "Dimension") {+ templateTracks.push({+ value: `${templateNode.value}${templateNode.unit}`,+ });+ } else if (templateNode.type === "Percentage") {+ templateTracks.push({ value: `${templateNode.value}%` });+ } else if (templateNode.type === "Number") {+ templateTracks.push({ value: templateNode.value });+ } else if (templateNode.type === "Function") {+ templateTracks.push({ value: csstree.generate(templateNode) });+ }+ }++ // Expand the template by the count+ const expandedTracks: GridTrack[] = [];+ for (let i = 0; i < count; i++) {+ expandedTracks.push(...templateTracks);+ }++ return expandedTracks;+};++/**+ * Serialize an array of tracks back to a CSS value string.+ *+ * @param tracks - Array of track values+ * @returns CSS string like "1fr 100px auto" or "none" if empty+ */+export const serializeGridTemplateTrackList = (tracks: GridTrack[]): string => {+ if (tracks.length === 0) {+ return "none";+ }+ return tracks.map((track) => track.value).join(" ");+};++/**+ * Represents a minmax() function with min and max values.+ */+export type Minmax = {+ min: string;+ max: string;+};++/**+ * Parse a minmax() function value into its min and max parts.+ * Returns undefined if the value is not a valid minmax() function.+ *+ * @example+ * parseMinmax("minmax(100px, 1fr)") // { min: "100px", max: "1fr" }+ * parseMinmax("1fr") // undefined+ */+export const parseMinmax = (value: string): Minmax | undefined => {+ const ast = cssTryParseValue(value);+ if (ast === undefined || ast.type !== "Value") {+ return undefined;+ }++ const children = ast.children.toArray();+ if (children.length !== 1) {+ return undefined;+ }++ const node = children[0];+ if (node.type !== "Function" || node.name !== "minmax") {+ return undefined;+ }++ const args = node.children.toArray();+ // minmax has two arguments separated by a comma+ // Structure: [min-value, Operator(","), max-value]+ const values: string[] = [];+ for (const arg of args) {+ if (arg.type === "Operator" && arg.value === ",") {+ continue;+ }+ values.push(csstree.generate(arg));+ }++ if (values.length !== 2) {+ return undefined;+ }++ return { min: values[0], max: values[1] };+};++/**+ * Create a minmax() CSS value from min and max parts.+ *+ * @example+ * serializeMinmax({ min: "100px", max: "1fr" }) // "minmax(100px,1fr)"+ */+export const serializeMinmax = (minmax: Minmax): string => {+ return `minmax(${minmax.min},${minmax.max})`;+};++/**+ * Result of checking if a grid template value is supported by the visual editor.+ */+export type GridTemplateSupport =+ | { supported: true }+ | {+ supported: false;+ reason: string;+ type: "subgrid" | "masonry" | "line-names" | "auto-fill" | "auto-fit";+ };++/**+ * Check if a grid-template-columns or grid-template-rows value can be+ * represented and edited by the visual grid UI.+ *+ * Unsupported values:+ * - `subgrid` - requires dedicated UI+ * - `masonry` - experimental, not a track definition+ * - `repeat(auto-fill, ...)` / `repeat(auto-fit, ...)` - dynamic track count+ * - Line names like `[header]` - would be silently discarded on edit+ *+ * Note: CSS variables are supported - use computedValue which resolves them.+ *+ * @param value - The CSS value string for grid-template-columns/rows+ * @returns Object indicating if supported, with reason and type if not+ */+export const checkGridTemplateSupport = (+ value: string+): GridTemplateSupport => {+ if (!value || value === "none") {+ return { supported: true };+ }++ // Check for subgrid+ if (value.includes("subgrid")) {+ return {+ supported: false,+ type: "subgrid",+ reason: "Subgrid is not supported in the visual editor",+ };+ }++ // Check for masonry+ if (value.includes("masonry")) {+ return {+ supported: false,+ type: "masonry",+ reason: "Masonry layout is not supported in the visual editor",+ };+ }++ const ast = cssTryParseValue(value);+ if (ast === undefined || ast.type !== "Value") {+ return { supported: true }; // Let invalid values pass through+ }++ const children = ast.children.toArray();++ for (const node of children) {+ // Check for line names (bracketed identifiers)+ if (node.type === "Brackets") {+ return {+ supported: false,+ type: "line-names",+ reason: "Named grid lines are not supported in the visual editor",+ };+ }++ // Check for auto-fill/auto-fit in repeat()+ if (node.type === "Function" && node.name === "repeat") {+ const repeatChildren = node.children.toArray();+ const countNode = repeatChildren[0];+ if (countNode?.type === "Identifier") {+ if (countNode.name === "auto-fill") {+ return {+ supported: false,+ type: "auto-fill",+ reason: "Dynamic grid tracks (auto-fill) cannot be edited visually",+ };+ }+ if (countNode.name === "auto-fit") {+ return {+ supported: false,+ type: "auto-fit",+ reason: "Dynamic grid tracks (auto-fit) cannot be edited visually",+ };+ }+ }+ }+ }++ return { supported: true };+};++/**+ * Describes the mode of a grid axis (columns or rows).+ *+ * - "explicit": Regular explicit tracks (e.g., "1fr 2fr 100px")+ * - "auto-fill": Dynamic tracks via repeat(auto-fill, ...)+ * - "auto-fit": Dynamic tracks via repeat(auto-fit, ...)+ * - "auto": Single "auto" keyword - implicit tracks based on children+ * - "none": No explicit tracks defined+ * - "subgrid": Subgrid inherits tracks from parent+ * - "masonry": Experimental masonry layout+ * - "line-names": Has named grid lines like [header]+ */+export type GridAxisMode =+ | "explicit"+ | "auto-fill"+ | "auto-fit"+ | "auto"+ | "none"+ | "subgrid"+ | "masonry"+ | "line-names";++/**+ * Analyze a grid template value to determine its mode.+ *+ * @param value - The CSS value string for grid-template-columns/rows+ * @returns The axis mode describing the type of grid track definition+ *+ * @example+ * getGridAxisMode("1fr 2fr 100px") // "explicit"+ * getGridAxisMode("repeat(auto-fill, minmax(200px, 1fr))") // "auto-fill"+ * getGridAxisMode("none") // "none"+ * getGridAxisMode("auto") // "auto"+ * getGridAxisMode("subgrid") // "subgrid"+ */+export const getGridAxisMode = (value: string): GridAxisMode => {+ if (!value || value === "none" || value === "") {+ return "none";+ }++ if (value === "auto") {+ return "auto";+ }++ if (value.includes("subgrid")) {+ return "subgrid";+ }++ if (value.includes("masonry")) {+ return "masonry";+ }++ const support = checkGridTemplateSupport(value);+ if (!support.supported) {+ // Map the unsupported type directly to mode+ return support.type;+ }++ return "explicit";+};++/**+ * Check if a grid axis mode represents a dynamic/implicit grid that+ * requires DOM probing to determine actual track count.+ *+ * @param mode - The grid axis mode+ * @returns true if the mode requires DOM-based track counting+ */+export const isImplicitGridMode = (mode: GridAxisMode): boolean => {+ return (+ mode === "auto-fill" ||+ mode === "auto-fit" ||+ mode === "auto" ||+ mode === "none"+ );+};++/**+ * Check if a grid axis mode is editable in the visual grid UI.+ *+ * @param mode - The grid axis mode+ * @returns true if the mode can be edited visually+ */+export const isEditableGridMode = (mode: GridAxisMode): boolean => {+ return mode === "explicit" || mode === "none" || mode === "auto";+};++/**+ * Get a display label for a grid axis mode (for the grid generator).+ *+ * @param mode - The grid axis mode+ * @param trackCount - The actual track count (for explicit modes)+ * @returns Display string like "3", "auto-fit", "none"+ */+export const getGridAxisLabel = (+ mode: GridAxisMode,+ trackCount: number+): string => {+ switch (mode) {+ case "auto-fill":+ return "auto-fill";+ case "auto-fit":+ return "auto-fit";+ case "auto":+ return "auto";+ case "none":+ return "none";+ case "subgrid":+ return "subgrid";+ case "masonry":+ return "masonry";+ case "line-names":+ return "[…]";+ default:+ return String(trackCount);+ }+};diff --git a/packages/css-data/src/property-parsers/index.ts b/packages/css-data/src/property-parsers/index.tsindex 7d33f13570..0c97ee2699 100644--- a/packages/css-data/src/property-parsers/index.ts+++ b/packages/css-data/src/property-parsers/index.ts@@ -1,4 +1,6 @@export * from "./linear-gradient";export * from "./conic-gradient";export * from "./radial-gradient";+export * from "./grid-template-tracks";+export * from "./grid-template-areas";export * from "./types";diff --git a/packages/design-system/src/components/css-value-list-item.tsx b/packages/design-system/src/components/css-value-list-item.tsxindex e77cb787b3..d9cfe43cf1 100644--- a/packages/design-system/src/components/css-value-list-item.tsx+++ b/packages/design-system/src/components/css-value-list-item.tsx@@ -146,7 +146,11 @@ export const CssValueListItem = forwardRef(}: Props,ref: Ref<HTMLButtonElement>) => {- const buttonsCount = Children.count(buttons?.props.children);+ const buttonsCount = buttons+ ? // When children is a single element, count results in 0+ Children.count(buttons.props.children) || 1+ : 0;+const fakeButtons = useMemo(() => (<>@@ -184,7 +188,7 @@ export const CssValueListItem = forwardRef(><DragHandleIconStyled />- <Flex shrink align="center">+ <Flex shrink align="center" css={{ overflow: "hidden" }}>{thumbnail ? <ThumbHolder>{thumbnail}</ThumbHolder> : null}{label}</Flex>diff --git a/packages/design-system/src/components/dialog.tsx b/packages/design-system/src/components/dialog.tsxindex 5d000cbc1e..b129801124 100644--- a/packages/design-system/src/components/dialog.tsx+++ b/packages/design-system/src/components/dialog.tsx@@ -709,7 +709,6 @@ const contentStyle = css(panelStyle, {width: "min-content",height: "min-content",minWidth: theme.sizes.sidebarWidth,- minHeight: theme.spacing[22],maxWidth: `calc(100vw - ${theme.spacing[15]})`,maxHeight: `calc(100vh - ${theme.spacing[15]})`,userSelect: "none",diff --git a/packages/design-system/src/components/floating-panel.tsx b/packages/design-system/src/components/floating-panel.tsxindex b54b8e670e..f44e75d978 100644--- a/packages/design-system/src/components/floating-panel.tsx+++ b/packages/design-system/src/components/floating-panel.tsx@@ -123,10 +123,13 @@ type FloatingPanelProps = {offset?: OffsetOptions;open?: boolean;onOpenChange?: (isOpen: boolean) => void;+ /** When false, the panel won't close when clicking outside it. */+ closeOnInteractOutside?: boolean;};const contentStyle = css({width: theme.sizes.sidebarWidth,+ overflow: "auto",});const defaultOffset: OffsetOptions = { mainAxis: 0, crossAxis: 0 };@@ -144,6 +147,7 @@ export const FloatingPanel = ({offset: offsetProp = defaultOffset,open: openProp,onOpenChange,+ closeOnInteractOutside = true,}: FloatingPanelProps) => {// Support both controlled and uncontrolled modesconst [internalOpen, setInternalOpen] = useState(false);@@ -155,6 +159,7 @@ export const FloatingPanel = ({const triggerRef = useRef<HTMLButtonElement>(null);const [position, setPosition] = useState<{ x: number; y: number }>();const currentPositionRef = useRef<{ x: number; y: number }>();+ const maxHeightRef = useRef<number | undefined>();const containerRef = useRef<HTMLElement | null>(null);// Wrap onOpenChange to reset position when panel closes@@ -162,6 +167,7 @@ export const FloatingPanel = ({if (isOpen === false) {currentPositionRef.current = undefined;setPosition(undefined);+ maxHeightRef.current = undefined;containerRef.current = null;}// Update internal state if uncontrolled@@ -176,6 +182,7 @@ export const FloatingPanel = ({if (open === false) {currentPositionRef.current = undefined;setPosition(undefined);+ maxHeightRef.current = undefined;containerRef.current = null;}}, [open]);@@ -220,6 +227,15 @@ export const FloatingPanel = ({offsetProp);currentPositionRef.current = { x, y };++ // Calculate max height based on container bounds+ const containerRect = containerRef.current.getBoundingClientRect();+ const availableHeight = containerRect.bottom - y - 10; // 10px padding+ if (availableHeight > 0) {+ maxHeightRef.current = availableHeight;+ contentElement.style.maxHeight = `${availableHeight}px`;+ }+setPosition({ x, y });return;}@@ -291,7 +307,7 @@ export const FloatingPanel = ({// When a dialog is centered, we don't want to close it when clicking outside// This allows having inline and left positioned dialogs open at the same time as a centered dialog,// while not allowing having multiple non-center positioned dialogs open at the same time.- if (placement === "center") {+ if (placement === "center" || closeOnInteractOutside === false) {event.preventDefault();}}}diff --git a/packages/design-system/src/components/select.tsx b/packages/design-system/src/components/select.tsxindex 83ded69397..c8fd384817 100644--- a/packages/design-system/src/components/select.tsx+++ b/packages/design-system/src/components/select.tsx@@ -24,6 +24,7 @@ import { Box } from "./box";import { ScrollArea } from "./scroll-area";export const SelectContent = styled(Primitive.Content, menuCss, {+ minWidth: "var(--radix-select-trigger-width)","&[data-side=top]": {"--ws-select-description-display-top": "block","--ws-select-description-order": 0,diff --git a/packages/http-client/package.json b/packages/http-client/package.jsonindex ea6b46375a..14c9aed156 100644--- a/packages/http-client/package.json+++ b/packages/http-client/package.json@@ -19,9 +19,12 @@"vitest": "^3.1.2"},"exports": {- "webstudio": "./src/index.ts",- "types": "./lib/types/index.d.ts",- "import": "./lib/index.js"+ ".": {+ "webstudio": "./src/index.ts",+ "types": "./lib/types/index.d.ts",+ "import": "./lib/index.js",+ "default": "./src/index.ts"+ }},"files": ["lib/*",diff --git a/packages/icons/icons/stretch-vertical.svg b/packages/icons/icons/stretch-vertical.svgindex 48519f844a..4a44aea781 100644--- a/packages/icons/icons/stretch-vertical.svg+++ b/packages/icons/icons/stretch-vertical.svg@@ -6,19 +6,13 @@xmlns="http://www.w3.org/2000/svg"><path- d="M5.4002 4.09685H4.09915C3.3806 4.09685 2.7981 4.67935 2.7981 5.3979V13.2042C2.7981 13.9227 3.3806 14.5052 4.09915 14.5052H5.4002C6.11875 14.5052 6.70125 13.9227 6.70125 13.2042V5.3979C6.70125 4.67935 6.11875 4.09685 5.4002 4.09685Z"+ d="M5.33329 1.33333H3.99996C3.26358 1.33333 2.66663 1.93028 2.66663 2.66666V13.3333C2.66663 14.0697 3.26358 14.6667 3.99996 14.6667H5.33329C6.06967 14.6667 6.66663 14.0697 6.66663 13.3333V2.66666C6.66663 1.93028 6.06967 1.33333 5.33329 1.33333Z"stroke="currentColor"stroke-linecap="round"stroke-linejoin="round"/><path- d="M11.9057 4.09685H10.6046C9.88609 4.09685 9.30359 4.67935 9.30359 5.3979V8.65052C9.30359 9.36907 9.88609 9.95157 10.6046 9.95157H11.9057C12.6242 9.95157 13.2067 9.36907 13.2067 8.65052V5.3979C13.2067 4.67935 12.6242 4.09685 11.9057 4.09685Z"- stroke="currentColor"- stroke-linecap="round"- stroke-linejoin="round"- />- <path- d="M14.4973 1.49475H1.49731"+ d="M12 1.33333H10.6667C9.93033 1.33333 9.33337 1.93028 9.33337 2.66666V13.3333C9.33337 14.0697 9.93033 14.6667 10.6667 14.6667H12C12.7364 14.6667 13.3334 14.0697 13.3334 13.3333V2.66666C13.3334 1.93028 12.7364 1.33333 12 1.33333Z"stroke="currentColor"stroke-linecap="round"stroke-linejoin="round"diff --git a/packages/icons/src/__generated__/components.tsx b/packages/icons/src/__generated__/components.tsxindex b37508c3f5..4af2103dee 100644--- a/packages/icons/src/__generated__/components.tsx+++ b/packages/icons/src/__generated__/components.tsx@@ -4839,7 +4839,7 @@ export const StretchVerticalIcon: IconComponent = forwardRef(stroke="currentColor"strokeLinecap="round"strokeLinejoin="round"- d="M5.4 4.097H4.1c-.72 0-1.302.582-1.302 1.3v7.807c0 .719.583 1.301 1.301 1.301H5.4c.719 0 1.301-.582 1.301-1.3V5.397c0-.719-.582-1.301-1.3-1.301ZM11.906 4.097h-1.301c-.719 0-1.301.582-1.301 1.3v3.254c0 .718.582 1.3 1.3 1.3h1.302c.718 0 1.3-.582 1.3-1.3V5.398c0-.719-.582-1.301-1.3-1.301ZM14.497 1.495h-13"+ d="M5.333 1.333H4c-.736 0-1.333.597-1.333 1.334v10.666c0 .737.597 1.334 1.333 1.334h1.333c.737 0 1.334-.597 1.334-1.334V2.667c0-.737-.597-1.334-1.334-1.334ZM12 1.333h-1.333c-.737 0-1.334.597-1.334 1.334v10.666c0 .737.597 1.334 1.334 1.334H12c.736 0 1.333-.597 1.333-1.334V2.667c0-.737-.597-1.334-1.333-1.334Z"/></svg>);diff --git a/packages/icons/src/__generated__/svg.ts b/packages/icons/src/__generated__/svg.tsindex e45d112c0f..46697d0f56 100644--- a/packages/icons/src/__generated__/svg.ts+++ b/packages/icons/src/__generated__/svg.ts@@ -356,7 +356,7 @@ export const StaggerAnimationIcon = `<svg xmlns="http://www.w3.org/2000/svg" filexport const StopIcon = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="100%" height="100%" style="display: block;"><rect width="9" height="9" x="3.5" y="3.5" fill="currentColor" rx="1"/></svg>`;-export const StretchVerticalIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M5.4 4.097H4.1c-.72 0-1.302.582-1.302 1.3v7.807c0 .719.583 1.301 1.301 1.301H5.4c.719 0 1.301-.582 1.301-1.3V5.397c0-.719-.582-1.301-1.3-1.301ZM11.906 4.097h-1.301c-.719 0-1.301.582-1.301 1.3v3.254c0 .718.582 1.3 1.3 1.3h1.302c.718 0 1.3-.582 1.3-1.3V5.398c0-.719-.582-1.301-1.3-1.301ZM14.497 1.495h-13"/></svg>`;+export const StretchVerticalIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M5.333 1.333H4c-.736 0-1.333.597-1.333 1.334v10.666c0 .737.597 1.334 1.333 1.334h1.333c.737 0 1.334-.597 1.334-1.334V2.667c0-.737-.597-1.334-1.334-1.334ZM12 1.333h-1.333c-.737 0-1.334.597-1.334 1.334v10.666c0 .737.597 1.334 1.334 1.334H12c.736 0 1.333-.597 1.333-1.334V2.667c0-.737-.597-1.334-1.333-1.334Z"/></svg>`;export const SubscriptIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M2.667 3.333 8 8.667M8 3.333 2.667 8.667M13.333 12.667h-2.666c0-1 .293-1.334 1-1.667.706-.333 1.666-.78 1.666-1.667 0-.313-.113-.62-.32-.86a1.407 1.407 0 0 0-1.746-.293c-.28.16-.494.413-.6.713"/></svg>`;diff --git a/packages/react-sdk/src/props.ts b/packages/react-sdk/src/props.tsindex e87e6c795f..3a877522ec 100644--- a/packages/react-sdk/src/props.ts+++ b/packages/react-sdk/src/props.ts@@ -135,7 +135,7 @@ export const idAttribute = "data-ws-id" as const;export const selectorIdAttribute = "data-ws-selector" as const;export const componentAttribute = "data-ws-component" as const;export const showAttribute = "data-ws-show" as const;-export const collapsedAttribute = "data-ws-collapsed" as const;+export const inflatedAttribute = "data-ws-collapsed" as const;export const textContentAttribute = "data-ws-text-content" as const;/**diff --git a/packages/sdk/src/__generated__/normalize.css.ts b/packages/sdk/src/__generated__/normalize.css.tsindex 279ba2d6ba..1b63338e9e 100644--- a/packages/sdk/src/__generated__/normalize.css.ts+++ b/packages/sdk/src/__generated__/normalize.css.ts@@ -65,6 +65,11 @@ export const span = div;export const html: StyleDecl[] = [{ property: "display", value: { type: "keyword", value: "grid" } },{ property: "min-height", value: { type: "unit", unit: "%", value: 100 } },+ { property: "grid-template-rows", value: { type: "keyword", value: "auto" } },+ {+ property: "grid-template-columns",+ value: { type: "unit", unit: "fr", value: 1 },+ },{property: "font-family",value: { type: "fontFamily", value: ["Arial", "Roboto", "sans-serif"] },diff --git a/packages/sdk/src/core-metas.ts b/packages/sdk/src/core-metas.tsindex a45d763172..d7e2f4816e 100644--- a/packages/sdk/src/core-metas.ts+++ b/packages/sdk/src/core-metas.ts@@ -15,7 +15,7 @@ import { tags } from "./__generated__/tags";export const rootComponent = "ws:root";const rootMeta: WsComponentMeta = {- label: "Global Root",+ label: "Global root",icon: SettingsIcon,presetStyle: {html,diff --git a/packages/sdk/src/css.test.tsx b/packages/sdk/src/css.test.tsxindex 8a13c3516f..24ff20d4e8 100644--- a/packages/sdk/src/css.test.tsx+++ b/packages/sdk/src/css.test.tsx@@ -468,7 +468,7 @@ test("generate :root preset and user styles", () => {[rootComponent,{- label: "Global Root",+ label: "Global root",presetStyle: {html: css`display: grid;diff --git a/packages/sdk/src/normalize.css b/packages/sdk/src/normalize.cssindex 9a61e08476..3929a5a675 100644--- a/packages/sdk/src/normalize.css+++ b/packages/sdk/src/normalize.css@@ -66,6 +66,8 @@ html {/* 1 */display: grid;min-height: 100%;+ grid-template-rows: auto;+ grid-template-columns: 1fr;/* 2 */font-family: Arial, Roboto, sans-serif;font-size: 16px;