Skip to content

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.

Add simple background parser (#1240)

Ivan Starkovfcee225a5f54
diff --git a/@types/css-tree.d.ts b/@types/css-tree.d.ts
index 58cf893b15..fd2e6dc9d6 100644
--- a/@types/css-tree.d.ts
+++ b/@types/css-tree.d.ts
@@ -4,6 +4,18 @@ declare module "css-tree" {
options?: import("@types/css-tree").ParseOptions
): import("@types/css-tree").CssNode;
+ export function walk(
+ ast: import("@types/css-tree").CssNode,
+ options:
+ | import("@types/css-tree").WalkOptionsNoVisit
+ | import("@types/css-tree").EnterOrLeaveFn
+ ): void;
+
+ export function generate(
+ ast: import("@types/css-tree").CssNode,
+ options?: import("@types/css-tree").GenerateOptions
+ ): string;
+
type Match =
| {
syntax: { type: "Property"; name: string };
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.tsx
index 71440ecf16..6a17e919e2 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
@@ -5,7 +5,7 @@ import {
FloatingPanelProvider,
} from "~/builder/shared/floating-panel";
import { useRef, useState } from "react";
-import type { StyleValue } from "@webstudio-is/css-data";
+import type { SetProperty } from "../../shared/use-style-data";
const defaultCurrentStyle = getLayerBackgroundStyleInfo(0, {
backgroundImage: {
@@ -24,15 +24,20 @@ export const BackgroundContentStory = () => {
const [currentStyle, setCurrentStyle] = useState(defaultCurrentStyle);
- const setProperty = (propertyName: string) => (style: StyleValue) => {
- setCurrentStyle({
- ...currentStyle,
- [propertyName]: {
- value: style,
- local: style,
- },
- });
- };
+ const setProperty: SetProperty =
+ (propertyName: string) => (style, options) => {
+ if (options?.isEphemeral) {
+ return;
+ }
+
+ setCurrentStyle({
+ ...currentStyle,
+ [propertyName]: {
+ value: style,
+ local: style,
+ },
+ });
+ };
return (
<>
@@ -47,6 +52,9 @@ export const BackgroundContentStory = () => {
currentStyle={currentStyle}
deleteProperty={deleteProperty}
setProperty={setProperty}
+ setBackgroundColor={(color) => {
+ setProperty("backgroundColor")(color);
+ }}
/>
}
>
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.tsx
index 198a67a7df..53a6179511 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
@@ -3,7 +3,7 @@
* as of now just implement feature parity with old backgrounds section
**/
-import type { StyleValue } from "@webstudio-is/css-data";
+import type { RgbValue, StyleValue } from "@webstudio-is/css-data";
import {
theme,
Flex,
@@ -48,6 +48,7 @@ type BackgroundContentProps = {
currentStyle: StyleInfo;
setProperty: SetBackgroundProperty;
deleteProperty: DeleteBackgroundProperty;
+ setBackgroundColor: (color: RgbValue) => void;
};
const safeDeleteProperty = (
@@ -192,6 +193,7 @@ export const BackgroundContent = (props: BackgroundContentProps) => {
setProperty={setProperty}
deleteProperty={deleteProperty}
currentStyle={props.currentStyle}
+ setBackgroundColor={props.setBackgroundColor}
/>
</Flex>
)}
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.tsx
index 6f0b01763e..2994686541 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
@@ -1,42 +1,79 @@
+import type { InvalidValue, RgbValue } from "@webstudio-is/css-data";
import { TextArea, theme } from "@webstudio-is/design-system";
import { useEffect, useRef, useState } from "react";
import { parseCssValue } from "../../shared/parse-css-value";
import type { ControlProps } from "../../style-sections";
+import { parseBackground } from "./background-parser";
+
+type IntermediateValue = {
+ type: "intermediate";
+ value: string;
+};
export const BackgroundGradient = (
- props: Omit<ControlProps, "property" | "items">
+ props: Omit<ControlProps, "property" | "items"> & {
+ setBackgroundColor: (color: RgbValue) => void;
+ }
) => {
const property = "backgroundImage";
+ const textAreaRef = useRef<HTMLTextAreaElement>(null);
const styleInfo = props.currentStyle[property];
const styleValue = styleInfo?.value;
- // In gradient section we want to show gradient data only
const [intermediateValue, setIntermediateValue] = useState<
- string | undefined
+ IntermediateValue | InvalidValue | undefined
>(undefined);
- const value =
- intermediateValue ??
+ const textAreaValue =
+ intermediateValue?.value ??
(styleValue?.type === "unparsed" ? styleValue.value : undefined);
- const handleChange = (value: string, isEphemeral: boolean) => {
- setIntermediateValue(isEphemeral ? value : undefined);
+ const handleChange = (value: string) => {
+ setIntermediateValue({
+ type: "intermediate",
+ value,
+ });
+ // This doesn't have the same behavior as CssValueInput.
+ // However, it's great to see the immediate results when making gradient changes,
+ // especially until we have a better gradient tool.
const newValue = parseCssValue(property, value);
if (newValue.type === "unparsed") {
- props.setProperty(property)(newValue, { isEphemeral });
+ props.setProperty(property)(newValue, { isEphemeral: true });
return;
}
- props.deleteProperty(property, { isEphemeral });
+ // Set backgroundImage at layer to none if it's invalid
+ props.setProperty(property)(
+ { type: "keyword", value: "none" },
+ { isEphemeral: true }
+ );
};
const handleOnComplete = () => {
- if (intermediateValue !== undefined) {
- handleChange(intermediateValue, false);
+ if (intermediateValue === undefined) {
+ return;
+ }
+
+ const { backgroundImage, backgroundColor } = parseBackground(
+ intermediateValue.value
+ );
+
+ if (backgroundColor !== undefined) {
+ props.setBackgroundColor(backgroundColor);
}
+
+ if (backgroundImage.type !== "invalid") {
+ setIntermediateValue(undefined);
+ props.setProperty(property)(backgroundImage);
+ return;
+ }
+
+ // Set invalid state
+ setIntermediateValue({ type: "invalid", value: intermediateValue.value });
+ props.deleteProperty(property, { isEphemeral: true });
};
const handleOnCompleteRef = useRef(handleOnComplete);
@@ -51,18 +88,30 @@ export const BackgroundGradient = (
return (
<TextArea
+ ref={textAreaRef}
css={{ minHeight: theme.spacing[14] }}
rows={2}
name="description"
disabled={props.disabled}
- value={value}
+ value={textAreaValue ?? ""}
+ state={intermediateValue?.type === "invalid" ? "invalid" : undefined}
onChange={(event) => {
- handleChange(event.target.value, true);
+ handleChange(event.target.value);
}}
onBlur={handleOnComplete}
onKeyDown={(event) => {
if (event.key === "Enter") {
handleOnComplete();
+ event.preventDefault();
+ }
+
+ if (event.key === "Escape") {
+ if (intermediateValue === undefined) {
+ return;
+ }
+ props.deleteProperty(property, { isEphemeral: true });
+ setIntermediateValue(undefined);
+ event.preventDefault();
}
}}
/>
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.ts
index f10d59d18b..92b2829f96 100644
--- 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.ts
@@ -3,6 +3,7 @@ import {
setLayerProperty,
addLayer,
swapLayers,
+ deleteLayer,
} from "./background-layers";
import { describe, test, expect } from "@jest/globals";
@@ -36,9 +37,18 @@ describe("setLayerProperty", () => {
throw new Error("newValue.type !== layers");
}
- changedProps.push([propertyName, newValue]);
+ 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
@@ -150,9 +160,18 @@ describe("setLayerProperty", () => {
throw new Error("newValue.type !== layers");
}
- changedProps.push([propertyName, newValue]);
+ 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
@@ -184,7 +203,191 @@ describe("setLayerProperty", () => {
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 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;
+ },
+ });
+
+ 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)",
+ },
+ ],
+ }
+ `);
+
+ 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)",
+ },
+ ],
+ }
+ `);
+ });
+});
+
+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", () => {
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.ts
index 59007a1af6..6a97302000 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
@@ -17,7 +17,7 @@ export const layeredBackgroundPropsDefaults = {
backgroundSize: { type: "keyword", value: "auto" },
} as const satisfies Record<string, BackgroundStyleValue>;
-export type BackgroundStyleValue = LayersValue["value"][number];
+export type BackgroundStyleValue = LayersValue | LayersValue["value"][number];
export const isBackgroundStyleValue = (
style: StyleValue
@@ -28,7 +28,8 @@ export const isBackgroundStyleValue = (
style.type === "unparsed" ||
style.type === "image" ||
style.type === "tuple" ||
- style.type === "invalid"
+ style.type === "invalid" ||
+ style.type === "layers"
) {
return true;
}
@@ -151,47 +152,92 @@ const getLayersValue = (styleValue?: StyleValueInfo) => {
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);
- for (const property of layeredBackgroundProps) {
- const styleValue = style[property];
-
- // If property is not defined, try copy from cascade or set empty
- const newPropertyStyle: LayersValue = getLayersValue(styleValue);
+ const layerCount = Math.max(getLayerCount(style), layerNum + 1);
+ const layerStyles = normalizeLayers(style, layerCount, batch);
- const missingLayerCount = layerCount - newPropertyStyle.value.length;
+ if (newValue.type === "layers") {
+ for (const property of layeredBackgroundProps) {
+ const newPropertyStyle = layerStyles[property];
- if (missingLayerCount < 0) {
- // In theory this should never happen.
- throw new Error(
- `Layer count for property ${property} exceeds expected ${layerCount}`
- );
- }
+ const insertItems =
+ property === propertyName
+ ? newValue.value
+ : Array.from(
+ Array(newValue.value.length),
+ () => layeredBackgroundPropsDefaults[property]
+ );
- let isPropertyChanged = 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);
- isPropertyChanged = true;
- }
+ newPropertyStyle.value.splice(layerNum, 1, ...insertItems);
- if (property === propertyName) {
- newPropertyStyle.value[layerNum] = newValue;
- isPropertyChanged = true;
- }
-
- if (isPropertyChanged) {
batch.setProperty(property)(newPropertyStyle);
}
+ } else {
+ layerStyles[propertyName].value[layerNum] = newValue;
+ batch.setProperty(propertyName)(layerStyles[propertyName]);
}
batch.publish(options);
@@ -201,11 +247,24 @@ export const addLayer = (
style: StyleInfo,
createBatchUpdate: CreateBatchUpdate
) => {
+ const batch = createBatchUpdate();
const layerCount = getLayerCount(style);
- setLayerProperty(layerCount, style, createBatchUpdate)("backgroundImage")({
- type: "keyword",
- value: "none",
- });
+
+ 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 =
@@ -215,28 +274,10 @@ export const deleteLayer =
const batch = createBatchUpdate();
- for (const property of layeredBackgroundProps) {
- const styleValue = style[property];
+ const layerStyles = normalizeLayers(style, layerCount, batch);
- // If property is not defined, try copy from cascade or set empty
- const newPropertyStyle: LayersValue = getLayersValue(styleValue);
-
- const missingLayerCount = layerCount - newPropertyStyle.value.length;
-
- if (missingLayerCount < 0) {
- // In theory this should never happen.
- throw new Error(
- `Layer count for property ${property} exceeds expected ${layerCount}`
- );
- }
-
- 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);
- }
+ for (const property of layeredBackgroundProps) {
+ const newPropertyStyle = layerStyles[property];
newPropertyStyle.value.splice(layerNum, 1);
@@ -258,28 +299,10 @@ export const swapLayers = (
const batch = createBatchUpdate();
const layerCount = Math.max(getLayerCount(style), newIndex + 1, oldIndex + 1);
- for (const property of layeredBackgroundProps) {
- const styleValue = style[property];
-
- // If property is not defined, try copy from cascade or set empty
- const newPropertyStyle: LayersValue = getLayersValue(styleValue);
+ const layerStyles = normalizeLayers(style, layerCount, batch);
- const missingLayerCount = layerCount - newPropertyStyle.value.length;
-
- if (missingLayerCount < 0) {
- // In theory this should never happen.
- throw new Error(
- `Layer count for property ${property} exceeds expected ${layerCount}`
- );
- }
-
- 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);
- }
+ for (const property of layeredBackgroundProps) {
+ const newPropertyStyle = layerStyles[property];
const newValue = [...newPropertyStyle.value];
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-parser.test.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-parser.test.ts
new file mode 100644
index 0000000000..c3463f7508
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-parser.test.ts
@@ -0,0 +1,184 @@
+import { describe, test, expect } from "@jest/globals";
+
+import { parseBackground } from "./background-parser";
+
+describe("parseBackground", () => {
+ test("parse background from figma", () => {
+ expect(
+ parseBackground(
+ "linear-gradient(180deg, #11181C 0%, rgba(17, 24, 28, 0) 36.09%), none, linear-gradient(180deg, rgba(230, 60, 254, 0.33) 0%, rgba(255, 174, 60, 0) 100%), radial-gradient(54.1% 95.83% at 100% 100%, #FFFFFF 0%, rgba(255, 255, 255, 0) 100%), linear-gradient(122.33deg, rgba(74, 78, 250, 0.2) 0%, rgba(0, 0, 0, 0) 69.38%), radial-gradient(92.26% 201.29% at 98.6% 10.65%, rgba(255, 174, 60, 0.3) 0%, rgba(227, 53, 255, 0) 100%) /* warning: gradient uses a rotation that is not supported by CSS and may not behave as expected */, radial-gradient(84.64% 267.51% at 10.07% 81.45%, rgba(53, 255, 182, 0.2) 0%, rgba(74, 78, 250, 0.2) 100%) /* warning: gradient uses a rotation that is not supported by CSS and may not behave as expected */, #EBFFFC;"
+ )
+ ).toMatchInlineSnapshot(`
+ {
+ "backgroundColor": {
+ "alpha": 1,
+ "b": 252,
+ "g": 255,
+ "r": 235,
+ "type": "rgb",
+ },
+ "backgroundImage": {
+ "type": "layers",
+ "value": [
+ {
+ "type": "unparsed",
+ "value": "linear-gradient(180deg,#11181C 0%,rgba(17,24,28,0) 36.09%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "linear-gradient(180deg,rgba(230,60,254,0.33) 0%,rgba(255,174,60,0) 100%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "radial-gradient(54.1% 95.83%at 100% 100%,#FFFFFF 0%,rgba(255,255,255,0) 100%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "linear-gradient(122.33deg,rgba(74,78,250,0.2) 0%,rgba(0,0,0,0) 69.38%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "radial-gradient(92.26% 201.29%at 98.6% 10.65%,rgba(255,174,60,0.3) 0%,rgba(227,53,255,0) 100%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "radial-gradient(84.64% 267.51%at 10.07% 81.45%,rgba(53,255,182,0.2) 0%,rgba(74,78,250,0.2) 100%)",
+ },
+ ],
+ },
+ }
+ `);
+ });
+
+ test("parse background from figma without backgroundColor", () => {
+ expect(
+ parseBackground(
+ "linear-gradient(180deg, #11181C 0%, rgba(17, 24, 28, 0) 36.09%), linear-gradient(180deg, rgba(230, 60, 254, 0.33) 0%, rgba(255, 174, 60, 0) 100%), radial-gradient(54.1% 95.83% at 100% 100%, #FFFFFF 0%, rgba(255, 255, 255, 0) 100%), linear-gradient(122.33deg, rgba(74, 78, 250, 0.2) 0%, rgba(0, 0, 0, 0) 69.38%), radial-gradient(92.26% 201.29% at 98.6% 10.65%, rgba(255, 174, 60, 0.3) 0%, rgba(227, 53, 255, 0) 100%) /* warning: gradient uses a rotation that is not supported by CSS and may not behave as expected */, radial-gradient(84.64% 267.51% at 10.07% 81.45%, rgba(53, 255, 182, 0.2) 0%, rgba(74, 78, 250, 0.2) 100%) /* warning: gradient uses a rotation that is not supported by CSS and may not behave as expected */"
+ )
+ ).toMatchInlineSnapshot(`
+ {
+ "backgroundColor": undefined,
+ "backgroundImage": {
+ "type": "layers",
+ "value": [
+ {
+ "type": "unparsed",
+ "value": "linear-gradient(180deg,#11181C 0%,rgba(17,24,28,0) 36.09%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "linear-gradient(180deg,rgba(230,60,254,0.33) 0%,rgba(255,174,60,0) 100%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "radial-gradient(54.1% 95.83%at 100% 100%,#FFFFFF 0%,rgba(255,255,255,0) 100%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "linear-gradient(122.33deg,rgba(74,78,250,0.2) 0%,rgba(0,0,0,0) 69.38%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "radial-gradient(92.26% 201.29%at 98.6% 10.65%,rgba(255,174,60,0.3) 0%,rgba(227,53,255,0) 100%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "radial-gradient(84.64% 267.51%at 10.07% 81.45%,rgba(53,255,182,0.2) 0%,rgba(74,78,250,0.2) 100%)",
+ },
+ ],
+ },
+ }
+ `);
+ });
+
+ test("parse background and skips url background", () => {
+ expect(
+ parseBackground(
+ "url(https://hello.world/some-image), linear-gradient(180deg, rgba(230, 60, 254, 0.33) 0%, rgba(255, 174, 60, 0) 100%), radial-gradient(54.1% 95.83% at 100% 100%, #FFFFFF 0%, rgba(255, 255, 255, 0) 100%), linear-gradient(122.33deg, rgba(74, 78, 250, 0.2) 0%, rgba(0, 0, 0, 0) 69.38%), radial-gradient(92.26% 201.29% at 98.6% 10.65%, rgba(255, 174, 60, 0.3) 0%, rgba(227, 53, 255, 0) 100%) /* warning: gradient uses a rotation that is not supported by CSS and may not behave as expected */, radial-gradient(84.64% 267.51% at 10.07% 81.45%, rgba(53, 255, 182, 0.2) 0%, rgba(74, 78, 250, 0.2) 100%) /* warning: gradient uses a rotation that is not supported by CSS and may not behave as expected */"
+ )
+ ).toMatchInlineSnapshot(`
+ {
+ "backgroundColor": undefined,
+ "backgroundImage": {
+ "type": "layers",
+ "value": [
+ {
+ "type": "unparsed",
+ "value": "linear-gradient(180deg,rgba(230,60,254,0.33) 0%,rgba(255,174,60,0) 100%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "radial-gradient(54.1% 95.83%at 100% 100%,#FFFFFF 0%,rgba(255,255,255,0) 100%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "linear-gradient(122.33deg,rgba(74,78,250,0.2) 0%,rgba(0,0,0,0) 69.38%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "radial-gradient(92.26% 201.29%at 98.6% 10.65%,rgba(255,174,60,0.3) 0%,rgba(227,53,255,0) 100%)",
+ },
+ {
+ "type": "unparsed",
+ "value": "radial-gradient(84.64% 267.51%at 10.07% 81.45%,rgba(53,255,182,0.2) 0%,rgba(74,78,250,0.2) 100%)",
+ },
+ ],
+ },
+ }
+ `);
+ });
+
+ test("parse background partially copied background", () => {
+ expect(
+ parseBackground(
+ "linear-gradient(180deg, #11181C 0%, rgba(17, 24, 28, 0) 36.09%), linear-gradient(180deg, "
+ )
+ ).toMatchInlineSnapshot(`
+ {
+ "backgroundColor": undefined,
+ "backgroundImage": {
+ "type": "layers",
+ "value": [
+ {
+ "type": "unparsed",
+ "value": "linear-gradient(180deg,#11181C 0%,rgba(17,24,28,0) 36.09%)",
+ },
+ ],
+ },
+ }
+ `);
+ });
+
+ test("parse background partially commented", () => {
+ expect(
+ parseBackground(
+ "linear-gradient(180deg, rgba(230, 60, 254, 0.33) 0%, rgba(255, 174, 60, 0) 100%), /* radial-gradient(54.1% 95.83% at 100% 100%, #FFFFFF 0%, rgba(255, 255, 255, 0) 100%) */"
+ )
+ ).toMatchInlineSnapshot(`
+ {
+ "backgroundColor": undefined,
+ "backgroundImage": {
+ "type": "layers",
+ "value": [
+ {
+ "type": "unparsed",
+ "value": "linear-gradient(180deg,rgba(230,60,254,0.33) 0%,rgba(255,174,60,0) 100%)",
+ },
+ ],
+ },
+ }
+ `);
+ });
+
+ test("parse bad background", () => {
+ expect(parseBackground("linear-gradient(180deg,")).toMatchInlineSnapshot(`
+ {
+ "backgroundColor": undefined,
+ "backgroundImage": {
+ "type": "invalid",
+ "value": "linear-gradient(180deg,",
+ },
+ }
+ `);
+ });
+});
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-parser.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-parser.ts
new file mode 100644
index 0000000000..347df3cf0a
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-parser.ts
@@ -0,0 +1,123 @@
+import * as csstree from "css-tree";
+import { colord } from "colord";
+import { parseCssValue } from "../../shared/parse-css-value";
+import type {
+ InvalidValue,
+ LayersValue,
+ RgbValue,
+ UnparsedValue,
+} from "@webstudio-is/css-data";
+
+export const gradientNames = [
+ "conic-gradient",
+ "linear-gradient",
+ "radial-gradient",
+ "repeating-conic-gradient",
+ "repeating-linear-gradient",
+ "repeating-radial-gradient",
+];
+
+export const parseBackground = (
+ background: string
+): {
+ backgroundImage: LayersValue | InvalidValue;
+ backgroundColor: RgbValue | undefined;
+} => {
+ const layers: string[] = [];
+
+ let tokenStream = background.trim();
+
+ tokenStream = tokenStream.endsWith(";")
+ ? tokenStream.slice(0, -1)
+ : tokenStream;
+
+ // The user can copy the whole style together with the name of the property from figma or any other tool.
+ // We need to remove the property name from the string.
+ const cleanupKeywords = ["background:", "background-image:"];
+
+ for (const cleanupKeyword of cleanupKeywords) {
+ tokenStream = tokenStream.startsWith(cleanupKeyword)
+ ? tokenStream.slice(cleanupKeyword.length).trim()
+ : tokenStream;
+ }
+
+ const cssAst = csstree.parse(tokenStream, { context: "value" });
+
+ let backgroundColorRaw: string | undefined;
+
+ let nestingLevel = 0;
+
+ csstree.walk(cssAst, {
+ enter: (node, item, list) => {
+ if (node.type === "Function") {
+ if (gradientNames.includes(node.name)) {
+ layers.push(csstree.generate(node));
+ }
+
+ // If the depth is at level 0 and the next item is null, it's likely that the backgroundColor
+ // is written as rgba(x,y,z,a) or similar format.
+ // nestingLevel is used as a fast way to check existance of parent Function node
+ if (item.next === null && nestingLevel === 0) {
+ backgroundColorRaw = csstree.generate(node);
+ }
+
+ nestingLevel++;
+ }
+
+ if (node.type === "Hash" && item.next === null && nestingLevel === 0) {
+ // If the depth is at level 0 and the next item is null, it's likely that the backgroundColor
+ // is written as hex #XYZFGH
+ backgroundColorRaw = csstree.generate(node);
+ }
+ },
+ leave: (node, item, list) => {
+ if (node.type === "Function") {
+ nestingLevel--;
+ }
+ },
+ });
+
+ const backgroundImages: UnparsedValue[] = [];
+
+ for (const layer of layers) {
+ if (
+ gradientNames.some((gradientName) => layer.startsWith(gradientName)) ===
+ false
+ ) {
+ break;
+ }
+
+ const layerStyle = parseCssValue("backgroundImage", layer);
+
+ if (layerStyle.type !== "unparsed") {
+ break;
+ }
+
+ backgroundImages.push(layerStyle);
+ }
+
+ let backgroundColor: RgbValue | undefined;
+
+ if (backgroundColorRaw !== undefined) {
+ const colordValue = colord(backgroundColorRaw);
+
+ if (colordValue.isValid()) {
+ const rgb = colordValue.toRgb();
+ backgroundColor = {
+ type: "rgb",
+ r: rgb.r,
+ g: rgb.g,
+ b: rgb.b,
+ alpha: rgb.a ?? 1,
+ };
+ }
+ }
+
+ return {
+ backgroundImage:
+ backgroundImages.length > 0
+ ? { type: "layers", value: backgroundImages }
+ : { type: "invalid", value: background },
+ backgroundColor,
+ };
+};
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.tsx
index 27ef6a916e..0f06dfeddd 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,6 +1,6 @@
import type { LayersValue } from "@webstudio-is/css-data";
import { styled, theme } from "@webstudio-is/design-system";
-import { useState } from "react";
+import { useRef, useState } from "react";
import type { StyleInfo } from "../../shared/style-info";
import type {
CreateBatchUpdate,
@@ -40,7 +40,12 @@ const Panel = styled("div", {
export const Backgrounds = () => {
const [styleInfo, setStyleInfo] = useState(() => styleInfoInitial);
+
const setProperty: SetProperty = (name) => (value, options) => {
+ if (options?.isEphemeral) {
+ return;
+ }
+
setStyleInfo((styleInfo) => ({
...styleInfo,
[name]: {
@@ -51,18 +56,40 @@ export const Backgrounds = () => {
}));
};
- const deleteProperty: DeleteProperty = (name) => {
+ 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,
- setProperty,
- publish: () => {
- // do nothing
+ deleteProperty: (property) => {
+ execCommands.current.push(() => {
+ deleteProperty(property);
+ });
+ },
+ setProperty: (property) => (style) => {
+ execCommands.current.push(() => {
+ setProperty(property)(style);
+ });
+ },
+ publish: (options) => {
+ if (options?.isEphemeral) {
+ return;
+ }
+
+ for (const command of execCommands.current) {
+ command();
+ }
+
+ execCommands.current = [];
},
});
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.tsx
index 94b03680d2..5bea94654d 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
@@ -34,6 +34,7 @@ import { BackgroundContent } from "./background-content";
import { getLayerName, LayerThumbnail } from "./background-thumbnail";
import { useSortable } from "./use-sortable";
import { useMemo } from "react";
+import type { RgbValue } from "@webstudio-is/css-data";
const Layer = (props: {
id: string;
@@ -42,6 +43,7 @@ const Layer = (props: {
setProperty: SetBackgroundProperty;
deleteProperty: DeleteBackgroundProperty;
deleteLayer: () => void;
+ setBackgroundColor: (color: RgbValue) => void;
}) => {
const backgrounImageStyle = props.layerStyle.backgroundImage?.value;
const isHidden =
@@ -74,6 +76,7 @@ const Layer = (props: {
currentStyle={props.layerStyle}
setProperty={props.setProperty}
deleteProperty={props.deleteProperty}
+ setBackgroundColor={props.setBackgroundColor}
/>
}
>
@@ -174,6 +177,7 @@ export const BackgroundsSection = ({
deleteProperty,
createBatchUpdate
)}
+ setBackgroundColor={setProperty("backgroundColor")}
/>
))}
diff --git a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx
index c5c492476c..2d8345d7fd 100644
--- a/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx
+++ b/apps/builder/app/builder/features/style-panel/shared/css-value-input/css-value-input.tsx
@@ -318,8 +318,15 @@ export const CssValueInput = ({
return;
}
+ const parsedValue = parseIntermediateOrInvalidValue(property, value);
+
+ if (parsedValue.type === "invalid") {
+ props.onChange(parsedValue);
+ return;
+ }
+
props.onChangeComplete({
- value: parseIntermediateOrInvalidValue(property, value),
+ value: parsedValue,
reason,
});
};
diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
index 6c066588e5..4d502b1df8 100644
--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx
+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
@@ -131,11 +131,13 @@ export const TextEditor = ({
onChange,
onSelectInstance,
}: TextEditorProps) => {
- const [paragraphClassName] = useState(() => nanoid());
- const [italicClassName] = useState(() => nanoid());
+ // class names must be started with letter so we add a prefix
+ const [paragraphClassName] = useState(() => `a${nanoid()}`);
+ const [italicClassName] = useState(() => `a${nanoid()}`);
useLayoutEffect(() => {
const engine = createCssEngine({ name: "text-editor" });
+
// reset paragraph styles and make it work inside <a>
engine.addPlaintextRule(`
.${paragraphClassName} { display: inline; margin: 0; }
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index 625d87588f..27413de577 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -258,7 +258,7 @@ const setCssVar = (id: string, property: string, value?: StyleValue) => {
document.body.style.removeProperty(customProperty);
return;
}
- document.body.style.setProperty(customProperty, toValue(value));
+ document.body.style.setProperty(customProperty, toValue(value, undefined));
};
const useUpdateStyle = () => {
diff --git a/packages/css-data/src/schema.ts b/packages/css-data/src/schema.ts
index 867b6d3cff..a5e4324653 100644
--- a/packages/css-data/src/schema.ts
+++ b/packages/css-data/src/schema.ts
@@ -55,6 +55,8 @@ export const UnparsedValue = z.object({
hidden: z.boolean().optional(),
});
+export type UnparsedValue = z.infer<typeof UnparsedValue>;
+
const FontFamilyValue = z.object({
type: z.literal("fontFamily"),
value: z.array(z.string()),
diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.ts
index ef40fb2a45..6150535542 100644
--- a/packages/css-engine/src/core/to-value.ts
+++ b/packages/css-engine/src/core/to-value.ts
@@ -16,8 +16,7 @@ const assertUnreachable = (_arg: never, errorMessage: string) => {
export const toValue = (
value?: StyleValue,
- options: ToCssOptions = defaultOptions,
- isEditMode?: boolean
+ options: ToCssOptions = defaultOptions
): string => {
if (value === undefined) {
return "";
@@ -37,11 +36,9 @@ export const toValue = (
return [...value.value, DEFAULT_FONT_FALLBACK].join(", ");
}
if (value.type === "var") {
- // We use var() in edit mode only
- const isEditMode = true;
const fallbacks = [];
for (const fallback of value.fallbacks) {
- fallbacks.push(toValue(fallback, options, isEditMode));
+ fallbacks.push(toValue(fallback, options));
}
const fallbacksString =
fallbacks.length > 0 ? `, ${fallbacks.join(", ")}` : "";
@@ -65,7 +62,7 @@ export const toValue = (
}
if (value.type === "image") {
- if (isEditMode && value.hidden) {
+ if (value.hidden) {
// We assume that property is background-image and use this to hide background layers
// In the future we might want to have a more generic way to hide values
// i.e. have knowledge about property-name, as none is property specific
@@ -77,7 +74,7 @@ export const toValue = (
}
if (value.type === "unparsed") {
- if (isEditMode && value.hidden) {
+ if (value.hidden) {
// We assume that property is background-image and use this to hide background layers
// In the future we might want to have a more generic way to hide values
// i.e. have knowledge about property-name, as none is property specific
@@ -88,15 +85,11 @@ export const toValue = (
}
if (value.type === "layers") {
- return value.value
- .map((value) => toValue(value, options, isEditMode))
- .join(",");
+ return value.value.map((value) => toValue(value, options)).join(",");
}
if (value.type === "tuple") {
- return value.value
- .map((value) => toValue(value, options, isEditMode))
- .join(" ");
+ return value.value.map((value) => toValue(value, options)).join(" ");
}
// Will give ts error in case of missing type