Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
Background section redesign part 1.1 (#1149)
Ivan Starkovbac386467c53
diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsxnew file mode 100644index 0000000000..29fcaf6571--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.tsx@@ -0,0 +1,209 @@+/**+ * Will be fully rewritten in next iteration,+ * as of now just implement feature parity with old backgrounds section+ **/++import type { StyleValue } from "@webstudio-is/css-data";+import { theme, Flex, Grid, Label } from "@webstudio-is/design-system";+import { ImageControl, TextControl } from "../../controls";+import type { StyleInfo } from "../../shared/style-info";+import type {+ DeleteProperty,+ SetProperty,+ StyleUpdateOptions,+} from "../../shared/use-style-data";++import {+ DeleteBackgroundProperty,+ isBackgroundLayeredProperty,+ isBackgroundStyleValue,+ type SetBackgroundProperty,+} from "./background-layers";++import { FloatingPanelProvider } from "~/builder/shared/floating-panel";+import { useRef } from "react";++type BackgroundContentProps = {+ currentStyle: StyleInfo;+ setProperty: SetBackgroundProperty;+ deleteProperty: DeleteBackgroundProperty;+};++const safeDeleteProperty = (+ deleteProperty: DeleteBackgroundProperty+): DeleteProperty => {+ return (property, options) => {+ const isLayered = isBackgroundLayeredProperty(property);+ if (isLayered) {+ return deleteProperty(property, options);+ }+ throw new Error(`Property ${property} should be background style property`);+ };+};++const safeSetProperty = (setBackgroundProperty: SetBackgroundProperty) => {+ const result: SetProperty = (property) => {+ // isBackgroundLayeredProperty is typeguard and ts don't understand === false+ if (!isBackgroundLayeredProperty(property)) {+ throw new Error(+ `Property ${property} should be background style property`+ );+ }+ return (style: string | StyleValue, options?: StyleUpdateOptions) => {+ if (typeof style === "string") {+ throw new Error("style should be StyleValue and not a string");+ }++ // isBackgroundStyleValue is typeguard and ts don't understand === false+ if (!isBackgroundStyleValue(style)) {+ throw new Error("Style should be valid BackgroundStyleValue");+ }++ return setBackgroundProperty(property)(style, options);+ };+ };+ return result;+};++/*+@todo remove comment after section done++Stackable: !default!+++background-image: url, linear-gradient, radial-gradient, repeating-linear-gradient, repeating-radial-gradient etc++background-clip: !border-box!, padding-box, content-box, text+background-origin: border-box, !padding-box!, content-box+background-size: cover, contain, !auto!, x[unit] y[unit]++background-position-x: !0%!, left, center, right, x[unit]+background-position-y: !0%!, top, center, bottom, y[unit]++background-repeat-x,+background-repeat-y: !repeat!, space, round, no-repeat++background-attachment: !scroll!, fixed, local++background-blend-mode: !normal!, multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color, luminosity++Not stackable:++background-color+*/++export const BackgroundContent = (props: BackgroundContentProps) => {+ const setProperty = safeSetProperty(props.setProperty);+ const deleteProperty = safeDeleteProperty(props.deleteProperty);++ const elementRef = useRef<HTMLDivElement>(null);++ return (+ <Flex+ css={{ p: theme.spacing[9] }}+ direction="column"+ gap={2}+ ref={elementRef}+ >+ <Grid css={{ gridTemplateColumns: "4fr 6fr" }} align="center" gap={2}>+ <Label color="default" truncate>+ Image+ </Label>+ <FloatingPanelProvider container={elementRef}>+ <ImageControl+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ currentStyle={props.currentStyle}+ property="backgroundImage"+ />+ </FloatingPanelProvider>++ <Label color="default" truncate>+ Clip+ </Label>++ <TextControl+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ currentStyle={props.currentStyle}+ property="backgroundClip"+ />++ <Label color="default" truncate>+ Origin+ </Label>++ <TextControl+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ currentStyle={props.currentStyle}+ property="backgroundOrigin"+ />++ <Label color="default" truncate>+ Size+ </Label>++ <TextControl+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ currentStyle={props.currentStyle}+ property="backgroundSize"+ />++ <Label color="default" truncate>+ Position X+ </Label>++ <TextControl+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ currentStyle={props.currentStyle}+ property="backgroundPositionX"+ />++ <Label color="default" truncate>+ Position Y+ </Label>++ <TextControl+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ currentStyle={props.currentStyle}+ property="backgroundPositionY"+ />++ <Label color="default" truncate>+ Repeat+ </Label>++ <TextControl+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ currentStyle={props.currentStyle}+ property="backgroundRepeat"+ />++ <Label color="default" truncate>+ Attachment+ </Label>+ <TextControl+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ currentStyle={props.currentStyle}+ property="backgroundAttachment"+ />++ <Label color="default" truncate>+ Blend mode+ </Label>+ <TextControl+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ currentStyle={props.currentStyle}+ property="backgroundBlendMode"+ />+ </Grid>+ </Flex>+ );+};diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.test.ts b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.test.tsnew file mode 100644index 0000000000..4add3d8218--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.test.ts@@ -0,0 +1,187 @@+import {+ layeredBackgroundProps,+ setLayerProperty,+ addLayer,+} from "./background-layers";++import { describe, test } from "@jest/globals";+import type { StyleInfo } from "../../shared/style-info";+import type { CreateBatchUpdate } from "../../shared/use-style-data";+import type {+ LayersValue,+ StyleProperty,+ StyleValue,+} from "@webstudio-is/css-data";++// @todo remove at node18+globalThis.structuredClone = (value) => {+ return value === undefined ? undefined : JSON.parse(JSON.stringify(value));+};++describe("setLayerProperty", () => {+ test("should work", () => {+ const styleInfo: StyleInfo = {};+ let changedProps: [string, LayersValue][] = [];+ let published = false;++ const createBatchUpdate: CreateBatchUpdate = () => ({+ setProperty:+ (propertyName: StyleProperty) => (newValue: string | StyleValue) => {+ if (typeof newValue === "string") {+ throw new Error("string is deprecated");+ }++ if (newValue.type !== "layers") {+ throw new Error("newValue.type !== layers");+ }++ changedProps.push([propertyName, newValue]);++ styleInfo[propertyName] = { value: newValue, local: newValue };+ },+ deleteProperty: (propertyName: string) => {+ // not used+ },+ publish: (options?: unknown) => {+ published = true;+ },+ });++ const setProperty = setLayerProperty(0, styleInfo, createBatchUpdate);++ setProperty("backgroundPositionX")({ type: "unit", value: 10, unit: "px" });++ expect(published).toBe(true);++ // All props changed if layer wasn't defined+ expect(changedProps.map((changedProp) => changedProp[0])).toEqual(+ layeredBackgroundProps+ );+ // All prop layers are set and have length 1+ expect(+ changedProps.map((changedProp) => changedProp[1].value.length)+ ).toEqual(layeredBackgroundProps.map(() => 1));++ changedProps = [];++ // Single property change if layer exists and has no errors should not touch all properties+ setProperty("backgroundRepeat")({ type: "keyword", value: "no-repeat" });+ expect(changedProps.map((changedProp) => changedProp[0])).toEqual([+ "backgroundRepeat",+ ]);++ changedProps = [];++ // Set non array value, should be restored to array+ styleInfo.backgroundClip = {+ value: { type: "keyword", value: "repeat" },+ local: { type: "keyword", value: "repeat" },+ };+ setProperty("backgroundRepeat")({ type: "keyword", value: "no-repeat" });++ expect(changedProps.map((changedProp) => changedProp[0])).toEqual([+ "backgroundClip",+ "backgroundRepeat",+ ]);++ expect(styleInfo.backgroundClip?.value.type).toEqual("layers");++ changedProps = [];++ // Set wrong count+ styleInfo.backgroundClip = {+ value: {+ type: "layers",+ value: [],+ },+ local: {+ type: "layers",+ value: [],+ },+ };++ setProperty("backgroundRepeat")({ type: "keyword", value: "no-repeat" });++ expect(changedProps.map((changedProp) => changedProp[0])).toEqual([+ "backgroundClip",+ "backgroundRepeat",+ ]);++ expect(+ changedProps.map((changedProp) => changedProp[1].value.length)+ ).toEqual([1, 1]);+ });++ test("should work with cascade", () => {+ const cascaded: NonNullable<StyleInfo["backgroundImage"]>["cascaded"] = {+ breakpointId: "mobile",+ value: {+ type: "layers",+ value: [+ {+ type: "unparsed",+ value: "linear-gradient(red, blue)",+ },+ {+ type: "unparsed",+ value: "linear-gradient(yellow, red)",+ },+ ],+ },+ };+ const styleInfo: StyleInfo = {+ backgroundImage: {+ cascaded,+ value: cascaded.value,+ },+ };+ let changedProps: [string, LayersValue][] = [];+ let published = false;++ const createBatchUpdate: CreateBatchUpdate = () => ({+ setProperty:+ (propertyName: StyleProperty) => (newValue: string | StyleValue) => {+ if (typeof newValue === "string") {+ throw new Error("string is deprecated");+ }++ if (newValue.type !== "layers") {+ throw new Error("newValue.type !== layers");+ }++ changedProps.push([propertyName, newValue]);++ styleInfo[propertyName] = { value: newValue, local: newValue };+ },+ deleteProperty: (propertyName: string) => {+ // not used+ },+ publish: (options?: unknown) => {+ published = true;+ },+ });++ const setProperty = setLayerProperty(0, styleInfo, createBatchUpdate);++ setProperty("backgroundPositionX")({ type: "unit", value: 10, unit: "px" });++ expect(published).toBe(true);++ expect(changedProps.map((changedProp) => changedProp[0])).toEqual(+ layeredBackgroundProps+ );++ // All prop layers are set and have length 2 (copied from cascaded)+ expect(+ changedProps.map((changedProp) => changedProp[1].value.length)+ ).toEqual(layeredBackgroundProps.map(() => 2));++ changedProps = [];++ addLayer(styleInfo, createBatchUpdate);++ expect(+ changedProps.map((changedProp) => changedProp[1].value.length)+ ).toEqual(layeredBackgroundProps.map(() => 3));+ });+});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.tsnew file mode 100644index 0000000000..b736ed3bd6--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-layers.ts@@ -0,0 +1,256 @@+import type { LayersValue, StyleValue } from "@webstudio-is/css-data";+import type { StyleInfo, StyleValueInfo } from "../../shared/style-info";+import type {+ CreateBatchUpdate,+ DeleteProperty,+ StyleUpdateOptions,+} from "../../shared/use-style-data";++export const layeredBackgroundPropsDefaults = {+ backgroundAttachment: { type: "keyword", value: "scroll" },+ backgroundClip: { type: "keyword", value: "border-box" },+ backgroundBlendMode: { type: "keyword", value: "normal" },+ backgroundImage: { type: "keyword", value: "none" },+ backgroundOrigin: { type: "keyword", value: "padding-box" },+ backgroundPositionX: { type: "unit", value: 0, unit: "%" },+ backgroundPositionY: { type: "unit", value: 0, unit: "%" },+ backgroundRepeat: { type: "keyword", value: "repeat" },+ backgroundSize: { type: "keyword", value: "auto" },+} as const satisfies Record<string, BackgroundStyleValue>;++export type BackgroundStyleValue = LayersValue["value"][number];++export const isBackgroundStyleValue = (+ style: StyleValue+): style is BackgroundStyleValue => {+ if (+ style.type === "unit" ||+ style.type === "keyword" ||+ style.type === "unparsed" ||+ style.type === "image" ||+ style.type === "invalid"+ ) {+ return true;+ }+ return false;+};++export const layeredBackgroundProps = Object.keys(+ layeredBackgroundPropsDefaults+) as (keyof typeof layeredBackgroundPropsDefaults)[];++export type LayeredBackgroundProperty = (typeof layeredBackgroundProps)[number];++export const isBackgroundLayeredProperty = (+ prop: string+): prop is LayeredBackgroundProperty => {+ return layeredBackgroundProps.includes(prop as LayeredBackgroundProperty);+};++const getPropertyLayerCount = (style: StyleValueInfo) => {+ if (style.value.type === "layers") {+ return style.value.value.length;+ }+ return 0;+};++export const getLayerCount = (style: StyleInfo) => {+ return Math.max(+ ...layeredBackgroundProps.map((prop) => {+ const styleValue = style[prop];++ if (styleValue !== undefined) {+ return getPropertyLayerCount(styleValue);+ }++ return 0;+ })+ );+};++export const getLayerBackgroundStyleInfo = (+ layerNum: number,+ style: StyleInfo+): StyleInfo => {+ const layerCount = getLayerCount(style);+ if (layerNum >= layerCount) {+ throw new Error(`${layerNum} is out of bounds`);+ }++ const result: StyleInfo = {};++ for (const [property, value] of Object.entries(+ layeredBackgroundPropsDefaults+ )) {+ result[property as LayeredBackgroundProperty] = { value };+ }++ for (const property of layeredBackgroundProps) {+ const resultProperty = result[property];+ if (resultProperty === undefined) {+ throw new Error(`Property ${property} is not defined`);+ }++ const styleValue = style[property];++ const valueStyle = styleValue?.value;+ const localStyle = styleValue?.local;+ const cascadedStyle = styleValue?.cascaded;++ if (valueStyle?.type === "layers") {+ const styleValue = valueStyle.value[layerNum];+ resultProperty["value"] = styleValue;+ }+ if (localStyle?.type === "layers") {+ const styleValue = localStyle.value[layerNum];+ resultProperty["local"] = styleValue;+ }+ if (cascadedStyle?.value.type === "layers") {+ const styleValue = cascadedStyle.value.value[layerNum];+ resultProperty["cascaded"] = {+ breakpointId: cascadedStyle.breakpointId,+ value: styleValue,+ };+ }+ }++ return result;+};++export type DeleteBackgroundProperty = ReturnType<typeof deleteLayerProperty>;++export const deleteLayerProperty =+ (+ layerNum: number,+ style: StyleInfo,+ deleteProperty: DeleteProperty,+ createBatchUpdate: CreateBatchUpdate+ ) =>+ (propertyName: LayeredBackgroundProperty, options?: StyleUpdateOptions) => {+ if (options?.isEphemeral) {+ deleteProperty(propertyName, options);+ return;+ }++ setLayerProperty(layerNum, style, createBatchUpdate)(propertyName)(+ layeredBackgroundPropsDefaults[propertyName]+ );+ };++export type SetBackgroundProperty = ReturnType<typeof setLayerProperty>;++export const setLayerProperty =+ (layerNum: number, style: StyleInfo, createBatchUpdate: CreateBatchUpdate) =>+ (propertyName: LayeredBackgroundProperty) =>+ (newValue: BackgroundStyleValue, options?: StyleUpdateOptions) => {+ const batch = createBatchUpdate();+ const layerCount = Math.max(getLayerCount(style), layerNum + 1);++ const 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];++ // If property is not defined, try copy from cascade or set empty+ let 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}`+ );+ }++ let isPropertyChanged = styleValue?.local?.type !== "layers";++ if (newPropertyStyle.value.length !== layerCount) {+ // All background properties must have the same number of layers+ const requiredLayers = new Array(missingLayerCount).fill(+ structuredClone(layeredBackgroundPropsDefaults[property])+ );+ newPropertyStyle.value = newPropertyStyle.value.concat(requiredLayers);+ isPropertyChanged = true;+ }++ if (property === propertyName) {+ newPropertyStyle.value[layerNum] = newValue;+ isPropertyChanged = true;+ }++ if (isPropertyChanged) {+ batch.setProperty(property)(newPropertyStyle);+ }+ }++ batch.publish(options);+ };++export const addLayer = (+ style: StyleInfo,+ createBatchUpdate: CreateBatchUpdate+) => {+ const layerCount = getLayerCount(style);+ setLayerProperty(layerCount, style, createBatchUpdate)("backgroundImage")({+ type: "keyword",+ value: "none",+ });+};++export const deleteLayer =+ (layerNum: number, style: StyleInfo, createBatchUpdate: CreateBatchUpdate) =>+ () => {+ const layerCount = getLayerCount(style);++ const batch = createBatchUpdate();++ 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;++ if (propertyStyle?.type === "layers") {+ newPropertyStyle = structuredClone(propertyStyle);+ } else if (styleValue?.cascaded?.value.type === "layers") {+ newPropertyStyle = structuredClone(styleValue?.cascaded?.value);+ } else {+ newPropertyStyle = { type: "layers", value: [] };+ }++ // 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 (newPropertyStyle.value.length > layerCount) {+ newPropertyStyle.value = newPropertyStyle.value.slice(0, layerCount);+ }++ newPropertyStyle.value.splice(layerNum, 1);++ if (newPropertyStyle.value.length === 0) {+ batch.deleteProperty(property);+ } else {+ batch.setProperty(property)(newPropertyStyle);+ }+ }+ batch.publish();+ };diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsxnew file mode 100644index 0000000000..69b308be89--- /dev/null+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-thumbnail.tsx@@ -0,0 +1,89 @@+import { Image as WebstudioImage, loaders } from "@webstudio-is/image";+import { styled, theme } from "@webstudio-is/design-system";+import type { StyleInfo } from "../../shared/style-info";+import brokenImage from "~/shared/images/broken-image-placeholder.svg";+import env from "~/shared/env";++const Thumbnail = styled("div", {+ width: theme.spacing[10],+ height: theme.spacing[10],+ backgroundImage: "linear-gradient(yellow, red)",+});++const NoneThumbnail = styled("div", {+ width: theme.spacing[10],+ height: theme.spacing[10],+ background:+ "repeating-conic-gradient(rgba(0,0,0,0.22) 0% 25%, transparent 0% 50%) 0% 33.33% / 40% 40%",+});++const StyledWebstudioImage = styled(WebstudioImage, {+ position: "relative",+ width: theme.spacing[10],+ height: theme.spacing[10],+ objectFit: "contain",++ // This is shown only if an image was not loaded and broken+ // From the spec:+ // - The pseudo-elements generated by ::before and ::after are contained by the element's formatting box,+ // and thus don't apply to "replaced" elements such as <img>, or to <br> elements+ // Not in spec but supported by all browsers:+ // - broken image is not a "replaced" element so this style is applied+ "&::after": {+ content: "' '",+ position: "absolute",+ width: "100%",+ height: "100%",+ left: 0,+ top: 0,+ backgroundSize: "contain",+ backgroundRepeat: "no-repeat",+ backgroundPosition: "center",+ backgroundImage: `url(${brokenImage})`,+ },+});++export const getLayerName = (layerStyle: StyleInfo) => {+ const backgroundImageStyle = layerStyle.backgroundImage?.value;+ if (backgroundImageStyle?.type === "image") {+ return "Image"; // backgroundImageStyle.value.value.name;+ }++ if (backgroundImageStyle?.type === "unparsed") {+ return "Gradient";+ }++ return "None";+};++export const LayerThumbnail = (props: { layerStyle: StyleInfo }) => {+ const backgroundImageStyle = props.layerStyle.backgroundImage?.value;++ if (backgroundImageStyle?.type === "image") {+ const asset = backgroundImageStyle.value.value;+ const remoteLocation = asset.location === "REMOTE";++ const loader = remoteLocation+ ? loaders.cloudflareImageLoader({+ resizeOrigin: env.RESIZE_ORIGIN,+ })+ : loaders.localImageLoader();++ return (+ <StyledWebstudioImage+ key={asset.id}+ loader={loader}+ src={asset.path}+ width={theme.spacing[10]}+ optimize={true}+ alt={getLayerName(props.layerStyle)}+ />+ );+ }++ if (backgroundImageStyle?.type === "unparsed") {+ return <Thumbnail />;+ }++ return <NoneThumbnail />;+};diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsxindex c0c66b8dfe..e80eae1f59 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.tsx@@ -1,19 +1,147 @@import type { RenderCategoryProps } from "../../style-sections";-import { ShowMore } from "../../shared/show-more";-import { renderProperty } from "../../style-sections";+import { styleConfigByName } from "../../shared/configs";+import { FloatingPanel } from "~/builder/shared/floating-panel";+import {+ Button,+ CssValueListItem,+ Flex,+ Grid,+ SmallIconButton,+ theme,+} from "@webstudio-is/design-system";+import { SmallToggleButton } from "@webstudio-is/design-system";+import {+ EyeconOpenIcon,+ EyeconClosedIcon,+ SubtractIcon,+} from "@webstudio-is/icons";+import { useState } from "react";+import { PropertyName } from "../../shared/property-name";+import type { StyleInfo } from "../../shared/style-info";+import { ColorControl } from "../../controls/color/color-control";+import {+ getLayerCount,+ layeredBackgroundProps,+ addLayer,+ deleteLayer,+ setLayerProperty,+ type SetBackgroundProperty,+ type DeleteBackgroundProperty,+ getLayerBackgroundStyleInfo,+ deleteLayerProperty,+} from "./background-layers";+import { BackgroundContent } from "./background-content";+import { getLayerName, LayerThumbnail } from "./background-thumbnail";++const Layer = (props: {+ layerStyle: StyleInfo;+ setProperty: SetBackgroundProperty;+ deleteProperty: DeleteBackgroundProperty;+ deleteLayer: () => void;+}) => {+ const [hidden, setHidden] = useState(false);++ return (+ <FloatingPanel+ title="Background"+ content={+ <BackgroundContent+ currentStyle={props.layerStyle}+ setProperty={props.setProperty}+ deleteProperty={props.deleteProperty}+ />+ }+ >+ <CssValueListItem+ label={+ <PropertyName+ style={props.layerStyle}+ property={layeredBackgroundProps}+ label={getLayerName(props.layerStyle)}+ onReset={props.deleteLayer}+ />+ }+ thumbnail={<LayerThumbnail layerStyle={props.layerStyle} />}+ hidden={hidden}+ buttons={+ <>+ <SmallToggleButton+ pressed={hidden}+ onPressedChange={setHidden}+ variant="normal"+ tabIndex={0}+ icon={hidden ? <EyeconClosedIcon /> : <EyeconOpenIcon />}+ />++ <SmallIconButton+ variant="destructive"+ tabIndex={0}+ icon={<SubtractIcon />}+ onClick={props.deleteLayer}+ />+ </>+ }+ />+ </FloatingPanel>+ );+};export const BackgroundsSection = ({- styleConfigsByCategory,- moreStyleConfigsByCategory,+ setProperty,+ deleteProperty,+ currentStyle,+ createBatchUpdate,}: RenderCategoryProps) => {+ const layersCount = getLayerCount(currentStyle);++ const { items } = styleConfigByName["backgroundColor"];return (- <>- {styleConfigsByCategory.map((entry) => renderProperty(entry))}- <ShowMore- styleConfigs={moreStyleConfigsByCategory.map((entry) =>- renderProperty(entry)- )}- />- </>+ <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 css={{ px: theme.spacing[9] }} direction="column" gap={2}>+ <Grid css={{ gridTemplateColumns: "4fr 6fr" }}>+ <PropertyName+ style={currentStyle}+ property={"backgroundColor"}+ label={"Color"}+ onReset={() => deleteProperty("backgroundColor")}+ />++ <ColorControl+ property={"backgroundColor"}+ items={items}+ currentStyle={currentStyle}+ setProperty={setProperty}+ deleteProperty={deleteProperty}+ />+ </Grid>+ <Button+ color="neutral"+ onClick={() => {+ addLayer(currentStyle, createBatchUpdate);+ }}+ >+ Add layer+ </Button>+ </Flex>+ </Flex>);};diff --git a/apps/builder/app/builder/features/style-panel/shared/property-name.tsx b/apps/builder/app/builder/features/style-panel/shared/property-name.tsxindex cf5aa35e2f..e1293d48c7 100644--- a/apps/builder/app/builder/features/style-panel/shared/property-name.tsx+++ b/apps/builder/app/builder/features/style-panel/shared/property-name.tsx@@ -47,7 +47,14 @@ const PropertyPopoverContent = ({</Button></Flex><Separator />- <Box css={{ px: theme.spacing[4], py: theme.spacing[3] }}>+ <Box+ css={{+ px: theme.spacing[4],+ py: theme.spacing[3],+ // @todo this info looks undone, limit width as a fast fix for huge text like in backgrounds+ maxWidth: theme.spacing[30],+ }}+ >{properties.map((property) => {const styleValueInfo = style[property];@@ -135,7 +142,13 @@ export const PropertyName = ({isFeatureEnabled("propertyReset") &&(styleSource === "local" || styleSource === "remote");- const labelElement = <Label color={styleSource}>{label}</Label>;+ const labelElement = (+ <Flex shrink>+ <Label color={styleSource} truncate>+ {label}+ </Label>+ </Flex>+ );if (isPopoverEnabled) {return (diff --git a/apps/builder/app/builder/features/style-panel/shared/style-info.test.ts b/apps/builder/app/builder/features/style-panel/shared/style-info.test.tsindex f4aba08e1e..7a2161b105 100644--- a/apps/builder/app/builder/features/style-panel/shared/style-info.test.ts+++ b/apps/builder/app/builder/features/style-panel/shared/style-info.test.ts@@ -157,13 +157,6 @@ test("compute inherited styles", () => {)).toMatchInlineSnapshot(`{- "boxSizing": {- "instanceId": "2",- "value": {- "type": "keyword",- "value": "border-box",- },- },"fontSize": {"instanceId": "1","value": {diff --git a/apps/builder/app/builder/features/style-panel/shared/style-info.ts b/apps/builder/app/builder/features/style-panel/shared/style-info.tsindex 7a4f828a2c..16666114b1 100644--- a/apps/builder/app/builder/features/style-panel/shared/style-info.ts+++ b/apps/builder/app/builder/features/style-panel/shared/style-info.ts@@ -198,10 +198,12 @@ export const getInheritedInfo = (const presetStyle = getPresetStyle(instancesIndex, ancestorInstance.id);if (presetStyle) {for (const [styleProperty, styleValue] of Object.entries(presetStyle)) {- inheritedStyle[styleProperty as StyleProperty] = {- instanceId: ancestorInstance.id,- value: styleValue,- };+ if (inheritableProperties.has(styleProperty)) {+ inheritedStyle[styleProperty as StyleProperty] = {+ instanceId: ancestorInstance.id,+ value: styleValue,+ };+ }}}diff --git a/apps/builder/app/builder/features/style-panel/style-settings.tsx b/apps/builder/app/builder/features/style-panel/style-settings.tsxindex 20f2f6a25d..f7e22d87d7 100644--- a/apps/builder/app/builder/features/style-panel/style-settings.tsx+++ b/apps/builder/app/builder/features/style-panel/style-settings.tsx@@ -185,6 +185,7 @@ export const StyleSettings = ({isOpen={isSearchMode ? true : undefined}label={categories[category].label}key={category}+ fullWidth={category === "backgrounds"}><>{renderCategory(categoryProps)}</></CollapsibleSection>diff --git a/apps/builder/app/builder/shared/floating-panel/floating-panel.tsx b/apps/builder/app/builder/shared/floating-panel/floating-panel.tsxindex 85f2b3dd3c..296a386203 100644--- a/apps/builder/app/builder/shared/floating-panel/floating-panel.tsx+++ b/apps/builder/app/builder/shared/floating-panel/floating-panel.tsx@@ -71,13 +71,7 @@ export const FloatingPanel = ({useLogic(onOpenChange);return (<FloatingPanelPopover open={isOpen} onOpenChange={handleOpenChange} modal>- <FloatingPanelPopoverTrigger- asChild- ref={triggerRef}- onClick={() => {- handleOpenChange(true);- }}- >+ <FloatingPanelPopoverTrigger asChild ref={triggerRef}>{children}</FloatingPanelPopoverTrigger><FloatingPanelPopoverContentdiff --git a/apps/builder/app/builder/shared/inspector/collapsible-section.tsx b/apps/builder/app/builder/shared/inspector/collapsible-section.tsxindex b2d15bd29a..cdf7533b16 100644--- a/apps/builder/app/builder/shared/inspector/collapsible-section.tsx+++ b/apps/builder/app/builder/shared/inspector/collapsible-section.tsx@@ -15,6 +15,7 @@ type CollapsibleSectionProps = {isOpenDefault?: boolean;isOpen?: boolean;rightSlot?: JSX.Element;+ fullWidth?: boolean;};const stateContainer = atom<{ [label: string]: boolean }>({});@@ -38,6 +39,7 @@ export const CollapsibleSection = ({isOpenDefault = false,isOpen,rightSlot,+ fullWidth = false,}: CollapsibleSectionProps) => {const [isOpenByUser, setIsOpenByUser] = useOpenState(label, isOpenDefault);const isOpenFinal = isOpen === undefined ? isOpenByUser : isOpen;@@ -80,7 +82,8 @@ export const CollapsibleSection = ({gap="3"direction="column"css={{- p: theme.spacing[9],+ pb: theme.spacing[9],+ px: fullWidth ? 0 : theme.spacing[9],paddingTop: 0,"&:empty": {display: "none",diff --git a/packages/css-data/src/schema.ts b/packages/css-data/src/schema.tsindex f0dcda8be0..7ed76900d2 100644--- a/packages/css-data/src/schema.ts+++ b/packages/css-data/src/schema.ts@@ -30,7 +30,7 @@ const Unit = z.union([export type Unit = z.infer<typeof Unit>;-const UnitValue = z.object({+export const UnitValue = z.object({type: z.literal("unit"),unit: Unit,value: z.number(),@@ -38,7 +38,7 @@ const UnitValue = z.object({export type UnitValue = z.infer<typeof UnitValue>;-const KeywordValue = z.object({+export const KeywordValue = z.object({type: z.literal("keyword"),// @todo use exact typevalue: z.string(),@@ -48,7 +48,7 @@ export type KeywordValue = z.infer<typeof KeywordValue>;/*** Valid unparsed css value**/-const UnparsedValue = z.object({+export const UnparsedValue = z.object({type: z.literal("unparsed"),value: z.string(),});@@ -77,7 +77,7 @@ export type ImageValue = z.infer<typeof ImageValue>;// We want to be able to render the invalid value// and show it is invalid visually, without saving it to the db-const InvalidValue = z.object({+export const InvalidValue = z.object({type: z.literal("invalid"),value: z.string(),});@@ -91,11 +91,15 @@ export type UnsetValue = z.infer<typeof UnsetValue>;// To support background layers https://developer.mozilla.org/en-US/docs/Web/CSS/background// and similar comma separated css properties-const ArrayValue = z.object({+// 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])),+ value: z.array(+ z.union([UnitValue, KeywordValue, UnparsedValue, ImageValue, InvalidValue])+ ),});-export type ArrayValue = z.infer<typeof ArrayValue>;++export type LayersValue = z.infer<typeof LayersValue>;export const TupleValueItem = z.union([UnitValue, KeywordValue, UnparsedValue]);export type TupleValueItem = z.infer<typeof TupleValueItem>;@@ -104,6 +108,7 @@ export const TupleValue = z.object({type: z.literal("tuple"),value: z.array(TupleValueItem),});+export type TupleValue = z.infer<typeof TupleValue>;/**@@ -118,7 +123,7 @@ export const validStaticValueTypes = ["rgb","image","unparsed",- "array",+ "layers","tuple",] as const;@@ -132,11 +137,14 @@ const SharedStaticStyleValue = z.union([FontFamilyValue,RgbValue,UnparsedValue,- ArrayValue,TupleValue,]);-const ValidStaticStyleValue = z.union([ImageValue, SharedStaticStyleValue]);+const ValidStaticStyleValue = z.union([+ ImageValue,+ LayersValue,+ SharedStaticStyleValue,+]);export type ValidStaticStyleValue = z.infer<typeof ValidStaticStyleValue>;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.tsxindex 334ae89a07..6e56c3adca 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@@ -36,19 +36,24 @@ const Thumbnail = styled("div", {backgroundImage: "linear-gradient(yellow, red)",});+const Panel = styled("div", {+ width: theme.spacing[30],+});+const ListItem = (props: {hidden: boolean;labelColor: "default" | "preset" | "local" | "remote";state: undefined | "open";focused: undefined | boolean;+ label?: React.ReactNode;}) => {const [pressed, onPressedChange] = React.useState(false);return (<CssValueListItemlabel={- <Label disabled={props.hidden} color={props.labelColor}>- Image+ <Label disabled={props.hidden} color={props.labelColor} truncate>+ {props.label ?? "Image"}</Label>}thumbnail={<Thumbnail />}@@ -84,7 +89,7 @@ export const Declarative = (props: {const [pressed, onPressedChange] = React.useState(false);return (- <>+ <Panel><StorySection title="Configurable"><FloatingPanelPopover><FloatingPanelPopoverTrigger asChild>@@ -122,6 +127,23 @@ export const Declarative = (props: {</FloatingPanelPopover></StorySection>+ <StorySection title="Overflows">+ <StoryGrid>+ {(["default", "preset", "local", "remote"] as const).map(+ (labelColor) => (+ <ListItem+ key={labelColor}+ hidden={false}+ labelColor={labelColor}+ state={undefined}+ focused={false}+ label="Very long text, very long text"+ />+ )+ )}+ </StoryGrid>+ </StorySection>+<StorySection title="Variants"><StoryGrid>{(["default", "preset", "local", "remote"] as const).map(@@ -161,6 +183,6 @@ export const Declarative = (props: {)}</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.tsxindex 7d6b433507..4127f20622 100644--- a/packages/design-system/src/components/css-value-list-item.tsx+++ b/packages/design-system/src/components/css-value-list-item.tsx@@ -1,4 +1,4 @@-import { type ComponentProps, forwardRef, Ref } from "react";+import { type ComponentProps, forwardRef, Ref, Children, useMemo } from "react";import { styled } from "../stitches.config";import { Flex } from "./flex";import { theme } from "../stitches.config";@@ -8,19 +8,37 @@ const DragHandleIconStyled = styled(DragHandleIcon, {visibility: "hidden",cursor: "grab",color: theme.colors.foregroundSubtle,+ flexShrink: 0,});const ThumbHolder = styled("div", {width: theme.spacing[10],height: theme.spacing[10],+ flexShrink: 0,});-const Item = styled(Flex, {+/**+ * We draw button above rela button positions, therefore we need to have same padding+ */+const sharedPaddingRight = theme.spacing[9];++/**+ * Should be a button as otherwise radix trigger doesn't work with keyboard interactions+ */+const ItemButton = styled("button", {+ appearance: "none",+ width: "100%",+ border: "none",+ display: "flex",+ alignItems: "center",+ justifyContent: "start",userSelect: "none",backgroundColor: theme.colors.backgroundPanel,- paddingRight: theme.spacing[9],+ padding: 0,++ paddingRight: sharedPaddingRight,+height: theme.spacing[13],- width: theme.spacing[30],position: "relative","&:focus-visible, &[data-focused=true], &[data-state=open]": {@@ -34,6 +52,7 @@ const Item = styled(Flex, {pointerEvents: "none",},+ outline: "none",backgroundColor: theme.colors.backgroundHover,},"&:hover": {@@ -54,7 +73,7 @@ const Item = styled(Flex, {},});-type Props = ComponentProps<typeof Item> & {+type Props = ComponentProps<typeof ItemButton> & {hidden?: boolean;label: React.ReactElement;thumbnail: React.ReactElement;@@ -66,6 +85,24 @@ type Props = ComponentProps<typeof Item> & {state?: "open";};+const ItemWrapper = styled("div", {+ position: "relative",+ width: "100%",+});++const IconButtonsWrapper = styled(Flex, {+ position: "absolute",+ right: 0,+ top: 0,+ bottom: 0,+ paddingRight: sharedPaddingRight,+});++const FakeSmallButton = styled("div", {+ width: theme.spacing[9],+ height: theme.spacing[9],+});+export const CssValueListItem = forwardRef(({@@ -77,40 +114,57 @@ export const CssValueListItem = forwardRef("data-state": dataState,...rest}: Props,- ref: Ref<HTMLDivElement>- ) => (- <Item- ref={ref}- align="center"- data-focused={focused}- data-state={state ?? dataState}- {...rest}- tabIndex={0}- >- <DragHandleIconStyled />-- <Flex gap={2}>- <ThumbHolder>{thumbnail}</ThumbHolder>- {label}- </Flex>-- <Flex grow={true} />-- <Flex- gap={2}- onClick={(event) => {- if (event.target !== event.currentTarget) {- // Having that CSSValueListItem is a button itself, prevent propagate click events- // from descendants of button wrapper.- // e.target === e.currentTarget means that click was between buttons in a gap- event.stopPropagation();- }- }}- >- {buttons}- </Flex>- </Item>- )+ ref: Ref<HTMLButtonElement>+ ) => {+ const buttonsCount = Children.count(buttons?.props.children);+ const fakeButtons = useMemo(+ () => (+ <>+ {Array.from(new Array(buttonsCount), (_v, index) => (+ <FakeSmallButton key={index} />+ ))}+ </>+ ),+ [buttonsCount]+ );++ return (+ <ItemWrapper>+ <ItemButton+ ref={ref}+ data-focused={focused}+ data-state={state ?? dataState}+ {...rest}+ tabIndex={0}+ >+ <DragHandleIconStyled />++ <Flex gap={2} shrink>+ <ThumbHolder>{thumbnail}</ThumbHolder>+ {label}+ </Flex>++ <Flex grow={true} />++ {/*+ We place fake divs with same dimensions as small buttons here to avoid following warning:+ 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}>+ {fakeButtons}+ </Flex>+ </ItemButton>++ {/*+ Real buttons are placed above ItemButton to avoid <button> cannot appear as a descendant of <button> warning+ */}+ <IconButtonsWrapper gap={2} align="center">+ {buttons}+ </IconButtonsWrapper>+ </ItemWrapper>+ );+ });CssValueListItem.displayName = "CssValueListItem";diff --git a/packages/design-system/src/index.ts b/packages/design-system/src/index.tsindex 8956d36881..0e33c6276f 100644--- a/packages/design-system/src/index.ts+++ b/packages/design-system/src/index.ts@@ -22,6 +22,8 @@ export * from "./components/two-rows-icon-button-container";export * from "./components/small-icon-button";export * from "./components/list-position-indicator";export * from "./components/position-grid";+export * from "./components/small-toggle-button";+export * from "./components/css-value-list-item";// Not aligneddiff --git a/packages/prisma-client/prisma/migrations/20230301134408_convert-background-to-layers/migration.ts b/packages/prisma-client/prisma/migrations/20230301134408_convert-background-to-layers/migration.tsnew file mode 100644index 0000000000..890138ca70--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230301134408_convert-background-to-layers/migration.ts@@ -0,0 +1,220 @@+import { z } from "zod";+import { PrismaClient } from "./client";++const Unit = z.string();++type Unit = z.infer<typeof Unit>;++const UnitValue = z.object({+ type: z.literal("unit"),+ unit: Unit,+ value: z.number(),+});++type UnitValue = z.infer<typeof UnitValue>;++const KeywordValue = z.object({+ type: z.literal("keyword"),+ // @todo use exact type+ value: z.string(),+});+type KeywordValue = z.infer<typeof KeywordValue>;++/**+ * Valid unparsed css value+ **/+const UnparsedValue = z.object({+ type: z.literal("unparsed"),+ value: z.string(),+});++const FontFamilyValue = z.object({+ type: z.literal("fontFamily"),+ value: z.array(z.string()),+});+type FontFamilyValue = z.infer<typeof FontFamilyValue>;++const RgbValue = z.object({+ type: z.literal("rgb"),+ r: z.number(),+ g: z.number(),+ b: z.number(),+ alpha: z.number(),+});+type RgbValue = z.infer<typeof RgbValue>;++const ImageValue = z.object({+ type: z.literal("image"),+ value: z.object({ type: z.literal("asset"), value: z.unknown() }),+});++type ImageValue = z.infer<typeof ImageValue>;++// We want to be able to render the invalid value+// and show it is invalid visually, without saving it to the db+const InvalidValue = z.object({+ type: z.literal("invalid"),+ value: z.string(),+});+type InvalidValue = z.infer<typeof InvalidValue>;++const UnsetValue = z.object({+ type: z.literal("unset"),+ value: z.literal(""),+});+type UnsetValue = z.infer<typeof UnsetValue>;++/**+ * Shared zod types with DB types.+ * ImageValue in DB has a different type+ */+const SharedStaticStyleValue = z.union([+ UnitValue,+ KeywordValue,+ FontFamilyValue,+ RgbValue,+ UnparsedValue,+]);++const ValidStaticStyleValue = z.union([ImageValue, SharedStaticStyleValue]);++type ValidStaticStyleValue = z.infer<typeof ValidStaticStyleValue>;++const VarValue = z.object({+ type: z.literal("var"),+ value: z.string(),+ fallbacks: z.array(ValidStaticStyleValue),+});+type VarValue = z.infer<typeof VarValue>;++/**+ * Shared types with DB types+ */+const SharedStyleValue = z.union([+ SharedStaticStyleValue,+ InvalidValue,+ UnsetValue,+ VarValue,+]);++const StoredImageValue = z.object({+ type: z.literal("image"),+ value: z.object({ type: z.literal("asset"), value: z.string() }),+});++const StoredLayersValue = z.object({+ type: z.literal("layers"),+ value: z.array(+ z.union([+ UnitValue,+ KeywordValue,+ UnparsedValue,+ StoredImageValue,+ InvalidValue,+ ])+ ),+});++export const StoredStyleDecl = z.object({+ styleSourceId: z.string(),+ breakpointId: z.string(),+ // @todo can't figure out how to make property to be enum+ property: z.string(),+ value: z.union([StoredImageValue, StoredLayersValue, SharedStyleValue]),+});++type StoredStyleDecl = z.infer<typeof StoredStyleDecl>;++const layeredBackgroundProps = [+ "backgroundAttachment",+ "backgroundClip",+ "backgroundBlendMode",+ "backgroundImage",+ "backgroundOrigin",+ "backgroundPositionX",+ "backgroundPositionY",+ "backgroundRepeat",+ "backgroundSize",+];++export default () => {+ const client = new PrismaClient({+ // Uncomment to see the queries in console as the migration runs+ // log: ["query", "info", "warn", "error"],+ });+ return client.$transaction(+ async (prisma) => {+ let cursor: undefined | { id: string; projectId: string } = undefined;+ let hasNext = true;+ const chunkSize = 1000;++ hasNext = true;+ while (hasNext) {+ const builds = await prisma.build.findMany({+ take: chunkSize,+ where: {+ OR: [{ isDev: true }, { isProd: true }],+ },+ orderBy: {+ id: "asc",+ },+ ...(cursor+ ? {+ skip: 1, // Skip the cursor+ cursor: { id_projectId: cursor },+ }+ : null),+ });+ const lastBuild = builds.at(-1);+ if (lastBuild) {+ cursor = { id: lastBuild.id, projectId: lastBuild.projectId };+ }+ hasNext = builds.length === chunkSize;++ const buildsToUpdate = [];++ for (const build of builds) {+ let hasConversion = false;++ const styles: StoredStyleDecl[] = JSON.parse(build.styles);++ for (const style of styles) {+ if (layeredBackgroundProps.includes(style.property)) {+ if (+ style.value.type === "image" ||+ style.value.type === "unit" ||+ style.value.type === "unparsed" ||+ style.value.type === "keyword"+ ) {+ hasConversion = true;++ style.value = {+ type: "layers",+ value: [style.value],+ };+ } else {+ // eslint-disable-next-line no-console+ console.warn("unsupported style value", style.value);+ }+ }+ }++ if (hasConversion) {+ build.styles = JSON.stringify(styles);+ buildsToUpdate.push(build as never);+ }+ }++ await Promise.all(+ buildsToUpdate.map(({ id, projectId, styles }) =>+ prisma.build.update({+ where: { id_projectId: { id, projectId } },+ data: { styles },+ })+ )+ );+ }+ },+ { timeout: 1000 * 60 * 8 }+ );+};diff --git a/packages/prisma-client/prisma/migrations/20230301134408_convert-background-to-layers/schema.prisma b/packages/prisma-client/prisma/migrations/20230301134408_convert-background-to-layers/schema.prismanew file mode 100644index 0000000000..0097aef08e--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20230301134408_convert-background-to-layers/schema.prisma@@ -0,0 +1,128 @@+// DO NOT EDIT THIS FILE!+// This is a copy of your schema.prisma that corresponds to the state of the database+// when all migrations up until this one are applied.+// It's used to generate a Prisma Client for the migration.++// This is your Prisma schema file,+// learn more about it in the docs: https://pris.ly/d/prisma-schema++generator client {+ provider = "prisma-client-js"+ previewFeatures = ["views", "clientExtensions"]+ output = "client"+}++datasource db {+ provider = "postgres"+ url = env("DATABASE_URL")+}++model Team {+ id String @id @default(uuid())+ users User[]+}++enum Location {+ FS+ REMOTE+}++enum UploadStatus {+ UPLOADING+ UPLOADED+}++model Asset {+ id String @default(uuid()) // not unique!+ projectId String+ format String+ size Int+ name String+ description String?+ location Location+ createdAt DateTime @default(now())+ meta String @default("{}")+ status UploadStatus @default(UPLOADED)++ @@id([id, projectId])+}++model User {+ id String @id @default(uuid())+ email String? @unique+ provider String?+ image String?+ username String?+ createdAt DateTime @default(now())+ team Team? @relation(fields: [teamId], references: [id])+ teamId String?+ projects Project[]+}++model Project {+ id String @id @default(uuid())+ createdAt DateTime @default(now())+ title String+ domain String @unique+ user User? @relation(fields: [userId], references: [id])+ userId String?+ build Build[]+ isDeleted Boolean @default(false)++ @@unique([id, isDeleted])+ @@unique([domain, isDeleted])+}++model Build {+ id String @default(uuid())+ createdAt DateTime @default(now())+ pages String++ project Project @relation(fields: [projectId], references: [id])+ projectId String++ isDev Boolean // exctly one is true per project+ isProd Boolean // at most one is true per project (none if not published)++ breakpoints String @default("[]")+ styles String @default("[]")+ styleSources String @default("[]")+ styleSourceSelections String @default("[]")+ props String @default("[]")+ instances String @default("[]")++ @@id([id, projectId])+}++model Breakpoints {+ buildId String @id+ values String @default("[]")+}++enum AuthorizationRelation {+ viewers+ editors+ builders+}++model AuthorizationToken {+ token String @default(uuid())+ // No relation to Project, as the Authorization system is not tied to a project+ projectId String+ name String @default("")+ relation AuthorizationRelation @default(viewers)+ createdAt DateTime @default(now())++ @@id([token, projectId])+}++// Dashboard+view DashboardProject {+ id String @id @default(uuid())+ createdAt DateTime @default(now())+ title String+ domain String+ userId String?+ isDeleted Boolean @default(false)+ isPublished Boolean+}diff --git a/packages/project-build/src/db/styles.ts b/packages/project-build/src/db/styles.tsindex 091d3572ee..3f33c7764a 100644--- a/packages/project-build/src/db/styles.ts+++ b/packages/project-build/src/db/styles.ts@@ -19,7 +19,44 @@ import {const parseValue = (styleValue: StoredStyleDecl["value"],assetsMap: Map<string, Asset>-) => {+): StyleDecl["value"] => {+ if (styleValue.type === "layers") {+ return {+ type: "layers" as const,+ value: styleValue.value.map((style) => {+ if (style.type === "image") {+ const item = style.value;+ const asset = assetsMap.get(item.value);+ if (asset === undefined) {+ warnOnce(true, `Asset with assetId "${item.value}" not found`);++ return {+ type: "invalid" as const,+ value: JSON.stringify(styleValue.value),+ };+ }++ if (asset.type !== "image") {+ warnOnce(true, `Asset with assetId "${item.value}" not an image`);+ return {+ type: "invalid" as const,+ value: JSON.stringify(styleValue.value),+ };+ }++ return {+ type: "image" as const,+ value: {+ type: "asset" as const,+ value: asset,+ },+ };+ }+ return style;+ }),+ };+ }+if (styleValue.type === "image") {const item = styleValue.value;const asset = assetsMap.get(item.value);@@ -66,6 +103,17 @@ export const parseStyles = async (assetIds.push(item.value);}}++ if (styleValue.type === "layers") {+ for (const layer of styleValue.value) {+ if (layer.type === "image") {+ const item = layer.value;+ if (item.type === "asset") {+ assetIds.push(item.value);+ }+ }+ }+ }}// Load all assets@@ -97,7 +145,9 @@ export const parseStyles = async (/*** prepare value to store in db*/-const serializeValue = (styleValue: StyleDecl["value"]) => {+const serializeValue = (+ styleValue: StyleDecl["value"]+): StoredStyleDecl["value"] => {if (styleValue.type === "image") {const asset = styleValue.value;return {@@ -109,6 +159,26 @@ const serializeValue = (styleValue: StyleDecl["value"]) => {},};}+ if (styleValue.type === "layers") {+ return {+ type: "layers" as const,+ value: styleValue.value.map((item) => {+ if (item.type === "image") {+ const asset = item.value;+ return {+ type: "image" as const,+ value: {+ type: asset.type,+ // only asset id is stored in db+ value: asset.value.id,+ },+ };+ }+ return item;+ }),+ };+ }+return styleValue;};diff --git a/packages/project-build/src/schema/styles.ts b/packages/project-build/src/schema/styles.tsindex 6c6d10bc46..be1921d40b 100644--- a/packages/project-build/src/schema/styles.ts+++ b/packages/project-build/src/schema/styles.ts@@ -3,6 +3,11 @@ import {type StyleProperty,SharedStyleValue,ImageValue,+ LayersValue,+ UnitValue,+ KeywordValue,+ UnparsedValue,+ InvalidValue,} from "@webstudio-is/css-data";const StoredImageValue = z.object({@@ -10,12 +15,25 @@ const StoredImageValue = z.object({value: z.object({ type: z.literal("asset"), value: z.string() }),});+const StoredLayersValue = z.object({+ type: z.literal("layers"),+ value: z.array(+ z.union([+ UnitValue,+ KeywordValue,+ UnparsedValue,+ StoredImageValue,+ InvalidValue,+ ])+ ),+});+export const StoredStyleDecl = z.object({styleSourceId: z.string(),breakpointId: z.string(),// @todo can't figure out how to make property to be enumproperty: z.string() as z.ZodType<StyleProperty>,- value: z.union([StoredImageValue, SharedStyleValue]),+ value: z.union([StoredImageValue, StoredLayersValue, SharedStyleValue]),});export type StoredStyleDecl = z.infer<typeof StoredStyleDecl>;@@ -29,7 +47,7 @@ export const StyleDecl = z.object({breakpointId: z.string(),// @todo can't figure out how to make property to be enumproperty: z.string() as z.ZodType<StyleProperty>,- value: z.union([ImageValue, SharedStyleValue]),+ value: z.union([ImageValue, LayersValue, SharedStyleValue]),});export type StyleDecl = z.infer<typeof StyleDecl>;diff --git a/packages/react-sdk/src/css/categories.ts b/packages/react-sdk/src/css/categories.tsindex 6f352e6225..344658dd53 100644--- a/packages/react-sdk/src/css/categories.ts+++ b/packages/react-sdk/src/css/categories.ts@@ -124,6 +124,7 @@ const backgrounds = ["backgroundPositionY","backgroundRepeat","backgroundSize",+ "backgroundBlendMode",] as const;const borders = [