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.

fix: performance optimizations (#5827)

Oleg Isonene7b7faeca592
diff --git a/apps/builder/app/builder/features/command-panel/groups/command-panel-options.test.tsx b/apps/builder/app/builder/features/command-panel/groups/command-panel-options.test.tsx
new file mode 100644
index 0000000000..7a981b371b
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/command-panel-options.test.tsx
@@ -0,0 +1,97 @@
+import { beforeEach, describe, expect, test } from "vitest";
+import { coreMetas, elementComponent } from "@webstudio-is/sdk";
+import type { Instances, Props } from "@webstudio-is/sdk";
+import { createDefaultPages } from "@webstudio-is/project-build";
+import {
+ $registeredComponentMetas,
+ $selectedPageId,
+ selectInstance,
+} from "~/shared/nano-states";
+import { $instances, $pages, $props } from "~/shared/sync/data-stores";
+import {
+ $commandSearch,
+ closeCommandPanel,
+ openCommandPanel,
+} from "../command-state";
+import { $instanceOptions } from "./instances-group";
+import { $tagOptions } from "./tags-group";
+
+beforeEach(() => {
+ closeCommandPanel();
+ $commandSearch.set("");
+ $instances.set(new Map());
+ $props.set(new Map());
+ $pages.set(undefined);
+ $selectedPageId.set(undefined);
+ $registeredComponentMetas.set(new Map(Object.entries(coreMetas)));
+});
+
+describe("$instanceOptions", () => {
+ test("does not build instance options until command search has text", () => {
+ const instances: Instances = new Map([
+ [
+ "box",
+ {
+ type: "instance",
+ id: "box",
+ component: elementComponent,
+ tag: "div",
+ children: [],
+ },
+ ],
+ ]);
+ $instances.set(instances);
+ $pages.set(createDefaultPages({ rootInstanceId: "box" }));
+
+ openCommandPanel();
+
+ expect($instanceOptions.get()).toEqual([]);
+
+ $commandSearch.set("box");
+
+ expect($instanceOptions.get()).toHaveLength(1);
+ expect($instanceOptions.get()[0]?.instance.id).toBe("box");
+ });
+});
+
+describe("$tagOptions", () => {
+ test("uses indexed html tags from props when validating content model", () => {
+ const instances: Instances = new Map([
+ [
+ "list",
+ {
+ type: "instance",
+ id: "list",
+ component: elementComponent,
+ children: [],
+ },
+ ],
+ ]);
+ const props: Props = new Map([
+ [
+ "list-tag",
+ {
+ id: "list-tag",
+ instanceId: "list",
+ name: "tag",
+ type: "string",
+ value: "ul",
+ },
+ ],
+ ]);
+
+ $instances.set(instances);
+ $props.set(props);
+ $pages.set(
+ createDefaultPages({ rootInstanceId: "list", homePageId: "home" })
+ );
+ $selectedPageId.set("home");
+ selectInstance(["list"]);
+ openCommandPanel();
+
+ const tags = $tagOptions.get().map((option) => option.tag);
+
+ expect(tags).toContain("li");
+ expect(tags).not.toContain("div");
+ });
+});
diff --git a/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
index 572bad1a2a..991619cf40 100644
--- a/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
@@ -40,9 +40,9 @@ export type CssVariableOption = BaseOption & {
export const $cssVariableOptions = computed(
[$isCommandPanelOpen, $cssVariableDefinitionsByVariable, $unusedCssVariables],
- (isOpen, definitionsByVariable, unusedVariables) => {
+ (isCommandPanelOpen, definitionsByVariable, unusedVariables) => {
const cssVariableOptions: CssVariableOption[] = [];
- if (!isOpen) {
+ if (!isCommandPanelOpen) {
return cssVariableOptions;
}
diff --git a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
index e9fb82ef70..cf2908c02b 100644
--- a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
@@ -1,5 +1,6 @@
import { useState } from "react";
import { computed } from "nanostores";
+import { ROOT_INSTANCE_ID } from "@webstudio-is/sdk";
import {
CommandGroup,
CommandGroupHeading,
@@ -9,7 +10,13 @@ import {
useSelectedAction,
useResetActionIndex,
} from "@webstudio-is/design-system";
-import { $dataSources } from "~/shared/sync/data-stores";
+import {
+ $dataSources,
+ $instances,
+ $pages,
+ $props,
+ $resources,
+} from "~/shared/sync/data-stores";
import {
$commandContent,
$isCommandPanelOpen,
@@ -22,11 +29,11 @@ import { updateWebstudioData } from "~/shared/instance-utils/data";
import {
DeleteDataVariableDialog,
RenameDataVariableDialog,
- $usedVariablesInInstances,
} from "~/builder/shared/data-variable-utils";
import type { BaseOption } from "../shared/types";
import { formatUsageCount, getUsageSearchTerms } from "../shared/usage-utils";
import { getInstanceLabel } from "~/builder/shared/instance-label";
+import { findVariableUsagesByInstance } from "~/shared/data-variables";
export type DataVariableOption = BaseOption & {
type: "dataVariable";
@@ -36,11 +43,28 @@ export type DataVariableOption = BaseOption & {
usages: number;
};
+const $usedVariablesInInstances = computed(
+ [$isCommandPanelOpen, $pages, $instances, $props, $dataSources, $resources],
+ (isCommandPanelOpen, pages, instances, props, dataSources, resources) => {
+ if (isCommandPanelOpen === false) {
+ return new Map();
+ }
+ return findVariableUsagesByInstance({
+ startingInstanceId: ROOT_INSTANCE_ID,
+ pages,
+ instances,
+ props,
+ dataSources,
+ resources,
+ });
+ }
+);
+
export const $dataVariableOptions = computed(
[$isCommandPanelOpen, $dataSources, $usedVariablesInInstances],
- (isOpen, dataSources, usedInInstances) => {
+ (isCommandPanelOpen, dataSources, usedInInstances) => {
const dataVariableOptions: DataVariableOption[] = [];
- if (!isOpen) {
+ if (!isCommandPanelOpen) {
return dataVariableOptions;
}
diff --git a/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx b/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx
index 94bf7ca2c1..41c1128475 100644
--- a/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx
@@ -16,7 +16,11 @@ import {
$selectedInstanceSelector,
} from "~/shared/nano-states";
import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils/lookup";
-import { closeCommandPanel, $isCommandPanelOpen } from "../command-state";
+import {
+ closeCommandPanel,
+ $commandSearch,
+ $isCommandPanelOpen,
+} from "../command-state";
import type { BaseOption } from "../shared/types";
import { setActiveSidebarPanel } from "~/builder/shared/nano-states";
import { humanizeString } from "~/shared/string-utils";
@@ -29,9 +33,13 @@ export type InstanceOption = BaseOption & {
};
export const $instanceOptions = computed(
- [$isCommandPanelOpen, $instances, $pages],
- (isOpen, instances, pages) => {
- if (!isOpen || !pages) {
+ [$isCommandPanelOpen, $commandSearch, $instances, $pages],
+ (isCommandPanelOpen, commandSearch, instances, pages) => {
+ if (
+ isCommandPanelOpen === false ||
+ commandSearch.trim().length === 0 ||
+ pages === undefined
+ ) {
return [];
}
const instanceOptions: InstanceOption[] = [];
diff --git a/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx
index f06e049dd7..ef0bba9771 100644
--- a/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx
@@ -9,11 +9,15 @@ import {
import { computed } from "nanostores";
import { elementComponent, tags } from "@webstudio-is/sdk";
import type { Instance } from "@webstudio-is/sdk";
-import { $registeredComponentMetas } from "~/shared/nano-states";
+import {
+ $propsIndex,
+ $registeredComponentMetas,
+ $selectedInstancePath,
+ $selectedPage,
+} from "~/shared/nano-states";
import { $instances } from "~/shared/sync/data-stores";
import { $props } from "~/shared/sync/data-stores";
import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";
-import { $selectedInstancePath, $selectedPage } from "~/shared/nano-states";
import { InstanceIcon } from "~/builder/shared/instance-label";
import { isTreeSatisfyingContentModel } from "~/shared/content-model";
import { closeCommandPanel, $isCommandPanelOpen } from "../command-state";
@@ -31,12 +35,21 @@ export const $tagOptions = computed(
$selectedInstancePath,
$instances,
$props,
+ $propsIndex,
$registeredComponentMetas,
$selectedPage,
],
- (isOpen, instancePath, instances, props, metas, selectedPage) => {
+ (
+ isCommandPanelOpen,
+ instancePath,
+ instances,
+ props,
+ propsIndex,
+ metas,
+ selectedPage
+ ) => {
const tagOptions: TagOption[] = [];
- if (!isOpen) {
+ if (isCommandPanelOpen === false) {
return tagOptions;
}
if (instancePath === undefined) {
@@ -66,6 +79,7 @@ export const $tagOptions = computed(
instances: newInstances,
props,
metas,
+ htmlTagsByInstanceId: propsIndex.htmlTagsByInstanceId,
instanceSelector,
});
if (isSatisfying) {
diff --git a/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx b/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx
index fa8238b541..fe2cc87d52 100644
--- a/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx
@@ -405,4 +405,44 @@ describe("canWrapInstance edge cases", () => {
);
expect(result).toBe(true);
});
+
+ test("should use provided html tag index when validating wrapper in parent", () => {
+ $instances.set(
+ new Map([
+ [
+ "list",
+ {
+ type: "instance",
+ id: "list",
+ component: elementComponent,
+ children: [{ type: "id", value: "box" }],
+ },
+ ],
+ [
+ "box",
+ {
+ type: "instance",
+ id: "box",
+ component: elementComponent,
+ tag: "div",
+ children: [],
+ },
+ ],
+ ])
+ );
+
+ const result = canWrapInstance(
+ "box",
+ ["box", "list"],
+ "list",
+ elementComponent,
+ "li",
+ $instances.get(),
+ new Map(),
+ $registeredComponentMetas.get(),
+ new Map([["list", "ul"]])
+ );
+
+ expect(result).toBe(true);
+ });
});
diff --git a/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx
index 9b0011cd60..8daff08183 100644
--- a/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx
@@ -12,17 +12,25 @@ import {
} from "@webstudio-is/design-system";
import { matchSorter } from "match-sorter";
import { computed } from "nanostores";
-import { elementComponent, tags } from "@webstudio-is/sdk";
+import {
+ elementComponent,
+ getHtmlTagsFromProps,
+ tags,
+} from "@webstudio-is/sdk";
import type {
Instance,
Instances,
Props,
WsComponentMeta,
} from "@webstudio-is/sdk";
-import { $registeredComponentMetas } from "~/shared/nano-states";
+import {
+ $propsIndex,
+ $registeredComponentMetas,
+ $selectedInstancePath,
+ $selectedPage,
+} from "~/shared/nano-states";
import { $instances } from "~/shared/sync/data-stores";
import { $props } from "~/shared/sync/data-stores";
-import { $selectedInstancePath, $selectedPage } from "~/shared/nano-states";
import {
getInstanceLabel,
InstanceIcon,
@@ -68,7 +76,10 @@ const canWrapInstance = (
tag: string | undefined,
instances: Instances,
props: Props,
- metas: Map<Instance["component"], WsComponentMeta>
+ metas: Map<Instance["component"], WsComponentMeta>,
+ htmlTagsByInstanceId: Map<Instance["id"], string> = getHtmlTagsFromProps(
+ props
+ )
): boolean => {
const selectedInstance = instances.get(selectedInstanceId);
const parentInstance = instances.get(parentInstanceId);
@@ -115,6 +126,7 @@ const canWrapInstance = (
instances: newInstances,
props,
metas,
+ htmlTagsByInstanceId,
instanceSelector: [
wrapperInstance.id,
...selectedInstanceSelector.slice(1),
@@ -130,6 +142,7 @@ const canWrapInstance = (
instances: newInstances,
props,
metas,
+ htmlTagsByInstanceId,
instanceSelector: [
selectedInstanceId,
wrapperInstance.id,
@@ -146,12 +159,21 @@ const $wrapOptions = computed(
$selectedInstancePath,
$instances,
$props,
+ $propsIndex,
$registeredComponentMetas,
$selectedPage,
],
- (isOpen, instancePath, instances, props, metas, selectedPage) => {
+ (
+ isCommandPanelOpen,
+ instancePath,
+ instances,
+ props,
+ propsIndex,
+ metas,
+ selectedPage
+ ) => {
const wrapOptions: WrapOption[] = [];
- if (!isOpen) {
+ if (isCommandPanelOpen === false) {
return wrapOptions;
}
if (instancePath === undefined || instancePath.length === 1) {
@@ -192,7 +214,8 @@ const $wrapOptions = computed(
undefined,
instances,
props,
- metas
+ metas,
+ propsIndex.htmlTagsByInstanceId
)
) {
const meta = metas.get(component);
@@ -217,7 +240,8 @@ const $wrapOptions = computed(
tag,
instances,
props,
- metas
+ metas,
+ propsIndex.htmlTagsByInstanceId
)
) {
const label = getInstanceLabel({ component: elementComponent, tag });
diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.tsx b/apps/builder/app/builder/features/navigator/navigator-tree.tsx
index bed90881e7..2a12bd804d 100644
--- a/apps/builder/app/builder/features/navigator/navigator-tree.tsx
+++ b/apps/builder/app/builder/features/navigator/navigator-tree.tsx
@@ -511,6 +511,7 @@ const canDrag = (instance: Instance, instanceSelector: InstanceSelector) => {
instances: $instances.get(),
props: $props.get(),
metas: $registeredComponentMetas.get(),
+ htmlTagsByInstanceId: $propsIndex.get().htmlTagsByInstanceId,
});
if (isContent) {
toast.error(
@@ -528,6 +529,7 @@ const canDrop = (
const instances = $instances.get();
const props = $props.get();
const metas = $registeredComponentMetas.get();
+ const { htmlTagsByInstanceId } = $propsIndex.get();
// in content mode allow drop only within same block
if ($isContentMode.get()) {
const parentInstance = instances.get(dropSelector[0]);
@@ -545,6 +547,7 @@ const canDrop = (
props,
instances,
instanceSelector: dropSelector,
+ htmlTagsByInstanceId,
});
if (dropSelector.length !== containerSelector.length) {
return false;
@@ -556,6 +559,7 @@ const canDrop = (
metas,
props,
instanceSelector: containerInstanceSelector,
+ htmlTagsByInstanceId,
});
return matches;
};
diff --git a/apps/builder/app/builder/features/style-panel/shared/model.tsx b/apps/builder/app/builder/features/style-panel/shared/model.tsx
index 5bd9d423fa..3b22696f92 100644
--- a/apps/builder/app/builder/features/style-panel/shared/model.tsx
+++ b/apps/builder/app/builder/features/style-panel/shared/model.tsx
@@ -24,16 +24,13 @@ import {
import { rootComponent } from "@webstudio-is/sdk";
import {
$registeredComponentMetas,
+ $propsIndex,
$selectedBreakpoint,
$selectedInstanceStates,
$selectedOrLastStyleSourceSelector,
} from "~/shared/nano-states";
import { $breakpoints } from "~/shared/sync/data-stores";
-import {
- $props,
- $styles,
- $styleSourceSelections,
-} from "~/shared/sync/data-stores";
+import { $styles, $styleSourceSelections } from "~/shared/sync/data-stores";
import {
getComputedStyleDecl,
getPresetStyleDeclKey,
@@ -46,6 +43,8 @@ import {
} from "~/shared/nano-states";
import type { InstanceSelector } from "~/shared/instance-utils/tree";
+const propertyNameCollator = new Intl.Collator();
+
const $presetStyles = computed($registeredComponentMetas, (metas) => {
const presetStyles = new Map<string, StyleValue>();
for (const [component, meta] of metas) {
@@ -65,14 +64,18 @@ const $presetStyles = computed($registeredComponentMetas, (metas) => {
});
export const $instanceTags = computed(
- [$registeredComponentMetas, $props, $selectedInstancePathWithRoot],
- (metas, props, instancePath) => {
+ [$registeredComponentMetas, $propsIndex, $selectedInstancePathWithRoot],
+ (metas, propsIndex, instancePath) => {
const instanceTags = new Map<Instance["id"], HtmlTags>();
if (instancePath === undefined) {
return instanceTags;
}
for (const { instance } of instancePath) {
- const tag = getHtmlTagFromInstance({ instance, metas, props });
+ const tag = getHtmlTagFromInstance({
+ instance,
+ metas,
+ htmlTagsByInstanceId: propsIndex.htmlTagsByInstanceId,
+ });
if (tag !== undefined) {
instanceTags.set(instance.id, tag as HtmlTags);
}
@@ -188,7 +191,7 @@ const getDefinedStyles = ({
// We are sorting by alphabet within each group.
const sortByProperty = (a: { property: string }, b: { property: string }) => {
- return Intl.Collator().compare(a.property, b.property);
+ return propertyNameCollator.compare(a.property, b.property);
};
return [
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx
index dd9f161854..02dd137644 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-instance-outline.tsx
@@ -1,5 +1,5 @@
import { deleteInstanceMutable } from "~/shared/instance-utils/mutation";
-import { updateWebstudioData } from "~/shared/instance-utils/data";
+import { updateInstanceData } from "~/shared/instance-utils/data";
import { useRef, useState } from "react";
import { useStore } from "@nanostores/react";
import { shallowEqual } from "shallow-equal";
@@ -377,7 +377,7 @@ export const BlockChildHoveredInstanceOutline = () => {
return;
}
- updateWebstudioData((data) => {
+ updateInstanceData((data) => {
deleteInstanceMutable(
data,
getInstancePath(outline.selector, data.instances)
diff --git a/apps/builder/app/builder/shared/css-variable-utils.tsx b/apps/builder/app/builder/shared/css-variable-utils.tsx
index 0b10debad0..9ac1f57a3f 100644
--- a/apps/builder/app/builder/shared/css-variable-utils.tsx
+++ b/apps/builder/app/builder/shared/css-variable-utils.tsx
@@ -53,23 +53,43 @@ const createVarNameRegex = (varName: string): RegExp => {
return new RegExp(`${escapeRegex(varName)}(?![\\w-])`, "g");
};
-// Traverse a StyleValue to find all var() references
-const findVarReferences = (value: StyleValue, varName: string): boolean => {
- const valueStr = toValue(value);
- return createVarNameRegex(varName).test(valueStr);
+const createVarNamesRegex = (definedVariables: Set<string>): RegExp => {
+ const alternatives = Array.from(definedVariables)
+ .sort((left, right) => right.length - left.length)
+ .map(escapeRegex)
+ .join("|");
+ return new RegExp(`(?:${alternatives})(?![\\w-])`, "g");
};
-// Find all CSS variable references in HTML Embed code props
-const findVarReferencesInProps = (props: Props, varName: string): boolean => {
- const regex = createVarNameRegex(varName);
- for (const prop of props.values()) {
- if (prop.type === "string" && prop.name === "code" && prop.value) {
- if (regex.test(prop.value)) {
- return true;
- }
+const collectVariableReferencesFromString = (value: string, regex: RegExp) => {
+ const varReferences = new Set<string>();
+ regex.lastIndex = 0;
+ for (const match of value.matchAll(regex)) {
+ varReferences.add(match[0]);
+ }
+ return varReferences;
+};
+
+const getDefinedVariables = (styles: Map<string, StyleDecl>) => {
+ const definedVariables = new Set<string>();
+ for (const styleDecl of styles.values()) {
+ if (styleDecl.property.startsWith("--")) {
+ definedVariables.add(styleDecl.property);
}
}
- return false;
+ return definedVariables;
+};
+
+const getInstancesByStyleSource = (
+ styleSourceSelections: StyleSourceSelections
+) => {
+ const instancesByStyleSource = new Map<string, Instance["id"]>();
+ for (const { instanceId, values } of styleSourceSelections.values()) {
+ for (const styleSourceId of values) {
+ instancesByStyleSource.set(styleSourceId, instanceId);
+ }
+ }
+ return instancesByStyleSource;
};
// Find CSS variable usage counts (how many times each variable is referenced via var())
@@ -88,15 +108,16 @@ export const findCssVariableUsagesByInstance = ({
const usageCounts = new Map<string, number>();
const usageInstances = new Map<string, Set<Instance["id"]>>();
- // Track which style sources belong to which instances
- const instancesByStyleSource = new Map<string, Instance["id"]>();
- for (const { instanceId, values } of styleSourceSelections.values()) {
- for (const styleSourceId of values) {
- instancesByStyleSource.set(styleSourceId, instanceId);
- }
+ const definedVariables = getDefinedVariables(styles);
+ if (definedVariables.size === 0) {
+ return { counts: usageCounts, instances: usageInstances };
}
+ const definedVariablesRegex = createVarNamesRegex(definedVariables);
+
+ const instancesByStyleSource = getInstancesByStyleSource(
+ styleSourceSelections
+ );
- // Helper to add a var reference
const addVarReference = (varName: string, instanceId: Instance["id"]) => {
const count = usageCounts.get(varName) ?? 0;
usageCounts.set(varName, count + 1);
@@ -109,17 +130,6 @@ export const findCssVariableUsagesByInstance = ({
instances.add(instanceId);
};
- // Collect all defined variables
- // Performance optimization: Only check variables that are defined
- // instead of searching for all possible var() patterns.
- // This is O(defined_vars × styles) instead of O(all_patterns × styles).
- const definedVariables = new Set<string>();
- for (const styleDecl of styles.values()) {
- if (styleDecl.property.startsWith("--")) {
- definedVariables.add(styleDecl.property);
- }
- }
-
// Track CSS variable references in StyleDecl values
for (const styleDecl of styles.values()) {
const instanceId = instancesByStyleSource.get(styleDecl.styleSourceId);
@@ -127,25 +137,22 @@ export const findCssVariableUsagesByInstance = ({
continue;
}
- // Check each defined variable if it's used in this style
- for (const varName of definedVariables) {
- if (findVarReferences(styleDecl.value, varName)) {
- addVarReference(varName, instanceId);
- }
+ for (const varName of collectVariableReferencesFromString(
+ toValue(styleDecl.value),
+ definedVariablesRegex
+ )) {
+ addVarReference(varName, instanceId);
}
}
// Track CSS variable references in HTML Embed code props
- for (const varName of definedVariables) {
- if (findVarReferencesInProps(props, varName)) {
- // Find which instance this belongs to
- for (const prop of props.values()) {
- if (prop.type === "string" && prop.name === "code" && prop.value) {
- const regex = createVarNameRegex(varName);
- if (regex.test(prop.value)) {
- addVarReference(varName, prop.instanceId);
- }
- }
+ for (const prop of props.values()) {
+ if (prop.type === "string" && prop.name === "code" && prop.value) {
+ for (const varName of collectVariableReferencesFromString(
+ prop.value,
+ definedVariablesRegex
+ )) {
+ addVarReference(varName, prop.instanceId);
}
}
}
@@ -176,13 +183,7 @@ export const $cssVariableInstancesByVariable = computed(
// Get all defined CSS variables (unique properties that start with --)
export const $definedCssVariables = computed($styles, (styles) => {
- const definedVariables = new Set<CustomProperty>();
- for (const styleDecl of styles.values()) {
- if (styleDecl.property.startsWith("--")) {
- definedVariables.add(styleDecl.property as CustomProperty);
- }
- }
- return definedVariables;
+ return getDefinedVariables(styles) as Set<CustomProperty>;
});
// Map CSS variables to the instances where they are defined
@@ -191,13 +192,9 @@ export const $cssVariableDefinitionsByVariable = computed(
(styleSourceSelections, styles) => {
const definitionsByVariable = new Map<string, Set<Instance["id"]>>();
- // Build map of styleSourceId to instanceId
- const instancesByStyleSource = new Map<string, Instance["id"]>();
- for (const { instanceId, values } of styleSourceSelections.values()) {
- for (const styleSourceId of values) {
- instancesByStyleSource.set(styleSourceId, instanceId);
- }
- }
+ const instancesByStyleSource = getInstancesByStyleSource(
+ styleSourceSelections
+ );
// Find all CSS variable definitions
for (const styleDecl of styles.values()) {
@@ -224,33 +221,29 @@ export const $referencedCssVariables = computed(
(styles, props) => {
const referencedVariables = new Set<string>();
- // Collect all defined variables first
- const definedVariables = new Set<string>();
+ const definedVariables = getDefinedVariables(styles);
+ if (definedVariables.size === 0) {
+ return referencedVariables;
+ }
+
+ const definedVariablesRegex = createVarNamesRegex(definedVariables);
for (const styleDecl of styles.values()) {
- if (styleDecl.property.startsWith("--")) {
- definedVariables.add(styleDecl.property);
+ for (const varName of collectVariableReferencesFromString(
+ toValue(styleDecl.value),
+ definedVariablesRegex
+ )) {
+ referencedVariables.add(varName);
}
}
-
- // Check which defined variables are referenced
- for (const varName of definedVariables) {
- // Check in styles
- // Performance optimization: We only need to know IF a variable is used (boolean),
- // not HOW MANY times, so we break on first match.
- for (const styleDecl of styles.values()) {
- if (findVarReferences(styleDecl.value, varName)) {
+ for (const prop of props.values()) {
+ if (prop.type === "string" && prop.name === "code" && prop.value) {
+ for (const varName of collectVariableReferencesFromString(
+ prop.value,
+ definedVariablesRegex
+ )) {
referencedVariables.add(varName);
- break;
}
}
-
- // Check in props if not already found
- if (
- !referencedVariables.has(varName) &&
- findVarReferencesInProps(props, varName)
- ) {
- referencedVariables.add(varName);
- }
}
return referencedVariables;
diff --git a/apps/builder/app/builder/shared/data-variable-utils.tsx b/apps/builder/app/builder/shared/data-variable-utils.tsx
index c5c3835c91..5b0c5f0bb7 100644
--- a/apps/builder/app/builder/shared/data-variable-utils.tsx
+++ b/apps/builder/app/builder/shared/data-variable-utils.tsx
@@ -1,5 +1,5 @@
import { useState, useEffect } from "react";
-import { atom, computed } from "nanostores";
+import { atom } from "nanostores";
import { useStore } from "@nanostores/react";
import { toast } from "@webstudio-is/design-system";
import {
@@ -37,23 +37,16 @@ export type DataVariableError = {
message: string;
};
-/**
- * Computed store that tracks which instances use each variable
- * Returns a Map of variable ID to Set of instance IDs
- */
-export const $usedVariablesInInstances = computed(
- [$pages, $instances, $props, $dataSources, $resources],
- (pages, instances, props, dataSources, resources) => {
- return findVariableUsagesByInstance({
- startingInstanceId: ROOT_INSTANCE_ID,
- pages,
- instances,
- props,
- dataSources,
- resources,
- });
- }
-);
+const getUsedVariablesInInstances = () => {
+ return findVariableUsagesByInstance({
+ startingInstanceId: ROOT_INSTANCE_ID,
+ pages: $pages.get(),
+ instances: $instances.get(),
+ props: $props.get(),
+ dataSources: $dataSources.get(),
+ resources: $resources.get(),
+ });
+};
type DeleteDataVariableDialogProps = {
variable?: { id: DataSource["id"]; name: string; usages: number };
@@ -112,7 +105,7 @@ export const DeleteDataVariableDialog = ({
export const deleteUnusedDataVariables = () => {
const dataSources = $dataSources.get();
- const usedVariablesInInstances = $usedVariablesInInstances.get();
+ const usedVariablesInInstances = getUsedVariablesInInstances();
const unusedVariableIds: DataSource["id"][] = [];
for (const dataSource of dataSources.values()) {
@@ -280,7 +273,6 @@ export const RenameDataVariableDialog = ({
export const DeleteUnusedDataVariablesDialog = () => {
const open = useStore($isDeleteUnusedDataVariablesDialogOpen);
- const usedVariablesInInstances = useStore($usedVariablesInInstances);
const dataSources = useStore($dataSources);
const handleClose = () => {
@@ -288,11 +280,14 @@ export const DeleteUnusedDataVariablesDialog = () => {
};
const unusedVariables: Array<{ id: string; name: string }> = [];
- for (const dataSource of dataSources.values()) {
- if (dataSource.type === "variable") {
- const usages = usedVariablesInInstances.get(dataSource.id);
- if (usages === undefined || usages.size === 0) {
- unusedVariables.push({ id: dataSource.id, name: dataSource.name });
+ if (open) {
+ const usedVariablesInInstances = getUsedVariablesInInstances();
+ for (const dataSource of dataSources.values()) {
+ if (dataSource.type === "variable") {
+ const usages = usedVariablesInInstances.get(dataSource.id);
+ if (usages === undefined || usages.size === 0) {
+ unusedVariables.push({ id: dataSource.id, name: dataSource.name });
+ }
}
}
}
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsx
index 2394df3c2e..0f4500ad86 100644
--- a/apps/builder/app/canvas/canvas.tsx
+++ b/apps/builder/app/canvas/canvas.tsx
@@ -305,16 +305,15 @@ export const Canvas = () => {
}, []);
const selectedPage = useStore($selectedPage);
+ const rootInstanceId = selectedPage?.rootInstanceId;
useEffect(() => {
- const rootInstanceId = selectedPage?.rootInstanceId;
if (rootInstanceId !== undefined) {
inflateInstance(rootInstanceId);
}
- });
+ }, [rootInstanceId]);
useWindowResizeDebounced(() => {
- const rootInstanceId = selectedPage?.rootInstanceId;
if (rootInstanceId !== undefined) {
inflateInstance(rootInstanceId);
}
diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
index 7b1ac56a21..617b0ae860 100644
--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx
+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
@@ -1,5 +1,5 @@
import { findAllEditableInstanceSelector } from "~/shared/instance-utils/lookup";
-import { updateWebstudioData } from "~/shared/instance-utils/data";
+import { updateInstanceData } from "~/shared/instance-utils/data";
import { color } from "@webstudio-is/css-engine";
import {
useState,
@@ -1101,7 +1101,7 @@ const RichTextContentPluginInternal = ({
findBlockChildSelector(rootInstanceSelector);
if (blockChildSelector) {
- updateWebstudioData((data) => {
+ updateInstanceData((data) => {
deleteInstanceMutable(
data,
getInstancePath(rootInstanceSelector, data.instances)
@@ -1165,7 +1165,7 @@ const RichTextContentPluginInternal = ({
.get()
.get(parentInstanceSelector[0]);
const isLastChild = parentInstance?.children.length === 1;
- updateWebstudioData((data) => {
+ updateInstanceData((data) => {
deleteInstanceMutable(
data,
getInstancePath(
@@ -1184,7 +1184,7 @@ const RichTextContentPluginInternal = ({
if (blockChildSelector) {
onNext(editor.getEditorState(), { reason: "left" });
- updateWebstudioData((data) => {
+ updateInstanceData((data) => {
deleteInstanceMutable(
data,
getInstancePath(blockChildSelector, data.instances)
@@ -1266,7 +1266,7 @@ const RichTextContentPluginInternal = ({
const isLastChild = parentInstance?.children.length === 1;
// Pressing Enter within an empty list item deletes the empty item
- updateWebstudioData((data) => {
+ updateInstanceData((data) => {
deleteInstanceMutable(
data,
getInstancePath(
diff --git a/apps/builder/app/canvas/instance-selection.ts b/apps/builder/app/canvas/instance-selection.ts
index ff8fcf7152..a764243f27 100644
--- a/apps/builder/app/canvas/instance-selection.ts
+++ b/apps/builder/app/canvas/instance-selection.ts
@@ -3,6 +3,7 @@ import {
$hoveredInstanceOutline,
$hoveredInstanceSelector,
$isContentMode,
+ $propsIndex,
$registeredComponentMetas,
} from "~/shared/nano-states";
import { $props } from "~/shared/sync/data-stores";
@@ -74,6 +75,7 @@ const handleEdit = (event: MouseEvent) => {
instances,
props: $props.get(),
metas: $registeredComponentMetas.get(),
+ htmlTagsByInstanceId: $propsIndex.get().htmlTagsByInstanceId,
});
// Do not allow edit bindable text instances with expression children in Content Mode
diff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.ts
index df815bbc0a..ade1d79edf 100644
--- a/apps/builder/app/canvas/shared/commands.ts
+++ b/apps/builder/app/canvas/shared/commands.ts
@@ -5,6 +5,7 @@ import { getElementByInstanceSelector } from "~/shared/dom-utils";
import { findAllEditableInstanceSelector } from "~/shared/instance-utils/lookup";
import {
$registeredComponentMetas,
+ $propsIndex,
$textEditingInstanceSelector,
$textToolbar,
} from "~/shared/nano-states";
@@ -85,6 +86,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
instances: $instances.get(),
props: $props.get(),
metas: $registeredComponentMetas.get(),
+ htmlTagsByInstanceId: $propsIndex.get().htmlTagsByInstanceId,
});
if (editableInstanceSelector === undefined) {
@@ -95,6 +97,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
instances: $instances.get(),
props: $props.get(),
metas: $registeredComponentMetas.get(),
+ htmlTagsByInstanceId: $propsIndex.get().htmlTagsByInstanceId,
results: selectors,
});
diff --git a/apps/builder/app/canvas/shared/use-drag-drop.ts b/apps/builder/app/canvas/shared/use-drag-drop.ts
index e97a766b7b..ad1c92865f 100644
--- a/apps/builder/app/canvas/shared/use-drag-drop.ts
+++ b/apps/builder/app/canvas/shared/use-drag-drop.ts
@@ -12,6 +12,7 @@ import {
} from "@webstudio-is/design-system";
import {
$dragAndDropState,
+ $propsIndex,
$registeredComponentMetas,
type ItemDropTarget,
} from "~/shared/nano-states";
@@ -67,6 +68,7 @@ const findClosestDroppableInstanceSelector = (
const instances = $instances.get();
const props = $props.get();
const metas = $registeredComponentMetas.get();
+ const { htmlTagsByInstanceId } = $propsIndex.get();
// prevent dropping anything into non containers like image
instanceSelector = findClosestContainer({
@@ -74,6 +76,7 @@ const findClosestDroppableInstanceSelector = (
props,
instances,
instanceSelector,
+ htmlTagsByInstanceId,
});
let droppableIndex = -1;
if (dragPayload?.type === "insert") {
@@ -103,6 +106,7 @@ const findClosestDroppableInstanceSelector = (
props,
metas,
instanceSelector: dropInstanceSelector,
+ htmlTagsByInstanceId,
});
droppableIndex = matches ? 0 : -1;
}
@@ -228,6 +232,7 @@ export const useDragAndDrop = () => {
instances: $instances.get(),
props: $props.get(),
metas: $registeredComponentMetas.get(),
+ htmlTagsByInstanceId: $propsIndex.get().htmlTagsByInstanceId,
}) ?? instanceSelector
);
},
diff --git a/apps/builder/app/shared/builder-data.ts b/apps/builder/app/shared/builder-data.ts
index a7475e202b..58a97b56ee 100644
--- a/apps/builder/app/shared/builder-data.ts
+++ b/apps/builder/app/shared/builder-data.ts
@@ -58,6 +58,12 @@ export const getBuilderData = (): BuilderData => {
const getPair = <Item extends { id: string }>(item: Item) =>
[item.id, item] as const;
+const hydrateIdMap = <Item extends { id: string }>(items: Item[]) =>
+ new Map(items.map(getPair));
+
+const hydrateMap = <Item, Key>(items: Item[], getKey: (item: Item) => Key) =>
+ new Map(items.map((item) => [getKey(item), item] as const));
+
export const loadBuilderData = async ({
projectId,
signal,
@@ -76,18 +82,19 @@ export const loadBuilderData = async ({
projectId: data.projectId,
project: data.project,
publisherHost: data.publisherHost,
- assets: new Map(data.assets.map(getPair)),
- instances: new Map(data.instances.map(getPair)),
- dataSources: new Map(data.dataSources.map(getPair)),
- resources: new Map(data.resources.map(getPair)),
- props: new Map(data.props.map(getPair)),
+ assets: hydrateIdMap(data.assets),
+ instances: hydrateIdMap(data.instances),
+ dataSources: hydrateIdMap(data.dataSources),
+ resources: hydrateIdMap(data.resources),
+ props: hydrateIdMap(data.props),
pages: migratePages(data.pages),
- breakpoints: new Map(data.breakpoints.map(getPair)),
- styleSources: new Map(data.styleSources.map(getPair)),
- styleSourceSelections: new Map(
- data.styleSourceSelections.map((item) => [item.instanceId, item])
+ breakpoints: hydrateIdMap(data.breakpoints),
+ styleSources: hydrateIdMap(data.styleSources),
+ styleSourceSelections: hydrateMap(
+ data.styleSourceSelections,
+ (item) => item.instanceId
),
- styles: new Map(data.styles.map((item) => [getStyleDeclKey(item), item])),
+ styles: hydrateMap(data.styles, (item) => getStyleDeclKey(item)),
marketplaceProduct: data.marketplaceProduct,
};
} catch (error) {
diff --git a/apps/builder/app/shared/content-model.test.tsx b/apps/builder/app/shared/content-model.test.tsx
index 38d4b33806..e7f4b56bd9 100644
--- a/apps/builder/app/shared/content-model.test.tsx
+++ b/apps/builder/app/shared/content-model.test.tsx
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
-import { coreMetas } from "@webstudio-is/sdk";
+import { coreMetas, type Prop, type Props } from "@webstudio-is/sdk";
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
import { $, expression, renderData, ws } from "@webstudio-is/template";
import {
@@ -647,6 +647,63 @@ describe("component content model", () => {
});
describe("rich text tree", () => {
+ test("uses provided html tags index without scanning props", () => {
+ const { instances } = renderData(
+ <$.Paragraph ws:id="instanceId"></$.Paragraph>
+ );
+ const props = new (class extends Map<string, Prop> {
+ values(): MapIterator<Prop> {
+ throw new Error("props should not be scanned");
+ }
+ })() as Props;
+
+ expect(
+ isRichTextTree({
+ instances,
+ props,
+ metas: defaultMetas,
+ instanceId: "instanceId",
+ htmlTagsByInstanceId: new Map(),
+ })
+ ).toBeTruthy();
+ });
+
+ test("reads updated tag props from mutable props maps", () => {
+ const { instances, props } = renderData(
+ <$.Body ws:id="bodyId">
+ <$.Box ws:id="boxId">
+ <ws.element ws:tag="article"></ws.element>
+ </$.Box>
+ </$.Body>
+ );
+
+ expect(
+ isTreeSatisfyingContentModel({
+ instances,
+ props,
+ metas: defaultMetas,
+ instanceSelector: ["bodyId"],
+ })
+ ).toBeTruthy();
+
+ props.set("tagPropId", {
+ id: "tagPropId",
+ instanceId: "boxId",
+ name: "tag",
+ type: "string",
+ value: "span",
+ });
+
+ expect(
+ isTreeSatisfyingContentModel({
+ instances,
+ props,
+ metas: defaultMetas,
+ instanceSelector: ["bodyId"],
+ })
+ ).toBeFalsy();
+ });
+
test("check empty instance is rich text", () => {
expect(
isRichTextTree({
diff --git a/apps/builder/app/shared/content-model.ts b/apps/builder/app/shared/content-model.ts
index e76412d964..dede4e815b 100644
--- a/apps/builder/app/shared/content-model.ts
+++ b/apps/builder/app/shared/content-model.ts
@@ -14,35 +14,24 @@ import type { InstanceSelector } from "./instance-utils/tree";
import { setIsSubsetOf } from "./shim";
type Metas = Map<Instance["component"], WsComponentMeta>;
-
-const htmlTagsByInstanceIdCache = new WeakMap<
- Props,
- Map<Instance["id"], string>
->();
-
-const getHtmlTagsByInstanceId = (props: Props) => {
- let tags = htmlTagsByInstanceIdCache.get(props);
- if (tags === undefined) {
- tags = getHtmlTagsFromProps(props);
- htmlTagsByInstanceIdCache.set(props, tags);
- }
- return tags;
-};
+type HtmlTagsByInstanceId = Map<Instance["id"], string>;
const getTag = ({
instance,
metas,
props,
+ htmlTagsByInstanceId,
}: {
instance: Instance;
metas: Metas;
props: Props;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
return getHtmlTagFromInstance({
instance,
metas,
props,
- htmlTagsByInstanceId: getHtmlTagsByInstanceId(props),
+ htmlTagsByInstanceId: htmlTagsByInstanceId ?? getHtmlTagsFromProps(props),
});
};
@@ -159,11 +148,13 @@ const computeAllowedCategories = ({
props,
metas,
instanceSelector,
+ htmlTagsByInstanceId,
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
let instance: undefined | Instance;
let allowedCategories: undefined | string[];
@@ -174,7 +165,7 @@ const computeAllowedCategories = ({
if (instance === undefined) {
continue;
}
- const tag = getTag({ instance, metas, props });
+ const tag = getTag({ instance, metas, props, htmlTagsByInstanceId });
allowedCategories = getElementChildren(tag, allowedCategories);
}
return allowedCategories;
@@ -299,6 +290,7 @@ export const isTreeSatisfyingContentModel = ({
props,
metas,
instanceSelector,
+ htmlTagsByInstanceId = getHtmlTagsFromProps(props),
onError,
_allowedCategories: allowedCategories,
_allowedAncestorCategories: allowedAncestorCategories,
@@ -308,6 +300,7 @@ export const isTreeSatisfyingContentModel = ({
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
onError?: (message: string) => void;
_allowedCategories?: string[];
_allowedAncestorCategories?: string[];
@@ -319,6 +312,7 @@ export const isTreeSatisfyingContentModel = ({
instances,
props,
metas,
+ htmlTagsByInstanceId,
});
allowedParentCategories ??= getAllowedParentCategories({
instanceSelector,
@@ -336,7 +330,7 @@ export const isTreeSatisfyingContentModel = ({
if (instance === undefined) {
return true;
}
- const tag = getTag({ instance, metas, props });
+ const tag = getTag({ instance, metas, props, htmlTagsByInstanceId });
const isTagSatisfying = isTagSatisfyingContentModel({
tag,
allowedCategories,
@@ -345,7 +339,12 @@ export const isTreeSatisfyingContentModel = ({
const parentInstance = instances.get(parentInstanceId);
let parentTag: undefined | string;
if (parentInstance) {
- parentTag = getTag({ instance: parentInstance, metas, props });
+ parentTag = getTag({
+ instance: parentInstance,
+ metas,
+ props,
+ htmlTagsByInstanceId,
+ });
}
if (parentTag) {
onError?.(
@@ -394,6 +393,7 @@ export const isTreeSatisfyingContentModel = ({
instances,
props,
metas,
+ htmlTagsByInstanceId,
instanceSelector: [child.value, ...instanceSelector],
onError,
_allowedCategories: allowedCategories,
@@ -449,12 +449,14 @@ const findContentTags = ({
props,
metas,
instance,
+ htmlTagsByInstanceId,
_tags: tags = new Set(),
}: {
instances: Instances;
props: Props;
metas: Metas;
instance: Instance;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
_tags?: Set<undefined | string>;
}) => {
for (const child of instance.children) {
@@ -465,13 +467,19 @@ const findContentTags = ({
tags.add(undefined);
continue;
}
- const tag = getTag({ instance: childInstance, metas, props });
+ const tag = getTag({
+ instance: childInstance,
+ metas,
+ props,
+ htmlTagsByInstanceId,
+ });
tags.add(tag);
findContentTags({
instances,
props,
metas,
instance: childInstance,
+ htmlTagsByInstanceId,
_tags: tags,
});
}
@@ -512,18 +520,20 @@ export const isRichTextTree = ({
instances,
props,
metas,
+ htmlTagsByInstanceId = getHtmlTagsFromProps(props),
}: {
instanceId: Instance["id"];
instances: Instances;
props: Props;
metas: Metas;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}): boolean => {
const instance = instances.get(instanceId);
// collection item is not rich text
if (instance === undefined) {
return false;
}
- const tag = getTag({ instance, metas, props });
+ const tag = getTag({ instance, metas, props, htmlTagsByInstanceId });
const elementContentModel = tag ? elementsByTag[tag] : undefined;
const componentContentModel = getComponentContentModel(
metas.get(instance.component)
@@ -546,6 +556,7 @@ export const isRichTextTree = ({
props,
metas,
instance,
+ htmlTagsByInstanceId,
});
const contentComponents = findContentComponents({
instances,
@@ -567,16 +578,26 @@ export const findClosestRichText = ({
props,
metas,
instanceSelector,
+ htmlTagsByInstanceId = getHtmlTagsFromProps(props),
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}): undefined | InstanceSelector => {
let foundRichText: undefined | InstanceSelector = undefined;
for (let index = 0; index < instanceSelector.length; index += 1) {
const instanceId = instanceSelector[index];
- if (!isRichTextTree({ instanceId, instances, props, metas })) {
+ if (
+ !isRichTextTree({
+ instanceId,
+ instances,
+ props,
+ metas,
+ htmlTagsByInstanceId,
+ })
+ ) {
break;
}
foundRichText = instanceSelector.slice(index);
@@ -589,17 +610,20 @@ export const isRichTextContent = ({
props,
metas,
instanceSelector,
+ htmlTagsByInstanceId,
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
const richTextSelector = findClosestRichText({
instanceSelector,
instances,
props,
metas,
+ htmlTagsByInstanceId,
});
return (
richTextSelector && richTextSelector.join() !== instanceSelector.join()
@@ -611,17 +635,20 @@ export const isRichText = ({
props,
metas,
instanceSelector,
+ htmlTagsByInstanceId,
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
const richTextSelector = findClosestRichText({
instanceSelector,
instances,
props,
metas,
+ htmlTagsByInstanceId,
});
return (
richTextSelector && richTextSelector.join() === instanceSelector.join()
@@ -633,11 +660,13 @@ export const findClosestContainer = ({
props,
metas,
instanceSelector,
+ htmlTagsByInstanceId = getHtmlTagsFromProps(props),
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
// page root with text can be used as container
if (instanceSelector.length === 1) {
@@ -650,7 +679,7 @@ export const findClosestContainer = ({
if (instance === undefined) {
continue;
}
- const tag = getTag({ instance, props, metas });
+ const tag = getTag({ instance, props, metas, htmlTagsByInstanceId });
const meta = metas.get(instance.component);
const elementChildren = tag ? elementsByTag[tag].children : undefined;
const componentChildren = getComponentContentModel(meta).children;
@@ -670,11 +699,13 @@ export const findClosestNonTextualContainer = ({
props,
metas,
instanceSelector,
+ htmlTagsByInstanceId = getHtmlTagsFromProps(props),
}: {
instances: Instances;
props: Props;
metas: Metas;
instanceSelector: InstanceSelector;
+ htmlTagsByInstanceId?: HtmlTagsByInstanceId;
}) => {
// page root with text can be used as container
if (instanceSelector.length === 1) {
@@ -687,7 +718,7 @@ export const findClosestNonTextualContainer = ({
if (instance === undefined) {
continue;
}
- const tag = getTag({ instance, props, metas });
+ const tag = getTag({ instance, props, metas, htmlTagsByInstanceId });
const meta = metas.get(instance.component);
const elementChildren = tag ? elementsByTag[tag].children : undefined;
const componentChildren = getComponentContentModel(meta).children;
@@ -716,6 +747,7 @@ export const findClosestNonTextualContainer = ({
props,
metas,
instance,
+ htmlTagsByInstanceId,
});
const contentComponents = findContentComponents({
instances,
diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.ts
index fd74491e70..2a5d97ee0f 100644
--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts
+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts
@@ -4,7 +4,11 @@ import {
} from "../instance-utils/fragment";
import { findClosestInsertable } from "../instance-utils/insert";
import { detectFragmentTokenConflicts } from "../instance-utils/fragment";
-import { updateWebstudioData, getWebstudioData } from "../instance-utils/data";
+import {
+ updateInstanceData,
+ updateWebstudioData,
+ getWebstudioData,
+} from "../instance-utils/data";
import {
insertInstanceChildrenMutable,
type Insertable,
@@ -236,7 +240,7 @@ const handleCutInstance = () => {
if (data === undefined) {
return;
}
- updateWebstudioData((data) => {
+ updateInstanceData((data) => {
deleteInstanceMutable(data, instancePath);
});
if (data === undefined) {
diff --git a/apps/builder/app/shared/data-variables.test.tsx b/apps/builder/app/shared/data-variables.test.tsx
index 65efbbbc9e..3e0fa6fee8 100644
--- a/apps/builder/app/shared/data-variables.test.tsx
+++ b/apps/builder/app/shared/data-variables.test.tsx
@@ -133,6 +133,27 @@ test("find global variables in slots", () => {
]);
});
+test("find legacy global variables with missing scope", () => {
+ const data = renderData(
+ <$.Body ws:id="bodyId">
+ <$.Box ws:id="boxId"></$.Box>
+ </$.Body>
+ );
+ data.dataSources.set("legacyGlobalVariableId", {
+ id: "legacyGlobalVariableId",
+ name: "legacyGlobalVariable",
+ type: "variable",
+ value: { type: "string", value: "" },
+ });
+
+ expect(
+ findAvailableVariables({ ...data, startingInstanceId: "boxId" })
+ ).toEqual([
+ expect.objectContaining({ name: "system", id: SYSTEM_VARIABLE_ID }),
+ expect.objectContaining({ name: "legacyGlobalVariable" }),
+ ]);
+});
+
test("unset expression variables", () => {
expect(
unsetExpressionVariables({
@@ -238,6 +259,23 @@ test("compute literal expression when object is frozen", () => {
);
});
+test("compute expression does not clone unused variables", () => {
+ const variables = new Map<string, unknown>([
+ ["usedVariable", 1],
+ ["unusedVariable", Object.freeze({ callback: () => undefined })],
+ ]);
+ expect(computeExpression("usedVariable + 1", variables)).toEqual(2);
+});
+
+test("compute expression cache reads current variables", () => {
+ expect(
+ computeExpression("cachedVariable", new Map([["cachedVariable", "first"]]))
+ ).toEqual("first");
+ expect(
+ computeExpression("cachedVariable", new Map([["cachedVariable", "second"]]))
+ ).toEqual("second");
+});
+
test("compute unset variables as undefined", () => {
expect(computeExpression(`a`, new Map())).toEqual(undefined);
expect(computeExpression("`${a}`", new Map())).toEqual("undefined");
@@ -833,6 +871,59 @@ test("unset global variables on all pages when delete", () => {
]);
});
+test("unset legacy global variables with missing scope when delete", () => {
+ const data = {
+ pages: createDefaultPages({ rootInstanceId: "homeBodyId" }),
+ ...renderData(
+ <$.Body ws:id="homeBodyId">
+ <$.Text ws:id="homeTextId"></$.Text>
+ </$.Body>
+ ),
+ };
+ data.pages.pages.set("aboutPage", {
+ id: "",
+ name: "",
+ path: "",
+ title: "",
+ meta: {},
+ rootInstanceId: "aboutBodyId",
+ });
+ data.instances.set("aboutBodyId", {
+ id: "aboutBodyId",
+ type: "instance",
+ component: "Body",
+ children: [{ type: "id", value: "aboutTextId" }],
+ });
+ data.instances.set("aboutTextId", {
+ id: "aboutTextId",
+ type: "instance",
+ component: "Text",
+ children: [],
+ });
+ data.dataSources.set("legacyGlobalVariableId", {
+ id: "legacyGlobalVariableId",
+ name: "legacyGlobalVariable",
+ type: "variable",
+ value: { type: "string", value: "" },
+ });
+ const legacyGlobalIdentifier = encodeDataVariableId("legacyGlobalVariableId");
+ data.instances.get("homeTextId")!.children = [
+ { type: "expression", value: legacyGlobalIdentifier },
+ ];
+ data.instances.get("aboutTextId")!.children = [
+ { type: "expression", value: legacyGlobalIdentifier },
+ ];
+
+ deleteVariableMutable(data, "legacyGlobalVariableId");
+
+ expect(data.instances.get("homeTextId")?.children).toEqual([
+ { type: "expression", value: "legacyGlobalVariable" },
+ ]);
+ expect(data.instances.get("aboutTextId")?.children).toEqual([
+ { type: "expression", value: "legacyGlobalVariable" },
+ ]);
+});
+
test("unset global variables in slots when delete", () => {
const globalVariable = new Variable("globalVariable", "");
const data = {
diff --git a/apps/builder/app/shared/data-variables.ts b/apps/builder/app/shared/data-variables.ts
index 90b0a394f0..1c67a0cd25 100644
--- a/apps/builder/app/shared/data-variables.ts
+++ b/apps/builder/app/shared/data-variables.ts
@@ -29,6 +29,57 @@ import {
import { setUnion } from "./shim";
const allowedJsChars = /[A-Za-z_]/;
+const compiledExpressionCacheLimit = 10_000;
+type CompiledExpression = (variables: {
+ get: (key: DataSource["name"]) => unknown;
+ // Dynamic expressions intentionally preserve the historical `any` result.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+}) => any;
+
+const compiledExpressionCache = new Map<string, CompiledExpression>();
+
+const getCompiledExpression = (expression: string) => {
+ const cached = compiledExpressionCache.get(expression);
+ if (cached) {
+ return cached;
+ }
+
+ const usedVariables = new Map<string, DataSource["name"]>();
+ const transpiled = transpileExpression({
+ expression,
+ executable: true,
+ replaceVariable: (identifier) => {
+ const id = decodeDataVariableId(identifier);
+ if (id) {
+ usedVariables.set(identifier, id);
+ } else {
+ // access all variable values from specified map
+ const name = decodeDataVariableName(identifier);
+ usedVariables.set(identifier, name);
+ }
+ },
+ });
+ let code = "";
+ // add only used variables in expression and get values
+ // from variables map without additional serializing of these values
+ for (const [identifier, name] of usedVariables) {
+ code += `let ${identifier} = _variables.get(${JSON.stringify(name)});\n`;
+ }
+ code += `return (${transpiled})`;
+
+ const compiledExpression = new Function(
+ "_variables",
+ code
+ ) as CompiledExpression;
+ compiledExpressionCache.set(expression, compiledExpression);
+ if (compiledExpressionCache.size > compiledExpressionCacheLimit) {
+ const oldestExpression = compiledExpressionCache.keys().next().value;
+ if (oldestExpression !== undefined) {
+ compiledExpressionCache.delete(oldestExpression);
+ }
+ }
+ return compiledExpression;
+};
/**
* variable names can contain any characters and
@@ -139,29 +190,6 @@ export const computeExpression = (
variables: Map<DataSource["name"], unknown>
) => {
try {
- const usedVariables = new Map();
- const transpiled = transpileExpression({
- expression,
- executable: true,
- replaceVariable: (identifier) => {
- const id = decodeDataVariableId(identifier);
- if (id) {
- usedVariables.set(identifier, id);
- } else {
- // access all variable values from specified map
- const name = decodeDataVariableName(identifier);
- usedVariables.set(identifier, name);
- }
- },
- });
- let code = "";
- // add only used variables in expression and get values
- // from variables map without additional serializing of these values
- for (const [identifier, name] of usedVariables) {
- code += `let ${identifier} = _variables.get(${JSON.stringify(name)});\n`;
- }
- code += `return (${transpiled})`;
-
/**
*
* We are using structuredClone on frozen values because, for some reason,
@@ -193,18 +221,22 @@ export const computeExpression = (
*
* ```
*/
- const proxiedVariables = new Map(
- [...variables.entries()].map(([key, value]) => [
- key,
- isPlainObject(value)
- ? createJsonStringifyProxy(
- Object.isFrozen(value) ? structuredClone(value) : value
- )
- : value,
- ])
- );
+ const proxiedVariables = new Map<DataSource["name"], unknown>();
+ const getVariable = (key: DataSource["name"]) => {
+ if (proxiedVariables.has(key)) {
+ return proxiedVariables.get(key);
+ }
+ const value = variables.get(key);
+ const proxiedValue = isPlainObject(value)
+ ? createJsonStringifyProxy(
+ Object.isFrozen(value) ? structuredClone(value) : value
+ )
+ : value;
+ proxiedVariables.set(key, proxiedValue);
+ return proxiedValue;
+ };
- const result = new Function("_variables", code)(proxiedVariables);
+ const result = getCompiledExpression(expression)({ get: getVariable });
return result;
} catch (error) {
console.error(error);
@@ -227,16 +259,33 @@ const getParentInstanceById = (instances: Instances) => {
return parentInstanceById;
};
+const getDataSourcesByScopeInstanceId = (dataSources: DataSources) => {
+ const dataSourcesByScopeInstanceId = new Map<
+ Instance["id"],
+ Array<DataSource>
+ >();
+ for (const dataSource of dataSources.values()) {
+ const instanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;
+ const dataSourcesByScope =
+ dataSourcesByScopeInstanceId.get(instanceId) ?? [];
+ dataSourcesByScope.push(dataSource);
+ dataSourcesByScopeInstanceId.set(instanceId, dataSourcesByScope);
+ }
+ return dataSourcesByScopeInstanceId;
+};
+
const findMaskedVariablesByInstanceId = ({
startingInstanceId,
parentInstanceById,
instances,
dataSources,
+ dataSourcesByScopeInstanceId = getDataSourcesByScopeInstanceId(dataSources),
}: {
startingInstanceId: Instance["id"];
parentInstanceById: Map<Instance["id"], Instance["id"]>;
instances: Instances;
dataSources: DataSources;
+ dataSourcesByScopeInstanceId?: Map<Instance["id"], Array<DataSource>>;
}) => {
let currentId: undefined | string = startingInstanceId;
const instanceIdsPath: Instance["id"][] = [];
@@ -253,20 +302,22 @@ const findMaskedVariablesByInstanceId = ({
// so child variables override parent variables
for (const instanceId of instanceIdsPath.reverse()) {
const instance = instances.get(instanceId);
- for (const dataSource of dataSources.values()) {
- if (dataSource.scopeInstanceId === instanceId) {
- // when current instance is collection
- // ignore its collection item parameter
- // when rebind variables
- if (
- instanceId === startingInstanceId &&
- instance?.component === collectionComponent &&
- dataSource.type === "parameter"
- ) {
- continue;
- }
- maskedVariables.set(dataSource.name, dataSource.id);
+ const scopedDataSources = dataSourcesByScopeInstanceId.get(instanceId);
+ if (scopedDataSources === undefined) {
+ continue;
+ }
+ for (const dataSource of scopedDataSources) {
+ // when current instance is collection
+ // ignore its collection item parameter
+ // when rebind variables
+ if (
+ instanceId === startingInstanceId &&
+ instance?.component === collectionComponent &&
+ dataSource.type === "parameter"
+ ) {
+ continue;
}
+ maskedVariables.set(dataSource.name, dataSource.id);
}
}
return maskedVariables;
@@ -286,6 +337,7 @@ export const findAvailableVariables = ({
parentInstanceById: getParentInstanceById(instances),
instances,
dataSources,
+ dataSourcesByScopeInstanceId: getDataSourcesByScopeInstanceId(dataSources),
});
const availableVariables: DataSource[] = [];
for (const dataSourceId of maskedVariables.values()) {
@@ -412,7 +464,7 @@ const traverseExpressions = ({
}
for (const dataSource of dataSources.values()) {
- const instanceId = dataSource.scopeInstanceId ?? "";
+ const instanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;
if (instanceIds.has(instanceId) && dataSource.type === "resource") {
instanceIdByResourceId.set(dataSource.resourceId, instanceId);
}
@@ -573,6 +625,8 @@ export const rebindTreeVariablesMutable = ({
}
// precompute parent instances outside of traverse
const parentInstanceById = getParentInstanceById(instances);
+ const dataSourcesByScopeInstanceId =
+ getDataSourcesByScopeInstanceId(dataSources);
traverseExpressions({
startingInstanceId,
pages,
@@ -587,10 +641,10 @@ export const rebindTreeVariablesMutable = ({
parentInstanceById,
instances,
dataSources,
+ dataSourcesByScopeInstanceId,
});
- let maskedIdByName = new Map(maskedVariables);
+ const maskedIdByName = new Map(maskedVariables);
if (args) {
- maskedIdByName = new Map(maskedIdByName);
for (const arg of args) {
maskedIdByName.delete(arg);
}
@@ -622,12 +676,15 @@ export const deleteVariableMutable = (
}
const unsetNameById = new Map<DataSource["id"], DataSource["name"]>();
unsetNameById.set(dataSource.id, dataSource.name);
- const startingInstanceId = dataSource.scopeInstanceId ?? "";
+ const startingInstanceId = dataSource.scopeInstanceId ?? ROOT_INSTANCE_ID;
const maskedIdByName = findMaskedVariablesByInstanceId({
startingInstanceId,
parentInstanceById: getParentInstanceById(data.instances),
instances: data.instances,
dataSources: data.dataSources,
+ dataSourcesByScopeInstanceId: getDataSourcesByScopeInstanceId(
+ data.dataSources
+ ),
});
// unset deleted variable in expressions
traverseExpressions({
diff --git a/apps/builder/app/shared/instance-utils/data.test.tsx b/apps/builder/app/shared/instance-utils/data.test.tsx
index 46d0727779..b346b6f016 100644
--- a/apps/builder/app/shared/instance-utils/data.test.tsx
+++ b/apps/builder/app/shared/instance-utils/data.test.tsx
@@ -7,6 +7,7 @@ import {
canDeleteInstanceInContentMode,
getWebstudioData,
unwrap,
+ updateInstanceData,
updateWebstudioData,
} from "./data";
import { registerContainers } from "../sync/sync-stores";
@@ -136,6 +137,42 @@ describe("data store helpers", () => {
);
});
+ test("updateInstanceData mutates only instance-related stores", () => {
+ const pages = createDefaultPages({ rootInstanceId: "body" });
+ const assets = new Map();
+ $pages.set(pages);
+ $instances.set(new Map());
+ $props.set(new Map());
+ $breakpoints.set(new Map());
+ $styleSourceSelections.set(new Map());
+ $styleSources.set(new Map());
+ $styles.set(new Map());
+ $dataSources.set(new Map());
+ $resources.set(new Map());
+ $assets.set(assets);
+
+ updateInstanceData((data) => {
+ data.instances.set("body", createInstance("body", "Body", []));
+ data.props.set("prop", {
+ id: "prop",
+ instanceId: "body",
+ name: "id",
+ type: "string",
+ value: "main",
+ });
+ });
+
+ expect($instances.get().get("body")).toEqual(
+ createInstance("body", "Body", [])
+ );
+ expect($props.get().get("prop")).toMatchObject({
+ instanceId: "body",
+ value: "main",
+ });
+ expect($pages.get()).toBe(pages);
+ expect($assets.get()).toBe(assets);
+ });
+
test("updateWebstudioData skips page templates without build access", () => {
const pages = createDefaultPages({ rootInstanceId: "body" });
const template: PageTemplate = {
@@ -162,6 +199,38 @@ describe("data store helpers", () => {
expect($instances.get().has("template-root")).toBe(false);
});
+ test("updateInstanceData skips page templates without build access", () => {
+ const pages = createDefaultPages({ rootInstanceId: "body" });
+ const template: PageTemplate = {
+ id: "template",
+ name: "Template",
+ title: "Template",
+ rootInstanceId: "template-root",
+ meta: {},
+ };
+ pages.pageTemplates = new Map([[template.id, template]]);
+ $pages.set(pages);
+ $selectedPageId.set(template.id);
+ $builderMode.set("design");
+ $authPermit.set("view");
+ $instances.set(new Map());
+ $props.set(new Map());
+ $styleSourceSelections.set(new Map());
+ $styleSources.set(new Map());
+ $styles.set(new Map());
+ $dataSources.set(new Map());
+ $resources.set(new Map());
+
+ updateInstanceData((data) => {
+ data.instances.set(
+ "template-root",
+ createInstance("template-root", "Body", [])
+ );
+ });
+
+ expect($instances.get().has("template-root")).toBe(false);
+ });
+
test("updateWebstudioData repairs cycles created during transaction", () => {
const pages = createDefaultPages({ rootInstanceId: "body" });
const instances = new Map([
diff --git a/apps/builder/app/shared/instance-utils/data.ts b/apps/builder/app/shared/instance-utils/data.ts
index 1d1a139fd3..d74ab17d9e 100644
--- a/apps/builder/app/shared/instance-utils/data.ts
+++ b/apps/builder/app/shared/instance-utils/data.ts
@@ -27,6 +27,17 @@ import {
} from "../sync/data-stores";
import type { InstanceSelector } from "./tree";
+export type WebstudioInstanceData = Pick<
+ WebstudioData,
+ | "instances"
+ | "props"
+ | "styleSourceSelections"
+ | "styleSources"
+ | "styles"
+ | "dataSources"
+ | "resources"
+>;
+
/**
* structuredClone can be invoked on draft and throw error
* extract current snapshot before cloning
@@ -57,7 +68,10 @@ export const canDeleteInstanceInContentMode = ({
);
};
-export const updateWebstudioData = (mutate: (data: WebstudioData) => void) => {
+export const updateWebstudioData = (
+ mutate: (data: WebstudioData) => void,
+ { validateInstances = true }: { validateInstances?: boolean } = {}
+) => {
const selectedPage = $selectedPage.get();
if (isPageTemplate(selectedPage) && $canOpenPageTemplates.get() === false) {
return;
@@ -104,6 +118,10 @@ export const updateWebstudioData = (mutate: (data: WebstudioData) => void) => {
assets,
});
+ if (validateInstances === false) {
+ return;
+ }
+
const cycles = findCycles(instances.values());
// Detect and fix cycles in the instance tree, then report
@@ -119,6 +137,45 @@ export const updateWebstudioData = (mutate: (data: WebstudioData) => void) => {
);
};
+export const updateInstanceData = (
+ mutate: (data: WebstudioInstanceData) => void
+) => {
+ const selectedPage = $selectedPage.get();
+ if (isPageTemplate(selectedPage) && $canOpenPageTemplates.get() === false) {
+ return;
+ }
+ serverSyncStore.createTransaction(
+ [
+ $instances,
+ $props,
+ $styleSourceSelections,
+ $styleSources,
+ $styles,
+ $dataSources,
+ $resources,
+ ],
+ (
+ instances,
+ props,
+ styleSourceSelections,
+ styleSources,
+ styles,
+ dataSources,
+ resources
+ ) => {
+ mutate({
+ instances,
+ props,
+ styleSourceSelections,
+ styleSources,
+ styles,
+ dataSources,
+ resources,
+ });
+ }
+ );
+};
+
export const getWebstudioData = (): WebstudioData => {
const pages = $pages.get();
if (pages === undefined) {
diff --git a/apps/builder/app/shared/instance-utils/lookup.ts b/apps/builder/app/shared/instance-utils/lookup.ts
index ae19cd63f6..09bc757664 100644
--- a/apps/builder/app/shared/instance-utils/lookup.ts
+++ b/apps/builder/app/shared/instance-utils/lookup.ts
@@ -97,12 +97,14 @@ export const findAllEditableInstanceSelector = ({
instances,
props,
metas,
+ htmlTagsByInstanceId,
results,
}: {
instanceSelector: InstanceSelector;
instances: Instances;
props: Props;
metas: Map<string, WsComponentMeta>;
+ htmlTagsByInstanceId?: Map<Instance["id"], string>;
results: InstanceSelector[];
}) => {
const [instanceId] = instanceSelector;
@@ -111,7 +113,15 @@ export const findAllEditableInstanceSelector = ({
return;
}
- if (isRichTextTree({ instanceId, instances, props, metas })) {
+ if (
+ isRichTextTree({
+ instanceId,
+ instances,
+ props,
+ metas,
+ htmlTagsByInstanceId,
+ })
+ ) {
results.push(instanceSelector);
return;
}
@@ -125,6 +135,7 @@ export const findAllEditableInstanceSelector = ({
instances,
props,
metas,
+ htmlTagsByInstanceId,
results,
});
}
diff --git a/apps/builder/app/shared/instance-utils/mutation.ts b/apps/builder/app/shared/instance-utils/mutation.ts
index deaeab0133..de9e3ae5f2 100644
--- a/apps/builder/app/shared/instance-utils/mutation.ts
+++ b/apps/builder/app/shared/instance-utils/mutation.ts
@@ -58,7 +58,12 @@ import {
findLocalStyleSourcesWithinInstances,
getReparentDropTargetMutable,
} from "./tree";
-import { canDeleteInstanceInContentMode, updateWebstudioData } from "./data";
+import {
+ canDeleteInstanceInContentMode,
+ updateInstanceData,
+ updateWebstudioData,
+ type WebstudioInstanceData,
+} from "./data";
import {
extractWebstudioFragment,
insertWebstudioFragmentCopy,
@@ -155,14 +160,17 @@ export const reparentInstance = (
sourceInstanceSelector: InstanceSelector,
dropTarget: DroppableTarget
) => {
- updateWebstudioData((data) => {
- const newSelector = reparentInstanceMutable(
- data,
- sourceInstanceSelector,
- dropTarget
- );
- selectInstance(newSelector);
- });
+ updateWebstudioData(
+ (data) => {
+ const newSelector = reparentInstanceMutable(
+ data,
+ sourceInstanceSelector,
+ dropTarget
+ );
+ selectInstance(newSelector);
+ },
+ { validateInstances: false }
+ );
};
const countInstanceChildReferences = (
@@ -335,7 +343,7 @@ const getDeleteTarget = (
};
export const deleteInstanceMutable = (
- data: Omit<WebstudioData, "pages">,
+ data: WebstudioInstanceData,
instancePath: undefined | InstancePath
) => {
if (instancePath === undefined) {
@@ -1112,7 +1120,7 @@ export const deleteSelectedInstance = () => {
}
}
- updateWebstudioData((data) => {
+ updateInstanceData((data) => {
const normalizedInstancePath = normalizeLegacySlotInstancePathMutable(
data.instances,
instancePath
diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.ts
index d421ff7f27..befc374539 100644
--- a/apps/builder/app/shared/nano-states/misc.ts
+++ b/apps/builder/app/shared/nano-states/misc.ts
@@ -47,6 +47,7 @@ export const $memoryProps = atom<Map<string, Props>>(new Map());
export const $propsIndex = computed($props, (props) => {
const propsByInstanceId = new Map<Instance["id"], Prop[]>();
+ const htmlTagsByInstanceId = new Map<Instance["id"], string>();
for (const prop of props.values()) {
const { instanceId } = prop;
let instanceProps = propsByInstanceId.get(instanceId);
@@ -55,9 +56,13 @@ export const $propsIndex = computed($props, (props) => {
propsByInstanceId.set(instanceId, instanceProps);
}
instanceProps.push(prop);
+ if (prop.type === "string" && prop.name === "tag") {
+ htmlTagsByInstanceId.set(instanceId, prop.value);
+ }
}
return {
propsByInstanceId,
+ htmlTagsByInstanceId,
};
});
diff --git a/apps/builder/app/shared/sync/patch/patch-auth.server.test.ts b/apps/builder/app/shared/sync/patch/patch-auth.server.test.ts
index ffcd6efcca..f1b33bfc8a 100644
--- a/apps/builder/app/shared/sync/patch/patch-auth.server.test.ts
+++ b/apps/builder/app/shared/sync/patch/patch-auth.server.test.ts
@@ -182,7 +182,7 @@ describe("authorizePatchEntries", () => {
applyContentModeTransaction.mockClear();
});
- test("checks every transaction with its own writer and required permit", async () => {
+ test("skips content-mode capabilities for writers with build permit", async () => {
readAccessToken
.mockResolvedValueOnce({ userId: "user-1", projectId: "project-1" })
.mockResolvedValueOnce({ userId: "user-2", projectId: "project-1" });
@@ -204,12 +204,8 @@ describe("authorizePatchEntries", () => {
],
};
- const contentModeCapabilities = createContentModeCapabilities(buildRow);
-
- const result = await authorizePatchEntries(
- context as never,
- patch,
- contentModeCapabilities
+ const result = await authorizePatchEntries(context as never, patch, () =>
+ createContentModeCapabilities(buildRow)
);
expect(result.rejected).toEqual([]);
@@ -217,17 +213,64 @@ describe("authorizePatchEntries", () => {
type: "user",
userId: "user-1",
});
- expect(getContentModeCapabilities).toHaveBeenCalledWith(
+ expect(result.authorized[1].context.authorization).toMatchObject({
+ type: "user",
+ userId: "user-2",
+ });
+ expect(getContentModeCapabilities).not.toHaveBeenCalled();
+ expect(applyContentModeTransaction).not.toHaveBeenCalled();
+ expect(hasProjectPermit).toHaveBeenCalledTimes(2);
+ expect(hasProjectPermit).toHaveBeenNthCalledWith(
+ 1,
+ { projectId: "project-1", permit: "build" },
expect.objectContaining({
- instances: expect.any(Map),
- metas: expect.any(Map),
- props: expect.any(Map),
- styleSources: expect.any(Map),
- styleSourceSelections: expect.any(Map),
- styles: expect.any(Map),
- breakpoints: expect.any(Map),
+ authorization: expect.objectContaining({ userId: "user-1" }),
+ })
+ );
+ expect(hasProjectPermit).toHaveBeenNthCalledWith(
+ 2,
+ { projectId: "project-1", permit: "build" },
+ expect.objectContaining({
+ authorization: expect.objectContaining({ userId: "user-2" }),
})
);
+ });
+
+ test("falls back to content-mode permissions without build permit", async () => {
+ readAccessToken
+ .mockResolvedValueOnce({ userId: "user-1", projectId: "project-1" })
+ .mockResolvedValueOnce({ userId: "user-2", projectId: "project-1" });
+ hasProjectPermit
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(true);
+
+ const patch: NormalizedPatchRequest = {
+ buildId: "build-1",
+ projectId: "project-1",
+ clientVersion: 1,
+ entries: [
+ {
+ transaction: transaction("props", "tx-edit") as never,
+ writer: { type: "token", authToken: "token-1" },
+ },
+ {
+ transaction: transaction("styles", "tx-build") as never,
+ writer: { type: "token", authToken: "token-2" },
+ },
+ ],
+ };
+
+ const result = await authorizePatchEntries(
+ createContext() as never,
+ patch,
+ () => createContentModeCapabilities(buildRow)
+ );
+
+ expect(result.rejected).toEqual([]);
+ expect(result.authorized).toHaveLength(2);
+ expect(getContentModeCapabilities).toHaveBeenCalledTimes(1);
+ expect(applyContentModeTransaction).toHaveBeenCalledTimes(2);
expect(applyContentModeTransaction).toHaveBeenNthCalledWith(
1,
expect.objectContaining({
@@ -254,28 +297,31 @@ describe("authorizePatchEntries", () => {
}),
})
);
- expect(hasProjectPermit).toHaveBeenCalledTimes(2);
expect(hasProjectPermit).toHaveBeenNthCalledWith(
1,
- { projectId: "project-1", permit: "edit" },
- expect.objectContaining({
- authorization: expect.objectContaining({ userId: "user-1" }),
- })
+ { projectId: "project-1", permit: "build" },
+ expect.anything()
);
expect(hasProjectPermit).toHaveBeenNthCalledWith(
2,
{ projectId: "project-1", permit: "build" },
- expect.objectContaining({
- authorization: expect.objectContaining({ userId: "user-2" }),
- })
+ expect.anything()
+ );
+ expect(hasProjectPermit).toHaveBeenNthCalledWith(
+ 3,
+ { projectId: "project-1", permit: "edit" },
+ expect.anything()
);
});
- test("does not require build permit after an authorized build-only transaction", async () => {
+ test("advances capabilities for build-permit entries in mixed batches", async () => {
readAccessToken
.mockResolvedValueOnce({ userId: "user-1", projectId: "project-1" })
.mockResolvedValueOnce({ userId: "user-2", projectId: "project-1" });
- hasProjectPermit.mockResolvedValue(true);
+ hasProjectPermit
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true);
const patch: NormalizedPatchRequest = {
buildId: "build-1",
@@ -283,7 +329,7 @@ describe("authorizePatchEntries", () => {
clientVersion: 1,
entries: [
{
- transaction: transaction("styles", "tx-build") as never,
+ transaction: transaction("props", "tx-build") as never,
writer: { type: "token", authToken: "token-1" },
},
{
@@ -296,22 +342,20 @@ describe("authorizePatchEntries", () => {
const result = await authorizePatchEntries(
createContext() as never,
patch,
- createContentModeCapabilities(buildRow)
+ () => createContentModeCapabilities(buildRow)
);
expect(result.rejected).toEqual([]);
expect(result.authorized).toHaveLength(2);
+ expect(getContentModeCapabilities).toHaveBeenCalledTimes(1);
expect(applyContentModeTransaction).toHaveBeenCalledTimes(2);
- expect(applyContentModeTransaction).toHaveBeenNthCalledWith(
- 1,
- expect.objectContaining({
- transaction: patch.entries[0].transaction,
- })
- );
expect(applyContentModeTransaction).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
transaction: patch.entries[1].transaction,
+ capabilities: expect.objectContaining({
+ appliedTransactionId: patch.entries[0].transaction.id,
+ }),
})
);
expect(hasProjectPermit).toHaveBeenNthCalledWith(
@@ -321,12 +365,85 @@ describe("authorizePatchEntries", () => {
);
expect(hasProjectPermit).toHaveBeenNthCalledWith(
2,
+ { projectId: "project-1", permit: "build" },
+ expect.anything()
+ );
+ expect(hasProjectPermit).toHaveBeenNthCalledWith(
+ 3,
{ projectId: "project-1", permit: "edit" },
expect.anything()
);
});
- test("does not require build permit after a rejected build-only transaction", async () => {
+ test("creates content-mode capabilities once for multiple content-mode entries", async () => {
+ readAccessToken
+ .mockResolvedValueOnce({ userId: "user-1", projectId: "project-1" })
+ .mockResolvedValueOnce({ userId: "user-2", projectId: "project-1" });
+ hasProjectPermit
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(false)
+ .mockResolvedValueOnce(true)
+ .mockResolvedValueOnce(true);
+ const getInitialContentModeCapabilities = vi.fn(() =>
+ createContentModeCapabilities(buildRow)
+ );
+
+ const patch: NormalizedPatchRequest = {
+ buildId: "build-1",
+ projectId: "project-1",
+ clientVersion: 1,
+ entries: [
+ {
+ transaction: transaction("props", "tx-edit-1") as never,
+ writer: { type: "token", authToken: "token-1" },
+ },
+ {
+ transaction: transaction("props", "tx-edit-2") as never,
+ writer: { type: "token", authToken: "token-2" },
+ },
+ ],
+ };
+
+ const result = await authorizePatchEntries(
+ createContext() as never,
+ patch,
+ getInitialContentModeCapabilities
+ );
+
+ expect(result.rejected).toEqual([]);
+ expect(result.authorized).toHaveLength(2);
+ expect(getInitialContentModeCapabilities).toHaveBeenCalledTimes(1);
+ expect(getContentModeCapabilities).toHaveBeenCalledTimes(1);
+ expect(applyContentModeTransaction).toHaveBeenCalledTimes(2);
+ expect(applyContentModeTransaction).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ transaction: patch.entries[0].transaction,
+ capabilities: expect.objectContaining({
+ editablePropIds: expect.any(Set),
+ instances: expect.any(Map),
+ metas: expect.any(Map),
+ props: expect.any(Map),
+ styleSources: expect.any(Map),
+ styleSourceSelections: expect.any(Map),
+ styles: expect.any(Map),
+ breakpoints: expect.any(Map),
+ contentRootIds: expect.any(Set),
+ }),
+ })
+ );
+ expect(applyContentModeTransaction).toHaveBeenNthCalledWith(
+ 2,
+ expect.objectContaining({
+ transaction: patch.entries[1].transaction,
+ capabilities: expect.objectContaining({
+ appliedTransactionId: patch.entries[0].transaction.id,
+ }),
+ })
+ );
+ });
+
+ test("continues authorizing later build-permit entries after a rejected entry", async () => {
readAccessToken
.mockResolvedValueOnce({ userId: "user-1", projectId: "project-1" })
.mockResolvedValueOnce({ userId: "user-2", projectId: "project-1" });
@@ -351,7 +468,7 @@ describe("authorizePatchEntries", () => {
const result = await authorizePatchEntries(
createContext() as never,
patch,
- createContentModeCapabilities(buildRow)
+ () => createContentModeCapabilities(buildRow)
);
expect(result.rejected).toEqual([
@@ -366,6 +483,12 @@ describe("authorizePatchEntries", () => {
}),
]);
expect(applyContentModeTransaction).toHaveBeenCalledTimes(2);
+ expect(applyContentModeTransaction).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ transaction: patch.entries[0].transaction,
+ })
+ );
expect(applyContentModeTransaction).toHaveBeenNthCalledWith(
2,
expect.objectContaining({
@@ -379,7 +502,7 @@ describe("authorizePatchEntries", () => {
);
expect(hasProjectPermit).toHaveBeenNthCalledWith(
2,
- { projectId: "project-1", permit: "edit" },
+ { projectId: "project-1", permit: "build" },
expect.anything()
);
});
@@ -404,7 +527,7 @@ describe("authorizePatchEntries", () => {
},
],
},
- createContentModeCapabilities(buildRow)
+ () => createContentModeCapabilities(buildRow)
);
expect(result.authorized).toEqual([]);
diff --git a/apps/builder/app/shared/sync/patch/patch-auth.server.ts b/apps/builder/app/shared/sync/patch/patch-auth.server.ts
index f743197117..a03c670936 100644
--- a/apps/builder/app/shared/sync/patch/patch-auth.server.ts
+++ b/apps/builder/app/shared/sync/patch/patch-auth.server.ts
@@ -45,11 +45,21 @@ export type AuthorizedPatchEntry = {
context: AppContext;
};
-export type RejectedPatchEntry = {
+type RejectedPatchEntry = {
entry: PatchEntry;
errors: string;
};
+type PatchEntryWithContext = {
+ entry: PatchEntry;
+ context: AppContext;
+ hasBuildPermit: boolean;
+};
+
+type GetInitialContentModeCapabilities = () =>
+ | ReturnType<typeof createContentModeCapabilities>
+ | Promise<ReturnType<typeof createContentModeCapabilities>>;
+
export const createWriterContext = async (
context: AppContext,
authToken: string
@@ -110,6 +120,18 @@ export const assertProjectPermit = async ({
}
};
+const hasProjectPermit = async ({
+ context,
+ permit,
+ projectId,
+}: {
+ context: AppContext;
+ permit: AuthPermit;
+ projectId: string;
+}) => {
+ return authorizeProject.hasProjectPermit({ projectId, permit }, context);
+};
+
export const createContentModeCapabilities = (build: {
instances: string;
props: string;
@@ -134,22 +156,70 @@ export const createContentModeCapabilities = (build: {
export const authorizePatchEntries = async (
context: AppContext,
patch: NormalizedPatchRequest,
- contentModeCapabilities: ReturnType<typeof createContentModeCapabilities>
+ getInitialContentModeCapabilities: GetInitialContentModeCapabilities
) => {
- let capabilities = contentModeCapabilities;
+ const entriesWithContext: PatchEntryWithContext[] = [];
const authorized: AuthorizedPatchEntry[] = [];
const rejected: RejectedPatchEntry[] = [];
for (const entry of patch.entries) {
try {
const writerContext = await resolveEntryWriterContext(context, entry);
+ const hasBuildPermit = await hasProjectPermit({
+ context: writerContext,
+ permit: "build",
+ projectId: patch.projectId,
+ });
+ entriesWithContext.push({
+ entry,
+ context: writerContext,
+ hasBuildPermit,
+ });
+ } catch (error) {
+ if (error instanceof AuthorizationError) {
+ rejected.push({ entry, errors: error.message });
+ continue;
+ }
+ throw error;
+ }
+ }
+
+ if (entriesWithContext.every(({ hasBuildPermit }) => hasBuildPermit)) {
+ authorized.push(
+ ...entriesWithContext.map(({ entry, context }) => ({ entry, context }))
+ );
+ if (authorized.length === 0 && rejected.length === 0) {
+ throw new Error("Transaction entries required");
+ }
+ return { authorized, rejected };
+ }
+
+ let capabilities = await getInitialContentModeCapabilities();
+ for (const {
+ entry,
+ context: writerContext,
+ hasBuildPermit,
+ } of entriesWithContext) {
+ try {
const contentModeResult = applyContentModeTransaction({
capabilities,
transaction: entry.transaction,
});
+ if (hasBuildPermit) {
+ if (contentModeResult?.success) {
+ capabilities = contentModeResult.capabilities;
+ }
+ authorized.push({ entry, context: writerContext });
+ continue;
+ }
+ if (contentModeResult?.success !== true) {
+ throw new AuthorizationError(
+ "You don't have permission to build this project."
+ );
+ }
await assertProjectPermit({
context: writerContext,
- permit: contentModeResult?.success ? "edit" : "build",
+ permit: "edit",
projectId: patch.projectId,
});
if (contentModeResult?.success) {
diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.test.ts b/apps/builder/app/shared/sync/patch/patch-service.server.test.ts
index 4a1c9f98ec..f86206c3a8 100644
--- a/apps/builder/app/shared/sync/patch/patch-service.server.test.ts
+++ b/apps/builder/app/shared/sync/patch/patch-service.server.test.ts
@@ -21,11 +21,13 @@ import {
applyPatchRequest,
loadAuthorizedPatchState,
} from "./patch-service.server";
+import type { AppContext } from "@webstudio-is/trpc-interface/index.server";
import type { NormalizedPatchRequest } from "./patch-normalize.server";
const buildRow = {
projectId: "project-1",
version: 3,
+ lastTransactionId: null,
instances: JSON.stringify([]),
props: JSON.stringify([]),
styleSources: JSON.stringify([]),
@@ -34,35 +36,40 @@ const buildRow = {
breakpoints: JSON.stringify([]),
};
-const createContext = () =>
- ({
+const createContext = () => {
+ const selectedColumns: string[] = [];
+ const context = {
postgrest: {
client: {
from: () => ({
select: (columns: string) => ({
+ selectedColumns,
eq: () => {
- if (columns === "*") {
- return Promise.resolve({
- data: [buildRow],
- error: undefined,
- });
- }
- return {
+ selectedColumns.push(columns);
+ const result = Promise.resolve({
+ data: [buildRow],
+ error: undefined,
+ });
+ return Object.assign(result, {
single: async () => ({
data: buildRow,
error: undefined,
}),
- };
+ });
},
}),
}),
},
},
- }) as never;
+ };
+ return Object.assign(context, {
+ selectedColumns,
+ }) as unknown as AppContext & { selectedColumns: string[] };
+};
-const transaction = (id: string) => ({
+const transaction = (id: string, namespace = "props") => ({
id,
- payload: [{ namespace: "props", patches: [] }],
+ payload: [{ namespace, patches: [] }],
});
const patch: NormalizedPatchRequest = {
@@ -106,20 +113,19 @@ describe("applyPatchRequest", () => {
build: { ...build, version: 4 },
}));
- const result = await applyPatchRequest(createContext(), patch);
+ const context = createContext();
- expect(createContentModeCapabilities).toHaveBeenCalledWith({
- breakpoints: JSON.stringify([]),
- instances: JSON.stringify([]),
- props: JSON.stringify([]),
- styleSourceSelections: JSON.stringify([]),
- styleSources: JSON.stringify([]),
- styles: JSON.stringify([]),
- });
+ const result = await applyPatchRequest(context, patch);
+
+ expect(createContentModeCapabilities).not.toHaveBeenCalled();
+ expect(context.selectedColumns).toEqual([
+ "projectId, version",
+ "projectId, version, lastTransactionId, props",
+ ]);
expect(authorizePatchEntries).toHaveBeenCalledWith(
expect.anything(),
patch,
- { capabilities: true }
+ expect.any(Function)
);
expect(patchLoadedBuild).toHaveBeenCalledWith(
expect.objectContaining({
@@ -143,6 +149,121 @@ describe("applyPatchRequest", () => {
});
});
+ test("loads content-mode capability columns only when authorization requests them", async () => {
+ authorizePatchEntries.mockImplementation(
+ async (_context, _patch, getInitialContentModeCapabilities) => {
+ await getInitialContentModeCapabilities();
+ return {
+ authorized: [{ entry: patch.entries[0], context: { writer: 1 } }],
+ rejected: [],
+ };
+ }
+ );
+ patchLoadedBuild.mockImplementation(async ({ build }) => ({
+ status: "ok",
+ version: 4,
+ build: { ...build, version: 4 },
+ }));
+ const context = createContext();
+
+ const result = await applyPatchRequest(context, patch);
+
+ expect(createContentModeCapabilities).toHaveBeenCalledWith({
+ breakpoints: JSON.stringify([]),
+ instances: JSON.stringify([]),
+ props: JSON.stringify([]),
+ styleSourceSelections: JSON.stringify([]),
+ styleSources: JSON.stringify([]),
+ styles: JSON.stringify([]),
+ });
+ expect(context.selectedColumns).toEqual([
+ "projectId, version",
+ "instances, props, styleSources, styleSourceSelections, styles, breakpoints",
+ "projectId, version, lastTransactionId, props",
+ ]);
+ expect(result).toEqual({
+ status: "ok",
+ version: 4,
+ entries: [{ seq: 1, transactionId: "tx-1", status: "accepted" }],
+ });
+ });
+
+ test("does not load patch columns or persist when every entry is rejected", async () => {
+ authorizePatchEntries.mockResolvedValue({
+ authorized: [],
+ rejected: [
+ {
+ entry: patch.entries[0],
+ errors: "You don't have permission to edit this project.",
+ },
+ ],
+ });
+ const context = createContext();
+
+ const result = await applyPatchRequest(context, patch);
+
+ expect(context.selectedColumns).toEqual(["projectId, version"]);
+ expect(patchLoadedBuild).not.toHaveBeenCalled();
+ expect(result).toEqual({
+ status: "partial",
+ version: 3,
+ entries: [
+ {
+ seq: 1,
+ transactionId: "tx-1",
+ status: "rejected",
+ errors: "You don't have permission to edit this project.",
+ },
+ ],
+ });
+ });
+
+ test("loads only base patch columns for asset-only patches", async () => {
+ const assetsPatch: NormalizedPatchRequest = {
+ ...patch,
+ entries: [
+ {
+ seq: 1,
+ transaction: transaction("tx-assets", "assets") as never,
+ writer: { type: "token", authToken: "token-1" },
+ },
+ ],
+ };
+ authorizePatchEntries.mockResolvedValue({
+ authorized: [{ entry: assetsPatch.entries[0], context: { writer: 1 } }],
+ rejected: [],
+ });
+ patchLoadedBuild.mockImplementation(async ({ build }) => ({
+ status: "ok",
+ version: 4,
+ build: { ...build, version: 4 },
+ }));
+ const context = createContext();
+
+ const result = await applyPatchRequest(context, assetsPatch);
+
+ expect(context.selectedColumns).toEqual([
+ "projectId, version",
+ "projectId, version, lastTransactionId",
+ ]);
+ expect(patchLoadedBuild).toHaveBeenCalledWith(
+ expect.objectContaining({
+ build: expect.objectContaining({
+ projectId: "project-1",
+ version: 3,
+ lastTransactionId: null,
+ }),
+ transactions: [assetsPatch.entries[0].transaction],
+ }),
+ { writer: 1 }
+ );
+ expect(result).toEqual({
+ status: "ok",
+ version: 4,
+ entries: [{ seq: 1, transactionId: "tx-assets", status: "accepted" }],
+ });
+ });
+
test("falls back to per-entry apply when a mixed authorized batch fails", async () => {
const context = { writer: 1 };
authorizePatchEntries.mockResolvedValue({
diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.ts b/apps/builder/app/shared/sync/patch/patch-service.server.ts
index bfc9daa0b0..69ce016142 100644
--- a/apps/builder/app/shared/sync/patch/patch-service.server.ts
+++ b/apps/builder/app/shared/sync/patch/patch-service.server.ts
@@ -3,7 +3,7 @@ import {
type AppContext,
} from "@webstudio-is/trpc-interface/index.server";
import { patchLoadedBuild } from "@webstudio-is/project/index.server";
-import { loadRawBuildById } from "@webstudio-is/project-build/index.server";
+import type { Database } from "@webstudio-is/postgrest/index.server";
import {
assertProjectPermit,
authorizePatchEntries,
@@ -16,7 +16,90 @@ import type {
PatchEntry,
} from "./patch-normalize.server";
-export type PatchEntryResult =
+type BuildRow = Database["public"]["Tables"]["Build"]["Row"];
+type BuildColumn = keyof BuildRow;
+
+const baseBuildPatchColumns = [
+ "projectId",
+ "version",
+ "lastTransactionId",
+] as const satisfies BuildColumn[];
+
+const contentModeBuildColumns = [
+ "instances",
+ "props",
+ "styleSources",
+ "styleSourceSelections",
+ "styles",
+ "breakpoints",
+] as const satisfies BuildColumn[];
+
+const namespaceBuildColumns = {
+ pages: ["pages"],
+ breakpoints: ["breakpoints"],
+ instances: ["instances"],
+ props: ["props"],
+ assets: [],
+ styleSourceSelections: ["styleSourceSelections"],
+ styleSources: ["styleSources"],
+ styles: ["styles"],
+ dataSources: ["dataSources"],
+ resources: ["resources"],
+ marketplaceProduct: ["marketplaceProduct"],
+} as const satisfies Record<string, readonly BuildColumn[]>;
+
+type BuildPatchNamespace = keyof typeof namespaceBuildColumns;
+
+const isBuildPatchNamespace = (
+ namespace: string
+): namespace is BuildPatchNamespace => {
+ return Object.hasOwn(namespaceBuildColumns, namespace);
+};
+
+const getNamespaceBuildColumns = (namespace: string) => {
+ if (isBuildPatchNamespace(namespace)) {
+ return namespaceBuildColumns[namespace];
+ }
+ return [];
+};
+
+const getBuildPatchColumns = (authorized: AuthorizedPatchEntry[]) => {
+ const columns = new Set<BuildColumn>(baseBuildPatchColumns);
+ for (const { entry } of authorized) {
+ for (const change of entry.transaction.payload) {
+ for (const column of getNamespaceBuildColumns(change.namespace)) {
+ columns.add(column);
+ }
+ }
+ }
+ return Array.from(columns);
+};
+
+const selectBuildColumns = async (
+ context: AppContext,
+ buildId: string,
+ columns: readonly BuildColumn[]
+) => {
+ const build = await context.postgrest.client
+ .from("Build")
+ .select(columns.join(", "))
+ .eq("id", buildId);
+
+ if (build.error) {
+ throw build.error;
+ }
+
+ if (build.data.length !== 1) {
+ throw new Error(
+ `Results contain ${build.data.length} row(s) requires 1 row`
+ );
+ }
+
+ return build.data[0] as unknown as Partial<BuildRow> &
+ Pick<BuildRow, (typeof columns)[number]>;
+};
+
+type PatchEntryResult =
| { seq?: number; transactionId: string; status: "accepted" }
| {
seq?: number;
@@ -25,7 +108,7 @@ export type PatchEntryResult =
errors: string;
};
-export type PatchResult =
+type PatchResult =
| { status: "ok"; version?: number; entries?: PatchEntryResult[] }
| { status: "partial"; version: number; entries: PatchEntryResult[] }
| { status: "version_mismatched"; errors: string }
@@ -78,22 +161,35 @@ const loadBuildState = async (context: AppContext, buildId: string) => {
};
};
-const loadBuildPatchState = async (context: AppContext, buildId: string) => {
- const build = await loadRawBuildById(context, buildId);
+const loadBuildForContentMode = async (
+ context: AppContext,
+ buildId: string
+) => {
+ return selectBuildColumns(context, buildId, contentModeBuildColumns);
+};
+
+const loadBuildForPatch = async ({
+ authorized,
+ context,
+ state,
+ buildId,
+}: {
+ authorized: AuthorizedPatchEntry[];
+ context: AppContext;
+ state: Awaited<ReturnType<typeof loadBuildState>>;
+ buildId: string;
+}) => {
+ const build = await selectBuildColumns(
+ context,
+ buildId,
+ getBuildPatchColumns(authorized)
+ );
return {
- build,
- projectId: String(build.projectId),
- version: Number(build.version),
- contentModeCapabilities: createContentModeCapabilities({
- instances: build.instances,
- props: build.props,
- styleSources: build.styleSources,
- styleSourceSelections: build.styleSourceSelections,
- styles: build.styles,
- breakpoints: build.breakpoints,
- }),
- };
+ ...build,
+ projectId: state.projectId,
+ version: state.version,
+ } as BuildRow;
};
const assertBuildProject = (
@@ -138,11 +234,10 @@ const applyAuthorizedEntries = async ({
version,
}: {
authorized: AuthorizedPatchEntry[];
- build: Awaited<ReturnType<typeof loadBuildPatchState>>["build"];
+ build?: BuildRow;
patch: NormalizedPatchRequest;
version: number;
}) => {
- let currentBuild = build;
if (authorized.length === 0) {
return {
version,
@@ -150,6 +245,10 @@ const applyAuthorizedEntries = async ({
status: "ok" as const,
};
}
+ if (build === undefined) {
+ throw new Error("Build data is required to apply patch entries.");
+ }
+ let currentBuild = build;
const applyContext = authorized[0].context;
const hasSharedContext = authorized.every(
@@ -220,18 +319,36 @@ export const applyPatchRequest = async (
context: AppContext,
patch: NormalizedPatchRequest
): Promise<PatchResult> => {
- const state = await loadBuildPatchState(context, patch.buildId);
+ const state = await loadBuildState(context, patch.buildId);
assertBuildProject(state, patch);
const { authorized, rejected } = await authorizePatchEntries(
context,
patch,
- state.contentModeCapabilities
+ async () => {
+ const build = await loadBuildForContentMode(context, patch.buildId);
+ return createContentModeCapabilities({
+ instances: build.instances,
+ props: build.props,
+ styleSources: build.styleSources,
+ styleSourceSelections: build.styleSourceSelections,
+ styles: build.styles,
+ breakpoints: build.breakpoints,
+ });
+ }
);
const applied = await applyAuthorizedEntries({
authorized,
- build: state.build,
+ build:
+ authorized.length === 0
+ ? undefined
+ : await loadBuildForPatch({
+ authorized,
+ context,
+ state,
+ buildId: patch.buildId,
+ }),
patch,
- version: patch.clientVersion,
+ version: authorized.length === 0 ? state.version : patch.clientVersion,
});
if (applied.status === "version_mismatched") {
diff --git a/apps/builder/app/shared/sync/project-queue.test.ts b/apps/builder/app/shared/sync/project-queue.test.ts
index 232a1d9296..59ae440164 100644
--- a/apps/builder/app/shared/sync/project-queue.test.ts
+++ b/apps/builder/app/shared/sync/project-queue.test.ts
@@ -49,6 +49,7 @@ vi.mock("~/shared/builder-data", () => ({
import type { Change } from "immerhin";
import { $hasUnsavedSyncChanges, $syncStatus } from "@webstudio-is/sync-client";
import { toast } from "@webstudio-is/design-system";
+import type { ServerSyncState } from "./sync-stores";
import {
$lastTransactionId,
commandQueue,
@@ -81,6 +82,8 @@ const makeTx = (id: string) => ({
payload: [{ namespace: "ns", patches: [], revisePatches: [] }] as Change[],
});
+const initialState: ServerSyncState = new Map();
+
const createMockBackoff = (overrides: Partial<Backoff> = {}): Backoff => {
let failures = 0;
return {
@@ -485,8 +488,31 @@ describe("project-queue", () => {
// ServerSyncStorage
describe("ServerSyncStorage", () => {
+ test("subscribe seeds initial data without loading builder data again", () => {
+ const serverState: ServerSyncState = new Map([["pages", undefined]]);
+ const storage = new ServerSyncStorage("p1", serverState);
+ const setState = vi.fn();
+ mockLoadBuilderData.mockClear();
+
+ storage.subscribe(setState, new AbortController().signal);
+
+ expect(mockLoadBuilderData).not.toHaveBeenCalled();
+ expect(setState).toHaveBeenCalledWith(new Map([["server", serverState]]));
+ });
+
+ test("subscribe does nothing when aborted", () => {
+ const storage = new ServerSyncStorage("p1", initialState);
+ const controller = new AbortController();
+ const setState = vi.fn();
+ controller.abort();
+
+ storage.subscribe(setState, controller.signal);
+
+ expect(setState).not.toHaveBeenCalled();
+ });
+
test("sendTransaction enqueues only for 'server' object", () => {
- const storage = new ServerSyncStorage("p1");
+ const storage = new ServerSyncStorage("p1", initialState);
storage.sendTransaction({
id: "tx-1",
@@ -502,7 +528,7 @@ describe("project-queue", () => {
});
test("sendTransaction ignores non-server objects", () => {
- const storage = new ServerSyncStorage("p1");
+ const storage = new ServerSyncStorage("p1", initialState);
storage.sendTransaction({
id: "tx-1",
@@ -515,7 +541,7 @@ describe("project-queue", () => {
});
test("sendTransaction sets $lastTransactionId", () => {
- const storage = new ServerSyncStorage("p1");
+ const storage = new ServerSyncStorage("p1", initialState);
storage.sendTransaction({
id: "tx-42",
diff --git a/apps/builder/app/shared/sync/project-queue.ts b/apps/builder/app/shared/sync/project-queue.ts
index ce45afe074..5b86ed0464 100644
--- a/apps/builder/app/shared/sync/project-queue.ts
+++ b/apps/builder/app/shared/sync/project-queue.ts
@@ -12,12 +12,12 @@ import {
createTransactionCompletionStore,
type SyncStatus,
} from "@webstudio-is/sync-client";
-import { loadBuilderData } from "~/shared/builder-data";
import { publicStaticEnv } from "~/env/env.static";
import { createNativeClient, nativeClient } from "~/shared/trpc/trpc-client";
import * as commandQueue from "./command-queue";
import type { SyncStorage } from "~/shared/sync-client";
import type { Transaction } from "@webstudio-is/sync-client";
+import type { ServerSyncState } from "./sync-stores";
export { commandQueue };
@@ -337,9 +337,11 @@ const pollQueue = async (signal: AbortSignal) => {
export class ServerSyncStorage implements SyncStorage {
name = "server";
private projectId: string;
+ private initialState: ServerSyncState;
- constructor(projectId: string) {
+ constructor(projectId: string, initialState: ServerSyncState) {
this.projectId = projectId;
+ this.initialState = initialState;
}
sendTransaction(transaction: Transaction<Change[]>) {
@@ -354,20 +356,10 @@ export class ServerSyncStorage implements SyncStorage {
}
}
subscribe(setState: (state: unknown) => void, signal: AbortSignal) {
- const projectId = this.projectId;
- loadBuilderData({ projectId, signal })
- .then((data: Record<string, unknown>) => {
- const serverData = new Map(Object.entries(data));
- setState(new Map([["server", serverData]]));
- })
- .catch((err: unknown) => {
- if (err instanceof Error) {
- console.error(err);
- return;
- }
-
- // Abort error do nothing
- });
+ if (signal.aborted) {
+ return;
+ }
+ setState(new Map([["server", this.initialState]]));
}
}
diff --git a/apps/builder/app/shared/sync/singleplayer-client.ts b/apps/builder/app/shared/sync/singleplayer-client.ts
index 063084e176..d6e8abb7c6 100644
--- a/apps/builder/app/shared/sync/singleplayer-client.ts
+++ b/apps/builder/app/shared/sync/singleplayer-client.ts
@@ -2,6 +2,7 @@ import type { Project } from "@webstudio-is/project";
import type { Build } from "@webstudio-is/project-build";
import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";
import type { SyncStorage } from "~/shared/sync-client";
+import type { ServerSyncState } from "./sync-stores";
import {
ServerSyncStorage,
enqueueProjectDetails,
@@ -17,14 +18,19 @@ export type SingleplayerSyncClient = {
export const createSingleplayerSyncClient = ({
authPermit,
authToken,
+ initialServerState,
projectId,
}: {
authPermit: AuthPermit;
authToken: string | undefined;
+ initialServerState?: ServerSyncState;
projectId: Project["id"];
}): SingleplayerSyncClient => {
return {
- storages: authPermit === "view" ? [] : [new ServerSyncStorage(projectId)],
+ storages:
+ authPermit === "view" || initialServerState === undefined
+ ? []
+ : [new ServerSyncStorage(projectId, initialServerState)],
destroy() {
stopPolling();
},
diff --git a/apps/builder/app/shared/sync/sync-client.test.ts b/apps/builder/app/shared/sync/sync-client.test.ts
index 1890f5f524..59e63b98a1 100644
--- a/apps/builder/app/shared/sync/sync-client.test.ts
+++ b/apps/builder/app/shared/sync/sync-client.test.ts
@@ -1,7 +1,53 @@
import { describe, expect, test } from "vitest";
import { __testing__ } from "./sync-client";
+import type { LoadedBuilderData } from "~/shared/builder-data";
+import { serverSyncStoreNames } from "./sync-stores";
-const { resolveMultiplayerRelayUrl } = __testing__;
+const { getServerSyncState, resolveMultiplayerRelayUrl } = __testing__;
+
+describe("getServerSyncState", () => {
+ test("keeps only server-synchronized builder data", () => {
+ const data = {
+ id: "build-1",
+ version: 1,
+ projectId: "project-1",
+ project: { id: "project-1" },
+ publisherHost: "example.com",
+ pages: "pages",
+ breakpoints: "breakpoints",
+ instances: "instances",
+ styles: "styles",
+ styleSources: "styleSources",
+ styleSourceSelections: "styleSourceSelections",
+ props: "props",
+ dataSources: "dataSources",
+ resources: "resources",
+ assets: "assets",
+ marketplaceProduct: "marketplaceProduct",
+ } as unknown as LoadedBuilderData;
+
+ const serverSyncState = getServerSyncState(data);
+
+ expect([...serverSyncState.keys()]).toEqual([...serverSyncStoreNames]);
+ expect(serverSyncState).toEqual(
+ new Map<string, unknown>([
+ ["pages", "pages"],
+ ["breakpoints", "breakpoints"],
+ ["instances", "instances"],
+ ["styles", "styles"],
+ ["styleSources", "styleSources"],
+ ["styleSourceSelections", "styleSourceSelections"],
+ ["props", "props"],
+ ["dataSources", "dataSources"],
+ ["resources", "resources"],
+ ["assets", "assets"],
+ ["marketplaceProduct", "marketplaceProduct"],
+ ])
+ );
+ expect([...serverSyncState.keys()]).not.toContain("project");
+ expect([...serverSyncState.keys()]).not.toContain("publisherHost");
+ });
+});
describe("resolveMultiplayerRelayUrl", () => {
test("keeps configured absolute URL outside local wstd.dev", () => {
diff --git a/apps/builder/app/shared/sync/sync-client.ts b/apps/builder/app/shared/sync/sync-client.ts
index 01dc45ff63..e471db06aa 100644
--- a/apps/builder/app/shared/sync/sync-client.ts
+++ b/apps/builder/app/shared/sync/sync-client.ts
@@ -2,7 +2,12 @@ import type { Project } from "@webstudio-is/project";
import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";
import type { SyncEmitter } from "@webstudio-is/sync-client";
import { SyncClient, type SyncStorage } from "~/shared/sync-client";
-import { registerContainers, createObjectPool } from "./sync-stores";
+import {
+ createObjectPool,
+ registerContainers,
+ serverSyncStoreNames,
+ type ServerSyncState,
+} from "./sync-stores";
import { loadBuilderData, type LoadedBuilderData } from "~/shared/builder-data";
import { publicStaticEnv } from "~/env/env.static";
import { isFeatureEnabled } from "@webstudio-is/feature-flags";
@@ -28,6 +33,7 @@ import {
let client: SyncClient | undefined;
let currentProjectId: string | undefined;
let modeClient: SyncModeClient | undefined;
+let initializationVersion = 0;
type SyncModeClient = {
clientId?: string;
@@ -60,8 +66,7 @@ const resolveMultiplayerRelayUrl = (
};
const applyBuilderData = (data: LoadedBuilderData) => {
- $publisherHost.set(data.publisherHost);
- $project.set(data.project);
+ applyBuilderMetadata(data);
$pages.set(data.pages);
$assets.set(data.assets);
$instances.set(data.instances);
@@ -75,6 +80,14 @@ const applyBuilderData = (data: LoadedBuilderData) => {
$marketplaceProduct.set(data.marketplaceProduct);
};
+const applyBuilderMetadata = (data: LoadedBuilderData) => {
+ $publisherHost.set(data.publisherHost);
+ $project.set(data.project);
+};
+
+const getServerSyncState = (data: LoadedBuilderData): ServerSyncState =>
+ new Map(serverSyncStoreNames.map((name) => [name, data[name]]));
+
/**
* Initialize the sync infrastructure and load project data.
* Can be used from both the builder and dashboard contexts.
@@ -106,6 +119,8 @@ export const initializeClientSync = ({
relayUrl: resolvedMultiplayerRelayUrl,
});
}
+ const shouldPreloadStorage =
+ useMultiplayer === false && authPermit !== "view";
// Note: "view" permit will skip transaction synchronization
@@ -114,8 +129,36 @@ export const initializeClientSync = ({
destroyClientSync();
}
- // Only register containers once and create sync client
- if (!client) {
+ const currentInitializationVersion = ++initializationVersion;
+
+ const loadData = (onSuccess: (data: LoadedBuilderData) => void) => {
+ loadBuilderData({ projectId, signal })
+ .then((data) => {
+ if (
+ signal.aborted ||
+ currentInitializationVersion !== initializationVersion
+ ) {
+ return;
+ }
+ onSuccess(data);
+ })
+ .catch((error) => {
+ if (
+ signal.aborted === false &&
+ currentInitializationVersion === initializationVersion
+ ) {
+ console.error("[builder-sync] failed to load project data:", error);
+ }
+ });
+ };
+
+ const completeDataLoad = (data: LoadedBuilderData) => {
+ applyBuilderData(data);
+ modeClient?.onDataLoaded(data);
+ onReady?.();
+ };
+
+ const connectClient = (initialData?: LoadedBuilderData) => {
registerContainers();
const object = createObjectPool();
const nextModeClient: SyncModeClient =
@@ -131,6 +174,10 @@ export const initializeClientSync = ({
: createSingleplayerSyncClient({
authPermit,
authToken,
+ initialServerState:
+ initialData === undefined
+ ? undefined
+ : getServerSyncState(initialData),
projectId,
});
modeClient = nextModeClient;
@@ -144,22 +191,37 @@ export const initializeClientSync = ({
client.clientId = nextModeClient.clientId;
}
currentProjectId = projectId;
+
+ client.connect({
+ signal,
+ onReady() {
+ if (initialData !== undefined) {
+ applyBuilderMetadata(initialData);
+ modeClient?.onDataLoaded(initialData);
+ onReady?.();
+ return;
+ }
+
+ loadData(completeDataLoad);
+ },
+ });
+ };
+
+ // Only register containers once and create sync client
+ if (!client) {
+ if (shouldPreloadStorage) {
+ loadData(connectClient);
+ return;
+ }
+
+ connectClient();
+ return;
}
client.connect({
signal,
onReady() {
- loadBuilderData({ projectId, signal })
- .then((data) => {
- applyBuilderData(data);
- modeClient?.onDataLoaded(data);
- onReady?.();
- })
- .catch((error) => {
- if (!signal.aborted) {
- console.error("[builder-sync] failed to load project data:", error);
- }
- });
+ loadData(completeDataLoad);
},
});
};
@@ -169,6 +231,7 @@ export const initializeClientSync = ({
* Call this when closing the builder or switching between projects.
*/
export const destroyClientSync = () => {
+ initializationVersion += 1;
modeClient?.destroy();
modeClient = undefined;
client = undefined;
@@ -179,5 +242,6 @@ export const destroyClientSync = () => {
export const getSyncClient = () => client;
export const __testing__ = {
+ getServerSyncState,
resolveMultiplayerRelayUrl,
};
diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.ts
index be4edad983..a60a340e9c 100644
--- a/apps/builder/app/shared/sync/sync-stores.ts
+++ b/apps/builder/app/shared/sync/sync-stores.ts
@@ -79,19 +79,40 @@ setAutoFreeze(false);
export const clientSyncStore = new Store();
export const serverSyncStore = new Store();
+const serverSyncStores = {
+ pages: $pages,
+ breakpoints: $breakpoints,
+ instances: $instances,
+ styles: $styles,
+ styleSources: $styleSources,
+ styleSourceSelections: $styleSourceSelections,
+ props: $props,
+ dataSources: $dataSources,
+ resources: $resources,
+ assets: $assets,
+ marketplaceProduct: $marketplaceProduct,
+} as const;
+
+type ServerSyncStoreName = keyof typeof serverSyncStores;
+type ServerSyncStoreValue = {
+ [Name in ServerSyncStoreName]: ReturnType<
+ (typeof serverSyncStores)[Name]["get"]
+ >;
+}[ServerSyncStoreName];
+export type ServerSyncState = Map<ServerSyncStoreName, ServerSyncStoreValue>;
+
+export const serverSyncStoreNames = Object.keys(
+ serverSyncStores
+) as ReadonlyArray<ServerSyncStoreName>;
+
export const registerContainers = () => {
// synchronize patches
- serverSyncStore.register("pages", $pages);
- serverSyncStore.register("breakpoints", $breakpoints);
- serverSyncStore.register("instances", $instances);
- serverSyncStore.register("styles", $styles);
- serverSyncStore.register("styleSources", $styleSources);
- serverSyncStore.register("styleSourceSelections", $styleSourceSelections);
- serverSyncStore.register("props", $props);
- serverSyncStore.register("dataSources", $dataSources);
- serverSyncStore.register("resources", $resources);
- serverSyncStore.register("assets", $assets);
- serverSyncStore.register("marketplaceProduct", $marketplaceProduct);
+ for (const name of serverSyncStoreNames) {
+ serverSyncStore.register<ServerSyncStoreValue>(
+ name,
+ serverSyncStores[name]
+ );
+ }
};
type SelectedPageAndInstance = {
diff --git a/packages/project-build/src/db/build-parser.ts b/packages/project-build/src/db/build-parser.ts
index 2b9f3a9aaa..34f1061f1c 100644
--- a/packages/project-build/src/db/build-parser.ts
+++ b/packages/project-build/src/db/build-parser.ts
@@ -1,15 +1,10 @@
-/* eslint no-console: ["error", { allow: ["time", "timeEnd"] }] */
-
import type { Instance } from "@webstudio-is/sdk";
import { breakCyclesMutable } from "../shared/graph-utils";
const parseCompactInstanceData = (serialized: string) => {
const instances = JSON.parse(serialized) as Instance[];
- // @todo: Remove after measurements on real data
- console.time("breakCyclesMutable");
breakCyclesMutable(instances, (node) => node.component === "Slot");
- console.timeEnd("breakCyclesMutable");
return instances;
};
diff --git a/packages/project-build/src/db/build.ts b/packages/project-build/src/db/build.ts
index e7249b28e2..9ba9c0b9fc 100644
--- a/packages/project-build/src/db/build.ts
+++ b/packages/project-build/src/db/build.ts
@@ -1,5 +1,3 @@
-/* eslint no-console: ["error", { allow: ["time", "timeEnd"] }] */
-
import type { Database } from "@webstudio-is/postgrest/index.server";
import {
AuthorizationError,
@@ -45,10 +43,7 @@ const parseCompactData = <Item>(serialized: string) =>
const parseCompactInstanceData = (serialized: string) => {
const instances = JSON.parse(serialized) as Instance[];
- // @todo: Remove after measurements on real data
- console.time("breakCyclesMutable");
breakCyclesMutable(instances, (node) => node.component === "Slot");
- console.timeEnd("breakCyclesMutable");
return instances;
};
@@ -56,32 +51,28 @@ const parseCompactInstanceData = (serialized: string) => {
const parseCompactBuild = async (
build: Database["public"]["Tables"]["Build"]["Row"]
) => {
- try {
- return {
- id: build.id,
- projectId: build.projectId,
- version: build.version,
- createdAt: build.createdAt,
- updatedAt: build.updatedAt,
- pages: migratePages(parseConfig<unknown>(build.pages)),
- breakpoints: parseCompactData<Breakpoint>(build.breakpoints),
- styles: parseCompactData<StyleDecl>(build.styles),
- styleSources: parseCompactData<StyleSource>(build.styleSources),
- styleSourceSelections: parseCompactData<StyleSourceSelection>(
- build.styleSourceSelections
- ),
- props: parseCompactData<Prop>(build.props),
- dataSources: parseCompactData<DataSource>(build.dataSources),
- resources: parseCompactData<Resource>(build.resources),
- instances: parseCompactInstanceData(build.instances),
- deployment: parseDeployment(build.deployment),
- marketplaceProduct: parseConfig<MarketplaceProduct>(
- build.marketplaceProduct
- ),
- } satisfies CompactBuild;
- } finally {
- // empty block
- }
+ return {
+ id: build.id,
+ projectId: build.projectId,
+ version: build.version,
+ createdAt: build.createdAt,
+ updatedAt: build.updatedAt,
+ pages: migratePages(parseConfig<unknown>(build.pages)),
+ breakpoints: parseCompactData<Breakpoint>(build.breakpoints),
+ styles: parseCompactData<StyleDecl>(build.styles),
+ styleSources: parseCompactData<StyleSource>(build.styleSources),
+ styleSourceSelections: parseCompactData<StyleSourceSelection>(
+ build.styleSourceSelections
+ ),
+ props: parseCompactData<Prop>(build.props),
+ dataSources: parseCompactData<DataSource>(build.dataSources),
+ resources: parseCompactData<Resource>(build.resources),
+ instances: parseCompactInstanceData(build.instances),
+ deployment: parseDeployment(build.deployment),
+ marketplaceProduct: parseConfig<MarketplaceProduct>(
+ build.marketplaceProduct
+ ),
+ } satisfies CompactBuild;
};
type AuthorizationToken = Awaited<ReturnType<typeof authDb.getTokenInfo>>;
diff --git a/packages/project/src/db/build-patch-core.ts b/packages/project/src/db/build-patch-core.ts
index 7a5ad83e8f..31801cac22 100644
--- a/packages/project/src/db/build-patch-core.ts
+++ b/packages/project/src/db/build-patch-core.ts
@@ -37,6 +37,53 @@ import type { Database } from "@webstudio-is/postgrest/index.server";
enableMapSet();
enablePatches();
+type TouchedKeys = {
+ keys: Set<string>;
+ wholeMap: boolean;
+};
+
+const createTouchedKeys = (): TouchedKeys => ({
+ keys: new Set(),
+ wholeMap: false,
+});
+
+const addTouchedPatchKeys = (touched: TouchedKeys, patches: Patch[]) => {
+ for (const patch of patches) {
+ const key = patch.path[0];
+ if (key === undefined) {
+ touched.wholeMap = true;
+ continue;
+ }
+ touched.keys.add(`${key}`);
+ }
+};
+
+const getTouchedMap = <Value>(
+ map: Map<string, Value>,
+ touched: TouchedKeys
+) => {
+ if (touched.wholeMap) {
+ return map;
+ }
+ const touchedMap = new Map<string, Value>();
+ for (const key of touched.keys) {
+ if (map.has(key) === false) {
+ continue;
+ }
+ const value = map.get(key) as Value;
+ touchedMap.set(key, value);
+ }
+ return touchedMap;
+};
+
+const validateTouchedMap = <Value>(
+ schema: { parse: (value: Map<string, Value>) => unknown },
+ map: Map<string, Value>,
+ touched: TouchedKeys
+) => {
+ schema.parse(getTouchedMap(map, touched));
+};
+
export type BuildPatchChange = {
namespace: string;
patches: Array<Patch>;
@@ -107,11 +154,18 @@ export const createBuildPatchUpdate = async ({
} = {};
let previewImageAssetId: string | null | undefined = undefined;
- const patchedStyleDeclKeysSet = new Set<string>();
+ const touchedBreakpoints = createTouchedKeys();
+ const touchedDataSources = createTouchedKeys();
+ const touchedInstances = createTouchedKeys();
+ const touchedProps = createTouchedKeys();
+ const touchedResources = createTouchedKeys();
+ const touchedStyles = createTouchedKeys();
+ const touchedStyleSources = createTouchedKeys();
+ const touchedStyleSourceSelections = createTouchedKeys();
const assetPatches: Patch[][] = [];
- for await (const transaction of transactions) {
- for await (const change of transaction.payload) {
+ for (const transaction of transactions) {
+ for (const change of transaction.payload) {
const { namespace, patches } = change;
if (patches.length === 0) {
continue;
@@ -131,12 +185,13 @@ export const createBuildPatchUpdate = async ({
}
if (namespace === "instances") {
+ addTouchedPatchKeys(touchedInstances, patches);
const instances =
buildData.instances ?? parseInstanceData(build.instances);
buildData.instances = applyPatches(instances, patches);
- const cycles = findCycles(buildData.instances.values());
+ const cycles = findCycles(buildData.instances?.values() ?? []);
if (cycles.length > 0) {
console.error(
"Cycles detected in the instance tree after patching",
@@ -153,6 +208,7 @@ export const createBuildPatchUpdate = async ({
}
if (namespace === "props") {
+ addTouchedPatchKeys(touchedProps, patches);
const props = buildData.props ?? parseData<Prop>(build.props);
buildData.props = applyPatches(props, patches);
continue;
@@ -164,6 +220,7 @@ export const createBuildPatchUpdate = async ({
}
if (namespace === "styleSourceSelections") {
+ addTouchedPatchKeys(touchedStyleSourceSelections, patches);
const styleSourceSelections =
buildData.styleSourceSelections ??
parseStyleSourceSelections(build.styleSourceSelections);
@@ -175,6 +232,7 @@ export const createBuildPatchUpdate = async ({
}
if (namespace === "styleSources") {
+ addTouchedPatchKeys(touchedStyleSources, patches);
const styleSources =
buildData.styleSources ?? parseData<StyleSource>(build.styleSources);
buildData.styleSources = applyPatches(styleSources, patches);
@@ -182,9 +240,7 @@ export const createBuildPatchUpdate = async ({
}
if (namespace === "styles") {
- for (const patch of patches) {
- patchedStyleDeclKeysSet.add(`${patch.path[0]}`);
- }
+ addTouchedPatchKeys(touchedStyles, patches);
const styles = buildData.styles ?? parseStyles(build.styles);
buildData.styles = applyPatches(styles, patches);
@@ -192,6 +248,7 @@ export const createBuildPatchUpdate = async ({
}
if (namespace === "dataSources") {
+ addTouchedPatchKeys(touchedDataSources, patches);
const dataSources =
buildData.dataSources ?? parseData<DataSource>(build.dataSources);
buildData.dataSources = applyPatches(dataSources, patches);
@@ -199,6 +256,7 @@ export const createBuildPatchUpdate = async ({
}
if (namespace === "resources") {
+ addTouchedPatchKeys(touchedResources, patches);
const resources =
buildData.resources ?? parseData<Resource>(build.resources);
buildData.resources = applyPatches(resources, patches);
@@ -206,6 +264,7 @@ export const createBuildPatchUpdate = async ({
}
if (namespace === "breakpoints") {
+ addTouchedPatchKeys(touchedBreakpoints, patches);
const breakpoints =
buildData.breakpoints ?? parseData<Breakpoint>(build.breakpoints);
buildData.breakpoints = applyPatches(breakpoints, patches);
@@ -236,66 +295,68 @@ export const createBuildPatchUpdate = async ({
};
if (buildData.pages) {
- update.pages = serializePages(Pages.parse(buildData.pages));
+ const pages = buildData.pages;
+ update.pages = serializePages(Pages.parse(pages));
}
if (buildData.breakpoints) {
- update.breakpoints = serializeData<Breakpoint>(
- Breakpoints.parse(buildData.breakpoints)
- );
+ const breakpoints = buildData.breakpoints;
+ validateTouchedMap(Breakpoints, breakpoints, touchedBreakpoints);
+ update.breakpoints = serializeData<Breakpoint>(breakpoints);
}
if (buildData.instances) {
- update.instances = serializeData<Instance>(
- Instances.parse(buildData.instances)
- );
+ const instances = buildData.instances;
+ validateTouchedMap(Instances, instances, touchedInstances);
+ update.instances = serializeData<Instance>(instances);
}
if (buildData.props) {
- update.props = serializeData<Prop>(Props.parse(buildData.props));
+ const props = buildData.props;
+ validateTouchedMap(Props, props, touchedProps);
+ update.props = serializeData<Prop>(props);
}
if (buildData.dataSources) {
- update.dataSources = serializeData<DataSource>(
- DataSources.parse(buildData.dataSources)
- );
+ const dataSources = buildData.dataSources;
+ validateTouchedMap(DataSources, dataSources, touchedDataSources);
+ update.dataSources = serializeData<DataSource>(dataSources);
}
if (buildData.resources) {
- update.resources = serializeData<Resource>(
- Resources.parse(buildData.resources)
- );
+ const resources = buildData.resources;
+ validateTouchedMap(Resources, resources, touchedResources);
+ update.resources = serializeData<Resource>(resources);
}
if (buildData.styleSources) {
- update.styleSources = serializeData<StyleSource>(
- StyleSources.parse(buildData.styleSources)
- );
+ const styleSources = buildData.styleSources;
+ validateTouchedMap(StyleSources, styleSources, touchedStyleSources);
+ update.styleSources = serializeData<StyleSource>(styleSources);
}
if (buildData.styleSourceSelections) {
+ const styleSourceSelections = buildData.styleSourceSelections;
+ validateTouchedMap(
+ StyleSourceSelections,
+ styleSourceSelections,
+ touchedStyleSourceSelections
+ );
update.styleSourceSelections = serializeStyleSourceSelections(
- StyleSourceSelections.parse(buildData.styleSourceSelections)
+ styleSourceSelections
);
}
if (buildData.styles) {
- const stylesToValidate: Styles = new Map();
- for (const styleId of patchedStyleDeclKeysSet) {
- const style = buildData.styles.get(styleId);
- if (style === undefined) {
- continue;
- }
- stylesToValidate.set(styleId, style);
- }
-
- Styles.parse(stylesToValidate);
- update.styles = serializeStyles(buildData.styles);
+ const styles = buildData.styles;
+ validateTouchedMap(Styles, styles, touchedStyles);
+ update.styles = serializeStyles(styles);
}
if (buildData.marketplaceProduct) {
+ const marketplaceProduct = buildData.marketplaceProduct;
update.marketplaceProduct = serializeConfig<MarketplaceProduct>(
- MarketplaceProduct.parse(buildData.marketplaceProduct)
+ MarketplaceProduct.parse(marketplaceProduct)
);
}
diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.ts
index a014e7b077..ff5378ce10 100644
--- a/packages/project/src/db/build-patch.test.ts
+++ b/packages/project/src/db/build-patch.test.ts
@@ -298,6 +298,259 @@ describe("patchBuild", () => {
}
});
+ test("validates only touched props while preserving untouched props", async () => {
+ const buildWithInvalidUntouchedProp = {
+ ...buildRow,
+ props: JSON.stringify([
+ {
+ id: "prop-1",
+ instanceId: "body-1",
+ name: "title",
+ type: "string",
+ value: "Old title",
+ },
+ {
+ id: "prop-invalid",
+ instanceId: "body-1",
+ name: "count",
+ type: "number",
+ value: "invalid number",
+ },
+ ]),
+ };
+
+ const result = await createBuildPatchUpdate({
+ build: buildWithInvalidUntouchedProp,
+ clientVersion: 3,
+ transactions: [transaction()],
+ });
+
+ expect(result.status).toBe("ok");
+ if (result.status === "ok") {
+ expect(JSON.parse(result.update?.props ?? "")).toEqual([
+ {
+ id: "prop-1",
+ instanceId: "body-1",
+ name: "title",
+ type: "string",
+ value: "New title",
+ },
+ {
+ id: "prop-invalid",
+ instanceId: "body-1",
+ name: "count",
+ type: "number",
+ value: "invalid number",
+ },
+ ]);
+ }
+ });
+
+ test("rejects invalid touched props", async () => {
+ await expect(
+ createBuildPatchUpdate({
+ build: buildRow,
+ clientVersion: 3,
+ transactions: [
+ transaction({
+ payload: [
+ {
+ namespace: "props",
+ patches: [
+ {
+ op: "replace",
+ path: ["prop-1", "value"],
+ value: 123,
+ },
+ ],
+ },
+ ],
+ }),
+ ],
+ })
+ ).rejects.toThrow();
+ });
+
+ test("rejects touched props set to undefined", async () => {
+ await expect(
+ createBuildPatchUpdate({
+ build: buildRow,
+ clientVersion: 3,
+ transactions: [
+ transaction({
+ payload: [
+ {
+ namespace: "props",
+ patches: [
+ {
+ op: "replace",
+ path: ["prop-1"],
+ value: undefined,
+ },
+ ],
+ },
+ ],
+ }),
+ ],
+ })
+ ).rejects.toThrow();
+ });
+
+ test("validates all props when patch replaces the props map", async () => {
+ await expect(
+ createBuildPatchUpdate({
+ build: buildRow,
+ clientVersion: 3,
+ transactions: [
+ transaction({
+ payload: [
+ {
+ namespace: "props",
+ patches: [
+ {
+ op: "replace",
+ path: [],
+ value: new Map([
+ [
+ "prop-invalid",
+ {
+ id: "prop-invalid",
+ instanceId: "body-1",
+ name: "count",
+ type: "number",
+ value: "invalid number",
+ },
+ ],
+ ]),
+ },
+ ],
+ },
+ ],
+ }),
+ ],
+ })
+ ).rejects.toThrow();
+ });
+
+ test("rejects touched styles set to undefined", async () => {
+ const style = {
+ styleSourceId: "style-source-1",
+ breakpointId: "breakpoint-1",
+ property: "width",
+ value: { type: "unit", value: 10, unit: "px" },
+ };
+ const buildWithStyle = {
+ ...buildRow,
+ styles: JSON.stringify([style]),
+ };
+ const styleKey = "style-source-1:breakpoint-1:width:";
+
+ await expect(
+ createBuildPatchUpdate({
+ build: buildWithStyle,
+ clientVersion: 3,
+ transactions: [
+ transaction({
+ payload: [
+ {
+ namespace: "styles",
+ patches: [
+ {
+ op: "replace",
+ path: [styleKey],
+ value: undefined,
+ },
+ ],
+ },
+ ],
+ }),
+ ],
+ })
+ ).rejects.toThrow();
+ });
+
+ test("validates only touched instances while preserving untouched instances", async () => {
+ const buildWithInvalidUntouchedInstance = {
+ ...buildRow,
+ instances: JSON.stringify([
+ {
+ id: "body-1",
+ type: "instance",
+ component: "Body",
+ children: [],
+ },
+ {
+ id: "instance-invalid",
+ type: "instance",
+ children: [],
+ },
+ ]),
+ };
+
+ const result = await createBuildPatchUpdate({
+ build: buildWithInvalidUntouchedInstance,
+ clientVersion: 3,
+ transactions: [
+ transaction({
+ payload: [
+ {
+ namespace: "instances",
+ patches: [
+ {
+ op: "replace",
+ path: ["body-1", "label"],
+ value: "Body label",
+ },
+ ],
+ },
+ ],
+ }),
+ ],
+ });
+
+ expect(result.status).toBe("ok");
+ if (result.status === "ok") {
+ expect(JSON.parse(result.update?.instances ?? "")).toEqual([
+ {
+ id: "body-1",
+ type: "instance",
+ component: "Body",
+ label: "Body label",
+ children: [],
+ },
+ {
+ id: "instance-invalid",
+ type: "instance",
+ children: [],
+ },
+ ]);
+ }
+ });
+
+ test("rejects invalid touched instances", async () => {
+ await expect(
+ createBuildPatchUpdate({
+ build: buildRow,
+ clientVersion: 3,
+ transactions: [
+ transaction({
+ payload: [
+ {
+ namespace: "instances",
+ patches: [
+ {
+ op: "remove",
+ path: ["body-1", "component"],
+ },
+ ],
+ },
+ ],
+ }),
+ ],
+ })
+ ).rejects.toThrow();
+ });
+
test("returns ok when retrying a transaction already saved by the server", async () => {
let didPatch = false;
server.use(
diff --git a/packages/project/src/db/build-patch.ts b/packages/project/src/db/build-patch.ts
index f95fad4027..213e2be763 100644
--- a/packages/project/src/db/build-patch.ts
+++ b/packages/project/src/db/build-patch.ts
@@ -57,6 +57,7 @@ export const patchLoadedBuild = async (
if (result.update === undefined) {
return { status: "ok", version: result.nextVersion, build };
}
+ const buildUpdate = result.update;
// build.patch does not have the worker's atomic Build+asset commit path.
// Apply app-side asset mutations before marking the Build with
@@ -68,7 +69,7 @@ export const patchLoadedBuild = async (
const update = await context.postgrest.client
.from("Build")
- .update(result.update, { count: "exact" })
+ .update(buildUpdate, { count: "exact" })
.match({
id: buildId,
projectId,
@@ -98,7 +99,7 @@ export const patchLoadedBuild = async (
return {
status: "ok",
version: result.nextVersion,
- build: { ...build, ...result.update, version: result.nextVersion },
+ build: { ...build, ...buildUpdate, version: result.nextVersion },
};
};
diff --git a/packages/sdk/src/instances-utils.test.tsx b/packages/sdk/src/instances-utils.test.tsx
index 49dfd48fb0..2bdb308a61 100644
--- a/packages/sdk/src/instances-utils.test.tsx
+++ b/packages/sdk/src/instances-utils.test.tsx
@@ -10,6 +10,7 @@ import {
} from "./instances-utils";
import type { WsComponentMeta } from "./schema/component-meta";
import type { Instance } from "./schema/instances";
+import type { Prop, Props } from "./schema/props";
test("find all tree instances", () => {
const { instances } = renderData(
@@ -156,6 +157,56 @@ test("get html tag from instance reads mutable props maps", () => {
expect(getHtmlTagFromInstance({ instance, metas, props })).toEqual("aside");
});
+test("get html tag from instance skips props when instance tag is set", () => {
+ const metas = new Map<Instance["component"], WsComponentMeta>([
+ ["Box", { presetStyle: { section: [] } }],
+ ]);
+ const props = new (class extends Map<string, Prop> {
+ values(): MapIterator<Prop> {
+ throw new Error("props should not be scanned");
+ }
+ })() as Props;
+
+ expect(
+ getHtmlTagFromInstance({
+ instance: {
+ id: "box",
+ type: "instance",
+ component: "Box",
+ tag: "nav",
+ children: [],
+ },
+ metas,
+ props,
+ })
+ ).toEqual("nav");
+});
+
+test("get html tag from instance skips props when provided tag map has no tag", () => {
+ const metas = new Map<Instance["component"], WsComponentMeta>([
+ ["Box", { presetStyle: { section: [] } }],
+ ]);
+ const props = new (class extends Map<string, Prop> {
+ values(): MapIterator<Prop> {
+ throw new Error("props should not be scanned");
+ }
+ })() as Props;
+
+ expect(
+ getHtmlTagFromInstance({
+ instance: {
+ id: "box",
+ type: "instance",
+ component: "Box",
+ children: [],
+ },
+ metas,
+ props,
+ htmlTagsByInstanceId: new Map(),
+ })
+ ).toEqual("section");
+});
+
test("get indexes within ancestors", () => {
const { instances } = renderData(
<$.Body ws:id="body0">
diff --git a/packages/sdk/src/instances-utils.ts b/packages/sdk/src/instances-utils.ts
index f4a73b5150..3ba6de26fe 100644
--- a/packages/sdk/src/instances-utils.ts
+++ b/packages/sdk/src/instances-utils.ts
@@ -80,19 +80,28 @@ export const getHtmlTagFromInstance = ({
}: {
instance: Instance;
metas: Map<Instance["component"], WsComponentMeta>;
- props: Props;
+ props?: Props;
htmlTagsByInstanceId?: Map<Instance["id"], string>;
}) => {
// XmlNode's "tag" prop is an XML element name, not an HTML rendering tag.
if (instance.component === "XmlNode") {
return;
}
+ if (instance.tag !== undefined) {
+ return instance.tag;
+ }
+ const propTag =
+ htmlTagsByInstanceId === undefined
+ ? props === undefined
+ ? undefined
+ : getHtmlTagsFromProps(props).get(instance.id)
+ : htmlTagsByInstanceId.get(instance.id);
+ if (propTag !== undefined) {
+ return propTag;
+ }
const meta = metas.get(instance.component);
const metaTag = Object.keys(meta?.presetStyle ?? {}).at(0);
- const propTag =
- htmlTagsByInstanceId?.get(instance.id) ??
- getHtmlTagsFromProps(props).get(instance.id);
- return instance.tag ?? propTag ?? metaTag;
+ return metaTag;
};
export type IndexesWithinAncestors = Map<Instance["id"], number>;