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
experimental: migrate background content to style object model (#4108)
Bogdan Chadkin39c9bb21725a
diff --git a/apps/builder/app/builder/features/style-panel/controls/index.ts b/apps/builder/app/builder/features/style-panel/controls/index.tsindex 7489539d90..5cb4efbc96 100644--- a/apps/builder/app/builder/features/style-panel/controls/index.ts+++ b/apps/builder/app/builder/features/style-panel/controls/index.ts@@ -6,4 +6,3 @@ export * from "./font-family/font-family-control";export * from "./font-weight/font-weight-control";export * from "./image/image-control";export * from "./position/position-control";-export type { ControlProps } from "./types";diff --git a/apps/builder/app/builder/features/style-panel/controls/select/select-control.tsx b/apps/builder/app/builder/features/style-panel/controls/select/select-control.tsxindex cc3eecb4d1..d9f817adcc 100644--- a/apps/builder/app/builder/features/style-panel/controls/select/select-control.tsx+++ b/apps/builder/app/builder/features/style-panel/controls/select/select-control.tsx@@ -1,29 +1,53 @@import { declarationDescriptions, parseCssValue } from "@webstudio-is/css-data";-import { toValue, type StyleProperty } from "@webstudio-is/css-engine";+import {+ StyleValue,+ toValue,+ type StyleProperty,+} from "@webstudio-is/css-engine";import { Box, Select, theme } from "@webstudio-is/design-system";import { styleConfigByName } from "../../shared/configs";import { toKebabCase } from "../../shared/keyword-utils";import { useComputedStyleDecl } from "../../shared/model";-import { resetEphemeralStyles, setProperty } from "../../shared/use-style-data";+import {+ resetEphemeralStyles,+ setProperty,+ type StyleUpdateOptions,+} from "../../shared/use-style-data";+import {+ getRepeatedStyleItem,+ setRepeatedStyleItem,+} from "../../shared/repeated-style";export const SelectControl = ({property,+ index,items = styleConfigByName(property).items,}: {property: StyleProperty;+ index?: number;items?: Array<{ label: string; name: string }>;}) => {- const computedStyleDecl = useComputedStyleDecl(property);- const setValue = setProperty(property);+ const styleDecl = useComputedStyleDecl(property);+ const value =+ index === undefined+ ? styleDecl.cascadedValue+ : getRepeatedStyleItem(styleDecl.cascadedValue, index);+ const setValue = (value: StyleValue, options?: StyleUpdateOptions) => {+ if (index === undefined) {+ setProperty(property)(value, options);+ } else {+ setRepeatedStyleItem(styleDecl, index, value, options);+ }+ };const options = items.map(({ name }) => name);// We can't render an empty string as a value when display was added but without a value.// One case is when advanced property is being added, but no value is set.- const value = toValue(computedStyleDecl.cascadedValue) || "empty";+ const valueString = toValue(value) || "empty";// Append selected value when not present in the list of options// because radix requires values to always be in the list.- if (options.includes(value) === false) {- options.push(value);+ if (options.includes(valueString) === false) {+ options.push(valueString);}return (@@ -32,15 +56,14 @@ export const SelectControl = ({placeholder=""options={options}getLabel={toKebabCase}- value={value}- onChange={(name) => {- const nextValue = parseCssValue(property, name);- setValue(nextValue);- }}+ value={valueString}+ onChange={(name) => setValue({ type: "keyword", value: name })}onItemHighlight={(name) => {// Remove preview when mouse leaves the item.if (name === undefined) {- setValue(computedStyleDecl.usedValue, { isEphemeral: true });+ if (value) {+ setValue(value, { isEphemeral: true });+ }return;}// Preview on mouse enter or focus.diff --git a/apps/builder/app/builder/features/style-panel/controls/types.ts b/apps/builder/app/builder/features/style-panel/controls/types.tsdeleted file mode 100644index a169ca77bc..0000000000--- a/apps/builder/app/builder/features/style-panel/controls/types.ts+++ /dev/null@@ -1,12 +0,0 @@-import type { StyleProperty } from "@webstudio-is/css-engine";-import type { StyleInfo } from "../shared/style-info";-import type { DeleteProperty, SetProperty } from "../shared/use-style-data";--export type ControlProps = {- property: StyleProperty;- items?: Array<{ label: string; name: string }>;- currentStyle: StyleInfo;- setProperty: SetProperty;- deleteProperty: DeleteProperty;- isAdvanced?: boolean;-};diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsxindex ba32e56c6f..e5fd1eebbe 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsx@@ -1,11 +1,9 @@-import { BackgroundContent } from "./background-content";-import { getLayerBackgroundStyleInfo } from "./background-layers";+import { useRef } from "react";+import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";import {FloatingPanel,FloatingPanelProvider,} from "~/builder/shared/floating-panel";-import { useRef, useState } from "react";-import type { SetProperty } from "../../shared/use-style-data";import {$breakpoints,$selectedBreakpointId,@@ -14,7 +12,7 @@ import {$styleSourceSelections,} from "~/shared/nano-states";import { registerContainers } from "~/shared/sync";-import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";+import { BackgroundContent } from "./background-content";const backgroundImage: StyleDecl = {breakpointId: "base",@@ -35,35 +33,9 @@ $styleSourceSelections.set();$selectedInstanceSelector.set(["box"]);-const defaultCurrentStyle = getLayerBackgroundStyleInfo(0, {- backgroundImage: {- value: backgroundImage.value,- },-});-const deleteProperty = () => () => {- // do nothing-};-export const BackgroundContentStory = () => {const elementRef = useRef<HTMLDivElement>(null);- const [currentStyle, setCurrentStyle] = useState(defaultCurrentStyle);-- const setProperty: SetProperty =- (propertyName: string) => (style, options) => {- if (options?.isEphemeral) {- return;- }-- setCurrentStyle({- ...currentStyle,- [propertyName]: {- value: style,- local: style,- },- });- };-return (<><div ref={elementRef} style={{ marginLeft: "400px" }}></div>@@ -72,17 +44,7 @@ export const BackgroundContentStory = () => {<FloatingPanelopen={true}title="Background"- content={- <BackgroundContent- index={0}- currentStyle={currentStyle}- deleteProperty={deleteProperty}- setProperty={setProperty}- setBackgroundColor={(color) => {- setProperty("backgroundColor")(color);- }}- />- }+ content={<BackgroundContent index={0} />}><div>Trigger</div></FloatingPanel>diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsxindex 43f55a65e5..f3b73857fc 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsx@@ -5,14 +5,13 @@import { useRef, useState } from "react";import { propertyDescriptions } from "@webstudio-is/css-data";-import type { StyleValue } from "@webstudio-is/css-engine";import {RepeatGridIcon,RepeatColumnIcon,RepeatRowIcon,CrossSmallIcon,} from "@webstudio-is/icons";-import { toValue } from "@webstudio-is/css-engine";+import { StyleValue, toValue } from "@webstudio-is/css-engine";import {theme,Flex,@@ -23,18 +22,6 @@ import {styled,} from "@webstudio-is/design-system";import { ImageControl, SelectControl } from "../../controls";-import type { StyleInfo } from "../../shared/style-info";-import type {- DeleteProperty,- SetProperty,- StyleUpdateOptions,-} from "../../shared/use-style-data";-import {- type DeleteBackgroundProperty,- isBackgroundLayeredProperty,- isBackgroundStyleValue,- type SetBackgroundProperty,-} from "./background-layers";import { FloatingPanelProvider } from "~/builder/shared/floating-panel";import { BackgroundSize } from "./background-size";import { BackgroundGradient } from "./background-gradient";@@ -42,55 +29,18 @@ import { BackgroundImage } from "./background-image";import { BackgroundPosition } from "./background-position";import { PropertyInlineLabel } from "../../property-label";import { ToggleGroupTooltip } from "../../controls/toggle-group/toggle-group-control";+import { useComputedStyleDecl } from "../../shared/model";+import {+ getRepeatedStyleItem,+ setRepeatedStyleItem,+} from "../../shared/repeated-style";-type BackgroundContentProps = {- index: number;- currentStyle: StyleInfo;- setProperty: SetBackgroundProperty;- deleteProperty: DeleteBackgroundProperty;- setBackgroundColor: (color: StyleValue) => void;-};--const safeDeleteProperty = (- deleteProperty: DeleteBackgroundProperty-): DeleteProperty => {- return (property, options) => {- const isLayered = isBackgroundLayeredProperty(property);- if (isLayered) {- return deleteProperty(property, options);- }- throw new Error(`Property ${property} should be background style property`);- };-};--const safeSetProperty = (setBackgroundProperty: SetBackgroundProperty) => {- const result: SetProperty = (property) => {- if (isBackgroundLayeredProperty(property)) {- return (style: string | StyleValue, options?: StyleUpdateOptions) => {- if (typeof style === "string") {- throw new Error("style should be StyleValue and not a string");- }-- if (isBackgroundStyleValue(style)) {- return setBackgroundProperty(property)(style, options);- }-- throw new Error("Style should be valid BackgroundStyleValue");- };- }-- throw new Error(`Property ${property} should be background style property`);- };-- return result;-};--const detectImageOrGradientToggle = (currentStyle: StyleInfo) => {- if (currentStyle?.backgroundImage?.value.type === "image") {+const detectImageOrGradientToggle = (styleValue?: StyleValue) => {+ if (styleValue?.type === "image") {return "image";}- if (currentStyle?.backgroundImage?.value.type === "keyword") {+ if (styleValue?.type === "keyword") {// The only allowed keyword for backgroundImage is nonereturn "image";}@@ -111,8 +61,9 @@ const Spacer = styled("div", {height: theme.spacing[5],});-const BackgroundRepeat = (props: BackgroundContentProps) => {- const { currentStyle, setProperty } = props;+const BackgroundRepeat = ({ index }: { index: number }) => {+ const styleDecl = useComputedStyleDecl("backgroundRepeat");+ const value = getRepeatedStyleItem(styleDecl.cascadedValue, index);const items = [{child: <CrossSmallIcon />,@@ -146,65 +97,75 @@ const BackgroundRepeat = (props: BackgroundContentProps) => {// onMouseEnter used to preserve default hovering behavior on tooltip.const [activeTooltip, setActiveTooltip] = useState<undefined | string>();return (- <>- <PropertyInlineLabel- label="Repeat"- description={propertyDescriptions.backgroundRepeat}- properties={["backgroundRepeat"]}- />-- <Flex css={{ justifySelf: "end" }}>- <ToggleGroup- type="single"- value={toValue(currentStyle.backgroundRepeat?.value)}- onValueChange={(value) => {- setProperty("backgroundRepeat")({- type: "keyword",- value,- });- }}+ <ToggleGroup+ type="single"+ value={toValue(value)}+ onValueChange={(value) => {+ setRepeatedStyleItem(styleDecl, index, { type: "keyword", value });+ }}+ >+ {items.map((item) => (+ <ToggleGroupTooltip+ key={item.value}+ isOpen={item.value === activeTooltip}+ onOpenChange={(isOpen) =>+ setActiveTooltip(isOpen ? item.value : undefined)+ }+ isSelected={false}+ label="Background Repeat"+ code={`background-repeat: ${item.value};`}+ description={item.description}+ properties={["backgroundRepeat"]}>- {items.map((item) => (- <ToggleGroupTooltip- key={item.value}- isOpen={item.value === activeTooltip}- onOpenChange={(isOpen) =>- setActiveTooltip(isOpen ? item.value : undefined)- }- isSelected={false}- label="Background Repeat"- code={`background-repeat: ${item.value};`}- description={item.description}- properties={["backgroundRepeat"]}- >- <ToggleGroupButton- value={item.value}- onMouseEnter={() =>- // reset only when highlighted is not active- setActiveTooltip((prevValue) =>- prevValue === item.value ? prevValue : undefined- )- }- >- {item.child}- </ToggleGroupButton>- </ToggleGroupTooltip>- ))}- </ToggleGroup>- </Flex>- </>+ <ToggleGroupButton+ value={item.value}+ onMouseEnter={() =>+ // reset only when highlighted is not active+ setActiveTooltip((prevValue) =>+ prevValue === item.value ? prevValue : undefined+ )+ }+ >+ {item.child}+ </ToggleGroupButton>+ </ToggleGroupTooltip>+ ))}+ </ToggleGroup>+ );+};++const BackgroundAttachment = ({ index }: { index: number }) => {+ const styleDecl = useComputedStyleDecl("backgroundAttachment");+ const value = getRepeatedStyleItem(styleDecl.cascadedValue, index);+ return (+ <ToggleGroup+ type="single"+ value={toValue(value)}+ onValueChange={(value) => {+ setRepeatedStyleItem(styleDecl, index, { type: "keyword", value });+ }}+ >+ <ToggleGroupButton value={"scroll"}>+ <Flex css={{ px: theme.spacing[3] }}>Scroll</Flex>+ </ToggleGroupButton>+ <ToggleGroupButton value={"fixed"}>+ <Flex css={{ px: theme.spacing[3] }}>Fixed</Flex>+ </ToggleGroupButton>+ </ToggleGroup>);};-export const BackgroundContent = (props: BackgroundContentProps) => {- const setProperty = safeSetProperty(props.setProperty);- const deleteProperty = safeDeleteProperty(props.deleteProperty);- const { currentStyle, index } = props;+export const BackgroundContent = ({ index }: { index: number }) => {+ const backgroundImage = useComputedStyleDecl("backgroundImage");const elementRef = useRef<HTMLDivElement>(null);const [imageGradientToggle, setImageGradientToggle] = useState<"image" | "gradient"- >(() => detectImageOrGradientToggle(currentStyle));+ >(() =>+ detectImageOrGradientToggle(+ getRepeatedStyleItem(backgroundImage.cascadedValue, index)+ )+ );return (<>@@ -251,7 +212,6 @@ export const BackgroundContent = (props: BackgroundContentProps) => {properties={["backgroundImage"]}/></Flex>-<FloatingPanelProvider container={elementRef}><ImageControl property="backgroundImage" index={index} /></FloatingPanelProvider>@@ -263,33 +223,23 @@ export const BackgroundContent = (props: BackgroundContentProps) => {description={propertyDescriptions.backgroundClip}properties={["backgroundClip"]}/>-- <SelectControl property="backgroundClip" />+ <SelectControl property="backgroundClip" index={index} /><PropertyInlineLabellabel="Origin"description={propertyDescriptions.backgroundOrigin}properties={["backgroundOrigin"]}/>-- <SelectControl property="backgroundOrigin" />+ <SelectControl property="backgroundOrigin" index={index} /></Grid><Spacer />- <BackgroundSize- setProperty={setProperty}- deleteProperty={deleteProperty}- currentStyle={currentStyle}- />+ <BackgroundSize index={index} /><Spacer />- <BackgroundPosition- currentStyle={currentStyle}- setProperty={setProperty}- deleteProperty={deleteProperty}- />+ <BackgroundPosition index={index} /><Gridcss={{@@ -299,32 +249,26 @@ export const BackgroundContent = (props: BackgroundContentProps) => {align="center"gap={2}>- {imageGradientToggle === "image" && <BackgroundRepeat {...props} />}+ {imageGradientToggle === "image" && (+ <>+ <PropertyInlineLabel+ label="Repeat"+ description={propertyDescriptions.backgroundRepeat}+ properties={["backgroundRepeat"]}+ />+ <Flex css={{ justifySelf: "end" }}>+ <BackgroundRepeat index={index} />+ </Flex>+ </>+ )}<PropertyInlineLabellabel="Attachment"description={propertyDescriptions.backgroundAttachment}properties={["backgroundAttachment"]}/>-<Flex css={{ justifySelf: "end" }}>- <ToggleGroup- type="single"- value={toValue(currentStyle.backgroundAttachment?.value)}- onValueChange={(value) => {- setProperty("backgroundAttachment")({- type: "keyword",- value,- });- }}- >- <ToggleGroupButton value={"scroll"}>- <Flex css={{ px: theme.spacing[3] }}>Scroll</Flex>- </ToggleGroupButton>- <ToggleGroupButton value={"fixed"}>- <Flex css={{ px: theme.spacing[3] }}>Fixed</Flex>- </ToggleGroupButton>- </ToggleGroup>+ <BackgroundAttachment index={index} /></Flex><PropertyInlineLabel@@ -332,25 +276,15 @@ export const BackgroundContent = (props: BackgroundContentProps) => {description={propertyDescriptions.backgroundBlendMode}properties={["backgroundBlendMode"]}/>-- <SelectControl property="backgroundBlendMode" />+ <SelectControl property="backgroundBlendMode" index={index} /></Grid></BackgroundSection><Separator css={{ gridColumn: "span 2" }} />{imageGradientToggle === "image" ? (- <BackgroundImage- setProperty={setProperty}- deleteProperty={deleteProperty}- currentStyle={currentStyle}- />+ <BackgroundImage index={index} />) : (- <BackgroundGradient- setProperty={setProperty}- deleteProperty={deleteProperty}- currentStyle={currentStyle}- setBackgroundColor={props.setBackgroundColor}- />+ <BackgroundGradient index={index} />)}</>);diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsxindex a3f0605a3a..d65136c978 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-gradient.tsx@@ -14,9 +14,15 @@ import {Tooltip,} from "@webstudio-is/design-system";import { useEffect, useRef, useState } from "react";-import type { ControlProps } from "../../controls";import { parseCssFragment } from "../../shared/parse-css-fragment";import { InfoCircleIcon } from "@webstudio-is/icons";+import { setProperty } from "../../shared/use-style-data";+import { useComputedStyleDecl } from "../../shared/model";+import {+ editRepeatedStyleItem,+ getRepeatedStyleItem,+ setRepeatedStyleItem,+} from "../../shared/repeated-style";type IntermediateValue = {type: "intermediate";@@ -26,16 +32,11 @@ type IntermediateValue = {const isTransparent = (color: StyleValue) =>color.type === "keyword" && color.value === "transparent";-export const BackgroundGradient = (- props: Omit<ControlProps, "property" | "items"> & {- setBackgroundColor: (color: StyleValue) => void;- }-) => {- const property = "backgroundImage";+export const BackgroundGradient = ({ index }: { index: number }) => {const textAreaRef = useRef<HTMLTextAreaElement>(null);-- const styleInfo = props.currentStyle[property];- const styleValue = styleInfo?.value;+ const property = "backgroundImage";+ const styleDecl = useComputedStyleDecl(property);+ const styleValue = getRepeatedStyleItem(styleDecl.cascadedValue, index);const [intermediateValue, setIntermediateValue] = useState<IntermediateValue | InvalidValue | undefined@@ -57,12 +58,14 @@ export const BackgroundGradient = (const newValue = parseCssValue(property, value);if (newValue.type === "unparsed") {- props.setProperty(property)(newValue, { isEphemeral: true });+ setRepeatedStyleItem(styleDecl, index, newValue, { isEphemeral: true });return;}// Set backgroundImage at layer to none if it's invalid- props.setProperty(property)(+ setRepeatedStyleItem(+ styleDecl,+ index,{ type: "keyword", value: "none" },{ isEphemeral: true });@@ -89,15 +92,23 @@ export const BackgroundGradient = (firstLayer.type === "invalid") {setIntermediateValue({ type: "invalid", value: intermediateValue.value });- props.deleteProperty(property, { isEphemeral: true });+ if (styleValue) {+ setRepeatedStyleItem(styleDecl, index, styleValue, {+ isEphemeral: true,+ });+ }return;}setIntermediateValue(undefined);if (backgroundColor && isTransparent(backgroundColor) === false) {- props.setBackgroundColor(backgroundColor);+ setProperty("backgroundColor")(backgroundColor);}// insert all new layers at current position- props.setProperty(property)(layers);+ editRepeatedStyleItem(+ [styleDecl],+ index,+ new Map([["backgroundImage", layers]])+ );};const handleOnCompleteRef = useRef(handleOnComplete);@@ -158,15 +169,6 @@ export const BackgroundGradient = (handleOnComplete();event.preventDefault();}-- if (event.key === "Escape") {- if (intermediateValue === undefined) {- return;- }- props.deleteProperty(property, { isEphemeral: true });- setIntermediateValue(undefined);- event.preventDefault();- }}}/></Flex>diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsxindex db6371290b..ca141a2124 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-image.tsx@@ -10,12 +10,17 @@ import {Text,} from "@webstudio-is/design-system";import { useRef, useState, useEffect } from "react";-import type { ControlProps } from "../../controls";+import type {} from "../../controls";import { useStore } from "@nanostores/react";import { $assets } from "~/shared/nano-states";import type { StyleUpdateOptions } from "../../shared/use-style-data";import { InfoCircleIcon } from "@webstudio-is/icons";import { parseCssFragment } from "../../shared/parse-css-fragment";+import { useComputedStyleDecl } from "../../shared/model";+import {+ getRepeatedStyleItem,+ setRepeatedStyleItem,+} from "../../shared/repeated-style";type IntermediateValue = {type: "intermediate";@@ -30,12 +35,11 @@ const isAbsoluteURL = (value: string) => {}};-export const BackgroundImage = (- props: Omit<ControlProps, "property" | "items">-) => {+export const BackgroundImage = ({ index }: { index: number }) => {const textAreaRef = useRef<HTMLTextAreaElement>(null);const assets = useStore($assets);- const styleValue = props.currentStyle.backgroundImage?.value;+ const styleDecl = useComputedStyleDecl("backgroundImage");+ const styleValue = getRepeatedStyleItem(styleDecl.cascadedValue, index);const [errors, setErrors] = useState<string[]>([]);const [intermediateValue, setIntermediateValue] = useState<IntermediateValue | InvalidValue | undefined@@ -100,7 +104,7 @@ export const BackgroundImage = (const [layer] = newValue.type === "layers" ? newValue.value : [newValue];if (layer?.type === "keyword") {setIntermediateValue(undefined);- props.setProperty("backgroundImage")(layer, options);+ setRepeatedStyleItem(styleDecl, index, layer, options);}if (layer?.type !== "image" || layer.value.type !== "url") {setIntermediateValue({@@ -112,7 +116,7 @@ export const BackgroundImage = (const url = layer.value.url;if (isAbsoluteURL(url) === true) {- props.setProperty("backgroundImage")(layer, options);+ setRepeatedStyleItem(styleDecl, index, layer, options);} else {const usedAsset = Array.from($assets.get().values()).find((asset) => asset.type === "image" && asset.name === url@@ -128,13 +132,12 @@ export const BackgroundImage = (}setErrors([]);- props.setProperty("backgroundImage")(+ setRepeatedStyleItem(+ styleDecl,+ index,{type: "image",- value: {- type: "asset",- value: usedAsset.id,- },+ value: { type: "asset", value: usedAsset.id },},options);@@ -182,17 +185,16 @@ export const BackgroundImage = (color={intermediateValue?.type === "invalid" ? "error" : undefined}value={intermediateValue !== undefined ? intermediateValue.value : ""}onChange={(value) => handleChange(value, { isEphemeral: true })}+ onBlur={() => {+ if (intermediateValue !== undefined) {+ handleChange(intermediateValue.value, { isEphemeral: false });+ }+ }}onKeyDown={(event) => {if (event.key === "Enter" && intermediateValue !== undefined) {handleChange(intermediateValue.value, { isEphemeral: false });event.preventDefault();}-- if (event.key === "Escape") {- props.deleteProperty("backgroundImage", { isEphemeral: true });- setIntermediateValue(undefined);- event.preventDefault();- }}}/></InputErrorsTooltip>diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.tsindex a1eb3a37f6..02bc0a8c54 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.ts+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.ts@@ -1,4 +1,4 @@-import type { LayersValue, StyleValue } from "@webstudio-is/css-engine";+import type { LayersValue } from "@webstudio-is/css-engine";import type { StyleInfo, StyleValueInfo } from "../../shared/style-info";import type {CreateBatchUpdate,@@ -20,23 +20,6 @@ export const layeredBackgroundPropsDefaults = {export type BackgroundStyleValue = LayersValue | LayersValue["value"][number];-export const isBackgroundStyleValue = (- style: StyleValue-): style is BackgroundStyleValue => {- if (- style.type === "unit" ||- style.type === "keyword" ||- style.type === "unparsed" ||- style.type === "image" ||- style.type === "tuple" ||- style.type === "invalid" ||- style.type === "layers"- ) {- return true;- }- return false;-};-type BackgroundProperty = keyof typeof layeredBackgroundPropsDefaults;export const layeredBackgroundProps = Object.keys(@@ -45,12 +28,6 @@ export const layeredBackgroundProps = Object.keys(export type LayeredBackgroundProperty = (typeof layeredBackgroundProps)[number];-export const isBackgroundLayeredProperty = (- prop: string-): prop is LayeredBackgroundProperty => {- return layeredBackgroundProps.includes(prop as LayeredBackgroundProperty);-};-const getPropertyLayerCount = (style: StyleValueInfo) => {if (style.value.type === "layers") {return style.value.value.length;diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-position.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-position.tsxindex f9bb55ad78..3b0cbea300 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-position.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-position.tsx@@ -1,14 +1,13 @@-import { keywordValues, propertyDescriptions } from "@webstudio-is/css-data";+import type { StyleValue } from "@webstudio-is/css-engine";+import { propertyDescriptions } from "@webstudio-is/css-data";import { Flex, Grid, PositionGrid } from "@webstudio-is/design-system";-import {- getStyleSource,- type StyleInfo,- type StyleValueInfo,-} from "../../shared/style-info";import { CssValueInputContainer } from "../../shared/css-value-input";-import type { DeleteProperty, SetProperty } from "../../shared/use-style-data";-import { useMemo } from "react";import { PropertyInlineLabel } from "../../property-label";+import { useComputedStyles } from "../../shared/model";+import {+ getRepeatedStyleItem,+ setRepeatedStyleItem,+} from "../../shared/repeated-style";const keyworkToValue: Record<string, number> = {left: 0,@@ -18,31 +17,25 @@ const keyworkToValue: Record<string, number> = {bottom: 100,};-const calculateBackgroundPosition = (info: StyleValueInfo | undefined) => {- if (info?.value.type === "unit") {- return info.value.value;+const calculateBackgroundPosition = (value: undefined | StyleValue) => {+ if (value?.type === "unit") {+ return value.value;}-- if (info?.value.type === "keyword") {- return keyworkToValue[info.value.value];+ if (value?.type === "keyword") {+ return keyworkToValue[value.value];}-return 0;};-export const BackgroundPosition = ({- currentStyle,- setProperty,- deleteProperty,-}: {- currentStyle: StyleInfo;- setProperty: SetProperty;- deleteProperty: DeleteProperty;-}) => {- const xInfo = currentStyle.backgroundPositionX;- const yInfo = currentStyle.backgroundPositionY;- const x = useMemo(() => calculateBackgroundPosition(xInfo), [xInfo]);- const y = useMemo(() => calculateBackgroundPosition(yInfo), [yInfo]);+export const BackgroundPosition = ({ index }: { index: number }) => {+ const [backgroundPositionX, backgroundPositionY] = useComputedStyles([+ "backgroundPositionX",+ "backgroundPositionY",+ ]);+ const xValue = getRepeatedStyleItem(backgroundPositionX.cascadedValue, index);+ const yValue = getRepeatedStyleItem(backgroundPositionY.cascadedValue, index);+ const x = calculateBackgroundPosition(xValue);+ const y = calculateBackgroundPosition(yValue);return (<Flex direction="column" gap="1">@@ -55,12 +48,12 @@ export const BackgroundPosition = ({<PositionGridselectedPosition={{ x, y }}onSelect={({ x, y }) => {- setProperty("backgroundPositionX")({+ setRepeatedStyleItem(backgroundPositionX, index, {type: "unit",value: x,unit: "%",});- setProperty("backgroundPositionY")({+ setRepeatedStyleItem(backgroundPositionY, index, {type: "unit",value: y,unit: "%",@@ -79,14 +72,21 @@ export const BackgroundPosition = ({/><CssValueInputContainerproperty="backgroundPositionX"- styleSource={getStyleSource(xInfo)}- keywords={keywordValues.backgroundPositionX.map((value) => ({- type: "keyword",- value,- }))}- value={xInfo?.value}- setValue={setProperty("backgroundPositionX")}- deleteProperty={deleteProperty}+ styleSource="default"+ keywords={[+ { type: "keyword", value: "center" },+ { type: "keyword", value: "left" },+ { type: "keyword", value: "right" },+ ]}+ value={xValue}+ setValue={(value, options) => {+ setRepeatedStyleItem(backgroundPositionX, index, value, options);+ }}+ deleteProperty={() => {+ if (xValue) {+ setRepeatedStyleItem(backgroundPositionX, index, xValue);+ }+ }}/><PropertyInlineLabellabel="Top"@@ -95,14 +95,21 @@ export const BackgroundPosition = ({/><CssValueInputContainerproperty="backgroundPositionY"- styleSource={getStyleSource(yInfo)}- keywords={keywordValues.backgroundPositionY.map((value) => ({- type: "keyword",- value,- }))}- value={yInfo?.value}- setValue={setProperty("backgroundPositionY")}- deleteProperty={deleteProperty}+ styleSource="default"+ keywords={[+ { type: "keyword", value: "center" },+ { type: "keyword", value: "top" },+ { type: "keyword", value: "bottom" },+ ]}+ value={yValue}+ setValue={(value, options) => {+ setRepeatedStyleItem(backgroundPositionY, index, value, options);+ }}+ deleteProperty={() => {+ if (yValue) {+ setRepeatedStyleItem(backgroundPositionY, index, yValue);+ }+ }}/></Grid></Flex>diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-size.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-size.tsxindex 82ce451406..50c02d7a42 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-size.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-size.tsx@@ -1,18 +1,22 @@import { Grid, Select, theme } from "@webstudio-is/design-system";import { toValue } from "@webstudio-is/css-engine";-import { styleConfigByName } from "../../shared/configs";-import { parseCssValue, propertyDescriptions } from "@webstudio-is/css-data";-import { CssValueInputContainer } from "../../shared/css-value-input";+import { propertyDescriptions } from "@webstudio-is/css-data";import {type StyleValue,TupleValue,TupleValueItem,} from "@webstudio-is/css-engine";+import { styleConfigByName } from "../../shared/configs";+import { CssValueInputContainer } from "../../shared/css-value-input";import type { SetValue } from "../../shared/use-style-data";-import type { ControlProps } from "../../controls";import { PropertyInlineLabel } from "../../property-label";+import { useComputedStyleDecl } from "../../shared/model";+import {+ getRepeatedStyleItem,+ setRepeatedStyleItem,+} from "../../shared/repeated-style";-const StyleKeywordAuto = { type: "keyword" as const, value: "auto" };+const autoKeyword = { type: "keyword" as const, value: "auto" };const toTuple = (valueX?: StyleValue | string,@@ -23,7 +27,7 @@ const toTuple = (return parsedValue.data;}- const parsedValueX = valueX ? TupleValueItem.parse(valueX) : StyleKeywordAuto;+ const parsedValueX = valueX ? TupleValueItem.parse(valueX) : autoKeyword;const parsedValueY = valueY ? TupleValueItem.parse(valueY) : parsedValueX;return {@@ -32,14 +36,11 @@ const toTuple = (};};-export const BackgroundSize = (- props: Omit<ControlProps, "property" | "items">-) => {+export const BackgroundSize = ({ index }: { index: number }) => {const property = "backgroundSize";+ const styleDecl = useComputedStyleDecl(property);+ const styleValue = getRepeatedStyleItem(styleDecl.cascadedValue, index);- const styleInfo = props.currentStyle[property];- const styleValue = styleInfo?.value;- const styleSource = "default";const { items: defaultItems } = styleConfigByName(property);const selectOptions = [@@ -50,10 +51,12 @@ export const BackgroundSize = (styleValue?.type === "keyword" ? toValue(styleValue) : "custom";const customSizeDisabled = styleValue?.type === "keyword";- const customSizeOptions = [StyleKeywordAuto];+ const customSizeOptions = [autoKeyword];const customSizeValue = toTuple(styleValue);- const setValue = props.setProperty(property);+ const setValue: SetValue = (value, options) => {+ setRepeatedStyleItem(styleDecl, index, value, options);+ };const setValueX: SetValue = (value, options) => {const [x] = value.type === "layers" ? value.value : [];@@ -88,13 +91,10 @@ export const BackgroundSize = (value={selectValue}onChange={(name: string) => {if (name === "custom") {- return setValue({- type: "tuple",- value: [StyleKeywordAuto, StyleKeywordAuto],- });+ setValue({ type: "tuple", value: [autoKeyword, autoKeyword] });+ } else {+ setValue({ type: "keyword", value: name });}- const cssValue = parseCssValue(property, name);- setValue(cssValue);}}onItemHighlight={(name) => {// No need to preview custom size as it needs additional user input.@@ -109,8 +109,7 @@ export const BackgroundSize = (return;}// Preview on mouse enter or focus.- const cssValue = parseCssValue(property, name);- setValue(cssValue, { isEphemeral: true });+ setValue({ type: "keyword", value: name }, { isEphemeral: true });}}onOpenChange={(isOpen) => {// Remove ephemeral changes when closing the menu.@@ -146,21 +145,21 @@ export const BackgroundSize = (<CssValueInputContainerdisabled={customSizeDisabled}property={property}- styleSource={styleSource}+ styleSource="default"keywords={customSizeOptions}value={customSizeValue.value[0]}setValue={setValueX}- deleteProperty={props.deleteProperty}+ deleteProperty={() => {}}/><CssValueInputContainerdisabled={customSizeDisabled}property={property}- styleSource={styleSource}+ styleSource="default"keywords={customSizeOptions}value={customSizeValue.value[1]}setValue={setValueY}- deleteProperty={props.deleteProperty}+ deleteProperty={() => {}}/></Grid></>diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsxindex d6ae5e8ca6..b86c13adbb 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsx@@ -84,15 +84,7 @@ const Layer = (props: {// This is a workaround to prevent the panel from moving around too much when the tabs are changed from the popover trigger.align="center"collisionPadding={{ bottom: 200, top: 200 }}- content={- <BackgroundContent- index={props.index}- currentStyle={props.layerStyle}- setProperty={props.setProperty}- deleteProperty={props.deleteProperty}- setBackgroundColor={props.setBackgroundColor}- />- }+ content={<BackgroundContent index={props.index} />}><CssValueListItemid={props.id}diff --git a/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts b/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.tsindex 09cb3d603d..b16e989f45 100644--- a/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts+++ b/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts@@ -218,6 +218,30 @@ test("set layers item into repeated style", () => {});});+test("unpack item from layers value in repeated style", () => {+ const $transitionProperty =+ createComputedStyleDeclStore("transitionProperty");+ addRepeatedStyleItem(+ [$transitionProperty.get()],+ parseCssFragment("opacity", "transitionProperty")+ );+ addRepeatedStyleItem(+ [$transitionProperty.get()],+ parseCssFragment("transform", "transitionProperty")+ );+ setRepeatedStyleItem($transitionProperty.get(), 1, {+ type: "layers",+ value: [{ type: "unparsed", value: "width" }],+ });+ expect($transitionProperty.get().cascadedValue).toEqual({+ type: "layers",+ value: [+ { type: "unparsed", value: "opacity" },+ { type: "unparsed", value: "width" },+ ],+ });+});+test("delete layer from repeated style", () => {const $transitionProperty =createComputedStyleDeclStore("transitionProperty");diff --git a/apps/builder/app/builder/features/style-panel/shared/repeated-style.tsx b/apps/builder/app/builder/features/style-panel/shared/repeated-style.tsxindex 606f7442d2..45f52f0286 100644--- a/apps/builder/app/builder/features/style-panel/shared/repeated-style.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/repeated-style.tsx@@ -106,19 +106,21 @@ export const editRepeatedStyleItem = (export const setRepeatedStyleItem = (styleDecl: ComputedStyleDecl,index: number,- newItem: StyleValue+ newItem: StyleValue,+ options?: StyleUpdateOptions) => {const batch = createBatchUpdate();const value = styleDecl.cascadedValue;const valueType: ItemType = value.type === "tuple" ? "tuple" : "layers";const oldItems = value.type === valueType ? value.value : [];const newItems: StyleValue[] = repeatUntil(oldItems, index);- newItems[index] = newItem;+ // unpack item when layers or tuple is provided+ newItems[index] = newItem.type === valueType ? newItem.value[0] : newItem;batch.setProperty(styleDecl.property as StyleProperty)({type: valueType,value: newItems as UnparsedValue[],});- batch.publish();+ batch.publish(options);};export const deleteRepeatedStyleItem = (