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.

Drag drop background layers (#1238)

Ivan Starkovd50123128dae
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.test.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.test.ts
index e989e81df3..f10d59d18b 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.test.ts
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.test.ts
@@ -2,6 +2,7 @@ import {
layeredBackgroundProps,
setLayerProperty,
addLayer,
+ swapLayers,
} from "./background-layers";
import { describe, test, expect } from "@jest/globals";
@@ -185,3 +186,79 @@ describe("setLayerProperty", () => {
).toEqual(layeredBackgroundProps.map(() => 3));
});
});
+
+describe("swapLayers", () => {
+ test("should work with cascade", () => {
+ const cascaded: NonNullable<StyleInfo["backgroundImage"]>["cascaded"] = {
+ breakpointId: "mobile",
+ value: {
+ type: "layers",
+ value: [
+ {
+ type: "unparsed",
+ value: "linear-gradient(red, blue)",
+ },
+ {
+ type: "unparsed",
+ value: "linear-gradient(yellow, red)",
+ },
+ ],
+ },
+ };
+ const styleInfo: StyleInfo = {
+ backgroundImage: {
+ cascaded,
+ value: cascaded.value,
+ },
+ };
+
+ let published = false;
+
+ const createBatchUpdate: CreateBatchUpdate = () => ({
+ setProperty:
+ (propertyName: StyleProperty) => (newValue: string | StyleValue) => {
+ if (typeof newValue === "string") {
+ throw new Error("string is deprecated");
+ }
+
+ if (newValue.type !== "layers") {
+ throw new Error("newValue.type !== layers");
+ }
+
+ styleInfo[propertyName] = { value: newValue, local: newValue };
+ },
+ deleteProperty: (propertyName: string) => {
+ // not used
+ },
+ publish: (options?: unknown) => {
+ published = true;
+ },
+ });
+
+ swapLayers(0, 1, styleInfo, createBatchUpdate);
+
+ expect(published).toBe(true);
+
+ expect(styleInfo.backgroundImage?.value).toEqual({
+ type: "layers",
+ value: [
+ { type: "unparsed", value: "linear-gradient(yellow, red)" },
+ { type: "unparsed", value: "linear-gradient(red, blue)" },
+ ],
+ });
+
+ expect(styleInfo.backgroundImage?.value).toEqual(
+ styleInfo.backgroundImage?.local
+ );
+
+ swapLayers(0, 1, styleInfo, createBatchUpdate);
+
+ expect(styleInfo.backgroundImage?.value).toEqual({
+ type: "layers",
+ value: [
+ { type: "unparsed", value: "linear-gradient(red, blue)" },
+ { type: "unparsed", value: "linear-gradient(yellow, red)" },
+ ],
+ });
+ });
+});
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.ts
index 3dfed74b72..59007a1af6 100644
--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.ts
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.ts
@@ -139,6 +139,18 @@ export const deleteLayerProperty =
export type SetBackgroundProperty = ReturnType<typeof setLayerProperty>;
+const getLayersValue = (styleValue?: StyleValueInfo) => {
+ const clonedStyleValue: StyleValueInfo | undefined =
+ structuredClone(styleValue);
+ if (clonedStyleValue?.local?.type === "layers") {
+ return clonedStyleValue.local;
+ }
+ if (clonedStyleValue?.cascaded?.value.type === "layers") {
+ return clonedStyleValue?.cascaded?.value;
+ }
+ return { type: "layers" as const, value: [] };
+};
+
export const setLayerProperty =
(layerNum: number, style: StyleInfo, createBatchUpdate: CreateBatchUpdate) =>
(propertyName: LayeredBackgroundProperty) =>
@@ -146,18 +158,6 @@ export const setLayerProperty =
const batch = createBatchUpdate();
const layerCount = Math.max(getLayerCount(style), layerNum + 1);
- const getLayersValue = (styleValue?: StyleValueInfo) => {
- const clonedStyleValue: StyleValueInfo | undefined =
- structuredClone(styleValue);
- if (clonedStyleValue?.local?.type === "layers") {
- return clonedStyleValue.local;
- }
- if (clonedStyleValue?.cascaded?.value.type === "layers") {
- return clonedStyleValue?.cascaded?.value;
- }
- return { type: "layers" as const, value: [] };
- };
-
for (const property of layeredBackgroundProps) {
const styleValue = style[property];
@@ -218,30 +218,24 @@ export const deleteLayer =
for (const property of layeredBackgroundProps) {
const styleValue = style[property];
- const propertyStyle = styleValue?.local;
-
// If property is not defined, try copy from cascade or set empty
- let newPropertyStyle: LayersValue;
+ const newPropertyStyle: LayersValue = getLayersValue(styleValue);
- if (propertyStyle?.type === "layers") {
- newPropertyStyle = structuredClone(propertyStyle);
- } else if (styleValue?.cascaded?.value.type === "layers") {
- newPropertyStyle = structuredClone(styleValue?.cascaded?.value);
- } else {
- newPropertyStyle = { type: "layers", value: [] };
- }
+ const missingLayerCount = layerCount - newPropertyStyle.value.length;
- // All layers must have the same number of layers
- if (newPropertyStyle.value.length < layerCount) {
- newPropertyStyle.value = newPropertyStyle.value.concat(
- new Array(layerCount - newPropertyStyle.value.length).fill(
- layeredBackgroundPropsDefaults[property]
- )
+ if (missingLayerCount < 0) {
+ // In theory this should never happen.
+ throw new Error(
+ `Layer count for property ${property} exceeds expected ${layerCount}`
);
}
- if (newPropertyStyle.value.length > layerCount) {
- newPropertyStyle.value = newPropertyStyle.value.slice(0, layerCount);
+ if (newPropertyStyle.value.length !== layerCount) {
+ // All background properties must have the same number of layers
+ const requiredLayers = new Array(missingLayerCount).fill(
+ structuredClone(layeredBackgroundPropsDefaults[property])
+ );
+ newPropertyStyle.value = newPropertyStyle.value.concat(requiredLayers);
}
newPropertyStyle.value.splice(layerNum, 1);
@@ -254,3 +248,49 @@ export const deleteLayer =
}
batch.publish();
};
+
+export const swapLayers = (
+ newIndex: number,
+ oldIndex: number,
+ style: StyleInfo,
+ createBatchUpdate: CreateBatchUpdate
+) => {
+ const batch = createBatchUpdate();
+ const layerCount = Math.max(getLayerCount(style), newIndex + 1, oldIndex + 1);
+
+ for (const property of layeredBackgroundProps) {
+ const styleValue = style[property];
+
+ // If property is not defined, try copy from cascade or set empty
+ const newPropertyStyle: LayersValue = getLayersValue(styleValue);
+
+ const missingLayerCount = layerCount - newPropertyStyle.value.length;
+
+ if (missingLayerCount < 0) {
+ // In theory this should never happen.
+ throw new Error(
+ `Layer count for property ${property} exceeds expected ${layerCount}`
+ );
+ }
+
+ if (newPropertyStyle.value.length !== layerCount) {
+ // All background properties must have the same number of layers
+ const requiredLayers = new Array(missingLayerCount).fill(
+ structuredClone(layeredBackgroundPropsDefaults[property])
+ );
+ newPropertyStyle.value = newPropertyStyle.value.concat(requiredLayers);
+ }
+
+ const newValue = [...newPropertyStyle.value];
+
+ newValue.splice(oldIndex, 1);
+
+ newValue.splice(newIndex, 0, newPropertyStyle.value[oldIndex]);
+
+ newPropertyStyle.value = newValue;
+
+ batch.setProperty(property)(newPropertyStyle);
+ }
+
+ batch.publish();
+};
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx
new file mode 100644
index 0000000000..27ef6a916e
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx
@@ -0,0 +1,87 @@
+import type { LayersValue } from "@webstudio-is/css-data";
+import { styled, theme } from "@webstudio-is/design-system";
+import { useState } from "react";
+import type { StyleInfo } from "../../shared/style-info";
+import type {
+ CreateBatchUpdate,
+ DeleteProperty,
+ SetProperty,
+} from "../../shared/use-style-data";
+import { BackgroundsSection } from "./backgrounds";
+
+const backgroundImageStyle: LayersValue = {
+ type: "layers",
+ value: [
+ {
+ type: "unparsed",
+ value: "linear-gradient(red, yellow)",
+ },
+ {
+ type: "unparsed",
+ value: "linear-gradient(blue, red)",
+ },
+ {
+ type: "keyword",
+ value: "none",
+ },
+ ],
+};
+
+const styleInfoInitial: StyleInfo = {
+ backgroundImage: {
+ value: backgroundImageStyle,
+ local: backgroundImageStyle,
+ },
+};
+
+const Panel = styled("div", {
+ width: theme.spacing[30],
+});
+
+export const Backgrounds = () => {
+ const [styleInfo, setStyleInfo] = useState(() => styleInfoInitial);
+ const setProperty: SetProperty = (name) => (value, options) => {
+ setStyleInfo((styleInfo) => ({
+ ...styleInfo,
+ [name]: {
+ ...styleInfo[name],
+ value: value,
+ local: value,
+ },
+ }));
+ };
+
+ const deleteProperty: DeleteProperty = (name) => {
+ setStyleInfo((styleInfo) => {
+ const { [name]: _, ...rest } = styleInfo;
+ return rest;
+ });
+ };
+
+ const createBatchUpdate: CreateBatchUpdate = () => ({
+ deleteProperty,
+ setProperty,
+ publish: () => {
+ // do nothing
+ },
+ });
+
+ return (
+ <Panel>
+ <BackgroundsSection
+ currentStyle={styleInfo}
+ setProperty={setProperty}
+ deleteProperty={deleteProperty}
+ createBatchUpdate={createBatchUpdate}
+ category={"backgrounds"}
+ styleConfigsByCategory={[]}
+ moreStyleConfigsByCategory={[]}
+ />
+ </Panel>
+ );
+};
+
+export default {
+ title: "Style/Background",
+ component: BackgroundsSection,
+};
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 f85c49dc30..94b03680d2 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
@@ -28,11 +28,16 @@ import {
type DeleteBackgroundProperty,
getLayerBackgroundStyleInfo,
deleteLayerProperty,
+ swapLayers,
} from "./background-layers";
import { BackgroundContent } from "./background-content";
import { getLayerName, LayerThumbnail } from "./background-thumbnail";
+import { useSortable } from "./use-sortable";
+import { useMemo } from "react";
const Layer = (props: {
+ id: string;
+ isHighlighted: boolean;
layerStyle: StyleInfo;
setProperty: SetBackgroundProperty;
deleteProperty: DeleteBackgroundProperty;
@@ -73,6 +78,8 @@ const Layer = (props: {
}
>
<CssValueListItem
+ active={props.isHighlighted}
+ data-id={props.id}
label={
<PropertyName
style={props.layerStyle}
@@ -116,27 +123,62 @@ export const BackgroundsSection = ({
const layersCount = getLayerCount(currentStyle);
const { items } = styleConfigByName["backgroundColor"];
+
+ const layers = useMemo(
+ () =>
+ Array.from(Array(layersCount), (_, index) => ({
+ id: `${index}`,
+ index,
+ })),
+ [layersCount]
+ );
+
+ const { dragItemId, placementIndicator, sortableRefCallback } = useSortable({
+ items: layers,
+ onSort: (newIndex, oldIndex) => {
+ swapLayers(newIndex, oldIndex, currentStyle, createBatchUpdate);
+ },
+ });
+
return (
<Flex gap={1} direction="column">
- {Array.from(Array(layersCount), (_, layerNum) => (
- <Layer
- key={layerNum}
- layerStyle={getLayerBackgroundStyleInfo(layerNum, currentStyle)}
- deleteLayer={deleteLayer(layerNum, currentStyle, createBatchUpdate)}
- setProperty={setLayerProperty(
- layerNum,
- currentStyle,
- createBatchUpdate
- )}
- deleteProperty={deleteLayerProperty(
- layerNum,
- currentStyle,
- deleteProperty,
- createBatchUpdate
- )}
- />
- ))}
+ <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) => (
+ <Layer
+ id={layer.id}
+ key={layer.id}
+ isHighlighted={dragItemId === layer.id}
+ layerStyle={getLayerBackgroundStyleInfo(layer.index, currentStyle)}
+ deleteLayer={deleteLayer(
+ layer.index,
+ currentStyle,
+ createBatchUpdate
+ )}
+ setProperty={setLayerProperty(
+ layer.index,
+ currentStyle,
+ createBatchUpdate
+ )}
+ deleteProperty={deleteLayerProperty(
+ layer.index,
+ currentStyle,
+ deleteProperty,
+ createBatchUpdate
+ )}
+ />
+ ))}
+ {placementIndicator}
+ </Flex>
<Flex css={{ px: theme.spacing[9] }} direction="column" gap={2}>
<Grid css={{ gridTemplateColumns: "1fr 128px" }}>
<PropertyName
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/use-sortable.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/use-sortable.tsx
new file mode 100644
index 0000000000..516b641bda
--- /dev/null
+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/use-sortable.tsx
@@ -0,0 +1,107 @@
+import { useState, useRef } from "react";
+import {
+ PlacementIndicator,
+ useDrag,
+ useDragCursor,
+ useDrop,
+ type DropTarget,
+} from "@webstudio-is/design-system";
+
+type UseSortable<Item> = {
+ items: Array<Item>;
+ onSort?: (newIndex: number, oldIndex: number) => void;
+};
+
+const getItemId = (element: Element) =>
+ element instanceof HTMLElement ? element.dataset?.id : undefined;
+
+export const useSortable = <Item extends { id: string }>({
+ items,
+ onSort,
+}: UseSortable<Item>) => {
+ const [dropTarget, setDropTarget] = useState<DropTarget<true>>();
+ const [dragItemId, setDragItemId] = useState<string>();
+ const rootRef = useRef<HTMLDivElement | null>(null);
+
+ useDragCursor(dragItemId !== undefined);
+
+ // drop target is always root
+ // we need useDrop only for dropTarget.placement & dropTarget.indexWithinChildren
+ const useDropHandlers = useDrop<true>({
+ elementToData() {
+ return true;
+ },
+ swapDropTarget() {
+ if (rootRef.current === null) {
+ throw new Error("Unexpected empty rootRef during drag");
+ }
+ return { data: true, element: rootRef.current };
+ },
+ onDropTargetChange(dropTarget) {
+ setDropTarget(dropTarget);
+ },
+ });
+
+ const useDragHandlers = useDrag<string>({
+ elementToData(element) {
+ // disable drag unless there are at least 2 items
+ if (items.length < 2) {
+ return false;
+ }
+
+ const closest = element.closest("[data-id]");
+ if (closest === null) {
+ return false;
+ }
+
+ return getItemId(closest) || false;
+ },
+ onStart({ data }) {
+ setDragItemId(data);
+ useDropHandlers.handleStart();
+ },
+ onMove: (point) => {
+ useDropHandlers.handleMove(point);
+ },
+ onEnd({ isCanceled }) {
+ useDropHandlers.handleEnd({ isCanceled });
+ setDragItemId(undefined);
+ setDropTarget(undefined);
+
+ if (isCanceled || dropTarget === undefined || dragItemId === undefined) {
+ return;
+ }
+
+ const oldIndex = items.findIndex((item) => item.id === dragItemId);
+ if (oldIndex !== -1) {
+ let newIndex = dropTarget.indexWithinChildren;
+
+ // placement.index does not take into account the fact that the drag item will be removed.
+ // we need to do this to account for it.
+ if (oldIndex < newIndex) {
+ newIndex = Math.max(0, newIndex - 1);
+ }
+
+ if (oldIndex !== newIndex) {
+ onSort?.(newIndex, oldIndex);
+ }
+ }
+ },
+ });
+
+ const placementIndicator = dropTarget ? (
+ <PlacementIndicator placement={dropTarget.placement} />
+ ) : undefined;
+
+ const sortableRefCallback = (element: HTMLDivElement | null) => {
+ useDropHandlers.rootRef(element);
+ useDragHandlers.rootRef(element);
+ rootRef.current = element;
+ };
+
+ return {
+ sortableRefCallback,
+ dragItemId,
+ placementIndicator,
+ };
+};
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 ec25ab5ae8..93135e1e42 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
@@ -44,6 +44,7 @@ const ListItem = (props: {
hidden: boolean;
labelColor: "default" | "preset" | "local" | "remote";
state: undefined | "open";
+ active: boolean;
focused: undefined | boolean;
label?: React.ReactNode;
}) => {
@@ -60,6 +61,7 @@ const ListItem = (props: {
hidden={props.hidden}
state={props.state}
focused={props.focused}
+ active={props.active}
buttons={
<>
<SmallToggleButton
@@ -134,6 +136,7 @@ export const Declarative = (props: {
<ListItem
key={labelColor}
hidden={false}
+ active={false}
labelColor={labelColor}
state={undefined}
focused={false}
@@ -151,6 +154,7 @@ export const Declarative = (props: {
<ListItem
key={labelColor}
hidden={false}
+ active={false}
labelColor={labelColor}
state={undefined}
focused={false}
@@ -163,6 +167,7 @@ export const Declarative = (props: {
<ListItem
key={labelColor}
hidden={true}
+ active={false}
labelColor={labelColor}
state={undefined}
focused={false}
@@ -175,6 +180,50 @@ export const Declarative = (props: {
<ListItem
key={labelColor}
hidden={false}
+ active={false}
+ labelColor={labelColor}
+ state={"open"}
+ focused={false}
+ />
+ )
+ )}
+ </StoryGrid>
+ </StorySection>
+
+ <StorySection title="Active">
+ <StoryGrid>
+ {(["default", "preset", "local", "remote"] as const).map(
+ (labelColor) => (
+ <ListItem
+ key={labelColor}
+ hidden={false}
+ active={true}
+ labelColor={labelColor}
+ state={undefined}
+ focused={false}
+ />
+ )
+ )}
+
+ {(["default", "preset", "local", "remote"] as const).map(
+ (labelColor) => (
+ <ListItem
+ key={labelColor}
+ hidden={true}
+ active={true}
+ labelColor={labelColor}
+ state={undefined}
+ focused={false}
+ />
+ )
+ )}
+
+ {(["default", "preset", "local", "remote"] as const).map(
+ (labelColor) => (
+ <ListItem
+ key={labelColor}
+ hidden={false}
+ active={true}
labelColor={labelColor}
state={"open"}
focused={false}
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 4127f20622..8f5fa3cf02 100644
--- a/packages/design-system/src/components/css-value-list-item.tsx
+++ b/packages/design-system/src/components/css-value-list-item.tsx
@@ -55,7 +55,7 @@ const ItemButton = styled("button", {
outline: "none",
backgroundColor: theme.colors.backgroundHover,
},
- "&:hover": {
+ "&:hover, &[data-active=true]": {
backgroundColor: theme.colors.backgroundHover,
[`& ${DragHandleIconStyled}`]: {
@@ -83,6 +83,7 @@ type Props = ComponentProps<typeof ItemButton> & {
// for Storybook purposes
focused?: boolean;
state?: "open";
+ active?: boolean;
};
const ItemWrapper = styled("div", {
@@ -111,6 +112,7 @@ export const CssValueListItem = forwardRef(
buttons,
focused,
state,
+ active,
"data-state": dataState,
...rest
}: Props,
@@ -134,6 +136,7 @@ export const CssValueListItem = forwardRef(
ref={ref}
data-focused={focused}
data-state={state ?? dataState}
+ data-active={active}
{...rest}
tabIndex={0}
>