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): Ability to add `box-shadow` to nodes. (#1634)

Jaya Krishna Namburu61f164d40e6c
diff --git a/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsx b/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsx
index 1173e7db2b..5b76bf3036 100644
--- a/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsx
+++ b/apps/builder/app/builder/features/style-panel/controls/position/position-control.tsx
@@ -12,6 +12,11 @@ import type { SetValue } from "../../shared/use-style-data";
import { NonResetablePropertyName } from "../../shared/property-name";
const toPosition = (value: TupleValue) => {
+ // Should never actually happen, just for TS
+ if (value.value[0].type !== "unit" || value.value[1].type !== "unit") {
+ return { x: 0, y: 0 };
+ }
+
return {
x: value.value[0].value,
y: value.value[1].value,
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 10d62f3d82..5d97a2162b 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,6 +1,6 @@
import type { InvalidValue, RgbValue } from "@webstudio-is/css-data";
import { parseCssValue, parseBackground } from "@webstudio-is/css-data";
-import { TextArea, theme } from "@webstudio-is/design-system";
+import { TextArea, textVariants, theme } from "@webstudio-is/design-system";
import { useEffect, useRef, useState } from "react";
import type { ControlProps } from "../../style-sections";
@@ -88,7 +88,7 @@ export const BackgroundGradient = (
return (
<TextArea
ref={textAreaRef}
- css={{ minHeight: theme.spacing[14] }}
+ css={{ minHeight: theme.spacing[14], ...textVariants.mono }}
rows={2}
name="description"
disabled={props.disabled}
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.tsx
index 48098a067c..334f9414eb 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
@@ -14,13 +14,12 @@ import { toValue } from "@webstudio-is/css-engine";
import { toPascalCase } from "../../shared/keyword-utils";
const Thumbnail = styled("div", {
+ borderRadius: 2,
width: theme.spacing[10],
height: theme.spacing[10],
});
-const NoneThumbnail = styled("div", {
- width: theme.spacing[10],
- height: theme.spacing[10],
+const NoneThumbnail = styled(Thumbnail, {
background:
"repeating-conic-gradient(rgba(0,0,0,0.22) 0% 25%, transparent 0% 50%) 0% 33.33% / 40% 40%",
});
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 028622a024..79d6061dd3 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
@@ -3,9 +3,8 @@ import type { RenderCategoryProps } from "../../style-sections";
import { styleConfigByName } from "../../shared/configs";
import { FloatingPanel } from "~/builder/shared/floating-panel";
import {
- ArrowFocus,
- Box,
CssValueListItem,
+ CssValueListArrowFocus,
Flex,
Grid,
Label,
@@ -13,9 +12,10 @@ import {
SectionTitleButton,
SectionTitleLabel,
SmallIconButton,
+ SmallToggleButton,
theme,
+ useSortable,
} from "@webstudio-is/design-system";
-import { SmallToggleButton } from "@webstudio-is/design-system";
import {
EyeconOpenIcon,
EyeconClosedIcon,
@@ -42,8 +42,7 @@ import {
} from "./background-layers";
import { BackgroundContent } from "./background-content";
import { getLayerName, LayerThumbnail } from "./background-thumbnail";
-import { useSortable } from "./use-sortable";
-import { useMemo, type ReactNode } from "react";
+import { useMemo } from "react";
import type { RgbValue, StyleProperty } from "@webstudio-is/css-data";
import {
CollapsibleSectionBase,
@@ -51,13 +50,9 @@ import {
} from "~/builder/shared/collapsible-section";
import { getDots } from "../../shared/collapsible-section";
-const LIST_ITEM_ATTRIBUTE = "data-list-item";
-
-const listItemAttributes = { [LIST_ITEM_ATTRIBUTE]: true };
-
const Layer = (props: {
id: string;
- tabIndex: -1 | 0;
+ index: number;
isHighlighted: boolean;
layerStyle: StyleInfo;
setProperty: SetBackgroundProperty;
@@ -103,9 +98,9 @@ const Layer = (props: {
}
>
<CssValueListItem
+ id={props.id}
active={props.isHighlighted}
- data-id={props.id}
- tabIndex={props.tabIndex}
+ index={props.index}
label={
<Label truncate onReset={props.deleteLayer}>
{getLayerName(props.layerStyle, assets)}
@@ -132,7 +127,6 @@ const Layer = (props: {
/>
</>
}
- {...listItemAttributes}
/>
</FloatingPanel>
);
@@ -202,28 +196,6 @@ const BackgroundsCollapsibleSection = ({
);
};
-const ListItemsFocusWrap = (props: { children: ReactNode }) => {
- return (
- <ArrowFocus
- render={({ handleKeyDown }) => (
- <Box
- css={{ display: "contents" }}
- onKeyDown={(event) => {
- if (event.key === "ArrowUp" || event.key === "ArrowDown") {
- handleKeyDown(event, {
- accept: (element) =>
- element.getAttribute(LIST_ITEM_ATTRIBUTE) === "true",
- });
- }
- }}
- >
- {props.children}
- </Box>
- )}
- />
- );
-};
-
export const BackgroundsSection = (props: RenderCategoryProps) => {
const { setProperty, deleteProperty, currentStyle, createBatchUpdate } =
props;
@@ -231,7 +203,7 @@ export const BackgroundsSection = (props: RenderCategoryProps) => {
const { items } = styleConfigByName("backgroundColor");
- const layers = useMemo(
+ const sortableItems = useMemo(
() =>
Array.from(Array(layersCount), (_, index) => ({
id: `${index}`,
@@ -241,7 +213,7 @@ export const BackgroundsSection = (props: RenderCategoryProps) => {
);
const { dragItemId, placementIndicator, sortableRefCallback } = useSortable({
- items: layers,
+ items: sortableItems,
onSort: (newIndex, oldIndex) => {
swapLayers(newIndex, oldIndex, currentStyle, createBatchUpdate);
},
@@ -256,21 +228,12 @@ export const BackgroundsSection = (props: RenderCategoryProps) => {
category={props.category}
>
<Flex gap={1} direction="column">
- <ListItemsFocusWrap>
- <Flex
- gap={1}
- direction="column"
- ref={sortableRefCallback}
- css={{
- pointerEvents: dragItemId ? "none" : "auto",
- // to make DnD work we have to disable scrolling using touch
- touchAction: "none",
- }}
- >
- {layers.map((layer, index) => (
+ <CssValueListArrowFocus dragItemId={dragItemId}>
+ <Flex gap={1} direction="column" ref={sortableRefCallback}>
+ {sortableItems.map((layer, index) => (
<Layer
id={layer.id}
- tabIndex={index === 0 ? 0 : -1}
+ index={index}
key={layer.id}
isHighlighted={dragItemId === layer.id}
layerStyle={getLayerBackgroundStyleInfo(
@@ -299,7 +262,7 @@ export const BackgroundsSection = (props: RenderCategoryProps) => {
{placementIndicator}
</Flex>
- </ListItemsFocusWrap>
+ </CssValueListArrowFocus>
<Grid
css={{
diff --git a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-content.tsx b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-content.tsx
new file mode 100644
index 0000000000..9d068d3e05
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-content.tsx
@@ -0,0 +1,111 @@
+import type { InvalidValue, LayersValue } from "@webstudio-is/css-data";
+import { parseBoxShadow } from "@webstudio-is/css-data";
+import {
+ Flex,
+ Label,
+ Text,
+ TextArea,
+ textVariants,
+ theme,
+ Tooltip,
+} from "@webstudio-is/design-system";
+import { InformationIcon } from "@webstudio-is/icons";
+import { useState } from "react";
+import type { RenderCategoryProps } from "../../style-sections";
+
+type IntermediateValue = {
+ type: "intermediate";
+ value: string;
+};
+
+const useContent = ({
+ onEditLayer,
+ index,
+}: {
+ onEditLayer: (index: number, layers: LayersValue) => void;
+ index: number;
+}) => {
+ const [intermediateValue, setIntermediateValue] = useState<
+ IntermediateValue | InvalidValue | undefined
+ >();
+
+ const handleChange = (value: string) => {
+ setIntermediateValue({
+ type: "intermediate",
+ value,
+ });
+ };
+
+ const handleComplete = () => {
+ if (intermediateValue === undefined) {
+ return;
+ }
+ const layers = parseBoxShadow(intermediateValue.value);
+ if (layers.type === "invalid") {
+ setIntermediateValue({
+ type: "invalid",
+ value: intermediateValue.value,
+ });
+ return;
+ }
+
+ onEditLayer(index, layers);
+ };
+
+ return { handleChange, handleComplete, intermediateValue };
+};
+
+type BoxShadowContentProps = {
+ index: number;
+ value: string;
+ onEditLayer: (index: number, layers: LayersValue) => void;
+ createBatchUpdate: RenderCategoryProps["createBatchUpdate"];
+};
+
+export const BoxShadowContent = (props: BoxShadowContentProps) => {
+ const { intermediateValue, handleChange, handleComplete } = useContent(props);
+ return (
+ <Flex
+ direction="column"
+ css={{
+ px: theme.spacing[5],
+ py: theme.spacing[5],
+ gap: theme.spacing[3],
+ minWidth: theme.spacing[30],
+ }}
+ >
+ <Label>
+ <Flex align={"center"} gap={1}>
+ Code
+ <Tooltip
+ variant="wrapped"
+ content={
+ <Text>
+ Paste a box-shadow value, for example:
+ <br />
+ <br />
+ 0px 2px 5px 0px rgba(0, 0, 0, 0.2)
+ </Text>
+ }
+ >
+ <InformationIcon />
+ </Tooltip>
+ </Flex>
+ </Label>
+ <TextArea
+ rows={3}
+ name="description"
+ value={intermediateValue?.value ?? props.value ?? ""}
+ css={{ minHeight: theme.spacing[14], ...textVariants.mono }}
+ state={intermediateValue?.type === "invalid" ? "invalid" : undefined}
+ onChange={(event) => handleChange(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ handleComplete();
+ event.preventDefault();
+ }
+ }}
+ />
+ </Flex>
+ );
+};
diff --git a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-layer.tsx b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-layer.tsx
new file mode 100644
index 0000000000..c382868ef5
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-layer.tsx
@@ -0,0 +1,109 @@
+import type { LayersValue, TupleValue } from "@webstudio-is/css-data";
+import {
+ Label,
+ SmallIconButton,
+ SmallToggleButton,
+ CssValueListItem,
+} from "@webstudio-is/design-system";
+import {
+ EyeconClosedIcon,
+ EyeconOpenIcon,
+ SubtractIcon,
+} from "@webstudio-is/icons";
+import { useMemo } from "react";
+import { FloatingPanel } from "~/builder/shared/floating-panel";
+import { BoxShadowContent } from "./box-shadow-content";
+import type { RenderCategoryProps } from "../../style-sections";
+import { colord, type RgbaColor } from "colord";
+import { toValue } from "@webstudio-is/css-engine";
+import { ColorThumb } from "../../shared/color-thumb";
+
+const useLayer = (layer: TupleValue) => {
+ return useMemo(() => {
+ const name = [];
+ const shadow = [];
+ let color: RgbaColor | undefined;
+ for (const item of Object.values(layer.value)) {
+ if (item.type === "unit") {
+ const value = toValue(item);
+ name.push(value);
+ shadow.push(value);
+ }
+
+ if (item.type === "rgb") {
+ color = colord(toValue(item)).toRgb();
+ shadow.push(toValue(item));
+ }
+
+ if (item.type === "keyword") {
+ if (colord(item.value).isValid() === false) {
+ name.push(item.value);
+ } else {
+ color = colord(item.value).toRgb();
+ }
+ shadow.push(item.value);
+ }
+ }
+
+ return { name: name.join(" "), shadow: shadow.join(" "), color };
+ }, [layer]);
+};
+
+export const Layer = (
+ props: Pick<RenderCategoryProps, "createBatchUpdate"> & {
+ id: string;
+ index: number;
+ layer: TupleValue;
+ isHighlighted: boolean;
+ onLayerHide: (index: number) => void;
+ onDeleteLayer: (index: number) => void;
+ onEditLayer: (index: number, layers: LayersValue) => void;
+ }
+) => {
+ const { index, id, layer, isHighlighted, onDeleteLayer, onLayerHide } = props;
+ const { name, shadow, color } = useLayer(layer);
+
+ return (
+ <FloatingPanel
+ title="Box Shadow"
+ content={
+ <BoxShadowContent
+ index={index}
+ value={shadow}
+ onEditLayer={props.onEditLayer}
+ createBatchUpdate={props.createBatchUpdate}
+ />
+ }
+ >
+ <CssValueListItem
+ id={id}
+ active={isHighlighted}
+ index={index}
+ label={<Label truncate>{name}</Label>}
+ hidden={layer?.hidden}
+ thumbnail={<ColorThumb color={color} />}
+ buttons={
+ <>
+ <SmallToggleButton
+ variant="normal"
+ pressed={layer?.hidden}
+ disabled={false}
+ tabIndex={-1}
+ onPressedChange={() => onLayerHide(index)}
+ icon={layer?.hidden ? <EyeconClosedIcon /> : <EyeconOpenIcon />}
+ />
+ <SmallIconButton
+ variant="destructive"
+ tabIndex={-1}
+ icon={<SubtractIcon />}
+ onClick={(event) => {
+ onDeleteLayer(index);
+ event.preventDefault();
+ }}
+ />
+ </>
+ }
+ ></CssValueListItem>
+ </FloatingPanel>
+ );
+};
diff --git a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-layers.tsx b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-layers.tsx
new file mode 100644
index 0000000000..b914060b7a
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-layers.tsx
@@ -0,0 +1,83 @@
+import type { LayersValue } from "@webstudio-is/css-data";
+import {
+ CssValueListArrowFocus,
+ Flex,
+ useSortable,
+} from "@webstudio-is/design-system";
+import type { RenderCategoryProps } from "../../style-sections";
+import { Layer } from "./box-shadow-layer";
+import {
+ deleteLayer,
+ getLayerCount,
+ hideLayer,
+ swapLayers,
+ updateBoxShadowLayer,
+} from "./box-shadow-utils";
+import { useMemo } from "react";
+
+type BoxShadowLayerProperies = RenderCategoryProps & {
+ layers: LayersValue;
+};
+
+export const BoxShadowLayers = ({
+ layers,
+ currentStyle,
+ createBatchUpdate,
+}: BoxShadowLayerProperies) => {
+ const layersCount = getLayerCount(currentStyle);
+
+ const sortableItems = useMemo(
+ () =>
+ Array.from(Array(layersCount), (_, index) => ({
+ id: String(index),
+ index,
+ })),
+ [layersCount]
+ );
+
+ const { dragItemId, placementIndicator, sortableRefCallback } = useSortable({
+ items: sortableItems,
+ onSort: (newIndex, oldIndex) => {
+ swapLayers(newIndex, oldIndex, currentStyle, createBatchUpdate);
+ },
+ });
+
+ const handleDeleteLayer = (index: number) => {
+ return deleteLayer(index, layers, createBatchUpdate);
+ };
+
+ const handleHideLayer = (index: number) => {
+ return hideLayer(index, layers, createBatchUpdate);
+ };
+
+ const onEditLayer = (index: number, newLayers: LayersValue) => {
+ return updateBoxShadowLayer(newLayers, layers, index, createBatchUpdate);
+ };
+
+ return (
+ <CssValueListArrowFocus dragItemId={dragItemId}>
+ <Flex direction="column" gap={2} ref={sortableRefCallback}>
+ {layers.value.map((layer, index) => {
+ if (layer.type !== "tuple") {
+ return null;
+ }
+ const id = String(index);
+ return (
+ <Layer
+ key={index}
+ id={id}
+ index={index}
+ layer={layer}
+ isHighlighted={dragItemId === id}
+ onLayerHide={handleHideLayer}
+ onDeleteLayer={handleDeleteLayer}
+ createBatchUpdate={createBatchUpdate}
+ onEditLayer={onEditLayer}
+ />
+ );
+ })}
+ {placementIndicator}
+ </Flex>
+ </CssValueListArrowFocus>
+ );
+};
diff --git a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-utils.test.ts b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-utils.test.ts
new file mode 100644
index 0000000000..64b27668da
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-utils.test.ts
@@ -0,0 +1,346 @@
+import { afterEach, describe, expect, test } from "@jest/globals";
+import type {
+ LayersValue,
+ StyleProperty,
+ StyleValue,
+ TupleValue,
+} from "@webstudio-is/css-data";
+import type { CreateBatchUpdate } from "../../shared/use-style-data";
+import {
+ addBoxShadow,
+ deleteLayer,
+ hideLayer,
+ swapLayers,
+ updateBoxShadowLayer,
+} from "./box-shadow-utils";
+import type { StyleInfo } from "../../shared/style-info";
+
+let styleInfo: StyleInfo = {};
+let published = false;
+const deletedProperties = new Set<string>();
+
+afterEach(() => {
+ styleInfo = {};
+ published = false;
+ deletedProperties.clear();
+});
+
+const createBatchUpdate: CreateBatchUpdate = () => ({
+ setProperty: (propertyName: StyleProperty) => (newValue: StyleValue) => {
+ styleInfo[propertyName] = { value: newValue, local: newValue };
+ },
+ deleteProperty: (propertyName: string) => {
+ deletedProperties.add(propertyName);
+ },
+ publish: (options?: unknown) => {
+ published = true;
+ },
+});
+
+describe("boxShadowUtils", () => {
+ test("delets a layer using the index", () => {
+ const layers: LayersValue = {
+ 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: "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",
+ },
+ ],
+ },
+ ],
+ };
+
+ deleteLayer(1, layers, createBatchUpdate);
+ const boxShadowValue = styleInfo["boxShadow"]?.value as LayersValue;
+
+ expect(published).toBe(true);
+ expect(boxShadowValue).toBeDefined();
+ expect(deletedProperties.has("boxShadow")).toBe(false);
+ expect(boxShadowValue.value[0].value).toMatchInlineSnapshot(`
+ [
+ {
+ "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",
+ },
+ ]
+ `);
+ });
+
+ test("delets the property when there is only one layer in it", () => {
+ const layers: LayersValue = {
+ type: "layers",
+ value: [
+ {
+ type: "tuple",
+ value: [
+ {
+ type: "unit",
+ unit: "px",
+ value: 60,
+ },
+ {
+ type: "unit",
+ unit: "px",
+ value: -16,
+ },
+ {
+ type: "keyword",
+ value: "teal",
+ },
+ ],
+ },
+ ],
+ };
+
+ deleteLayer(0, layers, createBatchUpdate);
+ expect(published).toBe(true);
+ expect(deletedProperties.has("boxShadow")).toBe(true);
+ });
+
+ test("hides the layer using index", () => {
+ const layers: LayersValue = {
+ type: "layers",
+ value: [
+ {
+ type: "tuple",
+ value: [
+ {
+ type: "unit",
+ unit: "px",
+ value: 60,
+ },
+ {
+ type: "unit",
+ unit: "px",
+ value: -16,
+ },
+ {
+ type: "keyword",
+ value: "teal",
+ },
+ ],
+ },
+ ],
+ };
+
+ hideLayer(0, layers, createBatchUpdate);
+ const boxShadowValue = styleInfo["boxShadow"]?.value as LayersValue;
+
+ expect(published).toBe(true);
+ expect(boxShadowValue).toBeDefined();
+ expect(deletedProperties.has("boxShadow")).toBe(false);
+ expect((boxShadowValue.value[0] as TupleValue).hidden).toBe(true);
+ });
+
+ test("adds layer to box-shadow proeprty", () => {
+ addBoxShadow(
+ `box-shadow: 10px 10px 10px 0px rgba(0, 0, 0, 0.75)`,
+ styleInfo,
+ createBatchUpdate
+ );
+
+ const boxShadow = styleInfo["boxShadow"]?.value as LayersValue;
+
+ expect(boxShadow).toBeDefined();
+ expect(published).toBe(true);
+ expect(boxShadow.value).toHaveLength(1);
+ expect(boxShadow.value).toMatchInlineSnapshot(`
+ [
+ {
+ "type": "tuple",
+ "value": [
+ {
+ "type": "unit",
+ "unit": "px",
+ "value": 10,
+ },
+ {
+ "type": "unit",
+ "unit": "px",
+ "value": 10,
+ },
+ {
+ "type": "unit",
+ "unit": "px",
+ "value": 10,
+ },
+ {
+ "type": "unit",
+ "unit": "px",
+ "value": 0,
+ },
+ {
+ "alpha": 0.75,
+ "b": 0,
+ "g": 0,
+ "r": 0,
+ "type": "rgb",
+ },
+ ],
+ },
+ ]
+ `);
+ });
+
+ test("updates the layer with new value using the index", () => {
+ const newLayer: LayersValue = {
+ type: "layers",
+ value: [
+ {
+ type: "tuple",
+ value: [
+ {
+ type: "unit",
+ unit: "px",
+ value: 50,
+ },
+ {
+ type: "unit",
+ unit: "px",
+ value: 50,
+ },
+ {
+ type: "keyword",
+ value: "green",
+ },
+ ],
+ },
+ ],
+ };
+
+ const oldLayers: LayersValue = {
+ type: "layers",
+ value: [
+ {
+ type: "tuple",
+ value: [
+ {
+ type: "unit",
+ unit: "px",
+ value: 60,
+ },
+ {
+ type: "unit",
+ unit: "px",
+ value: -16,
+ },
+ {
+ type: "keyword",
+ value: "teal",
+ },
+ ],
+ },
+ ],
+ };
+
+ updateBoxShadowLayer(newLayer, oldLayers, 0, createBatchUpdate);
+ const boxShadow = styleInfo["boxShadow"]?.value as LayersValue;
+ expect(boxShadow).toBeDefined();
+ expect(boxShadow.value[0]).toBe(newLayer.value[0]);
+ });
+
+ test("swaps the layers using indexe's", () => {
+ addBoxShadow(
+ `box-shadow: 0 60px 80px rgba(0,0,0,0.60), 0 45px 26px rgba(0,0,0,0.14);`,
+ styleInfo,
+ createBatchUpdate
+ );
+
+ swapLayers(0, 1, styleInfo, createBatchUpdate);
+ const boxShadow = styleInfo["boxShadow"]?.value as LayersValue;
+
+ expect(boxShadow.value[0].value).toMatchInlineSnapshot(`
+ [
+ {
+ "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",
+ },
+ ]
+ `);
+ });
+});
diff --git a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-utils.ts b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-utils.ts
new file mode 100644
index 0000000000..443435be42
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadow-utils.ts
@@ -0,0 +1,140 @@
+import { parseBoxShadow, type LayersValue } from "@webstudio-is/css-data";
+import type { RenderCategoryProps } from "../../style-sections";
+import type { StyleInfo } from "../../shared/style-info";
+import type { CreateBatchUpdate } from "../../shared/use-style-data";
+
+export const property = "boxShadow";
+
+export const deleteLayer = (
+ index: number,
+ layers: LayersValue,
+ createBatchUpdate: RenderCategoryProps["createBatchUpdate"]
+) => {
+ const batch = createBatchUpdate();
+ const layer = layers.value[index];
+
+ if (layer.type !== "tuple" && layer.type !== "unparsed") {
+ return;
+ }
+ const newLayers = [...layers.value];
+ newLayers.splice(index, 1);
+
+ if (newLayers.length === 0) {
+ batch.deleteProperty(property);
+ } else {
+ batch.setProperty(property)({
+ type: "layers",
+ value: newLayers,
+ });
+ }
+
+ batch.publish();
+};
+
+export const hideLayer = (
+ index: number,
+ layers: LayersValue,
+ createBatchUpdate: RenderCategoryProps["createBatchUpdate"]
+) => {
+ const batch = createBatchUpdate();
+ const layer = layers.value[index];
+
+ if (layer.type !== "tuple" && layer.type !== "unparsed") {
+ return;
+ }
+ const newLayers = [...layers.value];
+ newLayers.splice(index, 1, {
+ ...layer,
+ hidden: layer.hidden !== true,
+ });
+ batch.setProperty(property)({
+ type: "layers",
+ value: newLayers,
+ });
+
+ batch.publish();
+};
+
+export const addBoxShadow = (
+ shadow: string,
+ style: StyleInfo,
+ createBatchUpdate: RenderCategoryProps["createBatchUpdate"]
+) => {
+ const parsedLayers = parseBoxShadow(shadow);
+ // Will never be invalid, just a TS guard.
+ if (parsedLayers.type === "invalid") {
+ return;
+ }
+
+ const layers = style[property]?.value;
+
+ // Initially its none, so we can just set it.
+ if (layers?.type === "layers") {
+ // Adding layers we had before
+ parsedLayers.value = [...parsedLayers.value, ...layers.value];
+ }
+
+ const batch = createBatchUpdate();
+ batch.setProperty(property)(parsedLayers);
+ batch.publish();
+};
+
+export const updateBoxShadowLayer = (
+ newValue: LayersValue,
+ layers: LayersValue,
+ index: number,
+ createBatchUpdate: RenderCategoryProps["createBatchUpdate"]
+) => {
+ const batch = createBatchUpdate();
+ const layer = layers.value[index];
+
+ if (layer.type !== "tuple" && layer.type !== "unparsed") {
+ return;
+ }
+ const newLayers = [...layers.value];
+ newLayers.splice(index, 1, ...newValue.value);
+ batch.setProperty(property)({
+ type: "layers",
+ value: newLayers,
+ });
+
+ batch.publish();
+};
+
+export const getLayerCount = (style: StyleInfo) => {
+ const value = style[property]?.value;
+ const layers = value?.type === "layers" ? value : undefined;
+ return layers?.value.length ?? 0;
+};
+
+export const getValue = (style: StyleInfo) => {
+ const value = style[property]?.value;
+ return value?.type === "layers" && value.value.length > 0 ? value : undefined;
+};
+
+export const swapLayers = (
+ newIndex: number,
+ oldIndex: number,
+ style: StyleInfo,
+ createBatchUpdate: CreateBatchUpdate
+) => {
+ const batch = createBatchUpdate();
+ const value = getValue(style);
+
+ if (value === undefined) {
+ return;
+ }
+
+ const newValue = [...value.value];
+
+ newValue.splice(oldIndex, 1);
+
+ newValue.splice(newIndex, 0, value.value[oldIndex]);
+
+ batch.setProperty(property)({
+ ...value,
+ value: newValue,
+ });
+
+ batch.publish();
+};
diff --git a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.tsx b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.tsx
new file mode 100644
index 0000000000..267dcee1b1
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.tsx
@@ -0,0 +1,67 @@
+import {
+ SectionTitle,
+ SectionTitleButton,
+ SectionTitleLabel,
+} from "@webstudio-is/design-system";
+import { PlusIcon } from "@webstudio-is/icons";
+import { CollapsibleSectionBase } from "~/builder/shared/collapsible-section";
+import { useState } from "react";
+import { getDots } from "../../shared/collapsible-section";
+import { PropertyName } from "../../shared/property-name";
+import { getStyleSource } from "../../shared/style-info";
+import type { RenderCategoryProps } from "../../style-sections";
+import { BoxShadowLayers } from "./box-shadow-layers";
+import { addBoxShadow, property } from "./box-shadow-utils";
+
+const label = "Box Shadows";
+
+export const BoxShadowsSection = (props: RenderCategoryProps) => {
+ const { currentStyle, deleteProperty } = props;
+ const [isOpen, setIsOpen] = useState(true);
+ const layersStyleSource = getStyleSource(currentStyle[property]);
+ const value = currentStyle[property]?.value;
+
+ return (
+ <CollapsibleSectionBase
+ fullWidth
+ label={label}
+ isOpen={isOpen}
+ onOpenChange={setIsOpen}
+ trigger={
+ <SectionTitle
+ dots={getDots(currentStyle, [property])}
+ suffix={
+ <SectionTitleButton
+ prefix={<PlusIcon />}
+ onClick={() => {
+ addBoxShadow(
+ // Just using some default shadow by default
+ "0px 2px 5px 0px rgba(0, 0, 0, 0.2)",
+ currentStyle,
+ props.createBatchUpdate
+ );
+ setIsOpen(true);
+ }}
+ />
+ }
+ >
+ <PropertyName
+ title="Box Shadows"
+ style={currentStyle}
+ properties={[property]}
+ label={
+ <SectionTitleLabel color={layersStyleSource}>
+ {label}
+ </SectionTitleLabel>
+ }
+ onReset={() => deleteProperty(property)}
+ />
+ </SectionTitle>
+ }
+ >
+ {value?.type === "layers" && value.value.length > 0 && (
+ <BoxShadowLayers layers={value} {...props} />
+ )}
+ </CollapsibleSectionBase>
+ );
+};
diff --git a/apps/builder/app/builder/features/style-panel/sections/index.ts b/apps/builder/app/builder/features/style-panel/sections/index.ts
index 7f302a0580..8854f025ed 100644
--- a/apps/builder/app/builder/features/style-panel/sections/index.ts
+++ b/apps/builder/app/builder/features/style-panel/sections/index.ts
@@ -9,3 +9,4 @@ export * from "./backgrounds/backgrounds";
export * from "./borders/borders";
export * from "./outline/outline";
export * from "./effects/effects";
+export * from "./box-shadows/box-shadows";
diff --git a/apps/builder/app/builder/features/style-panel/shared/color-picker.tsx b/apps/builder/app/builder/features/style-panel/shared/color-picker.tsx
index 3ce1a77128..39714da58f 100644
--- a/apps/builder/app/builder/features/style-panel/shared/color-picker.tsx
+++ b/apps/builder/app/builder/features/style-panel/shared/color-picker.tsx
@@ -10,12 +10,10 @@ import type {
StyleValue,
} from "@webstudio-is/css-data";
import {
- Box,
Popover,
PopoverTrigger,
PopoverContent,
css,
- rawTheme,
} from "@webstudio-is/design-system";
import { toValue } from "@webstudio-is/css-engine";
import { theme } from "@webstudio-is/design-system";
@@ -24,6 +22,7 @@ import { CssValueInput } from "./css-value-input";
import type { IntermediateStyleValue } from "./css-value-input/css-value-input";
import { isCanvasPointerEventsEnabledStore } from "~/builder/shared/nano-states";
import { useStore } from "@nanostores/react";
+import { ColorThumb } from "./color-thumb";
// To support color names
extend([namesPlugin]);
@@ -89,37 +88,6 @@ const styleValueToRgbaColor = (value: CssColorPickerValueInput): RgbaColor => {
};
};
-const whiteColor = { r: 255, g: 255, b: 255, a: 1 };
-const borderColorSwatch = colord(rawTheme.colors.borderColorSwatch).toRgb();
-const transparent = colord("transparent").toRgb();
-
-const distance = (a: RgbaColor, b: RgbaColor) => {
- // Use Euclidian distance, if will not give good results use https://zschuessler.github.io/DeltaE/
- return Math.sqrt(
- Math.pow(a.r / 255 - b.r / 255, 2) +
- Math.pow(a.g / 255 - b.g / 255, 2) +
- Math.pow(a.b / 255 - b.b / 255, 2) +
- Math.pow(a.a - b.a, 2)
- );
-};
-
-const lerp = (a: number, b: number, t: number) => {
- return a * (1 - t) + b * t;
-};
-
-const lerpColor = (a: RgbaColor, b: RgbaColor, t: number) => {
- return {
- r: lerp(a.r, b.r, t),
- g: lerp(a.g, b.g, t),
- b: lerp(a.b, b.b, t),
- a: lerp(a.a, b.a, t),
- };
-};
-
-const clamp = (value: number, min: number, max: number) => {
- return Math.min(Math.max(value, min), max);
-};
-
// Dragging over canvas iframe with CORS policies will lead to loosing events and getting stuck in mousedown state.
const useFixDragOverCanvas = () => {
const isCanvasPointerEventsEnabled = useStore(
@@ -212,34 +180,6 @@ export const ColorPicker = ({
};
}
- const prefixColorRgba = styleValueToRgbaColor(prefixColor);
-
- // @todo transparent icon can be better
- const background =
- prefixColorRgba.a < 1
- ? // chessboard 5x5
- `repeating-conic-gradient(rgba(0,0,0,0.22) 0% 25%, transparent 0% 50%) 0% 33.33% / 40% 40%, ${toValue(
- prefixColor
- )}`
- : toValue(prefixColor);
-
- const distanceToStartDrawBorder = 0.15;
-
- // White color is invisible on white background, so we need to draw border
- // the more color is white the more border is visible
- const borderColor = colord(
- lerpColor(
- transparent,
- borderColorSwatch,
- clamp(
- (distanceToStartDrawBorder - distance(whiteColor, prefixColorRgba)) /
- distanceToStartDrawBorder,
- 0,
- 1
- )
- )
- ).toRgbString();
-
/**
* By default, the color can be transparent, but if the user chooses a color from the picker,
* we must set alpha = 1 otherwise all selected colors will be transparent.
@@ -267,18 +207,7 @@ export const ColorPicker = ({
aria-label="Open color picker"
onClick={() => setDisplayColorPicker((shown) => !shown)}
>
- <Box
- css={{
- margin: theme.spacing[3],
- width: theme.spacing[10],
- height: theme.spacing[10],
- backgroundBlendMode: "difference",
- borderRadius: 2,
- background,
- borderColor,
- borderStyle: "solid",
- }}
- />
+ <ColorThumb color={rgbValue} css={{ margin: theme.spacing[3] }} />
</PopoverTrigger>
<PopoverContent>
diff --git a/apps/builder/app/builder/features/style-panel/shared/color-thumb.tsx b/apps/builder/app/builder/features/style-panel/shared/color-thumb.tsx
new file mode 100644
index 0000000000..82843d4f16
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/shared/color-thumb.tsx
@@ -0,0 +1,87 @@
+import { rawTheme, Box, theme, css } from "@webstudio-is/design-system";
+import { colord, type RgbaColor } from "colord";
+import { forwardRef, type ElementRef, type ComponentProps } from "react";
+
+const whiteColor = { r: 255, g: 255, b: 255, a: 1 };
+const borderColorSwatch = colord(rawTheme.colors.borderColorSwatch).toRgb();
+const transparent = colord("transparent").toRgb();
+
+const distance = (a: RgbaColor, b: RgbaColor) => {
+ // Use Euclidian distance, if will not give good results use https://zschuessler.github.io/DeltaE/
+ return Math.sqrt(
+ Math.pow(a.r / 255 - b.r / 255, 2) +
+ Math.pow(a.g / 255 - b.g / 255, 2) +
+ Math.pow(a.b / 255 - b.b / 255, 2) +
+ Math.pow(a.a - b.a, 2)
+ );
+};
+
+const lerp = (a: number, b: number, t: number) => {
+ return a * (1 - t) + b * t;
+};
+
+const lerpColor = (a: RgbaColor, b: RgbaColor, t: number) => {
+ return {
+ r: lerp(a.r, b.r, t),
+ g: lerp(a.g, b.g, t),
+ b: lerp(a.b, b.b, t),
+ a: lerp(a.a, b.a, t),
+ };
+};
+
+const clamp = (value: number, min: number, max: number) => {
+ return Math.min(Math.max(value, min), max);
+};
+
+const style = css({
+ width: theme.spacing[10],
+ height: theme.spacing[10],
+ backgroundBlendMode: "difference",
+ borderRadius: 2,
+ borderStyle: "solid",
+});
+
+export const ColorThumb = forwardRef<
+ ElementRef<typeof Box>,
+ Omit<ComponentProps<typeof Box>, "color"> & { color: RgbaColor | undefined }
+>(({ color, css, ...rest }, ref) => {
+ const colorString = colord(color || transparent).toRgbString();
+ // @todo transparent icon can be better
+ const background =
+ color === null || (color && color.a < 1)
+ ? // chessboard 5x5
+ `repeating-conic-gradient(rgba(0,0,0,0.22) 0% 25%, transparent 0% 50%) 0% 33.33% / 40% 40%, ${colorString}`
+ : colorString;
+
+ const distanceToStartDrawBorder = 0.15;
+
+ // White color is invisible on white background, so we need to draw border
+ // the more color is white the more border is visible
+ const borderColor = colord(
+ lerpColor(
+ transparent,
+ borderColorSwatch,
+ clamp(
+ (distanceToStartDrawBorder -
+ distance(whiteColor, color || transparent)) /
+ distanceToStartDrawBorder,
+ 0,
+ 1
+ )
+ )
+ ).toRgbString();
+
+ return (
+ <Box
+ {...rest}
+ ref={ref}
+ css={{
+ background,
+ borderColor,
+ }}
+ className={style({ css })}
+ />
+ );
+});
+
+ColorThumb.displayName = "ColorThumb";
diff --git a/apps/builder/app/builder/features/style-panel/style-sections.tsx b/apps/builder/app/builder/features/style-panel/style-sections.tsx
index 9e98d7e930..2be98227f8 100644
--- a/apps/builder/app/builder/features/style-panel/style-sections.tsx
+++ b/apps/builder/app/builder/features/style-panel/style-sections.tsx
@@ -22,6 +22,7 @@ import {
BordersSection,
OutlineSection,
EffectsSection,
+ BoxShadowsSection,
} from "./sections";
export const categories = [
@@ -34,6 +35,7 @@ export const categories = [
"position",
"backgrounds",
"borders",
+ "boxShadows",
"outline",
"effects",
];
@@ -143,4 +145,5 @@ export const sections: {
borders: BordersSection,
outline: OutlineSection,
effects: EffectsSection,
+ boxShadows: BoxShadowsSection,
};
diff --git a/packages/css-data/src/property-parsers/background.ts b/packages/css-data/src/property-parsers/background.ts
index d21868b036..ec21dbf1a5 100644
--- a/packages/css-data/src/property-parsers/background.ts
+++ b/packages/css-data/src/property-parsers/background.ts
@@ -54,7 +54,6 @@ export const backgroundToLonghand = (
backgroundColor: string | undefined;
} => {
const layers: string[] = [];
-
let tokenStream = background.trim();
tokenStream = tokenStream.endsWith(";")
diff --git a/packages/css-data/src/property-parsers/box-shadow.test.ts b/packages/css-data/src/property-parsers/box-shadow.test.ts
new file mode 100644
index 0000000000..4dd55cdd79
--- /dev/null
+++ b/packages/css-data/src/property-parsers/box-shadow.test.ts
@@ -0,0 +1,294 @@
+import { describe, expect, test } from "@jest/globals";
+
+import { parseBoxShadow } from "./box-shadow";
+
+describe("parseBoxShadow", () => {
+ test("parses value and returns invalid when used a invalid color", () => {
+ expect(parseBoxShadow(`10px 10px 5px foo`)).toMatchInlineSnapshot(`
+ {
+ "type": "invalid",
+ "value": "10px 10px 5px foo",
+ }
+ `);
+ });
+
+ test("throws error when passed a value without a unit", () => {
+ expect(parseBoxShadow(`10 10px 5px red`)).toMatchInlineSnapshot(`
+ {
+ "type": "invalid",
+ "value": "10 10px 5px red",
+ }
+ `);
+ });
+
+ test("inset and color values can be interchanged", () => {
+ expect(parseBoxShadow(`inset 10px 10px 5px black;`)).toMatchInlineSnapshot(`
+ {
+ "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",
+ },
+ ],
+ },
+ ],
+ }
+ `);
+ });
+
+ test("parses value when inset is used but missing blur-radius", () => {
+ expect(parseBoxShadow(`box-shadow: inset 5em 1em gold`))
+ .toMatchInlineSnapshot(`
+ {
+ "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",
+ },
+ ],
+ },
+ ],
+ }
+ `);
+ });
+
+ test("parses value when offsetX and offsetY are used", () => {
+ expect(parseBoxShadow(`box-shadow: 60px -16px teal;`))
+ .toMatchInlineSnapshot(`
+ {
+ "type": "layers",
+ "value": [
+ {
+ "type": "tuple",
+ "value": [
+ {
+ "type": "unit",
+ "unit": "px",
+ "value": 60,
+ },
+ {
+ "type": "unit",
+ "unit": "px",
+ "value": -16,
+ },
+ {
+ "type": "keyword",
+ "value": "teal",
+ },
+ ],
+ },
+ ],
+ }
+ `);
+ });
+
+ test("parses value from figma", () => {
+ expect(
+ parseBoxShadow(
+ "box-shadow: 0 60px 80px rgba(0,0,0,0.60), 0 45px 26px rgba(0,0,0,0.14);"
+ )
+ ).toMatchInlineSnapshot(`
+ {
+ "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": "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",
+ },
+ ],
+ },
+ ],
+ }
+ `);
+ });
+
+ test(`parses multiple layers of box-shadow property`, () => {
+ expect(
+ parseBoxShadow(`box-shadow:
+ 0 0 5px rgba(0, 0, 0, 0.2),
+ inset 0 0 10px rgba(0, 0, 0, 0.3),
+ 0 0 15px rgba(0, 0, 0, 0.4);
+ `)
+ ).toMatchInlineSnapshot(`
+ {
+ "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": "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": "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",
+ },
+ ],
+ },
+ ],
+ }
+ `);
+ });
+});
diff --git a/packages/css-data/src/property-parsers/box-shadow.ts b/packages/css-data/src/property-parsers/box-shadow.ts
new file mode 100644
index 0000000000..2086d99698
--- /dev/null
+++ b/packages/css-data/src/property-parsers/box-shadow.ts
@@ -0,0 +1,134 @@
+import * as csstree from "css-tree";
+import { LayersValue, TupleValue } from "@webstudio-is/css-data";
+import type {
+ InvalidValue,
+ TupleValueItem,
+ Unit,
+} from "@webstudio-is/css-data";
+import { colord } from "colord";
+
+const cssTreeTryParseValue = (input: string) => {
+ try {
+ const ast = csstree.parse(input, { context: "value" });
+ return ast;
+ } catch {
+ return undefined;
+ }
+};
+
+export const parseBoxShadow = (
+ boxShadow: string
+): LayersValue | InvalidValue => {
+ let tokenStream = boxShadow.trim();
+ tokenStream = tokenStream.endsWith(";")
+ ? tokenStream.slice(0, -1)
+ : tokenStream;
+
+ const cleanupKeywords = ["box-shadow:"];
+
+ for (const cleanupKeyword of cleanupKeywords) {
+ tokenStream = tokenStream.startsWith(cleanupKeyword)
+ ? tokenStream.slice(cleanupKeyword.length).trim()
+ : tokenStream;
+ }
+
+ const cssAst = cssTreeTryParseValue(tokenStream);
+
+ if (cssAst === undefined) {
+ return {
+ type: "invalid",
+ value: boxShadow,
+ };
+ }
+
+ const parsed = csstree.lexer.matchProperty("box-shadow", cssAst);
+ if (parsed.error) {
+ return {
+ type: "invalid",
+ value: boxShadow,
+ };
+ }
+
+ const layers: TupleValue[] = [];
+
+ csstree.walk(cssAst, (node) => {
+ if (node.type === "Value") {
+ const children = node.children;
+ let layer: csstree.CssNode[] = [];
+
+ for (const child of children) {
+ if (children.last === child) {
+ layer.push(child);
+ }
+
+ if (child.type === "Operator" || children.last === child) {
+ const shadow: TupleValueItem[] = [];
+
+ /**
+ * https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow#syntax
+ * `inset` and color can be at the start or end and their sequence can be anywhere.
+ * The rest need to foolow the sequence all the time
+ */
+
+ for (let index = 0; index < layer.length; index++) {
+ const item = layer[index];
+
+ if (item.type === "Identifier") {
+ shadow.push({
+ type: "keyword",
+ value: item.name,
+ });
+ }
+
+ if (item.type === "Function" || item.type === "Hash") {
+ const colorValue = colord(csstree.generate(item));
+ if (!colorValue.isValid()) {
+ return;
+ }
+ const rgb = colorValue.toRgb();
+ shadow.push({
+ type: "rgb",
+ alpha: rgb.a,
+ r: rgb.r,
+ g: rgb.g,
+ b: rgb.b,
+ });
+ }
+
+ if (item.type === "Dimension") {
+ shadow.push({
+ type: "unit",
+ value: Number(item.value),
+ unit: item.unit as Unit,
+ });
+ }
+
+ if (item.type === "Number") {
+ shadow.push({
+ type: "unit",
+ value: Number(item.value),
+ unit: "number",
+ });
+ }
+ }
+
+ layers.push({
+ type: "tuple",
+ value: shadow,
+ });
+ layer = [];
+ continue;
+ }
+
+ layer.push(child);
+ }
+ }
+ });
+
+ return layers.length > 0
+ ? {
+ type: "layers",
+ value: layers,
+ }
+ : { type: "invalid", value: boxShadow };
+};
diff --git a/packages/css-data/src/property-parsers/index.ts b/packages/css-data/src/property-parsers/index.ts
index f9c0d37739..795a8f57c2 100644
--- a/packages/css-data/src/property-parsers/index.ts
+++ b/packages/css-data/src/property-parsers/index.ts
@@ -1 +1,2 @@
export * from "./background";
+export * from "./box-shadow";
diff --git a/packages/css-data/src/property-parsers/parsers.ts b/packages/css-data/src/property-parsers/parsers.ts
index 6b947c4ec2..a6ffdf0fee 100644
--- a/packages/css-data/src/property-parsers/parsers.ts
+++ b/packages/css-data/src/property-parsers/parsers.ts
@@ -2,3 +2,4 @@
Longhand properties parsers. Each named export should match a property name.
*/
export { parseBackgroundImage as backgroundImage } from "./background";
+export { parseBoxShadow as boxShadow } from "./box-shadow";
diff --git a/packages/css-data/src/schema.ts b/packages/css-data/src/schema.ts
index b89b404a6e..b61773f8c5 100644
--- a/packages/css-data/src/schema.ts
+++ b/packages/css-data/src/schema.ts
@@ -99,31 +99,38 @@ const UnsetValue = z.object({
});
export type UnsetValue = z.infer<typeof UnsetValue>;
-export const TupleValueItem = z.union([UnitValue, KeywordValue, UnparsedValue]);
+export const TupleValueItem = z.union([
+ UnitValue,
+ KeywordValue,
+ UnparsedValue,
+ RgbValue,
+]);
export type TupleValueItem = z.infer<typeof TupleValueItem>;
export const TupleValue = z.object({
type: z.literal("tuple"),
value: z.array(TupleValueItem),
+ hidden: z.boolean().optional(),
});
export type TupleValue = z.infer<typeof TupleValue>;
+const LayerValueItem = z.union([
+ UnitValue,
+ KeywordValue,
+ UnparsedValue,
+ ImageValue,
+ TupleValue,
+ InvalidValue,
+]);
+
+export type LayerValueItem = z.infer<typeof LayerValueItem>;
// To support background layers https://developer.mozilla.org/en-US/docs/Web/CSS/background
// and similar comma separated css properties
// InvalidValue used in case of asset not found
export const LayersValue = z.object({
type: z.literal("layers"),
- value: z.array(
- z.union([
- UnitValue,
- KeywordValue,
- UnparsedValue,
- ImageValue,
- TupleValue,
- InvalidValue,
- ])
- ),
+ value: z.array(LayerValueItem),
});
export type LayersValue = z.infer<typeof LayersValue>;
diff --git a/packages/css-data/tsconfig.dts.json b/packages/css-data/tsconfig.dts.json
index e84928fb3a..e54663ff02 100644
--- a/packages/css-data/tsconfig.dts.json
+++ b/packages/css-data/tsconfig.dts.json
@@ -2,6 +2,7 @@
"extends": "./tsconfig.json",
"include": ["src"],
"compilerOptions": {
+ "rootDir": "src",
"declarationDir": "lib/types"
}
}
diff --git a/packages/css-engine/src/core/to-value.ts b/packages/css-engine/src/core/to-value.ts
index 7af0afa333..e13933175a 100644
--- a/packages/css-engine/src/core/to-value.ts
+++ b/packages/css-engine/src/core/to-value.ts
@@ -91,9 +91,17 @@ export const toValue = (
}
if (value.type === "layers") {
- return value.value
- .map((value) => toValue(value, transformValue))
+ const valueString = value.value
+ .filter(
+ (layer) =>
+ "hidden" in layer === false ||
+ ("hidden" in layer && layer.hidden === false)
+ )
+ .map((layer) => {
+ return toValue(layer, transformValue);
+ })
.join(", ");
+ return valueString === "" ? "none" : valueString;
}
if (value.type === "tuple") {
diff --git a/packages/design-system/src/components/css-value-list-item.stories.tsx b/packages/design-system/src/components/css-value-list-item.stories.tsx
index 7c0b75efac..abedacdc59 100644
--- a/packages/design-system/src/components/css-value-list-item.stories.tsx
+++ b/packages/design-system/src/components/css-value-list-item.stories.tsx
@@ -1,5 +1,8 @@
import { css, styled, theme } from "../stitches.config";
-import { CssValueListItem } from "./css-value-list-item";
+import {
+ CssValueListArrowFocus,
+ CssValueListItem,
+} from "./css-value-list-item";
import { Label, labelColors } from "./label";
import { SmallToggleButton } from "./small-toggle-button";
import {
@@ -15,9 +18,6 @@ import {
FloatingPanelPopoverTrigger,
} from "./floating-panel-popover";
import { StorySection, StoryGrid } from "./storybook";
-import { ArrowFocus } from "./primitives/arrow-focus";
-import { Box } from "./box";
-import type { ReactNode } from "react";
export default {
component: CssValueListItem,
@@ -54,7 +54,7 @@ const ListItem = (props: {
active: boolean;
focused: undefined | boolean;
label?: React.ReactNode;
- tabIndex?: -1 | 0;
+ index: number;
}) => {
const [pressed, onPressedChange] = React.useState(false);
@@ -70,7 +70,8 @@ const ListItem = (props: {
state={props.state}
focused={props.focused}
active={props.active}
- tabIndex={props.tabIndex ?? 0}
+ index={props.index}
+ id={String(props.index)}
buttons={
<>
<SmallToggleButton
@@ -93,28 +94,6 @@ const ListItem = (props: {
);
};
-const ListItemsFocusWrap = (props: { children: ReactNode }) => {
- return (
- <ArrowFocus
- render={({ handleKeyDown }) => (
- <Box
- css={{ display: "contents" }}
- onKeyDown={(event) => {
- if (event.key === "ArrowUp" || event.key === "ArrowDown") {
- handleKeyDown(event, {
- accept: (element) => {
- return element.getAttribute(LIST_ITEM_ATTRIBUTE) === "true";
- },
- });
- }
- }}
- >
- {props.children}
- </Box>
- )}
- />
- );
-};
export const Declarative = (props: {
hidden: boolean;
focused: boolean;
@@ -128,6 +107,8 @@ export const Declarative = (props: {
<FloatingPanelPopover>
<FloatingPanelPopoverTrigger asChild>
<CssValueListItem
+ id="0"
+ index={0}
label={
<Label disabled={props.hidden} color={props.labelColor}>
Image
@@ -163,11 +144,11 @@ export const Declarative = (props: {
<StorySection title="Overflows">
<StoryGrid>
- <ListItemsFocusWrap>
+ <>
{labelColors.map((labelColor, index) => (
<ListItem
key={labelColor}
- tabIndex={index === 0 ? 0 : -1}
+ index={index}
hidden={false}
active={false}
labelColor={labelColor}
@@ -176,17 +157,17 @@ export const Declarative = (props: {
label="Very long text, very long text"
/>
))}
- </ListItemsFocusWrap>
+ </>
</StoryGrid>
</StorySection>
<StorySection title="Variants">
<StoryGrid>
- <ListItemsFocusWrap>
+ <CssValueListArrowFocus>
{labelColors.map((labelColor, index) => (
<ListItem
key={labelColor}
- tabIndex={index === 0 ? 0 : -1}
+ index={index}
hidden={false}
active={false}
labelColor={labelColor}
@@ -198,7 +179,7 @@ export const Declarative = (props: {
{labelColors.map((labelColor) => (
<ListItem
key={labelColor}
- tabIndex={-1}
+ index={-1}
hidden={true}
active={false}
labelColor={labelColor}
@@ -207,10 +188,10 @@ export const Declarative = (props: {
/>
))}
- {labelColors.map((labelColor) => (
+ {labelColors.map((labelColor, index) => (
<ListItem
key={labelColor}
- tabIndex={-1}
+ index={index}
hidden={false}
active={false}
labelColor={labelColor}
@@ -218,17 +199,17 @@ export const Declarative = (props: {
focused={false}
/>
))}
- </ListItemsFocusWrap>
+ </CssValueListArrowFocus>
</StoryGrid>
</StorySection>
<StorySection title="Active">
<StoryGrid>
- <ListItemsFocusWrap>
+ <CssValueListArrowFocus>
{labelColors.map((labelColor, index) => (
<ListItem
key={labelColor}
- tabIndex={index === 0 ? 0 : -1}
+ index={index}
hidden={false}
active={true}
labelColor={labelColor}
@@ -237,10 +218,10 @@ export const Declarative = (props: {
/>
))}
- {labelColors.map((labelColor) => (
+ {labelColors.map((labelColor, index) => (
<ListItem
key={labelColor}
- tabIndex={-1}
+ index={index}
hidden={true}
active={true}
labelColor={labelColor}
@@ -249,10 +230,10 @@ export const Declarative = (props: {
/>
))}
- {labelColors.map((labelColor) => (
+ {labelColors.map((labelColor, index) => (
<ListItem
key={labelColor}
- tabIndex={-1}
+ index={index}
hidden={false}
active={true}
labelColor={labelColor}
@@ -260,7 +241,7 @@ export const Declarative = (props: {
focused={false}
/>
))}
- </ListItemsFocusWrap>
+ </CssValueListArrowFocus>
</StoryGrid>
</StorySection>
</Panel>
diff --git a/packages/design-system/src/components/css-value-list-item.tsx b/packages/design-system/src/components/css-value-list-item.tsx
index f03f7e64fb..5a7b32c473 100644
--- a/packages/design-system/src/components/css-value-list-item.tsx
+++ b/packages/design-system/src/components/css-value-list-item.tsx
@@ -4,13 +4,18 @@ import {
forwardRef,
Children,
useMemo,
+ type ReactNode,
} from "react";
import { styled } from "../stitches.config";
import { Flex } from "./flex";
+import { Box } from "./box";
import { theme } from "../stitches.config";
import { DragHandleIcon } from "@webstudio-is/icons";
import { ArrowFocus } from "./primitives/arrow-focus";
+const LIST_ITEM_ATTRIBUTE = "data-list-item";
+const listItemAttributes = { [LIST_ITEM_ATTRIBUTE]: true };
+
const DragHandleIconStyled = styled(DragHandleIcon, {
visibility: "hidden",
cursor: "grab",
@@ -29,6 +34,19 @@ const ThumbHolder = styled("div", {
*/
const sharedPaddingRight = theme.spacing[9];
+const IconButtonsWrapper = styled(Flex, {
+ position: "absolute",
+ right: 0,
+ top: 0,
+ bottom: 0,
+ paddingRight: sharedPaddingRight,
+ visibility: "hidden",
+});
+
+const FakeIconButtonsWrapper = styled(Flex, {
+ paddingLeft: theme.spacing[5],
+});
+
/**
* Should be a button as otherwise radix trigger doesn't work with keyboard interactions
*/
@@ -62,16 +80,10 @@ const ItemButton = styled("button", {
outline: "none",
backgroundColor: theme.colors.backgroundHover,
},
- "&:hover, &[data-active=true]": {
- backgroundColor: theme.colors.backgroundHover,
-
- [`& ${DragHandleIconStyled}`]: {
- visibility: "visible",
- },
- },
variants: {
hidden: {
true: {
+ opacity: 0.2,
[`& ${ThumbHolder}`]: {
opacity: 0.2,
},
@@ -81,9 +93,11 @@ const ItemButton = styled("button", {
});
type Props = ComponentProps<typeof ItemButton> & {
+ id: string;
+ index: number;
hidden?: boolean;
label: React.ReactElement;
- thumbnail: React.ReactElement;
+ thumbnail?: React.ReactElement;
buttons?: React.ReactElement;
// to support Radix trigger asChild
"data-state"?: "open";
@@ -96,14 +110,19 @@ type Props = ComponentProps<typeof ItemButton> & {
const ItemWrapper = styled("div", {
position: "relative",
width: "100%",
-});
-
-const IconButtonsWrapper = styled(Flex, {
- position: "absolute",
- right: 0,
- top: 0,
- bottom: 0,
- paddingRight: sharedPaddingRight,
+ "&:hover, &[data-active=true]": {
+ [`& ${ItemButton}`]: {
+ backgroundColor: theme.colors.backgroundHover,
+ },
+ [`& ${DragHandleIconStyled}`]: {
+ visibility: "visible",
+ },
+ },
+ "&:hover, &[data-active=true], &:focus-within": {
+ [`& ${IconButtonsWrapper}`]: {
+ visibility: "visible",
+ },
+ },
});
const FakeSmallButton = styled("div", {
@@ -120,6 +139,9 @@ export const CssValueListItem = forwardRef(
focused,
state,
active,
+ index,
+ id,
+ hidden,
"data-state": dataState,
...rest
}: Props,
@@ -146,18 +168,24 @@ export const CssValueListItem = forwardRef(
handleKeyDown(event);
}
}}
+ data-active={active}
>
<ItemButton
ref={ref}
+ data-id={id}
data-focused={focused}
data-state={state ?? dataState}
data-active={active}
+ tabIndex={index === 0 ? 0 : -1}
+ {...listItemAttributes}
{...rest}
+ hidden={hidden}
+ disabled={hidden === true}
>
<DragHandleIconStyled />
<Flex gap={2} shrink>
- <ThumbHolder>{thumbnail}</ThumbHolder>
+ {thumbnail ? <ThumbHolder>{thumbnail}</ThumbHolder> : null}
{label}
</Flex>
@@ -168,13 +196,9 @@ export const CssValueListItem = forwardRef(
Warning: validateDOMNesting(...): <button> cannot appear as a descendant of <button>
Real buttons will be placed on top of fake buttons
*/}
- <Flex
- shrink={false}
- css={{ paddingLeft: theme.spacing[5] }}
- gap={2}
- >
+ <FakeIconButtonsWrapper shrink={false} gap={2}>
{fakeButtons}
- </Flex>
+ </FakeIconButtonsWrapper>
</ItemButton>
{/*
@@ -191,3 +215,36 @@ export const CssValueListItem = forwardRef(
);
CssValueListItem.displayName = "CssValueListItem";
+
+export const CssValueListArrowFocus = ({
+ children,
+ dragItemId,
+}: {
+ children: ReactNode;
+ dragItemId?: string;
+}) => {
+ return (
+ <ArrowFocus
+ render={({ handleKeyDown }) => (
+ <Box
+ css={{
+ display: "contents",
+ pointerEvents: dragItemId ? "none" : "auto",
+ // to make DnD work we have to disable scrolling using touch
+ touchAction: "none",
+ }}
+ onKeyDown={(event) => {
+ if (event.key === "ArrowUp" || event.key === "ArrowDown") {
+ handleKeyDown(event, {
+ accept: (element) =>
+ element.getAttribute(LIST_ITEM_ATTRIBUTE) === "true",
+ });
+ }
+ }}
+ >
+ {children}
+ </Box>
+ )}
+ />
+ );
+};
diff --git a/packages/design-system/src/components/primitives/dnd/index.ts b/packages/design-system/src/components/primitives/dnd/index.ts
index f922a6e1a1..3b940e267f 100644
--- a/packages/design-system/src/components/primitives/dnd/index.ts
+++ b/packages/design-system/src/components/primitives/dnd/index.ts
@@ -7,4 +7,5 @@ export {
} from "./placement-indicator";
export { useHold } from "./use-hold";
export { useDragCursor } from "./use-drag-cursor";
+export { useSortable } from "./use-sortable";
export { type Rect, type Point, type Placement } from "./geometry-utils";
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/use-sortable.tsx b/packages/design-system/src/components/primitives/dnd/use-sortable.tsx
similarity index 93%
rename from apps/builder/app/builder/features/style-panel/sections/backgrounds/use-sortable.tsx
rename to packages/design-system/src/components/primitives/dnd/use-sortable.tsx
index b98a0d588c..3f3f5237ca 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/use-sortable.tsx
+++ b/packages/design-system/src/components/primitives/dnd/use-sortable.tsx
@@ -1,14 +1,13 @@
import { useState, useRef } from "react";
import { createPortal } from "react-dom";
+import { useDrop, type DropTarget } from "./use-drop";
+import { useDrag } from "./use-drag";
+import type { Placement } from "./geometry-utils";
+import { useDragCursor } from "./use-drag-cursor";
import {
- type Placement,
PlacementIndicator,
computeIndicatorPlacement,
- useDrag,
- useDragCursor,
- useDrop,
- type DropTarget,
-} from "@webstudio-is/design-system";
+} from "./placement-indicator";
type UseSortable<Item> = {
items: Array<Item>;