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.

perf: Skip resources in statically hidden subtrees (#6233)

Oleg Isonen130d3717596a
diff --git a/apps/builder/app/shared/nano-states/props.test.tsx b/apps/builder/app/shared/nano-states/props.test.tsx
index e07f830884..1a274b87b0 100644
--- a/apps/builder/app/shared/nano-states/props.test.tsx
+++ b/apps/builder/app/shared/nano-states/props.test.tsx
@@ -10,7 +10,7 @@ import {
SYSTEM_VARIABLE_ID,
collectionComponent,
} from "@webstudio-is/sdk";
-import { textContentAttribute } from "@webstudio-is/react-sdk";
+import { showAttribute, textContentAttribute } from "@webstudio-is/react-sdk";
import {
$instances,
$pages,
@@ -20,6 +20,7 @@ import {
$resources,
} from "../sync/data-stores";
import {
+ __testing__,
$propValuesByInstanceSelector,
$variableValuesByInstanceSelector,
} from "./props";
@@ -39,6 +40,8 @@ import { $systemDataByPage, updateCurrentSystem } from "../system";
import { registerContainers } from "../sync/sync-stores";
import { $resourcesCache, getResourceKey } from "../resources";
+const { $computedResourceRequests } = __testing__;
+
const initialSystem = {
origin: "https://undefined.wstd.work",
params: {},
@@ -83,6 +86,92 @@ beforeEach(() => {
$resourcesCache.set(new Map());
});
+test("does not preload resources in statically hidden subtrees", () => {
+ $instances.set(
+ toMap([
+ {
+ id: "root",
+ type: "instance",
+ component: "Body",
+ children: [
+ { type: "id", value: "hidden" },
+ { type: "id", value: "visible" },
+ { type: "id", value: "dynamic" },
+ ],
+ },
+ {
+ id: "hidden",
+ type: "instance",
+ component: "Box",
+ children: [{ type: "id", value: "hidden-child" }],
+ },
+ {
+ id: "hidden-child",
+ type: "instance",
+ component: "Box",
+ children: [],
+ },
+ {
+ id: "visible",
+ type: "instance",
+ component: "Box",
+ children: [],
+ },
+ {
+ id: "dynamic",
+ type: "instance",
+ component: "Box",
+ children: [],
+ },
+ ])
+ );
+ selectPageRoot("root");
+ $props.set(
+ toMap([
+ {
+ id: "hidden-show",
+ instanceId: "hidden",
+ name: showAttribute,
+ type: "boolean",
+ value: false,
+ },
+ {
+ id: "dynamic-show",
+ instanceId: "dynamic",
+ name: showAttribute,
+ type: "expression",
+ value: "false",
+ },
+ ])
+ );
+ $dataSources.set(
+ toMap(
+ ["hidden", "hidden-child", "visible", "dynamic"].map((instanceId) => ({
+ id: `${instanceId}-data-source`,
+ scopeInstanceId: instanceId,
+ type: "resource" as const,
+ name: instanceId,
+ resourceId: `${instanceId}-resource`,
+ }))
+ )
+ );
+ $resources.set(
+ toMap(
+ ["hidden", "hidden-child", "visible", "dynamic"].map((name) => ({
+ id: `${name}-resource`,
+ name,
+ url: JSON.stringify(`https://example.com/${name}`),
+ method: "get" as const,
+ headers: [],
+ }))
+ )
+ );
+
+ expect(
+ $computedResourceRequests.get().map((request) => request.name)
+ ).toEqual(["visible", "dynamic"]);
+});
+
test("collect prop values", () => {
setBoxInstance("box");
selectPageRoot("box");
diff --git a/apps/builder/app/shared/nano-states/props.ts b/apps/builder/app/shared/nano-states/props.ts
index 3dfa9e48ef..47f02c232c 100644
--- a/apps/builder/app/shared/nano-states/props.ts
+++ b/apps/builder/app/shared/nano-states/props.ts
@@ -13,13 +13,13 @@ import {
portalComponent,
ROOT_INSTANCE_ID,
SYSTEM_VARIABLE_ID,
- findTreeInstanceIds,
} from "@webstudio-is/sdk";
import { transpileExpression } from "@webstudio-is/expression";
import {
normalizeProps,
textContentAttribute,
getCollectionEntries,
+ findTreeInstanceIdsExcludingStaticHidden,
} from "@webstudio-is/react-sdk";
import { mapGroupBy } from "~/shared/shim";
import { $instances } from "../sync/data-stores";
@@ -584,16 +584,21 @@ const $computedResourceRequests = computed(
[
$selectedPage,
$instances,
+ $props,
$dataSources,
$resources,
$resourceVariableValues,
],
- (page, instances, dataSources, resources, values) => {
+ (page, instances, props, dataSources, resources, values) => {
const computedResourceRequests: ResourceRequest[] = [];
if (page === undefined) {
return computedResourceRequests;
}
- const instanceIds = findTreeInstanceIds(instances, page.rootInstanceId);
+ const instanceIds = findTreeInstanceIdsExcludingStaticHidden({
+ instances,
+ props,
+ rootInstanceId: page.rootInstanceId,
+ });
instanceIds.add(ROOT_INSTANCE_ID);
// load only resources bound to variables on current page
// action resources should not be loaded automatically
@@ -624,3 +629,5 @@ export const subscribeResources = () => {
preloadResources(computedResourceRequests);
});
};
+
+export const __testing__ = { $computedResourceRequests };
diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts
index fcc4a962b0..b0a8938aef 100644
--- a/packages/cli/src/prebuild.test.ts
+++ b/packages/cli/src/prebuild.test.ts
@@ -40,6 +40,7 @@ import {
SYSTEM_VARIABLE_ID,
type Resource,
} from "@webstudio-is/sdk";
+import { showAttribute } from "@webstudio-is/react-sdk";
import {
generateRedirectsModule,
getAssetResourcePrerenderPaths,
@@ -781,6 +782,98 @@ test("hydrates encoded filenames from an embedded SSG database", async () => {
});
describe("prebuild", () => {
+ test("excludes resources in statically hidden subtrees", async () => {
+ const siteData = createSiteData({
+ instances: [
+ [
+ "root",
+ {
+ id: "root",
+ component: "Body",
+ children: [
+ { type: "id", value: "hidden" },
+ { type: "id", value: "visible" },
+ { type: "id", value: "dynamic" },
+ ],
+ },
+ ],
+ [
+ "hidden",
+ {
+ id: "hidden",
+ component: "Box",
+ children: [{ type: "id", value: "hidden-child" }],
+ },
+ ],
+ [
+ "hidden-child",
+ { id: "hidden-child", component: "Box", children: [] },
+ ],
+ ["visible", { id: "visible", component: "Box", children: [] }],
+ ["dynamic", { id: "dynamic", component: "Box", children: [] }],
+ ],
+ props: [
+ [
+ "hidden-show",
+ {
+ id: "hidden-show",
+ instanceId: "hidden",
+ name: showAttribute,
+ type: "boolean",
+ value: false,
+ },
+ ],
+ [
+ "dynamic-show",
+ {
+ id: "dynamic-show",
+ instanceId: "dynamic",
+ name: showAttribute,
+ type: "expression",
+ value: "false",
+ },
+ ],
+ ],
+ });
+ const resourceNames = ["hidden", "hidden-child", "visible", "dynamic"];
+ siteData.build.dataSources = resourceNames.map((name) => [
+ `${name}-data-source`,
+ {
+ id: `${name}-data-source`,
+ scopeInstanceId: name,
+ type: "resource",
+ name,
+ resourceId: `${name}-resource`,
+ },
+ ]) as never;
+ siteData.build.resources = resourceNames.map((name) => [
+ `${name}-resource`,
+ {
+ id: `${name}-resource`,
+ name,
+ url: JSON.stringify(`https://example.com/${name}`),
+ method: "get",
+ headers: [],
+ },
+ ]) as never;
+ await writeSiteData(siteData);
+
+ await prebuild({
+ assets: false,
+ template: ["react-router"],
+ preserveRouteTemplates: true,
+ });
+
+ const generatedServer = await readFile(
+ "app/__generated__/_index.server.tsx",
+ "utf8"
+ );
+ expect(generatedServer).not.toContain("https://example.com/hidden");
+ expect(generatedServer).not.toContain("https://example.com/hidden-child");
+ expect(generatedServer).toContain("https://example.com/visible");
+ expect(generatedServer).toContain("https://example.com/dynamic");
+ });
+
test("imports only configured Code Text language and theme assets", async () => {
await writeSiteData(
createCodeTextSiteData([
diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.ts
index d9a16988b3..b950bda79e 100644
--- a/packages/cli/src/prebuild.ts
+++ b/packages/cli/src/prebuild.ts
@@ -20,10 +20,10 @@ import {
normalizeProps,
generateRemixRoute,
generateRemixParams,
+ findTreeInstanceIdsExcludingStaticHidden,
} from "@webstudio-is/react-sdk";
import {
createScope,
- findTreeInstanceIds,
getAllPages,
isAssetsResource,
getPagePath,
@@ -961,13 +961,17 @@ export const prebuild = async (options: {
pages,
source: "prebuild",
});
+ const normalizedPropsMap = new Map(
+ normalizedProps.map((prop) => [prop.id, prop])
+ );
for (const page of generatedPages) {
const instanceMap = new Map(siteData.build.instances);
- const pageInstanceSet = findTreeInstanceIds(
- instanceMap,
- page.rootInstanceId
- );
+ const pageInstanceSet = findTreeInstanceIdsExcludingStaticHidden({
+ instances: instanceMap,
+ props: normalizedPropsMap,
+ rootInstanceId: page.rootInstanceId,
+ });
// support global data variables
pageInstanceSet.add(ROOT_INSTANCE_ID);
// collect used instances and metas
diff --git a/packages/react-sdk/src/props.ts b/packages/react-sdk/src/props.ts
index 3a877522ec..ad15c488f0 100644
--- a/packages/react-sdk/src/props.ts
+++ b/packages/react-sdk/src/props.ts
@@ -1,10 +1,13 @@
import {
type Prop,
+ type Instances,
+ type Props,
type Assets,
type Pages,
type ImageAsset,
getPagePath,
findPageByIdOrPath,
+ findTreeInstanceIdsExcludingSubtrees,
} from "@webstudio-is/sdk";
export const normalizeProps = ({
@@ -138,6 +141,32 @@ export const showAttribute = "data-ws-show" as const;
export const inflatedAttribute = "data-ws-collapsed" as const;
export const textContentAttribute = "data-ws-text-content" as const;
+export const findTreeInstanceIdsExcludingStaticHidden = ({
+ instances,
+ props,
+ rootInstanceId,
+}: {
+ instances: Instances;
+ props: Props;
+ rootInstanceId: string;
+}) => {
+ const hiddenInstanceIds = new Set<string>();
+ for (const prop of props.values()) {
+ if (
+ prop.name === showAttribute &&
+ prop.type === "boolean" &&
+ prop.value === false
+ ) {
+ hiddenInstanceIds.add(prop.instanceId);
+ }
+ }
+ return findTreeInstanceIdsExcludingSubtrees(
+ instances,
+ rootInstanceId,
+ hiddenInstanceIds
+ );
+};
+
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
diff --git a/packages/sdk/src/instances-utils.test.tsx b/packages/sdk/src/instances-utils.test.tsx
index 2bdb308a61..44f3e97051 100644
--- a/packages/sdk/src/instances-utils.test.tsx
+++ b/packages/sdk/src/instances-utils.test.tsx
@@ -2,6 +2,7 @@ import { expect, test } from "vitest";
import { $, renderData, ws } from "@webstudio-is/template";
import {
findTreeInstanceIds,
+ findTreeInstanceIdsExcludingSubtrees,
findTreeInstanceIdsExcludingSlotDescendants,
getHtmlTagsFromProps,
getHtmlTagFromInstance,
@@ -25,6 +26,21 @@ test("find all tree instances", () => {
expect(findTreeInstanceIds(instances, "3")).toEqual(new Set(["3", "4", "5"]));
});
+test("find tree instances excluding complete subtrees", () => {
+ const { instances } = renderData(
+ <$.Body ws:id="root">
+ <$.Box ws:id="hidden">
+ <$.Box ws:id="hidden-child"></$.Box>
+ </$.Box>
+ <$.Box ws:id="visible"></$.Box>
+ </$.Body>
+ );
+
+ expect(
+ findTreeInstanceIdsExcludingSubtrees(instances, "root", new Set(["hidden"]))
+ ).toEqual(new Set(["root", "visible"]));
+});
+
test("find all tree instances excluding slot descendants", () => {
const { instances } = renderData(
<$.Body ws:id="body">
diff --git a/packages/sdk/src/instances-utils.ts b/packages/sdk/src/instances-utils.ts
index 3ba6de26fe..a18a1b507e 100644
--- a/packages/sdk/src/instances-utils.ts
+++ b/packages/sdk/src/instances-utils.ts
@@ -36,6 +36,22 @@ export const findTreeInstanceIds = (
return ids;
};
+export const findTreeInstanceIdsExcludingSubtrees = (
+ instances: Instances,
+ rootInstanceId: Instance["id"],
+ excludedRootIds: Set<Instance["id"]>
+) => {
+ const ids = new Set<Instance["id"]>([rootInstanceId]);
+ traverseInstances(instances, rootInstanceId, (instance) => {
+ if (excludedRootIds.has(instance.id)) {
+ ids.delete(instance.id);
+ return false;
+ }
+ ids.add(instance.id);
+ });
+ return ids;
+};
+
export const findTreeInstanceIdsExcludingSlotDescendants = (
instances: Instances,
rootInstanceId: Instance["id"]