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.

feat: support css variables in shadow properties (#5032)

Bogdan Chadkin11bb528ed6af
diff --git a/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx b/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx
index 058a6d9462..2fdbd6042a 100644
--- a/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx
+++ b/apps/builder/app/builder/features/style-panel/shared/filter-content.tsx
@@ -215,23 +215,21 @@ export const FilterSectionContent = ({
) : undefined}
</Flex>
- {filterFunction === "drop-shadow" &&
- layer.type === "function" &&
- layer.args.type === "tuple" ? (
+ {filterFunction === "drop-shadow" && layer.type === "function" && (
<ShadowContent
index={index}
property="drop-shadow"
layer={layer.args}
propertyValue={toValue(layer.args)}
+ hideCodeEditor={true}
onEditLayer={(_, dropShadowLayers, options) => {
handleComplete(
`drop-shadow(${toValue(dropShadowLayers)})`,
options
);
}}
- hideCodeEditor={true}
/>
- ) : undefined}
+ )}
<Separator css={{ gridAutoColumns: "span 2" }} />
<Flex
diff --git a/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsx b/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsx
index b4439fe10b..10811f7fa2 100644
--- a/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsx
+++ b/apps/builder/app/builder/features/style-panel/shared/shadow-content.tsx
@@ -1,20 +1,15 @@
-import { useEffect, useMemo, useState } from "react";
+import { useEffect, useState } from "react";
import {
toValue,
+ type ShadowValue,
type InvalidValue,
type LayersValue,
- type RgbValue,
type StyleValue,
- type TupleValue,
- type UnitValue,
type VarValue,
+ type CssProperty,
+ type RgbValue,
} from "@webstudio-is/css-engine";
-import {
- extractShadowProperties,
- keywordValues,
- propertySyntaxes,
- type ExtractedShadowProperties,
-} from "@webstudio-is/css-data";
+import { keywordValues, propertySyntaxes } from "@webstudio-is/css-data";
import {
Flex,
Grid,
@@ -31,16 +26,18 @@ import {
ShadowInsetIcon,
ShadowNormalIcon,
} from "@webstudio-is/icons";
-import type { IntermediateStyleValue } from "../shared/css-value-input";
-import { CssValueInputContainer } from "../shared/css-value-input";
-import type { StyleUpdateOptions } from "../shared/use-style-data";
+import { humanizeString } from "~/shared/string-utils";
+import { PropertyInlineLabel } from "../property-label";
+import type { IntermediateStyleValue } from "./css-value-input";
+import { CssValueInputContainer } from "./css-value-input";
+import type { StyleUpdateOptions } from "./use-style-data";
import {
CssFragmentEditor,
CssFragmentEditorContent,
parseCssFragment,
} from "./css-fragment";
-import { PropertyInlineLabel } from "../property-label";
import { ColorPicker } from "./color-picker";
+import { $availableColorVariables, $availableUnitVariables } from "./model";
/*
When it comes to checking and validating individual CSS properties for the box-shadow,
@@ -80,18 +77,6 @@ type ShadowContentProps = {
hideCodeEditor?: boolean;
};
-const convertValuesToTupple = (
- values: Partial<Record<keyof ExtractedShadowProperties, StyleValue>>
-): TupleValue => {
- return {
- type: "tuple",
- value: (Object.values(values) as Array<StyleValue>).filter(
- (item: StyleValue): item is UnitValue | RgbValue =>
- item !== null && item !== undefined
- ),
- };
-};
-
const shadowPropertySyntaxes = {
"box-shadow": {
x: propertySyntaxes.boxShadowOffsetX,
@@ -115,6 +100,14 @@ const shadowPropertySyntaxes = {
},
} as const;
+const defaultColor: RgbValue = {
+ type: "rgb",
+ r: 0,
+ g: 0,
+ b: 0,
+ alpha: 1,
+};
+
export const ShadowContent = ({
layer,
computedLayer,
@@ -130,25 +123,25 @@ export const ShadowContent = ({
useEffect(() => {
setIntermediateValue({ type: "intermediate", value: propertyValue });
}, [propertyValue]);
- const layerValues = useMemo<ExtractedShadowProperties>(() => {
- let value: TupleValue = { type: "tuple", value: [] };
- if (layer.type === "tuple") {
- value = layer;
- }
- if (layer.type === "var" && computedLayer?.type === "tuple") {
- value = computedLayer;
- }
- return extractShadowProperties(value);
- }, [layer, computedLayer]);
-
- const { offsetX, offsetY, blur, spread, color, inset } = layerValues;
- const colorControlProp = color ?? {
- type: "rgb",
- r: 0,
- g: 0,
- b: 0,
- alpha: 1,
+ let shadowValue: ShadowValue = {
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", value: 0, unit: "px" },
+ offsetY: { type: "unit", value: 0, unit: "px" },
};
+ if (layer.type === "shadow") {
+ shadowValue = layer;
+ }
+ if (layer.type === "var" && computedLayer?.type === "shadow") {
+ shadowValue = computedLayer;
+ }
+ const computedShadow =
+ computedLayer?.type === "shadow" ? computedLayer : shadowValue;
+
+ const parsedShadowProperty: CssProperty =
+ property === "drop-shadow" ? "text-shadow" : property;
+
+ const disabledControls = layer.type === "var" || layer.type === "unparsed";
const handleChange = (value: string) => {
setIntermediateValue({
@@ -161,17 +154,21 @@ export const ShadowContent = ({
if (intermediateValue === undefined) {
return;
}
+ // prevent reparsing value from string when not changed
+ // because it may contain css variables
+ // which cannot be safely parsed into ShadowValue
+ if (intermediateValue.value === propertyValue) {
+ return;
+ }
// dropShadow is a function under the filter property.
// To parse the value correctly, we need to change the property to textShadow.
// https://developer.mozilla.org/en-US/docs/Web/CSS/filter-function/drop-shadow#formal_syntax
// https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow#formal_syntax
// Both share a similar syntax but the property name is different.
const parsed = parseCssFragment(intermediateValue.value, [
- property === "drop-shadow" ? "text-shadow" : property,
+ parsedShadowProperty,
]);
- const parsedValue = parsed.get(
- property === "drop-shadow" ? "text-shadow" : property
- );
+ const parsedValue = parsed.get(parsedShadowProperty);
if (parsedValue?.type === "layers" || parsedValue?.type === "var") {
onEditLayer(index, parsedValue, { isEphemeral: false });
return;
@@ -182,11 +179,11 @@ export const ShadowContent = ({
});
};
- const handlePropertyChange = (
- params: Partial<Record<keyof ExtractedShadowProperties, StyleValue>>,
+ const updateShadow = (
+ params: Partial<ShadowValue>,
options: StyleUpdateOptions = { isEphemeral: false }
) => {
- const newLayer = convertValuesToTupple({ ...layerValues, ...params });
+ const newLayer: ShadowValue = { ...shadowValue, ...params };
setIntermediateValue({
type: "intermediate",
value: toValue(newLayer),
@@ -214,13 +211,16 @@ export const ShadowContent = ({
// outline-offset is a fake property for validating box-shadow's offsetX.
property="outline-offset"
styleSource="local"
- disabled={layer.type === "var"}
- value={offsetX ?? { type: "unit", value: 0, unit: "px" }}
- onUpdate={(value, options) =>
- handlePropertyChange({ offsetX: value }, options)
- }
+ disabled={disabledControls}
+ getOptions={() => $availableUnitVariables.get()}
+ value={shadowValue.offsetX}
+ onUpdate={(value, options) => {
+ if (value.type === "unit" || value.type === "var") {
+ updateShadow({ offsetX: value }, options);
+ }
+ }}
onDelete={(options) =>
- handlePropertyChange({ offsetX: offsetX ?? undefined }, options)
+ updateShadow({ offsetX: shadowValue.offsetX }, options)
}
/>
</Flex>
@@ -235,13 +235,16 @@ export const ShadowContent = ({
// outline-offset is a fake property for validating box-shadow's offsetY.
property="outline-offset"
styleSource="local"
- disabled={layer.type === "var"}
- value={offsetY ?? { type: "unit", value: 0, unit: "px" }}
- onUpdate={(value, options) =>
- handlePropertyChange({ offsetY: value }, options)
- }
+ disabled={disabledControls}
+ getOptions={() => $availableUnitVariables.get()}
+ value={shadowValue.offsetY}
+ onUpdate={(value, options) => {
+ if (value.type === "unit" || value.type === "var") {
+ updateShadow({ offsetY: value }, options);
+ }
+ }}
onDelete={(options) =>
- handlePropertyChange({ offsetY: offsetY ?? undefined }, options)
+ updateShadow({ offsetY: shadowValue.offsetY }, options)
}
/>
</Flex>
@@ -256,13 +259,16 @@ export const ShadowContent = ({
// border-top-width is a fake property for validating box-shadow's blur.
property="border-top-width"
styleSource="local"
- disabled={layer.type === "var"}
- value={blur ?? { type: "unit", value: 0, unit: "px" }}
- onUpdate={(value, options) =>
- handlePropertyChange({ blur: value }, options)
- }
+ disabled={disabledControls}
+ getOptions={() => $availableUnitVariables.get()}
+ value={shadowValue.blur ?? { type: "unit", value: 0, unit: "px" }}
+ onUpdate={(value, options) => {
+ if (value.type === "unit" || value.type === "var") {
+ updateShadow({ blur: value }, options);
+ }
+ }}
onDelete={(options) =>
- handlePropertyChange({ blur: blur ?? undefined }, options)
+ updateShadow({ blur: shadowValue.blur }, options)
}
/>
</Flex>
@@ -278,13 +284,18 @@ export const ShadowContent = ({
// outline-offset is a fake property for validating box-shadow's spread.
property="outline-offset"
styleSource="local"
- disabled={layer.type === "var"}
- value={spread ?? { type: "unit", value: 0, unit: "px" }}
- onUpdate={(value, options) =>
- handlePropertyChange({ spread: value }, options)
+ disabled={disabledControls}
+ getOptions={() => $availableUnitVariables.get()}
+ value={
+ shadowValue.spread ?? { type: "unit", value: 0, unit: "px" }
}
+ onUpdate={(value, options) => {
+ if (value.type === "unit" || value.type === "var") {
+ updateShadow({ spread: value }, options);
+ }
+ }}
onDelete={(options) =>
- handlePropertyChange({ spread: spread ?? undefined }, options)
+ updateShadow({ spread: shadowValue.spread }, options)
}
/>
</Flex>
@@ -305,48 +316,45 @@ export const ShadowContent = ({
/>
<ColorPicker
property="color"
- disabled={layer.type === "var"}
- value={colorControlProp}
- currentColor={colorControlProp}
- getOptions={() =>
- keywordValues["color"].map((value) => ({
- type: "keyword",
- value,
- }))
- }
- onChange={(styleValue) =>
- handlePropertyChange({ color: styleValue }, { isEphemeral: true })
- }
- onChangeComplete={(styleValue) =>
- handlePropertyChange({ color: styleValue })
- }
- onAbort={() => handlePropertyChange({ color: colorControlProp })}
- onReset={() => {
- handlePropertyChange({ color: undefined });
+ disabled={disabledControls}
+ value={shadowValue.color ?? defaultColor}
+ currentColor={computedShadow?.color ?? defaultColor}
+ getOptions={() => [
+ ...(keywordValues.color ?? []).map((item) => ({
+ type: "keyword" as const,
+ value: item,
+ })),
+ ...$availableColorVariables.get(),
+ ]}
+ onChange={(value) => {
+ if (value.type === "rgb" || value.type === "var") {
+ updateShadow({ color: value }, { isEphemeral: true });
+ }
}}
+ onChangeComplete={(value) => {
+ if (value.type === "rgb" || value.type === "var") {
+ updateShadow({ color: value });
+ }
+ }}
+ onAbort={() => updateShadow({ color: shadowValue.color })}
+ onReset={() => updateShadow({ color: undefined })}
/>
</Flex>
{property === "box-shadow" ? (
<Flex direction="column" gap="1">
<PropertyInlineLabel
- label="Inset"
+ label={humanizeString(shadowValue.position)}
description={shadowPropertySyntaxes["box-shadow"].position}
/>
<ToggleGroup
type="single"
- disabled={layer.type === "var"}
- value={inset?.value ?? "outset"}
+ disabled={disabledControls}
+ value={shadowValue.position}
defaultValue="inset"
- onValueChange={(value) => {
- if (value === "inset") {
- handlePropertyChange({
- inset: { type: "keyword", value: "inset" },
- });
- } else {
- handlePropertyChange({ inset: undefined });
- }
- }}
+ onValueChange={(value) =>
+ updateShadow({ position: value as ShadowValue["position"] })
+ }
>
<Tooltip content="Outset">
<ToggleGroupButton value="outset">
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index 691dd31d59..859ab0fdee 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -627,6 +627,20 @@ const traverseStyleValue = (
}
return;
}
+ if (value.type === "shadow") {
+ traverseStyleValue(value.offsetX, callback);
+ traverseStyleValue(value.offsetY, callback);
+ if (value.blur) {
+ traverseStyleValue(value.blur, callback);
+ }
+ if (value.spread) {
+ traverseStyleValue(value.spread, callback);
+ }
+ if (value.color) {
+ traverseStyleValue(value.color, callback);
+ }
+ return;
+ }
value satisfies never;
};
diff --git a/apps/builder/app/shared/style-object-model.test.tsx b/apps/builder/app/shared/style-object-model.test.tsx
index d9fb2d0f63..7f96dcddb5 100644
--- a/apps/builder/app/shared/style-object-model.test.tsx
+++ b/apps/builder/app/shared/style-object-model.test.tsx
@@ -11,7 +11,12 @@ import {
} from "@webstudio-is/sdk";
import { $, renderData } from "@webstudio-is/template";
import { camelCaseProperty, parseCss } from "@webstudio-is/css-data";
-import type { CssProperty, StyleValue } from "@webstudio-is/css-engine";
+import type {
+ CssProperty,
+ LayersValue,
+ ShadowValue,
+ StyleValue,
+} from "@webstudio-is/css-engine";
import {
type StyleObjectModel,
getComputedStyleDecl,
@@ -404,6 +409,43 @@ test("parse single custom property without tuples", () => {
).toEqual({ type: "unparsed", value: "contrast(300%) brightness(100%)" });
});
+test("compute custom properties in shadows", () => {
+ const model = createModel({
+ css: `
+ bodyLocal {
+ --blur: 30px;
+ --color: #ff0000;
+ box-shadow: 10px 20px;
+ }
+ `,
+ jsx: <$.Body ws:id="body" class="bodyLocal"></$.Body>,
+ });
+ const layers = model.styles.get("bodyLocal:base:boxShadow:")
+ ?.value as LayersValue;
+ const shadowValue = layers.value[0] as ShadowValue;
+ shadowValue.blur = { type: "var", value: "blur" };
+ shadowValue.color = { type: "var", value: "color" };
+ expect(
+ getComputedStyleDecl({
+ model,
+ instanceSelector: ["body"],
+ property: "box-shadow",
+ }).computedValue
+ ).toEqual({
+ type: "layers",
+ value: [
+ {
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "px", value: 10 },
+ offsetY: { type: "unit", unit: "px", value: 20 },
+ blur: { type: "unit", value: 30, unit: "px" },
+ color: { type: "rgb", r: 255, g: 0, b: 0, alpha: 1 },
+ },
+ ],
+ });
+});
+
test("support custom properties in tuples", () => {
const model = createModel({
css: `
diff --git a/apps/builder/app/shared/style-object-model.ts b/apps/builder/app/shared/style-object-model.ts
index 0b82600251..53981068b0 100644
--- a/apps/builder/app/shared/style-object-model.ts
+++ b/apps/builder/app/shared/style-object-model.ts
@@ -262,20 +262,36 @@ const substituteVars = (
if (styleValue.type === "var") {
return mapper(styleValue);
}
+ if (styleValue.type === "shadow") {
+ const newShadowValue = { ...styleValue };
+ if (newShadowValue.offsetX.type === "var") {
+ newShadowValue.offsetX = mapper(newShadowValue.offsetX) as VarValue;
+ }
+ if (newShadowValue.offsetY.type === "var") {
+ newShadowValue.offsetY = mapper(newShadowValue.offsetY) as VarValue;
+ }
+ if (newShadowValue.blur?.type === "var") {
+ newShadowValue.blur = mapper(newShadowValue.blur) as VarValue;
+ }
+ if (newShadowValue.spread?.type === "var") {
+ newShadowValue.spread = mapper(newShadowValue.spread) as VarValue;
+ }
+ if (newShadowValue.color?.type === "var") {
+ newShadowValue.color = mapper(newShadowValue.color) as VarValue;
+ }
+ return newShadowValue;
+ }
if (styleValue.type === "layers" || styleValue.type === "tuple") {
- const newItems: UnparsedValue[] = [];
- let hasVars = false;
- for (const item of styleValue.value) {
+ const newItems = styleValue.value.map((item) => {
if (item.type === "var") {
- hasVars = true;
- newItems.push(mapper(item) as UnparsedValue);
- } else {
- newItems.push(item as UnparsedValue);
+ return mapper(item) as UnparsedValue;
}
- }
- if (hasVars) {
- return { ...styleValue, value: newItems };
- }
+ if (item.type === "shadow") {
+ return substituteVars(item, mapper) as UnparsedValue;
+ }
+ return item as UnparsedValue;
+ });
+ return { ...styleValue, value: newItems };
}
return styleValue;
};
diff --git a/packages/css-data/src/index.ts b/packages/css-data/src/index.ts
index 5cb4613926..c810758d77 100644
--- a/packages/css-data/src/index.ts
+++ b/packages/css-data/src/index.ts
@@ -9,8 +9,6 @@ export {
export * from "./__generated__/animatable-properties";
export * from "./__generated__/pseudo-elements";
-// longhand property parsers
-export * from "./property-parsers/index";
// shorthand property parsers
export * from "./parse-css-value";
export * from "./parse-css";
diff --git a/packages/css-data/src/parse-css-value.test.ts b/packages/css-data/src/parse-css-value.test.ts
index d85cad31d7..b0d9ac9981 100644
--- a/packages/css-data/src/parse-css-value.test.ts
+++ b/packages/css-data/src/parse-css-value.test.ts
@@ -658,22 +658,6 @@ test("parse multiple var in repeated value as layers and tuples", () => {
});
});
-test("parse var in box-shadow", () => {
- expect(parseCssValue("box-shadow", "var(--shadow)")).toEqual({
- type: "var",
- value: "shadow",
- });
- expect(
- parseCssValue("box-shadow", "var(--shadow-1), var(--shadow-2)")
- ).toEqual({
- type: "layers",
- value: [
- { type: "var", value: "shadow-1" },
- { type: "var", value: "shadow-2" },
- ],
- });
-});
-
describe("parse shadows", () => {
test("parses value and returns invalid when used a invalid boxShadow is passed", () => {
expect(parseCssValue("box-shadow", `10px 10px 5px foo`)).toEqual({
@@ -701,13 +685,12 @@ describe("parse shadows", () => {
type: "layers",
value: [
{
- type: "tuple",
- value: [
- { type: "unit", unit: "px", value: 1 },
- { type: "unit", unit: "px", value: 1 },
- { type: "unit", unit: "px", value: 2 },
- { type: "keyword", value: "black" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "px", value: 1 },
+ offsetY: { type: "unit", unit: "px", value: 1 },
+ blur: { type: "unit", unit: "px", value: 2 },
+ color: { type: "keyword", value: "black" },
},
],
});
@@ -718,14 +701,12 @@ describe("parse shadows", () => {
type: "layers",
value: [
{
- type: "tuple",
- value: [
- { type: "keyword", value: "inset" },
- { type: "unit", unit: "px", value: 10 },
- { type: "unit", unit: "px", value: 10 },
- { type: "unit", unit: "px", value: 5 },
- { type: "keyword", value: "black" },
- ],
+ type: "shadow",
+ position: "inset",
+ offsetX: { type: "unit", unit: "px", value: 10 },
+ offsetY: { type: "unit", unit: "px", value: 10 },
+ blur: { type: "unit", unit: "px", value: 5 },
+ color: { type: "keyword", value: "black" },
},
],
});
@@ -736,13 +717,11 @@ describe("parse shadows", () => {
type: "layers",
value: [
{
- type: "tuple",
- value: [
- { type: "keyword", value: "inset" },
- { type: "unit", unit: "em", value: 5 },
- { type: "unit", unit: "em", value: 1 },
- { type: "keyword", value: "gold" },
- ],
+ type: "shadow",
+ position: "inset",
+ offsetX: { type: "unit", unit: "em", value: 5 },
+ offsetY: { type: "unit", unit: "em", value: 1 },
+ color: { type: "keyword", value: "gold" },
},
],
});
@@ -753,12 +732,11 @@ describe("parse shadows", () => {
type: "layers",
value: [
{
- type: "tuple",
- value: [
- { type: "unit", unit: "px", value: 60 },
- { type: "unit", unit: "px", value: -16 },
- { type: "keyword", value: "teal" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "px", value: 60 },
+ offsetY: { type: "unit", unit: "px", value: -16 },
+ color: { type: "keyword", value: "teal" },
},
],
});
@@ -774,22 +752,20 @@ describe("parse shadows", () => {
type: "layers",
value: [
{
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 60 },
- { type: "unit", unit: "px", value: 80 },
- { alpha: 0.6, b: 0, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "number", value: 0 },
+ offsetY: { type: "unit", unit: "px", value: 60 },
+ blur: { type: "unit", unit: "px", value: 80 },
+ color: { alpha: 0.6, b: 0, g: 0, r: 0, type: "rgb" },
},
{
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 45 },
- { type: "unit", unit: "px", value: 26 },
- { alpha: 0.14, b: 0, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "number", value: 0 },
+ offsetY: { type: "unit", unit: "px", value: 45 },
+ blur: { type: "unit", unit: "px", value: 26 },
+ color: { alpha: 0.14, b: 0, g: 0, r: 0, type: "rgb" },
},
],
});
@@ -809,36 +785,48 @@ describe("parse shadows", () => {
type: "layers",
value: [
{
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 5 },
- { alpha: 0.2, b: 0, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "number", value: 0 },
+ offsetY: { type: "unit", unit: "number", value: 0 },
+ blur: { type: "unit", unit: "px", value: 5 },
+ color: { alpha: 0.2, b: 0, g: 0, r: 0, type: "rgb" },
},
{
- type: "tuple",
- value: [
- { type: "keyword", value: "inset" },
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 10 },
- { alpha: 0.3, b: 0, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "inset",
+ offsetX: { type: "unit", unit: "number", value: 0 },
+ offsetY: { type: "unit", unit: "number", value: 0 },
+ blur: { type: "unit", unit: "px", value: 10 },
+ color: { alpha: 0.3, b: 0, g: 0, r: 0, type: "rgb" },
},
{
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 15 },
- { alpha: 0.4, b: 0, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "number", value: 0 },
+ offsetY: { type: "unit", unit: "number", value: 0 },
+ blur: { type: "unit", unit: "px", value: 15 },
+ color: { alpha: 0.4, b: 0, g: 0, r: 0, type: "rgb" },
},
],
});
});
+
+ test("parse var in box-shadow", () => {
+ expect(parseCssValue("box-shadow", "var(--shadow)")).toEqual({
+ type: "var",
+ value: "shadow",
+ });
+ expect(
+ parseCssValue("box-shadow", "var(--shadow-1), var(--shadow-2)")
+ ).toEqual({
+ type: "layers",
+ value: [
+ { type: "var", value: "shadow-1" },
+ { type: "var", value: "shadow-2" },
+ ],
+ });
+ });
});
describe("parse filters", () => {
@@ -865,13 +853,12 @@ describe("parse filters", () => {
type: "function",
name: "drop-shadow",
args: {
- type: "tuple",
- value: [
- { type: "unit", unit: "px", value: 10 },
- { type: "unit", unit: "px", value: 10 },
- { type: "unit", unit: "px", value: 25 },
- { alpha: 1, b: 255, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "px", value: 10 },
+ offsetY: { type: "unit", unit: "px", value: 10 },
+ blur: { type: "unit", unit: "px", value: 25 },
+ color: { alpha: 1, b: 255, g: 0, r: 0, type: "rgb" },
},
},
],
@@ -885,13 +872,27 @@ describe("parse filters", () => {
type: "function",
name: "drop-shadow",
args: {
- type: "tuple",
- value: [
- { type: "unit", unit: "px", value: 10 },
- { type: "unit", unit: "px", value: 10 },
- { type: "unit", unit: "px", value: 25 },
- { alpha: 1, b: 255, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "px", value: 10 },
+ offsetY: { type: "unit", unit: "px", value: 10 },
+ blur: { type: "unit", unit: "px", value: 25 },
+ color: { alpha: 1, b: 255, g: 0, r: 0, type: "rgb" },
+ },
+ },
+ ],
+ });
+ expect(
+ parseCssValue("filter", "drop-shadow(10px 10px 25px var(--color))")
+ ).toEqual({
+ type: "tuple",
+ value: [
+ {
+ type: "function",
+ name: "drop-shadow",
+ args: {
+ type: "unparsed",
+ value: "10px 10px 25px var(--color)",
},
},
],
@@ -935,13 +936,12 @@ describe("parse filters", () => {
type: "function",
name: "drop-shadow",
args: {
- type: "tuple",
- value: [
- { type: "unit", unit: "px", value: 16 },
- { type: "unit", unit: "px", value: 16 },
- { type: "unit", unit: "px", value: 20 },
- { type: "keyword", value: "blue" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "px", value: 16 },
+ offsetY: { type: "unit", unit: "px", value: 16 },
+ blur: { type: "unit", unit: "px", value: 20 },
+ color: { type: "keyword", value: "blue" },
},
},
{
diff --git a/packages/css-data/src/parse-css-value.ts b/packages/css-data/src/parse-css-value.ts
index 0a887423b3..0f3723f59a 100644
--- a/packages/css-data/src/parse-css-value.ts
+++ b/packages/css-data/src/parse-css-value.ts
@@ -1,4 +1,5 @@
-import { colord } from "colord";
+import { colord, extend } from "colord";
+import namesPlugin from "colord/plugins/names";
import { type CssNode, generate, lexer, List, parse } from "css-tree";
import warnOnce from "warn-once";
import {
@@ -16,10 +17,15 @@ import {
type FunctionValue,
type TupleValueItem,
type CssProperty,
+ type ShadowValue,
+ UnparsedValue,
} from "@webstudio-is/css-engine";
import { keywordValues } from "./__generated__/keyword-values";
import { units } from "./__generated__/units";
+// To support color names
+extend([namesPlugin]);
+
export const cssTryParseValue = (input: string): undefined | CssNode => {
try {
const ast = parse(input, { context: "value" });
@@ -133,8 +139,6 @@ const repeatedProps = new Set<CssProperty>([
]);
const tupleProps = new Set<CssProperty>([
- "box-shadow",
- "text-shadow",
"scale",
"translate",
"rotate",
@@ -161,6 +165,49 @@ const parseColor = (colorString: string): undefined | RgbValue => {
}
};
+const parseShadow = (
+ nodes: CssNode[],
+ input: string
+): ShadowValue | UnparsedValue => {
+ // https://drafts.csswg.org/css-borders-4/#box-shadow-position
+ let position: "inset" | "outset" = "outset";
+ let color: undefined | RgbValue | KeywordValue;
+ const units: UnitValue[] = [];
+ for (const node of nodes) {
+ const item = parseLiteral(node, ["inset"]);
+ if (item?.type === "keyword" && item.value === "inset") {
+ position = item.value;
+ } else if (item?.type === "keyword" && parseColor(item.value)) {
+ color = item;
+ } else if (item?.type === "rgb") {
+ color = item;
+ } else if (item?.type === "unit") {
+ units.push(item);
+ } else {
+ return { type: "unparsed", value: input };
+ }
+ }
+ if (units.length < 2) {
+ return { type: "unparsed", value: input };
+ }
+ const shadowValue: ShadowValue = {
+ type: "shadow",
+ position,
+ offsetX: units[0],
+ offsetY: units[1],
+ };
+ if (units.length > 2) {
+ shadowValue.blur = units[2];
+ }
+ if (units.length > 3) {
+ shadowValue.spread = units[3];
+ }
+ if (color) {
+ shadowValue.color = color;
+ }
+ return shadowValue;
+};
+
const parseLiteral = (
node: undefined | null | CssNode,
keywords?: readonly string[]
@@ -195,7 +242,10 @@ const parseLiteral = (
}
if (node?.type === "Identifier") {
const name = node.name.toLowerCase();
- if (keywords?.map((keyword) => keyword.toLowerCase()).includes(name)) {
+ if (
+ keywords?.map((keyword) => keyword.toLowerCase()).includes(name) ||
+ parseColor(name)
+ ) {
return {
type: "keyword",
value: name,
@@ -298,7 +348,6 @@ const parseLiteral = (
node.name === "blur" ||
node.name === "brightness" ||
node.name === "contrast" ||
- node.name === "drop-shadow" ||
node.name === "grayscale" ||
node.name === "hue-rotate" ||
node.name === "invert" ||
@@ -312,12 +361,19 @@ const parseLiteral = (
if (matchedValue) {
args.value.push(matchedValue as TupleValueItem);
}
- if (arg.type === "Identifier") {
- args.value.push({ type: "keyword", value: arg.name });
- }
}
return { type: "function", args, name: node.name };
}
+ if (node.name === "drop-shadow") {
+ return {
+ type: "function",
+ args: parseShadow(
+ node.children.toArray(),
+ generate({ type: "Value", children: node.children })
+ ),
+ name: node.name,
+ };
+ }
}
};
@@ -440,6 +496,10 @@ export const parseCssValue = (
};
}
+ if (property === "box-shadow" || property === "text-shadow") {
+ return parseShadow(nodes, input);
+ }
+
// Probably a tuple like background-size or box-shadow
if (
ast.type === "Value" &&
diff --git a/packages/css-data/src/property-parsers/index.ts b/packages/css-data/src/property-parsers/index.ts
deleted file mode 100644
index 985e4601c2..0000000000
--- a/packages/css-data/src/property-parsers/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "./shadow-properties-extractor";
diff --git a/packages/css-data/src/property-parsers/shadow-properties-extractor.test.ts b/packages/css-data/src/property-parsers/shadow-properties-extractor.test.ts
deleted file mode 100644
index 755323c2c7..0000000000
--- a/packages/css-data/src/property-parsers/shadow-properties-extractor.test.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-import { describe, expect, test } from "vitest";
-import { extractShadowProperties } from "./shadow-properties-extractor";
-import type { LayersValue, TupleValue } from "@webstudio-is/css-engine";
-import { parseCssValue } from "../parse-css-value";
-
-describe("Extract Box-Shadow Properties", () => {
- test("tokenize and extracts values from 5em 5em 2em 2em #0000", () => {
- const { inset, blur, spread, color } = extractShadowProperties({
- type: "tuple",
- value: [
- {
- type: "unit",
- value: 5,
- unit: "em",
- },
- {
- type: "unit",
- value: 5,
- unit: "em",
- },
- {
- type: "unit",
- value: 2,
- unit: "em",
- },
- {
- type: "unit",
- value: 2,
- unit: "em",
- },
- {
- type: "rgb",
- alpha: 0,
- r: 0,
- g: 0,
- b: 0,
- },
- ],
- });
-
- expect(inset).not.toBeDefined();
- expect(blur).toBeDefined();
- expect(spread?.value).toBe(2);
- expect(color?.type).toBe("rgb");
- });
-
- test("tokenize and extracts values from inset 5em 5em red", () => {
- const { inset, spread, color, offsetX } = extractShadowProperties({
- type: "tuple",
- value: [
- {
- type: "keyword",
- value: "inset",
- },
- {
- type: "unit",
- value: 5,
- unit: "em",
- },
- {
- type: "unit",
- value: 5,
- unit: "em",
- },
- {
- type: "keyword",
- value: "red",
- },
- ],
- });
-
- expect(inset).toBeDefined();
- expect(spread).not.toBeDefined();
- expect(offsetX?.value).toBe(5);
- expect(color?.type).toBe("keyword");
- });
-
- test("tokenize and extracts values from 5em 5em #fff", () => {
- const { offsetX, offsetY, color } = extractShadowProperties({
- type: "tuple",
- value: [
- {
- type: "unit",
- value: 5,
- unit: "em",
- },
- {
- type: "unit",
- value: 5,
- unit: "em",
- },
- {
- type: "rgb",
- alpha: 1,
- b: 255,
- g: 255,
- r: 255,
- },
- ],
- });
-
- expect(offsetX?.value).toBe(5);
- expect(offsetY?.value).toBe(5);
- expect(color).toBeDefined();
- });
-
- test("tokenize and extracts values from 5em 5em", () => {
- const { offsetX, offsetY } = extractShadowProperties({
- type: "tuple",
- value: [
- {
- type: "unit",
- value: 5,
- unit: "em",
- },
- {
- type: "unit",
- value: 5,
- unit: "em",
- },
- ],
- });
-
- expect(offsetX?.value).toBe(5);
- expect(offsetY?.value).toBe(5);
- });
-
- test("tokenize and extract values from 5em 5em 0em 5em inset #ffff", () => {
- const layers = parseCssValue(
- "box-shadow",
- "5em 5em 0em 5em inset #ffff"
- ) as LayersValue;
-
- const layer = layers.value.find(
- (layer): layer is TupleValue => layer.type === "tuple"
- );
- if (!layer) {
- throw new Error(`Parsing box-shadow layer failed`);
- }
-
- const { blur, spread, color, offsetX, inset } =
- extractShadowProperties(layer);
-
- expect(blur).toBeDefined();
- expect(blur?.value).toBe(0);
- expect(spread?.value).toBe(5);
- expect(offsetX?.value).toBe(5);
- expect(color).toBeDefined();
- expect(inset).toBeDefined();
- });
-});
-
-describe("Extract Text-Shadow Properties", () => {
- test("tokenize and extracts values from 5em 10em 2em #0000", () => {
- const { offsetX, offsetY, blur, color } = extractShadowProperties(
- (parseCssValue("text-shadow", "5em 10em 2em #0000") as LayersValue)
- ?.value[0] as TupleValue
- );
-
- expect(offsetY).toBeDefined();
- expect(offsetX?.value).toBe(5);
- expect(color?.type).toBe("rgb");
- expect(blur?.value).toBe(2);
- });
-
- test("tokenize and extracts values from 5em 10em", () => {
- const { offsetX, offsetY, blur, color } = extractShadowProperties(
- (parseCssValue("text-shadow", "5em 10em") as LayersValue)
- ?.value[0] as TupleValue
- );
-
- expect(offsetY?.value).toBe(10);
- expect(offsetX?.value).toBe(5);
-
- expect(color).not.toBeDefined();
- expect(blur).not.toBeDefined();
- });
-});
diff --git a/packages/css-data/src/property-parsers/shadow-properties-extractor.ts b/packages/css-data/src/property-parsers/shadow-properties-extractor.ts
deleted file mode 100644
index fa57b8b482..0000000000
--- a/packages/css-data/src/property-parsers/shadow-properties-extractor.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import type {
- KeywordValue,
- RgbValue,
- TupleValue,
- TupleValueItem,
- UnitValue,
-} from "@webstudio-is/css-engine";
-
-/*
- extractBoxShadowProperties accepts a TupleValue
- and just tokenizes the valuess of box-shadow items.
- https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow#syntax
-
- To validate the box-shadow string value, should be used
- in combination with parseShadow function.
-
- Eg:
- extractBoxShadowProperties(parseShadow('boxShadow', "5em 5em 5em 5em #ffff"))
-*/
-
-export type ExtractedShadowProperties = {
- inset?: KeywordValue | undefined;
- color?: RgbValue | KeywordValue | undefined;
- offsetX: UnitValue;
- offsetY: UnitValue;
- blur: UnitValue;
- spread: UnitValue;
-};
-
-export const extractShadowProperties = (
- shadow: TupleValue
-): ExtractedShadowProperties => {
- let properties = [...shadow.value];
- let inset: KeywordValue | undefined = undefined;
- let color: KeywordValue | RgbValue | undefined = undefined;
-
- properties = properties.filter(
- (prop: TupleValueItem): prop is KeywordValue => {
- if (prop.type === "keyword" && prop.value === "inset") {
- inset = prop;
- return false;
- }
-
- if (prop.type === "keyword" || prop.type === "rgb") {
- color = prop;
- return false;
- }
-
- return true;
- }
- );
-
- const [offsetX, offsetY, blur, spread] = properties.filter(
- (item): item is UnitValue => item.type === "unit"
- );
-
- return {
- ...(color !== undefined && { color }),
- ...(inset !== undefined && { inset }),
- offsetX,
- offsetY,
- blur,
- spread,
- };
-};
diff --git a/packages/css-data/src/tailwind-parser/parse.test.ts b/packages/css-data/src/tailwind-parser/parse.test.ts
index 1feca109a2..bad09fca7a 100644
--- a/packages/css-data/src/tailwind-parser/parse.test.ts
+++ b/packages/css-data/src/tailwind-parser/parse.test.ts
@@ -115,40 +115,36 @@ describe("parseTailwindToWebstudio", () => {
type: "layers",
value: [
{
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "number", value: 0 },
- { alpha: 0, b: 0, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "number", value: 0 },
+ offsetY: { type: "unit", unit: "number", value: 0 },
+ color: { alpha: 0, b: 0, g: 0, r: 0, type: "rgb" },
},
{
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "number", value: 0 },
- { alpha: 0, b: 0, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "number", value: 0 },
+ offsetY: { type: "unit", unit: "number", value: 0 },
+ color: { alpha: 0, b: 0, g: 0, r: 0, type: "rgb" },
},
{
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 4 },
- { type: "unit", unit: "px", value: 6 },
- { type: "unit", unit: "px", value: -1 },
- { alpha: 0.1, b: 0, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "number", value: 0 },
+ offsetY: { type: "unit", unit: "px", value: 4 },
+ blur: { type: "unit", unit: "px", value: 6 },
+ spread: { type: "unit", unit: "px", value: -1 },
+ color: { alpha: 0.1, b: 0, g: 0, r: 0, type: "rgb" },
},
{
- type: "tuple",
- value: [
- { type: "unit", unit: "number", value: 0 },
- { type: "unit", unit: "px", value: 2 },
- { type: "unit", unit: "px", value: 4 },
- { type: "unit", unit: "px", value: -2 },
- { alpha: 0.1, b: 0, g: 0, r: 0, type: "rgb" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", unit: "number", value: 0 },
+ offsetY: { type: "unit", unit: "px", value: 2 },
+ blur: { type: "unit", unit: "px", value: 4 },
+ spread: { type: "unit", unit: "px", value: -2 },
+ color: { alpha: 0.1, b: 0, g: 0, r: 0, type: "rgb" },
},
],
},
diff --git a/packages/css-engine/src/core/to-value.test.ts b/packages/css-engine/src/core/to-value.test.ts
index b9ae3a2ad8..3e61ee011e 100644
--- a/packages/css-engine/src/core/to-value.test.ts
+++ b/packages/css-engine/src/core/to-value.test.ts
@@ -178,13 +178,12 @@ describe("Convert WS CSS Values to native CSS strings", () => {
type: "function",
name: "drop-shadow",
args: {
- type: "tuple",
- value: [
- { type: "unit", value: 10, unit: "px" },
- { type: "unit", value: 10, unit: "px" },
- { type: "unit", value: 10, unit: "px" },
- { type: "keyword", value: "red" },
- ],
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", value: 10, unit: "px" },
+ offsetY: { type: "unit", value: 10, unit: "px" },
+ blur: { type: "unit", value: 10, unit: "px" },
+ color: { type: "keyword", value: "red" },
},
});
@@ -235,3 +234,79 @@ describe("Convert WS CSS Values to native CSS strings", () => {
expect(value).toBe("");
});
});
+
+describe("serialize shadow value", () => {
+ test("minimal value", () => {
+ expect(
+ toValue({
+ type: "layers",
+ value: [
+ {
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", value: 1, unit: "px" },
+ offsetY: { type: "unit", value: 2, unit: "px" },
+ },
+ ],
+ })
+ ).toEqual("1px 2px");
+ });
+
+ test("full value", () => {
+ expect(
+ toValue({
+ type: "layers",
+ value: [
+ {
+ type: "shadow",
+ position: "inset",
+ offsetX: { type: "unit", value: 1, unit: "px" },
+ offsetY: { type: "unit", value: 2, unit: "px" },
+ blur: { type: "unit", value: 3, unit: "px" },
+ spread: { type: "unit", value: 4, unit: "px" },
+ color: { type: "rgb", r: 0, g: 0, b: 0, alpha: 1 },
+ },
+ ],
+ })
+ ).toEqual("1px 2px 3px 4px rgba(0, 0, 0, 1) inset");
+ });
+
+ test("hidden value", () => {
+ expect(
+ toValue({
+ type: "layers",
+ value: [
+ {
+ type: "shadow",
+ hidden: true,
+ position: "outset",
+ offsetX: { type: "unit", value: 1, unit: "px" },
+ offsetY: { type: "unit", value: 2, unit: "px" },
+ },
+ ],
+ })
+ ).toEqual("none");
+ });
+
+ test("multiple values", () => {
+ expect(
+ toValue({
+ type: "layers",
+ value: [
+ {
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", value: 1, unit: "px" },
+ offsetY: { type: "unit", value: 2, unit: "px" },
+ },
+ {
+ type: "shadow",
+ position: "outset",
+ offsetX: { type: "unit", value: 3, unit: "px" },
+ offsetY: { type: "unit", value: 4, unit: "px" },
+ },
+ ],
+ })
+ ).toEqual("1px 2px, 3px 4px");
+ });
+});
diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.ts
index b6f0430e15..efaf8f5dc9 100644
--- a/packages/css-engine/src/core/to-value.ts
+++ b/packages/css-engine/src/core/to-value.ts
@@ -131,6 +131,23 @@ export const toValue = (
.join(" ");
}
+ if (value.type === "shadow") {
+ let shadow = `${toValue(value.offsetX)} ${toValue(value.offsetY)}`;
+ if (value.blur) {
+ shadow += ` ${toValue(value.blur)}`;
+ }
+ if (value.spread) {
+ shadow += ` ${toValue(value.spread)}`;
+ }
+ if (value.color) {
+ shadow += ` ${toValue(value.color)}`;
+ }
+ if (value.position === "inset") {
+ shadow += ` inset`;
+ }
+ return shadow;
+ }
+
if (value.type === "function") {
// Right now, we are using function-value only for filter and backdrop-filter functions
if (value.hidden === true) {
diff --git a/packages/css-engine/src/schema.ts b/packages/css-engine/src/schema.ts
index 9737813ccf..9aa2bc5e12 100644
--- a/packages/css-engine/src/schema.ts
+++ b/packages/css-engine/src/schema.ts
@@ -171,12 +171,26 @@ export const TupleValue = z.object({
export type TupleValue = z.infer<typeof TupleValue>;
+export const ShadowValue = z.object({
+ type: z.literal("shadow"),
+ hidden: z.boolean().optional(),
+ position: z.union([z.literal("inset"), z.literal("outset")]),
+ offsetX: z.union([UnitValue, VarValue]),
+ offsetY: z.union([UnitValue, VarValue]),
+ blur: z.union([UnitValue, VarValue]).optional(),
+ spread: z.union([UnitValue, VarValue]).optional(),
+ color: z.union([RgbValue, KeywordValue, VarValue]).optional(),
+});
+
+export type ShadowValue = z.infer<typeof ShadowValue>;
+
const LayerValueItem = z.union([
UnitValue,
KeywordValue,
UnparsedValue,
ImageValue,
TupleValue,
+ ShadowValue,
RgbValue,
InvalidValue,
FunctionValue,
@@ -209,6 +223,7 @@ export const StyleValue = z.union([
InvalidValue,
UnsetValue,
VarValue,
+ ShadowValue,
]);
export type StyleValue = z.infer<typeof StyleValue>;