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
Support multiple style sources in preview (#905)
Bogdan Chadkin02654371b506
diff --git a/apps/designer/app/shared/css-utils/generate-css-text.ts b/apps/designer/app/shared/css-utils/generate-css-text.tsindex 1aac7f2dc9..ef46a63cd8 100644--- a/apps/designer/app/shared/css-utils/generate-css-text.ts+++ b/apps/designer/app/shared/css-utils/generate-css-text.ts@@ -49,7 +49,10 @@ export const generateCssText = async (}}- const styleRules = getStyleRules(canvasData.tree?.styles);+ const styleRules = getStyleRules(+ canvasData.build?.styles,+ canvasData.tree?.styleSourceSelections+ );for (const { breakpointId, instanceId, style } of styleRules) {engine.addStyleRule(`[${idAttribute}="${instanceId}"]`, {breakpoint: breakpointId,diff --git a/apps/designer/app/shared/db/canvas.server.ts b/apps/designer/app/shared/db/canvas.server.tsindex b8c020394b..9e443f7418 100644--- a/apps/designer/app/shared/db/canvas.server.ts+++ b/apps/designer/app/shared/db/canvas.server.ts@@ -38,6 +38,7 @@ export const loadCanvasData = async (}return {+ build,tree,breakpoints: breakpoints.values,buildId: build.id,diff --git a/packages/project-build/src/schema/styles.ts b/packages/project-build/src/schema/styles.tsindex 2e3177ba33..c3586e775c 100644--- a/packages/project-build/src/schema/styles.ts+++ b/packages/project-build/src/schema/styles.ts@@ -25,8 +25,8 @@ export const StoredStyles = z.array(StoredStylesItem);export type StoredStyles = z.infer<typeof StoredStyles>;export const StylesItem = z.object({- breakpointId: z.string(),instanceId: 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([ImageValue, SharedStyleValue]),@@ -37,3 +37,17 @@ export type StylesItem = z.infer<typeof StylesItem>;export const Styles = z.array(StylesItem);export type Styles = z.infer<typeof Styles>;++export const NewStylesItem = z.object({+ styleSourceId: z.string(),+ breakpointId: z.string(),+ // @todo can't figure out how to make property to be enum+ property: z.string() as z.ZodType<StyleProperty>,+ value: z.union([ImageValue, SharedStyleValue]),+});++export type NewStylesItem = z.infer<typeof NewStylesItem>;++export const NewStyles = z.array(NewStylesItem);++export type NewStyles = z.infer<typeof NewStyles>;diff --git a/packages/project-build/src/types.ts b/packages/project-build/src/types.tsindex 63a144f06a..6e7e6192a0 100644--- a/packages/project-build/src/types.ts+++ b/packages/project-build/src/types.ts@@ -1,5 +1,6 @@import type { Instance } from "./schema/instances";import type { Props } from "./schema/props";+import type { StyleSourceSelections } from "./schema/style-sources";import type { Styles } from "./schema/styles";export type Tree = {@@ -9,4 +10,5 @@ export type Tree = {root: Instance;props: Props;styles: Styles;+ styleSourceSelections: StyleSourceSelections;};diff --git a/packages/project/src/db/build.ts b/packages/project/src/db/build.tsindex a2c1c3e1f8..cc47276702 100644--- a/packages/project/src/db/build.ts+++ b/packages/project/src/db/build.ts@@ -5,13 +5,21 @@ import {Prisma,Project,} from "@webstudio-is/prisma-client";+import { StyleSources } from "@webstudio-is/project-build";import * as db from ".";import { Build, Page, Pages } from "./schema";import * as pagesUtils from "../shared/pages";+import { parseNewStyles } from "./styles";-export const parseBuild = (build: DbBuild): Build => {+export const parseBuild = async (build: DbBuild): Promise<Build> => {const pages = Pages.parse(JSON.parse(build.pages));- return { ...build, pages };+ return {+ ...build,+ createdAt: build.createdAt.toISOString(),+ pages,+ styles: await parseNewStyles(build.styles),+ styleSources: StyleSources.parse(JSON.parse(build.styleSources)),+ };};export const loadById = async (id: Build["id"]): Promise<Build> => {diff --git a/packages/project/src/db/schema.ts b/packages/project/src/db/schema.tsindex 43a4c623e0..5da010be09 100644--- a/packages/project/src/db/schema.ts+++ b/packages/project/src/db/schema.ts@@ -1,5 +1,6 @@import { z, type ZodType } from "zod";-import { Project, Build as DbBuild } from "@webstudio-is/prisma-client";+import { Project } from "@webstudio-is/prisma-client";+import type { NewStyles, StyleSources } from "@webstudio-is/project-build";import type { Data } from "@webstudio-is/react-sdk";export type { Project };@@ -70,6 +71,19 @@ export const Pages: z.ZodType<{ homePage: Page; pages: Array<Page> }> =});export type Pages = z.infer<typeof Pages>;-export type Build = Omit<DbBuild, "pages"> & { pages: Pages };+export type Build = {+ id: string;+ projectId: string;+ createdAt: string;+ isDev: boolean;+ isProd: boolean;+ pages: Pages;+ styles: NewStyles;+ styleSources: StyleSources;+};-export type CanvasData = Data & { buildId: Build["id"]; page: Page };+export type CanvasData = Data & {+ build: null | Build;+ buildId: Build["id"];+ page: Page;+};diff --git a/packages/project/src/db/styles.ts b/packages/project/src/db/styles.tsindex b838db5f7b..4eaea5ef53 100644--- a/packages/project/src/db/styles.ts+++ b/packages/project/src/db/styles.ts@@ -12,6 +12,7 @@ import {StyleSources,StyleSourceSelections,type Tree,+ NewStyles,} from "@webstudio-is/project-build";import type { Project } from "./schema";import {@@ -47,6 +48,45 @@ const parseValue = (return styleValue;};+export const parseNewStyles = async (stylesString: string) => {+ const storedStyles = StoredStyles.parse(JSON.parse(stylesString));++ const assetIds: string[] = [];+ for (const { value: styleValue } of storedStyles) {+ if (styleValue.type === "image") {+ for (const item of styleValue.value) {+ if (item.type === "asset") {+ assetIds.push(item.value);+ }+ }+ }+ }++ // Load all assets+ const assets = await prisma.asset.findMany({+ where: {+ id: {+ in: assetIds,+ },+ },+ });+ const assetsMap = new Map<string, Asset>();+ for (const asset of assets) {+ assetsMap.set(asset.id, formatAsset(asset));+ }++ const styles: NewStyles = storedStyles.map((styleDecl) => {+ return {+ styleSourceId: styleDecl.styleSourceId,+ breakpointId: styleDecl.breakpointId,+ property: styleDecl.property,+ value: parseValue(styleDecl.value, assetsMap),+ };+ });++ return styles;+};+export const parseStyles = async (treeId: string,stylesString: string,diff --git a/packages/project/src/db/tree.ts b/packages/project/src/db/tree.tsindex 2573292952..d94b8e91cc 100644--- a/packages/project/src/db/tree.ts+++ b/packages/project/src/db/tree.ts@@ -6,8 +6,6 @@ import {type InstancesItem,Instance,Instances,- type Styles,- type Props,StyleSourceSelections,StyleSources,StoredStyles,@@ -50,17 +48,16 @@ export const createTree = ({buildId: string;}): TreeData => {const root = utils.tree.createInstance({ component: "Body" });- const styles: Styles = [];const instances: Instances = [];normalizeTree(root, instances);- const props: Props = [];return {projectId,buildId,root,- props,- styles,+ props: [],+ styles: [],+ styleSourceSelections: [],};};@@ -177,11 +174,16 @@ export const loadById = async (tree.styleSelections);+ const styleSourceSelections = StyleSourceSelections.parse(+ JSON.parse(tree.styleSelections)+ );+return {...tree,root,props,styles,+ styleSourceSelections,};};diff --git a/packages/project/src/shared/styles/style-rules.test.ts b/packages/project/src/shared/styles/style-rules.test.tsindex 2b73fd448b..014470800a 100644--- a/packages/project/src/shared/styles/style-rules.test.ts+++ b/packages/project/src/shared/styles/style-rules.test.ts@@ -1,34 +1,75 @@import { test, expect } from "@jest/globals";-import type { Styles } from "@webstudio-is/project-build";+import type {+ NewStyles,+ StyleSourceSelections,+} from "@webstudio-is/project-build";import { getStyleRules } from "./style-rules";-test("get a list of style rules grouped by instance and breakpoint", () => {- const styles: Styles = [+test("compute styles from different style sources", () => {+ const styles: NewStyles = [{breakpointId: "a",- instanceId: "1",+ styleSourceId: "styleSource1",property: "width",value: { type: "unit", value: 10, unit: "px" },},{breakpointId: "a",- instanceId: "2",+ styleSourceId: "styleSource2",property: "display",value: { type: "keyword", value: "block" },},{breakpointId: "a",- instanceId: "3",+ styleSourceId: "styleSource4",+ property: "color",+ value: { type: "keyword", value: "green" },+ },+ {+ breakpointId: "a",+ styleSourceId: "styleSource4",+ property: "width",+ value: { type: "keyword", value: "min-content" },+ },+ {+ breakpointId: "a",+ styleSourceId: "styleSource3",property: "color",value: { type: "keyword", value: "red" },},+ {+ breakpointId: "b",+ styleSourceId: "styleSource5",+ property: "color",+ value: { type: "keyword", value: "orange" },+ },+ {+ breakpointId: "a",+ styleSourceId: "styleSource6",+ property: "color",+ value: { type: "keyword", value: "blue" },+ },+ ];+ const styleSourceSelections: StyleSourceSelections = [+ {+ instanceId: "instance1",+ values: ["styleSource1"],+ },+ {+ instanceId: "instance2",+ values: ["styleSource4", "styleSource5", "styleSource3"],+ },+ {+ instanceId: "instance3",+ values: ["styleSource6"],+ },];- expect(getStyleRules(styles)).toMatchInlineSnapshot(`+ expect(getStyleRules(styles, styleSourceSelections)).toMatchInlineSnapshot(`[{"breakpointId": "a",- "instanceId": "1",+ "instanceId": "instance1","style": {"width": {"type": "unit",@@ -39,21 +80,35 @@ test("get a list of style rules grouped by instance and breakpoint", () => {},{"breakpointId": "a",- "instanceId": "2",+ "instanceId": "instance2","style": {- "display": {+ "color": {+ "type": "keyword",+ "value": "red",+ },+ "width": {"type": "keyword",- "value": "block",+ "value": "min-content",+ },+ },+ },+ {+ "breakpointId": "b",+ "instanceId": "instance2",+ "style": {+ "color": {+ "type": "keyword",+ "value": "orange",},},},{"breakpointId": "a",- "instanceId": "3",+ "instanceId": "instance3","style": {"color": {"type": "keyword",- "value": "red",+ "value": "blue",},},},diff --git a/packages/project/src/shared/styles/style-rules.ts b/packages/project/src/shared/styles/style-rules.tsindex 4b89fc0518..0fe11292ce 100644--- a/packages/project/src/shared/styles/style-rules.ts+++ b/packages/project/src/shared/styles/style-rules.ts@@ -1,5 +1,9 @@-import type { Style } from "@webstudio-is/css-data";-import type { Styles } from "@webstudio-is/project-build";+import type { Breakpoint, Style } from "@webstudio-is/css-data";+import type {+ NewStyles,+ StyleSource,+ StyleSourceSelections,+} from "@webstudio-is/project-build";type StyleRule = {instanceId: string;@@ -7,19 +11,54 @@ type StyleRule = {style: Style;};-export const getStyleRules = (styles?: Styles) => {- const stylesMap = new Map<string, StyleRule>();- if (styles === undefined) {+/**+ * Merge styles from different style sources+ * and group by instance and breakpoint+ */+export const getStyleRules = (+ styles?: NewStyles,+ styleSourceSelections?: StyleSourceSelections+) => {+ if (styles === undefined || styleSourceSelections === undefined) {return [];}- for (const { breakpointId, instanceId, property, value } of styles) {- const id = `${breakpointId}:${instanceId}`;- let styleRule = stylesMap.get(id);- if (styleRule === undefined) {- styleRule = { breakpointId, instanceId, style: {} };- stylesMap.set(id, styleRule);+ const stylesByStyleSourceId = new Map<StyleSource["id"], NewStyles>();+ for (const styleDecl of styles) {+ const { styleSourceId } = styleDecl;+ let styleSourceStyles = stylesByStyleSourceId.get(styleSourceId);+ // instance can be undefined when style is from other tree+ if (styleSourceStyles === undefined) {+ styleSourceStyles = [];+ stylesByStyleSourceId.set(styleSourceId, styleSourceStyles);}- styleRule.style[property] = value;+ styleSourceStyles.push(styleDecl);}- return Array.from(stylesMap.values());++ const styleRules: StyleRule[] = [];+ for (const { instanceId, values } of styleSourceSelections) {+ const styleRuleByBreakpointId = new Map<Breakpoint["id"], StyleRule>();++ for (const styleSourceId of values) {+ const styleSourceStyles = stylesByStyleSourceId.get(styleSourceId);+ // instance can be undefined when style is from other tree+ if (styleSourceStyles === undefined) {+ continue;+ }+ for (const { breakpointId, property, value } of styleSourceStyles) {+ let styleRule = styleRuleByBreakpointId.get(breakpointId);+ if (styleRule === undefined) {+ styleRule = {+ instanceId,+ breakpointId,+ style: {},+ };+ styleRuleByBreakpointId.set(breakpointId, styleRule);+ }+ styleRule.style[property] = value;+ }+ }+ styleRules.push(...styleRuleByBreakpointId.values());+ }++ return styleRules;};