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
refactor: rewrite backgrounds section with repeated style (#4112)
Bogdan Chadkindcc75c1fd52b
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 f3b73857fc..d2d2b301d0 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@@ -11,7 +11,7 @@ import {RepeatRowIcon,CrossSmallIcon,} from "@webstudio-is/icons";-import { StyleValue, toValue } from "@webstudio-is/css-engine";+import { type StyleValue, toValue } from "@webstudio-is/css-engine";import {theme,Flex,diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.test.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.test.tsdeleted file mode 100644index 036af51b27..0000000000--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.test.ts+++ /dev/null@@ -1,530 +0,0 @@-import {- layeredBackgroundProps,- setLayerProperty,- addLayer,- swapLayers,- deleteLayer,-} from "./background-layers";--import { describe, test, expect } from "@jest/globals";-import type { StyleInfo } from "../../shared/style-info";-import type { CreateBatchUpdate } from "../../shared/use-style-data";-import type {- LayersValue,- StyleProperty,- StyleValue,-} from "@webstudio-is/css-engine";--describe("setLayerProperty", () => {- test("should work", () => {- const styleInfo: StyleInfo = {};- let changedProps: [string, LayersValue][] = [];- let published = false;-- const createBatchUpdate: CreateBatchUpdate = () => ({- setProperty:- (propertyName: StyleProperty) => (newValue: string | StyleValue) => {- if (typeof newValue === "string") {- throw new Error("string is deprecated");- }-- if (newValue.type !== "layers") {- throw new Error("newValue.type !== layers");- }-- const index = changedProps.findIndex(- ([property]) => property === propertyName- );-- styleInfo[propertyName] = { value: newValue, local: newValue };-- if (index !== -1) {- changedProps[index] = [propertyName, newValue];- return;- }-- changedProps.push([propertyName, newValue]);- },- deleteProperty: (_propertyName: string) => {- // not used- },- publish: (_options?: unknown) => {- published = true;- },- });-- const setProperty = setLayerProperty(0, styleInfo, createBatchUpdate);-- setProperty("backgroundPositionX")({ type: "unit", value: 10, unit: "px" });-- expect(published).toBe(true);-- // All props changed if layer wasn't defined- expect(changedProps.map((changedProp) => changedProp[0])).toEqual(- layeredBackgroundProps- );- // All prop layers are set and have length 1- expect(- changedProps.map((changedProp) => changedProp[1].value.length)- ).toEqual(layeredBackgroundProps.map(() => 1));-- changedProps = [];-- // Single property change if layer exists and has no errors should not touch all properties- setProperty("backgroundRepeat")({ type: "keyword", value: "no-repeat" });- expect(changedProps.map((changedProp) => changedProp[0])).toEqual([- "backgroundRepeat",- ]);-- changedProps = [];-- // Set non array value, should be restored to array- styleInfo.backgroundClip = {- value: { type: "keyword", value: "repeat" },- local: { type: "keyword", value: "repeat" },- };- setProperty("backgroundRepeat")({ type: "keyword", value: "no-repeat" });-- expect(changedProps.map((changedProp) => changedProp[0])).toEqual([- "backgroundClip",- "backgroundRepeat",- ]);-- expect(styleInfo.backgroundClip?.value.type).toEqual("layers");-- changedProps = [];-- // Set wrong count- styleInfo.backgroundClip = {- value: {- type: "layers",- value: [],- },- local: {- type: "layers",- value: [],- },- };-- setProperty("backgroundRepeat")({ type: "keyword", value: "no-repeat" });-- expect(changedProps.map((changedProp) => changedProp[0])).toEqual([- "backgroundClip",- "backgroundRepeat",- ]);-- expect(- changedProps.map((changedProp) => changedProp[1].value.length)- ).toEqual([1, 1]);- });-- test("should work with cascade", () => {- const cascaded: NonNullable<StyleInfo["backgroundImage"]>["cascaded"] = {- breakpointId: "mobile",- value: {- type: "layers",- value: [- {- type: "unparsed",- value: "linear-gradient(red, blue)",- },- {- type: "unparsed",- value: "linear-gradient(yellow, red)",- },- ],- },- };- const styleInfo: StyleInfo = {- backgroundImage: {- cascaded,- value: cascaded.value,- },- };- let changedProps: [string, LayersValue][] = [];- let published = false;-- const createBatchUpdate: CreateBatchUpdate = () => ({- setProperty:- (propertyName: StyleProperty) => (newValue: string | StyleValue) => {- if (typeof newValue === "string") {- throw new Error("string is deprecated");- }-- if (newValue.type !== "layers") {- throw new Error("newValue.type !== layers");- }-- const index = changedProps.findIndex(- ([property]) => property === propertyName- );-- styleInfo[propertyName] = { value: newValue, local: newValue };-- if (index !== -1) {- changedProps[index] = [propertyName, newValue];- return;- }-- changedProps.push([propertyName, newValue]);- },- deleteProperty: (_propertyName: string) => {- // not used- },- publish: (_options?: unknown) => {- published = true;- },- });-- const setProperty = setLayerProperty(0, styleInfo, createBatchUpdate);-- setProperty("backgroundPositionX")({ type: "unit", value: 10, unit: "px" });-- expect(published).toBe(true);-- expect(changedProps.map((changedProp) => changedProp[0])).toEqual(- layeredBackgroundProps- );-- // All prop layers are set and have length 2 (copied from cascaded)- expect(- changedProps.map((changedProp) => changedProp[1].value.length)- ).toEqual(layeredBackgroundProps.map(() => 2));-- changedProps = [];-- addLayer(styleInfo, createBatchUpdate);-- expect(- changedProps.map((changedProp) => changedProp[1].value.length)- ).toEqual(layeredBackgroundProps.map(() => 3));-- expect(- styleInfo.backgroundImage?.value.type === "layers" &&- styleInfo.backgroundImage?.value.value[0].type === "keyword" &&- styleInfo.backgroundImage?.value.value[0].value- ).toEqual("none");- });-- test("should insert mutiple layers", () => {- const cascaded: NonNullable<StyleInfo["backgroundImage"]>["cascaded"] = {- breakpointId: "mobile",- value: {- type: "layers",- value: [- {- type: "unparsed",- value: "linear-gradient(red, blue)",- },- {- type: "unparsed",- value: "linear-gradient(yellow, red)",- },- ],- },- };-- const cascadedPositionX: NonNullable<- StyleInfo["backgroundPositionX"]- >["cascaded"] = {- breakpointId: "mobile",- value: {- type: "layers",- value: [- {- type: "unit",- value: 10,- unit: "%",- },- {- type: "unit",- value: 50,- unit: "%",- },- ],- },- };-- const styleInfo: StyleInfo = {- backgroundImage: {- cascaded,- value: cascaded.value,- },- backgroundPositionX: {- cascaded: cascadedPositionX,- value: cascadedPositionX.value,- },- };-- let published = false;-- const createBatchUpdate: CreateBatchUpdate = () => ({- setProperty:- (propertyName: StyleProperty) => (newValue: string | StyleValue) => {- if (typeof newValue === "string") {- throw new Error("string is deprecated");- }-- if (newValue.type !== "layers") {- throw new Error("newValue.type !== layers");- }-- styleInfo[propertyName] = { value: newValue, local: newValue };- },- deleteProperty: (_propertyName: string) => {- // not used- },- publish: (_options?: unknown) => {- published = true;- },- });-- const setProperty = setLayerProperty(1, styleInfo, createBatchUpdate);-- setProperty("backgroundImage")({- type: "layers",- value: [- {- type: "unparsed",- value: "linear-gradient(blue, blue)",- },- ],- });-- expect(published).toBe(true);-- expect(styleInfo.backgroundImage?.value.type).toEqual("layers");- expect(styleInfo.backgroundImage?.value).toMatchInlineSnapshot(`- {- "type": "layers",- "value": [- {- "type": "unparsed",- "value": "linear-gradient(red, blue)",- },- {- "type": "unparsed",- "value": "linear-gradient(blue, blue)",- },- ],- }- `);-- // We should not reset existing properties to default values- expect(styleInfo.backgroundPositionX?.value).toMatchInlineSnapshot(`- {- "type": "layers",- "value": [- {- "type": "unit",- "unit": "%",- "value": 10,- },- {- "type": "unit",- "unit": "%",- "value": 50,- },- ],- }- `);-- setProperty("backgroundImage")({- type: "layers",- value: [- {- type: "unparsed",- value: "linear-gradient(green, blue)",- },- {- type: "unparsed",- value: "linear-gradient(yellow, blue)",- },- ],- });-- expect(styleInfo.backgroundImage?.value).toMatchInlineSnapshot(`- {- "type": "layers",- "value": [- {- "type": "unparsed",- "value": "linear-gradient(red, blue)",- },- {- "type": "unparsed",- "value": "linear-gradient(green, blue)",- },- {- "type": "unparsed",- "value": "linear-gradient(yellow, blue)",- },- ],- }- `);-- expect(styleInfo.backgroundPositionX?.value).toMatchInlineSnapshot(`- {- "type": "layers",- "value": [- {- "type": "unit",- "unit": "%",- "value": 10,- },- {- "type": "unit",- "unit": "%",- "value": 50,- },- {- "type": "unit",- "unit": "%",- "value": 0,- },- ],- }- `);- });-});--describe("deleteLayer", () => {- const cascaded: NonNullable<StyleInfo["backgroundImage"]>["cascaded"] = {- breakpointId: "mobile",- value: {- type: "layers",- value: [- {- type: "unparsed",- value: "linear-gradient(red, blue)",- },- {- type: "unparsed",- value: "linear-gradient(yellow, red)",- },- ],- },- };- const styleInfo: StyleInfo = {- backgroundImage: {- cascaded,- value: cascaded.value,- },- };-- let published = false;- const deletedProperties = new Set<string>();-- const createBatchUpdate: CreateBatchUpdate = () => ({- setProperty:- (propertyName: StyleProperty) => (newValue: string | StyleValue) => {- if (typeof newValue === "string") {- throw new Error("string is deprecated");- }-- if (newValue.type !== "layers") {- throw new Error("newValue.type !== layers");- }-- styleInfo[propertyName] = { value: newValue, local: newValue };- },- deleteProperty: (propertyName: string) => {- // not used- deletedProperties.add(propertyName);- },- publish: (_options?: unknown) => {- published = true;- },- });-- deleteLayer(0, styleInfo, createBatchUpdate)();-- expect(published).toBe(true);-- expect(styleInfo.backgroundImage?.value).toEqual({- type: "layers",- value: [{ type: "unparsed", value: "linear-gradient(yellow, red)" }],- });-- expect(deletedProperties.size).toBe(0);-- deleteLayer(0, styleInfo, createBatchUpdate)();-- expect(deletedProperties.size).toBe(layeredBackgroundProps.length);-});--describe("swapLayers", () => {- test("should work with cascade", () => {- const cascaded: NonNullable<StyleInfo["backgroundImage"]>["cascaded"] = {- breakpointId: "mobile",- value: {- type: "layers",- value: [- {- type: "unparsed",- value: "linear-gradient(red, blue)",- },- {- type: "unparsed",- value: "linear-gradient(yellow, red)",- },- ],- },- };- const styleInfo: StyleInfo = {- backgroundImage: {- cascaded,- value: cascaded.value,- },- };-- let published = false;-- const createBatchUpdate: CreateBatchUpdate = () => ({- setProperty:- (propertyName: StyleProperty) => (newValue: string | StyleValue) => {- if (typeof newValue === "string") {- throw new Error("string is deprecated");- }-- if (newValue.type !== "layers") {- throw new Error("newValue.type !== layers");- }-- styleInfo[propertyName] = { value: newValue, local: newValue };- },- deleteProperty: (_propertyName: string) => {- // not used- },- publish: (_options?: unknown) => {- published = true;- },- });-- swapLayers(0, 1, styleInfo, createBatchUpdate);-- expect(published).toBe(true);-- expect(styleInfo.backgroundImage?.value).toEqual({- type: "layers",- value: [- { type: "unparsed", value: "linear-gradient(yellow, red)" },- { type: "unparsed", value: "linear-gradient(red, blue)" },- ],- });-- expect(styleInfo.backgroundImage?.value).toEqual(- styleInfo.backgroundImage?.local- );-- swapLayers(0, 1, styleInfo, createBatchUpdate);-- expect(styleInfo.backgroundImage?.value).toEqual({- type: "layers",- value: [- { type: "unparsed", value: "linear-gradient(red, blue)" },- { type: "unparsed", value: "linear-gradient(yellow, red)" },- ],- });- });-});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.tsdeleted file mode 100644index 02bc0a8c54..0000000000--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.ts+++ /dev/null@@ -1,331 +0,0 @@-import type { LayersValue } from "@webstudio-is/css-engine";-import type { StyleInfo, StyleValueInfo } from "../../shared/style-info";-import type {- CreateBatchUpdate,- DeleteProperty,- StyleUpdateOptions,-} from "../../shared/use-style-data";--export const layeredBackgroundPropsDefaults = {- backgroundAttachment: { type: "keyword", value: "scroll" },- backgroundClip: { type: "keyword", value: "border-box" },- backgroundBlendMode: { type: "keyword", value: "normal" },- backgroundImage: { type: "keyword", value: "none" },- backgroundOrigin: { type: "keyword", value: "padding-box" },- backgroundPositionX: { type: "unit", value: 0, unit: "%" },- backgroundPositionY: { type: "unit", value: 0, unit: "%" },- backgroundRepeat: { type: "keyword", value: "repeat" },- backgroundSize: { type: "keyword", value: "auto" },-} as const satisfies Record<string, BackgroundStyleValue>;--export type BackgroundStyleValue = LayersValue | LayersValue["value"][number];--type BackgroundProperty = keyof typeof layeredBackgroundPropsDefaults;--export const layeredBackgroundProps = Object.keys(- layeredBackgroundPropsDefaults-) as [BackgroundProperty, ...BackgroundProperty[]];--export type LayeredBackgroundProperty = (typeof layeredBackgroundProps)[number];--const getPropertyLayerCount = (style: StyleValueInfo) => {- if (style.value.type === "layers") {- return style.value.value.length;- }- return 0;-};--export const getLayerCount = (style: StyleInfo) => {- return Math.max(- ...layeredBackgroundProps.map((prop) => {- const styleValue = style[prop];-- if (styleValue !== undefined) {- return getPropertyLayerCount(styleValue);- }-- return 0;- })- );-};--export const getLayerBackgroundStyleInfo = (- layerNum: number,- style: StyleInfo-): StyleInfo => {- const layerCount = getLayerCount(style);- if (layerNum >= layerCount) {- throw new Error(`${layerNum} is out of bounds`);- }-- const result: StyleInfo = {};-- for (const [property, value] of Object.entries(- layeredBackgroundPropsDefaults- )) {- result[property as LayeredBackgroundProperty] = { value };- }-- for (const property of layeredBackgroundProps) {- const resultProperty = result[property];- if (resultProperty === undefined) {- throw new Error(`Property ${property} is not defined`);- }-- const styleValue = style[property];-- const valueStyle = styleValue?.value;- const localStyle = styleValue?.local;- const cascadedStyle = styleValue?.cascaded;- const previousSourceStyle = styleValue?.previousSource;- const nextSourceStyle = styleValue?.nextSource;-- if (valueStyle?.type === "layers") {- const styleValue = valueStyle.value[layerNum];- resultProperty["value"] = styleValue;- }-- if (localStyle?.type === "layers") {- const styleValue = localStyle.value[layerNum];- resultProperty["local"] = styleValue;- }-- if (previousSourceStyle?.value?.type === "layers") {- const styleValue = previousSourceStyle.value.value[layerNum];- resultProperty["previousSource"] = {- styleSourceId: previousSourceStyle.styleSourceId,- value: styleValue,- };- }-- if (nextSourceStyle?.value?.type === "layers") {- const styleValue = nextSourceStyle.value.value[layerNum];- resultProperty["nextSource"] = {- styleSourceId: nextSourceStyle.styleSourceId,- value: styleValue,- };- }-- if (cascadedStyle?.value.type === "layers") {- const styleValue = cascadedStyle.value.value[layerNum];- resultProperty["cascaded"] = {- breakpointId: cascadedStyle.breakpointId,- value: styleValue,- };- }- }-- return result;-};--export type DeleteBackgroundProperty = ReturnType<typeof deleteLayerProperty>;--export const deleteLayerProperty =- (- layerNum: number,- style: StyleInfo,- deleteProperty: DeleteProperty,- createBatchUpdate: CreateBatchUpdate- ) =>- (propertyName: LayeredBackgroundProperty, options?: StyleUpdateOptions) => {- if (options?.isEphemeral) {- deleteProperty(propertyName, options);- return;- }-- setLayerProperty(layerNum, style, createBatchUpdate)(propertyName)(- layeredBackgroundPropsDefaults[propertyName]- );- };--export type SetBackgroundProperty = ReturnType<typeof setLayerProperty>;--const getLayersValue = (styleValue?: StyleValueInfo) => {- const clonedStyleValue: StyleValueInfo | undefined =- structuredClone(styleValue);- if (clonedStyleValue?.local?.type === "layers") {- return clonedStyleValue.local;- }-- if (clonedStyleValue?.nextSource?.value?.type === "layers") {- return clonedStyleValue?.nextSource?.value;- }-- if (clonedStyleValue?.previousSource?.value?.type === "layers") {- return clonedStyleValue?.previousSource?.value;- }-- if (clonedStyleValue?.cascaded?.value.type === "layers") {- return clonedStyleValue?.cascaded?.value;- }- return { type: "layers" as const, value: [] };-};--const isLayerStylesRecord = (value: {- [property in LayeredBackgroundProperty]?: LayersValue;-}): value is Record<LayeredBackgroundProperty, LayersValue> => {- for (const property of layeredBackgroundProps) {- if (value[property] === undefined) {- return false;- }- }- return true;-};--const normalizeLayers = (- style: StyleInfo,- layerCount: number,- batch: ReturnType<CreateBatchUpdate>-) => {- const layerStyle: { [property in LayeredBackgroundProperty]?: LayersValue } =- {};-- for (const property of layeredBackgroundProps) {- const styleValue = style[property];-- // If a property is not defined, try copying it from the cascade, or set it as empty.- const newPropertyStyle: LayersValue = getLayersValue(styleValue);-- const missingLayerCount = layerCount - newPropertyStyle.value.length;-- if (missingLayerCount < 0) {- // This should never happen.- throw new Error(- `Layer count for property ${property} exceeds expected ${layerCount}`- );- }-- let isStyleChanged = styleValue?.local?.type !== "layers";-- if (newPropertyStyle.value.length !== layerCount) {- // All background properties must have the same number of layers- const requiredLayers = new Array(missingLayerCount).fill(- structuredClone(layeredBackgroundPropsDefaults[property])- );- newPropertyStyle.value = newPropertyStyle.value.concat(requiredLayers);- isStyleChanged = true;- }-- layerStyle[property] = newPropertyStyle;- if (isStyleChanged) {- batch.setProperty(property)(newPropertyStyle);- }- }-- if (isLayerStylesRecord(layerStyle)) {- return layerStyle;- }-- throw new Error("Invalid layer styles");-};--export const setLayerProperty =- (layerNum: number, style: StyleInfo, createBatchUpdate: CreateBatchUpdate) =>- (propertyName: LayeredBackgroundProperty) =>- (newValue: BackgroundStyleValue, options?: StyleUpdateOptions) => {- const batch = createBatchUpdate();-- const layerCount = Math.max(getLayerCount(style), layerNum + 1);- const layerStyles = normalizeLayers(style, layerCount, batch);-- if (newValue.type === "layers") {- for (const property of layeredBackgroundProps) {- const newPropertyStyle = layerStyles[property];-- const insertItems =- property === propertyName- ? newValue.value- : Array.from(Array(newValue.value.length), (_, index) =>- // Do not override existing values with defaults for layerNum layer- index === 0- ? (newPropertyStyle.value[layerNum] ??- layeredBackgroundPropsDefaults[property])- : layeredBackgroundPropsDefaults[property]- );-- newPropertyStyle.value.splice(layerNum, 1, ...insertItems);-- batch.setProperty(property)(newPropertyStyle);- }- } else {- layerStyles[propertyName].value[layerNum] = newValue;- batch.setProperty(propertyName)(layerStyles[propertyName]);- }-- batch.publish(options);- };--export const addLayer = (- style: StyleInfo,- createBatchUpdate: CreateBatchUpdate-) => {- const batch = createBatchUpdate();- const layerCount = getLayerCount(style);-- const layerStyles = normalizeLayers(style, layerCount, batch);-- for (const property of layeredBackgroundProps) {- const newPropertyStyle = layerStyles[property];-- const newValue = [...newPropertyStyle.value];-- newValue.splice(0, 0, layeredBackgroundPropsDefaults[property]);-- newPropertyStyle.value = newValue;-- batch.setProperty(property)(newPropertyStyle);- }-- batch.publish();-};--export const deleteLayer =- (layerNum: number, style: StyleInfo, createBatchUpdate: CreateBatchUpdate) =>- () => {- const layerCount = getLayerCount(style);-- const batch = createBatchUpdate();-- const layerStyles = normalizeLayers(style, layerCount, batch);-- for (const property of layeredBackgroundProps) {- const newPropertyStyle = layerStyles[property];-- newPropertyStyle.value.splice(layerNum, 1);-- if (newPropertyStyle.value.length === 0) {- batch.deleteProperty(property);- } else {- batch.setProperty(property)(newPropertyStyle);- }- }- batch.publish();- };--export const swapLayers = (- newIndex: number,- oldIndex: number,- style: StyleInfo,- createBatchUpdate: CreateBatchUpdate-) => {- const batch = createBatchUpdate();- const layerCount = Math.max(getLayerCount(style), newIndex + 1, oldIndex + 1);-- const layerStyles = normalizeLayers(style, layerCount, batch);-- for (const property of layeredBackgroundProps) {- const newPropertyStyle = layerStyles[property];-- const newValue = [...newPropertyStyle.value];-- newValue.splice(oldIndex, 1);-- newValue.splice(newIndex, 0, newPropertyStyle.value[oldIndex]);-- newPropertyStyle.value = newValue;-- batch.setProperty(property)(newPropertyStyle);- }-- batch.publish();-};diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsxindex 770fbd0b7b..70f332cac6 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx@@ -2,12 +2,28 @@ import { useStore } from "@nanostores/react";import type { Assets } from "@webstudio-is/sdk";import { Image as WebstudioImage } from "@webstudio-is/image";import { styled, theme } from "@webstudio-is/design-system";+import {+ StyleValue,+ toValue,+ type StyleProperty,+} from "@webstudio-is/css-engine";import { $assets, $imageLoader } from "~/shared/nano-states";-import type { StyleInfo } from "../../shared/style-info";import brokenImage from "~/shared/images/broken-image-placeholder.svg";-import { layeredBackgroundProps } from "./background-layers";-import { toValue } from "@webstudio-is/css-engine";import { toPascalCase } from "../../shared/keyword-utils";+import { useComputedStyles } from "../../shared/model";+import { getRepeatedStyleItem } from "../../shared/repeated-style";++export const repeatedProperties = [+ "backgroundImage",+ "backgroundAttachment",+ "backgroundClip",+ "backgroundOrigin",+ "backgroundPositionX",+ "backgroundPositionY",+ "backgroundRepeat",+ "backgroundSize",+ "backgroundBlendMode",+] satisfies [StyleProperty, ...StyleProperty[]];const Thumbnail = styled("div", {borderRadius: 2,@@ -58,8 +74,10 @@ const gradientNames = ["repeating-radial-gradient",];-export const getLayerName = (layerStyle: StyleInfo, assets: Assets) => {- const backgroundImageStyle = layerStyle.backgroundImage?.value;+export const getBackgroundLabel = (+ backgroundImageStyle: StyleValue,+ assets: Assets+) => {if (backgroundImageStyle?.type === "image" &&backgroundImageStyle.value.type === "asset"@@ -88,20 +106,26 @@ export const getLayerName = (layerStyle: StyleInfo, assets: Assets) => {return "None";};-export const LayerThumbnail = (props: { layerStyle: StyleInfo }) => {+type RepeatedProperty = (typeof repeatedProperties)[number];++export const BackgroundThumbnail = ({ index }: { index: number }) => {const assets = useStore($assets);const imageLoader = useStore($imageLoader);- const backgroundImageStyle = props.layerStyle.backgroundImage?.value;+ const styles = useComputedStyles(repeatedProperties);+ const [backgroundImage] = styles;+ const backgroundImageValue = getRepeatedStyleItem(+ backgroundImage.cascadedValue,+ index+ );if (- backgroundImageStyle?.type === "image" &&- backgroundImageStyle.value.type === "asset"+ backgroundImageValue?.type === "image" &&+ backgroundImageValue.value.type === "asset") {- const asset = assets.get(backgroundImageStyle.value.value);+ const asset = assets.get(backgroundImageValue.value.value);if (asset === undefined) {return null;}-return (<StyledWebstudioImagekey={asset.id}@@ -114,29 +138,26 @@ export const LayerThumbnail = (props: { layerStyle: StyleInfo }) => {}if (- backgroundImageStyle?.type === "image" &&- backgroundImageStyle.value.type === "url"+ backgroundImageValue?.type === "image" &&+ backgroundImageValue.value.type === "url") {return (<StyledWebstudioImage- key={backgroundImageStyle.value.url}+ key={backgroundImageValue.value.url}loader={imageLoader}- src={backgroundImageStyle.value.url}+ src={backgroundImageValue.value.url}width={theme.spacing[10]}optimize={true}/>);}- if (backgroundImageStyle?.type === "unparsed") {- const cssStyle: {- [property in (typeof layeredBackgroundProps)[number]]?: string;- } = {};-- for (const property of layeredBackgroundProps) {- cssStyle[property] = toValue(props.layerStyle[property]?.value);+ if (backgroundImageValue?.type === "unparsed") {+ const cssStyle: { [property in RepeatedProperty]?: string } = {};+ for (const { property, cascadedValue } of styles) {+ const value = getRepeatedStyleItem(cascadedValue, index);+ cssStyle[property as RepeatedProperty] = toValue(value);}-return <Thumbnail css={cssStyle} />;}diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsxindex 1d72108842..5aefb988b0 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx@@ -1,136 +1,55 @@-import type { LayersValue } from "@webstudio-is/css-engine";+import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";import { styled, theme } from "@webstudio-is/design-system";-import { useRef, useState } from "react";-import type { StyleInfo } from "../../shared/style-info";-import type {- CreateBatchUpdate,- DeleteProperty,- SetProperty,-} from "../../shared/use-style-data";+import { registerContainers } from "~/shared/sync";+import {+ $breakpoints,+ $selectedBreakpointId,+ $selectedInstanceSelector,+ $styles,+ $styleSourceSelections,+} from "~/shared/nano-states";import { Section } from "./backgrounds";-const backgroundImageStyle: LayersValue = {- type: "layers",- value: [- {- type: "unparsed",- value: "linear-gradient(red, yellow)",- },- {- type: "unparsed",- value: "linear-gradient(blue, red)",- },- {- type: "keyword",- value: "none",- },- ],+const backgroundImage: StyleDecl = {+ breakpointId: "base",+ styleSourceId: "local",+ property: "backgroundImage",+ value: {+ type: "layers",+ value: [+ {+ type: "unparsed",+ value: "linear-gradient(red, yellow)",+ },+ {+ type: "unparsed",+ value: "linear-gradient(blue, red)",+ },+ {+ type: "keyword",+ value: "none",+ },+ ],+ },};+registerContainers();+$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));+$selectedBreakpointId.set("base");+$styles.set(new Map([[getStyleDeclKey(backgroundImage), backgroundImage]]));+$styleSourceSelections.set(+ new Map([["box", { instanceId: "box", values: ["local"] }]])+);+$selectedInstanceSelector.set(["box"]);+const Panel = styled("div", {width: theme.spacing[30],});-const useStyleInfo = (styleInfoInitial: StyleInfo) => {- const [styleInfo, setStyleInfo] = useState(() => styleInfoInitial);-- const setProperty: SetProperty = (name) => (value, options) => {- if (options?.isEphemeral) {- return;- }-- setStyleInfo((styleInfo) => ({- ...styleInfo,- [name]: {- ...styleInfo[name],- value: value,- local: value,- },- }));- };-- const deleteProperty: DeleteProperty = (name, options) => {- if (options?.isEphemeral) {- return;- }-- setStyleInfo((styleInfo) => {- const { [name]: _, ...rest } = styleInfo;- return rest;- });- };-- const execCommands = useRef<(() => void)[]>([]);-- const createBatchUpdate: CreateBatchUpdate = () => ({- deleteProperty: (property) => {- execCommands.current.push(() => {- deleteProperty(property);- });- },- setProperty: (property) => (style) => {- execCommands.current.push(() => {- setProperty(property)(style);- });- },- publish: (options) => {- if (options?.isEphemeral) {- execCommands.current = [];- return;- }-- for (const command of execCommands.current) {- command();- }-- execCommands.current = [];- },- });-- return { styleInfo, setProperty, deleteProperty, createBatchUpdate };-};--export const BackgroundsCollapsible = () => {- const { styleInfo, setProperty, deleteProperty, createBatchUpdate } =- useStyleInfo({- backgroundImage: {- cascaded: {- value: backgroundImageStyle,- breakpointId: "mobile",- },- value: backgroundImageStyle,- },- });-- return (- <Panel>- <Section- currentStyle={styleInfo}- setProperty={setProperty}- deleteProperty={deleteProperty}- createBatchUpdate={createBatchUpdate}- />- </Panel>- );-};-export const Backgrounds = () => {- const { styleInfo, setProperty, deleteProperty, createBatchUpdate } =- useStyleInfo({- backgroundImage: {- value: backgroundImageStyle,- local: backgroundImageStyle,- },- });-return (<Panel>- <Section- currentStyle={styleInfo}- setProperty={setProperty}- deleteProperty={deleteProperty}- createBatchUpdate={createBatchUpdate}- />+ <Section /></Panel>);};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 b86c13adbb..247610b5a0 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@@ -1,207 +1,52 @@import { useStore } from "@nanostores/react";-import { useMemo } from "react";-import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";+import type { StyleProperty } from "@webstudio-is/css-engine";import { propertyDescriptions } from "@webstudio-is/css-data";-import {- CssValueListItem,- CssValueListArrowFocus,- Flex,- Grid,- Label,- SmallIconButton,- SmallToggleButton,- theme,- useSortable,-} from "@webstudio-is/design-system";-import {- EyeconOpenIcon,- EyeconClosedIcon,- SubtractIcon,-} from "@webstudio-is/icons";-import type { SectionProps } from "../shared/section";-import { FloatingPanel } from "~/builder/shared/floating-panel";+import { Flex, Grid, theme } from "@webstudio-is/design-system";import { $assets } from "~/shared/nano-states";-import type { StyleInfo } from "../../shared/style-info";import { ColorControl } from "../../controls/color/color-control";-import {- getLayerCount,- layeredBackgroundProps,- addLayer,- deleteLayer,- setLayerProperty,- type SetBackgroundProperty,- type DeleteBackgroundProperty,- getLayerBackgroundStyleInfo,- deleteLayerProperty,- swapLayers,-} from "./background-layers";-import { BackgroundContent } from "./background-content";-import { getLayerName, LayerThumbnail } from "./background-thumbnail";import { RepeatedStyleSection } from "../../shared/style-section";import { PropertyLabel } from "../../property-label";+import {+ addRepeatedStyleItem,+ RepeatedStyle,+} from "../../shared/repeated-style";+import { useComputedStyles } from "../../shared/model";+import { parseCssFragment } from "../../shared/parse-css-fragment";+import { BackgroundContent } from "./background-content";+import {+ getBackgroundLabel,+ BackgroundThumbnail,+ repeatedProperties,+} from "./background-thumbnail";-const Layer = (props: {- id: string;- index: number;- isHighlighted: boolean;- layerStyle: StyleInfo;- setProperty: SetBackgroundProperty;- deleteProperty: DeleteBackgroundProperty;- deleteLayer: () => void;- setBackgroundColor: (color: StyleValue) => void;-}) => {- const assets = useStore($assets);-- const backgroundImageStyle = props.layerStyle.backgroundImage?.value;- const isHidden =- backgroundImageStyle?.type === "image" ||- backgroundImageStyle?.type === "unparsed"- ? Boolean(backgroundImageStyle.hidden)- : false;-- const handleHiddenChange = (hidden: boolean) => {- if (- backgroundImageStyle?.type === "image" ||- backgroundImageStyle?.type === "unparsed"- ) {- props.setProperty("backgroundImage")({- ...backgroundImageStyle,- hidden,- });- }- };-- const canDisable =- backgroundImageStyle?.type !== "image" &&- backgroundImageStyle?.type !== "unparsed";-- return (- <FloatingPanel- title="Background"- // Background Panel is big, and the size differs when the tabs are changed.- // This results in the panel moving around when the tabs are changed.- // And sometimes, the tab moves away from the cursor, when the content change happens on the top.- // 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} />}- >- <CssValueListItem- id={props.id}- draggable={true}- active={props.isHighlighted}- index={props.index}- label={- <Label truncate onReset={props.deleteLayer}>- {getLayerName(props.layerStyle, assets)}- </Label>- }- thumbnail={<LayerThumbnail layerStyle={props.layerStyle} />}- hidden={isHidden}- buttons={- <>- <SmallToggleButton- disabled={canDisable}- pressed={isHidden}- onPressedChange={handleHiddenChange}- variant="normal"- tabIndex={-1}- icon={isHidden ? <EyeconClosedIcon /> : <EyeconOpenIcon />}- />-- <SmallIconButton- variant="destructive"- tabIndex={-1}- icon={<SubtractIcon />}- onClick={props.deleteLayer}- />- </>- }- />- </FloatingPanel>- );-};--export const properties = [- "backgroundAttachment",- "backgroundClip",- "backgroundColor",- "backgroundImage",- "backgroundOrigin",- "backgroundPositionX",- "backgroundPositionY",- "backgroundRepeat",- "backgroundSize",- "backgroundBlendMode",-] satisfies Array<StyleProperty>;--export const Section = (props: SectionProps) => {- const { setProperty, deleteProperty, currentStyle, createBatchUpdate } =- props;- const layersCount = getLayerCount(currentStyle);-- const sortableItems = useMemo(- () =>- Array.from(Array(layersCount), (_, index) => ({- id: `${index}`,- index,- })),- [layersCount]- );+export const properties = [...repeatedProperties, "backgroundColor"] satisfies [+ StyleProperty,+ ...StyleProperty[],+];- const { dragItemId, placementIndicator, sortableRefCallback } = useSortable({- items: sortableItems,- onSort: (newIndex, oldIndex) => {- swapLayers(newIndex, oldIndex, currentStyle, createBatchUpdate);- },- });+export const Section = () => {+ const styles = useComputedStyles(repeatedProperties);+ const assets = useStore($assets);return (<RepeatedStyleSectionlabel="Backgrounds"description="Add one or more backgrounds to the instance such as a color, image, or gradient."- properties={layeredBackgroundProps}+ properties={properties}onAdd={() => {- addLayer(currentStyle, createBatchUpdate);+ addRepeatedStyleItem(styles, parseCssFragment("none", "background"));}}><Flex gap={1} direction="column">- <CssValueListArrowFocus dragItemId={dragItemId}>- <Flex direction="column" ref={sortableRefCallback}>- {sortableItems.map((layer, index) => (- <Layer- id={layer.id}- index={index}- key={layer.id}- isHighlighted={dragItemId === layer.id}- layerStyle={getLayerBackgroundStyleInfo(- layer.index,- currentStyle- )}- deleteLayer={deleteLayer(- layer.index,- currentStyle,- createBatchUpdate- )}- setProperty={setLayerProperty(- layer.index,- currentStyle,- createBatchUpdate- )}- deleteProperty={deleteLayerProperty(- layer.index,- currentStyle,- deleteProperty,- createBatchUpdate- )}- setBackgroundColor={setProperty("backgroundColor")}- />- ))}-- {placementIndicator}- </Flex>- </CssValueListArrowFocus>-+ <RepeatedStyle+ label="Backgrounds"+ styles={styles}+ getItemProps={(_index, primaryValue) => ({+ label: getBackgroundLabel(primaryValue, assets),+ })}+ renderThumbnail={(index) => <BackgroundThumbnail index={index} />}+ renderItemContent={(index) => <BackgroundContent index={index} />}+ /><Gridcss={{px: theme.spacing[9],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 b16e989f45..8b06039d8d 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@@ -18,6 +18,7 @@ import {$styles,} from "~/shared/nano-states";import { registerContainers } from "~/shared/sync";+import { setProperty } from "./use-style-data";registerContainers();@@ -117,6 +118,19 @@ test("add tuple to repeated style", () => {});});+test("ignore when new item is not layers or tuple", () => {+ const $backgroundColor = createComputedStyleDeclStore("backgroundColor");+ addRepeatedStyleItem(+ [$backgroundColor.get()],+ parseCssFragment("none", "background")+ );+ expect($backgroundColor.get().source.name).toEqual("default");+ expect($backgroundColor.get().cascadedValue).toEqual({+ type: "keyword",+ value: "transparent",+ });+});+test("edit layer in repeated style", () => {const $transitionProperty =createComputedStyleDeclStore("transitionProperty");@@ -389,6 +403,33 @@ test("toggle tuple in repeated style", () => {});});+test("toggle repeated style item when value is not repeated", () => {+ const $transitionProperty =+ createComputedStyleDeclStore("transitionProperty");+ const $transitionBehavior =+ createComputedStyleDeclStore("transitionBehavior");+ addRepeatedStyleItem(+ [$transitionProperty.get()],+ parseCssFragment("all", "transition")+ );+ addRepeatedStyleItem(+ [$transitionProperty.get()],+ parseCssFragment("opacity", "transition")+ );+ setProperty("transitionBehavior")({ type: "keyword", value: "inherit" });+ toggleRepeatedStyleItem(+ [$transitionProperty.get(), $transitionBehavior.get()],+ 1+ );+ expect($transitionBehavior.get().cascadedValue).toEqual({+ type: "layers",+ value: [+ { type: "keyword", value: "normal" },+ { type: "keyword", value: "normal", hidden: true },+ ],+ });+});+test("swap layers in 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 45f52f0286..b378cebd30 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@@ -26,6 +26,7 @@ import { repeatUntil } from "~/shared/array-utils";import type { ComputedStyleDecl } from "~/shared/style-object-model";import { createBatchUpdate, type StyleUpdateOptions } from "./use-style-data";import { ColorThumb } from "./color-thumb";+import { properties } from "@webstudio-is/css-data";export const getRepeatedStyleItem = (styleValue: StyleValue, index: number) => {if (styleValue.type === "layers" || styleValue.type === "tuple") {@@ -36,13 +37,19 @@ export const getRepeatedStyleItem = (styleValue: StyleValue, index: number) => {type ItemType = "layers" | "tuple";const normalizeStyleValue = (- value: undefined | StyleValue,+ styleDecl: ComputedStyleDecl,primaryValue: StyleValue,itemType: ItemType = primaryValue.type === "tuple" ? "tuple" : "layers") => {const primaryItemsCount =primaryValue.type === itemType ? primaryValue.value.length : 0;- const items = value?.type === itemType ? value.value : [];+ const value = styleDecl.cascadedValue;+ const items = value.type === itemType ? value.value : [];+ // prefill initial value when no items to repeated+ if (items.length === 0 && primaryItemsCount > 0) {+ const meta = properties[styleDecl.property as keyof typeof properties];+ items.push(meta.initial);+ }return {type: itemType,value: repeatUntil(items, primaryItemsCount),@@ -55,16 +62,21 @@ export const addRepeatedStyleItem = () => {const batch = createBatchUpdate();const currentStyles = new Map(- styles.map((styleDecl) => [styleDecl.property, styleDecl.cascadedValue])+ styles.map((styleDecl) => [styleDecl.property, styleDecl]));const primaryValue = styles[0].cascadedValue;- // infer type from new items- // because current values could be css wide keywords- const itemType: ItemType =- Array.from(newItems.values())[0]?.type === "tuple" ? "tuple" : "layers";for (const [property, value] of newItems) {- const oldValue = currentStyles.get(property);- const newValue = normalizeStyleValue(oldValue, primaryValue, itemType);+ if (value.type !== "layers" && value.type !== "tuple") {+ continue;+ }+ // infer type from new items+ // because current values could be css wide keywords+ const itemType: ItemType = value.type;+ const styleDecl = currentStyles.get(property);+ if (styleDecl === undefined) {+ continue;+ }+ const newValue = normalizeStyleValue(styleDecl, primaryValue, itemType);if (value.type !== itemType) {console.error(`Unexpected item type "${value.type}" for ${property} repeated value`@@ -85,12 +97,15 @@ export const editRepeatedStyleItem = () => {const batch = createBatchUpdate();const currentStyles = new Map(- styles.map((styleDecl) => [styleDecl.property, styleDecl.cascadedValue])+ styles.map((styleDecl) => [styleDecl.property, styleDecl]));const primaryValue = styles[0].cascadedValue;for (const [property, value] of newItems) {- const oldValue = currentStyles.get(property);- const newValue = normalizeStyleValue(oldValue, primaryValue);+ const styleDecl = currentStyles.get(property);+ if (styleDecl === undefined) {+ continue;+ }+ const newValue = normalizeStyleValue(styleDecl, primaryValue);if (value.type !== newValue.type) {console.error(`Unexpected item type "${value.type}" for ${property} repeated value`@@ -130,8 +145,7 @@ export const deleteRepeatedStyleItem = (const batch = createBatchUpdate();const primaryValue = styles[0].cascadedValue;for (const styleDecl of styles) {- const oldValue = styleDecl.cascadedValue;- const newValue = normalizeStyleValue(oldValue, primaryValue);+ const newValue = normalizeStyleValue(styleDecl, primaryValue);newValue.value.splice(index, 1);if (newValue.value.length > 0) {batch.setProperty(styleDecl.property as StyleProperty)(newValue);@@ -150,8 +164,7 @@ export const toggleRepeatedStyleItem = (const batch = createBatchUpdate();const primaryValue = styles[0].cascadedValue;for (const styleDecl of styles) {- const oldValue = styleDecl.cascadedValue;- const newValue = normalizeStyleValue(oldValue, primaryValue);+ const newValue = normalizeStyleValue(styleDecl, primaryValue);newValue.value[index] = {...newValue.value[index],hidden: false === (newValue.value[index].hidden ?? false),@@ -169,8 +182,7 @@ export const swapRepeatedStyleItems = (const batch = createBatchUpdate();const primaryValue = styles[0].cascadedValue;for (const styleDecl of styles) {- const oldValue = styleDecl.cascadedValue;- const newValue = normalizeStyleValue(oldValue, primaryValue);+ const newValue = normalizeStyleValue(styleDecl, primaryValue);// You can swap only if there are at least two layers// As we are checking across multiple properties, we can't be sure// which property don't have two layers so we are checking here.@@ -191,9 +203,11 @@ export const RepeatedStyle = (props: {index: number,primaryValue: StyleValue) => { label: string; color?: RgbaColor };+ renderThumbnail?: (index: number, primaryValue: StyleValue) => JSX.Element;renderItemContent: (index: number, primaryValue: StyleValue) => JSX.Element;}) => {- const { label, styles, getItemProps, renderItemContent } = props;+ const { label, styles, getItemProps, renderThumbnail, renderItemContent } =+ props;// first property should describe the amount of layers or tuple itemsconst primaryValue = styles[0].cascadedValue;const primaryItems =@@ -233,6 +247,14 @@ export const RepeatedStyle = (props: {<FloatingPanelkey={index}title={label}+ // Background Panel is big, and the size differs when the tabs are changed.+ // This results in the panel moving around when the tabs are changed.+ // And sometimes, the tab moves away from the cursor,+ // when the content change happens on the top.+ // 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={renderItemContent(index, primaryValue)}><CssValueListItem@@ -242,7 +264,10 @@ export const RepeatedStyle = (props: {index={index}label={<Label truncate>{itemLabel}</Label>}hidden={primaryValue.hidden}- thumbnail={itemColor && <ColorThumb color={itemColor} />}+ thumbnail={+ renderThumbnail?.(index, primaryValue) ??+ (itemColor && <ColorThumb color={itemColor} />)+ }buttons={<><SmallToggleButton