Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
perf: generate page prop for links (#2357)
Bogdan Chadkin5f93ecb228db
diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex 592fc37217..8ff667909c 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -8,6 +8,8 @@ import {type Components,createElementsTree,getIndexesWithinAncestors,+ normalizeProps,+ getPropsByInstanceId,} from "@webstudio-is/react-sdk";import * as baseComponents from "@webstudio-is/sdk-components-react";import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";@@ -33,7 +35,6 @@ import {WebstudioComponentPreview,} from "./features/webstudio-component";import {- propsIndexStore,assetsStore,pagesStore,instancesStore,@@ -44,6 +45,7 @@ import {registeredComponentMetasStore,subscribeComponentHooks,dataSourcesLogicStore,+ propsStore,} from "~/shared/nano-states";import { useDragAndDrop } from "./shared/use-drag-drop";import { useCopyPaste } from "~/shared/copy-paste";@@ -59,11 +61,6 @@ import type { ImageLoader } from "@webstudio-is/image";registerContainers();-const propsByInstanceIdStore = computed(- propsIndexStore,- (propsIndex) => propsIndex.propsByInstanceId-);-const useElementsTree = (components: Components,instances: Instances,@@ -106,6 +103,26 @@ const useElementsTree = ();}, [metas, instances, page]);+ const propsByInstanceIdStore = useMemo(() => {+ return computed(+ [propsStore, assetsStore, pagesMapStore],+ (props, assets, pages) => {+ if (pages === undefined) {+ return new Map();+ }+ const normalizedProps = normalizeProps({+ props: Array.from(props.values()),+ assetBaseUrl: params.assetBaseUrl,+ assets,+ pages: pages,+ });+ return getPropsByInstanceId(+ new Map(normalizedProps.map((prop) => [prop.id, prop]))+ );+ }+ );+ }, [params.assetBaseUrl, pagesMapStore]);+return useMemo(() => {return createElementsTree({renderer: isPreviewMode ? "preview" : "canvas",@@ -136,6 +153,7 @@ const useElementsTree = (rootInstanceId,components,pagesMapStore,+ propsByInstanceIdStore,isPreviewMode,indexesWithinAncestors,imageLoader,diff --git a/fixtures/webstudio-remix-vercel/app/__generated__/_index.tsx b/fixtures/webstudio-remix-vercel/app/__generated__/_index.tsxindex e4ee05fac3..fd16702ead 100644--- a/fixtures/webstudio-remix-vercel/app/__generated__/_index.tsx+++ b/fixtures/webstudio-remix-vercel/app/__generated__/_index.tsx@@ -43,10 +43,10 @@ export const pageData: PageData = {"tUn-hTQ0dKjsaRZ4q3m21",{id: "tUn-hTQ0dKjsaRZ4q3m21",- instanceId: "9I4GRU1sev48hREkQcKQ-",name: "href",- type: "page",- value: "szYLvBduHPmbtqQKCDY0b",+ instanceId: "9I4GRU1sev48hREkQcKQ-",+ type: "string",+ value: "/_route_with_symbols_",},],[@@ -73,13 +73,10 @@ export const pageData: PageData = {"z8GMy7HFi_j_felIKxGP5",{id: "z8GMy7HFi_j_felIKxGP5",- instanceId: "81ejLVXyFEV1SxiJrWhyw",name: "href",- type: "page",- value: {- pageId: "-J9I4Oo6mONfQlf_3-OqG",- instanceId: "qmxnOlSxUGpuhuonVArWJ",- },+ instanceId: "81ejLVXyFEV1SxiJrWhyw",+ type: "string",+ value: "/heading-with-id#my-heading",},],],@@ -208,10 +205,18 @@ const Page = (props: { scripts?: ReactNode }) => {{"go download this little kitten"}</Link><Box data-ws-id="82HYqzxZeahPxSDFNWem5" data-ws-component="Box" />- <Link data-ws-id="9I4GRU1sev48hREkQcKQ-" data-ws-component="Link">+ <Link+ data-ws-id="9I4GRU1sev48hREkQcKQ-"+ data-ws-component="Link"+ href={"/_route_with_symbols_"}+ >{"Symbols in path"}</Link>- <Link data-ws-id="81ejLVXyFEV1SxiJrWhyw" data-ws-component="Link">+ <Link+ data-ws-id="81ejLVXyFEV1SxiJrWhyw"+ data-ws-component="Link"+ href={"/heading-with-id#my-heading"}+ >{"Link to instance"}</Link></Box>diff --git a/package.json b/package.jsonindex b8cc0b12d4..a8ed42637e 100644--- a/package.json+++ b/package.json@@ -4,7 +4,7 @@"version": "0.0.0","private": true,"scripts": {- "build": "turbo run build",+ "build": "turbo run build --filter='!./fixtures/*'","build-packages": "turbo run build --filter=\"!@webstudio-is/builder\"","dts": "turbo run dts","size-test": "turbo run size-test",diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex c9e9247a85..a48b17f365 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -281,8 +281,15 @@ export const prebuild = async (options: {siteData.build.instances.filter(([id]) => pageInstanceSet.has(id));const dataSources: [DataSource["id"], DataSource][] = [];+ // use whole project props to access id props from other pages+ const normalizedProps = normalizeProps({+ props: siteData.build.props.map(([_id, prop]) => prop),+ assetBaseUrl,+ assets: new Map(siteData.assets.map((asset) => [asset.id, asset])),+ pages: new Map(siteData.pages.map((page) => [page.id, page])),+ });const props: [Prop["id"], Prop][] = [];- for (const [_propId, prop] of siteData.build.props) {+ for (const prop of normalizedProps) {if (pageInstanceSet.has(prop.instanceId)) {props.push([prop.id, prop]);}@@ -444,17 +451,10 @@ export const prebuild = async (options: {}const pageData = siteDataByPage[pathName];- const props = new Map(- normalizeProps({- props: pageData.build.props.map(([_id, prop]) => prop),- assetBaseUrl,- assets: new Map(pageData.assets.map((asset) => [asset.id, asset])),- }).map((prop) => [prop.id, prop])- );// serialize data only used in runtimeconst renderedPageData: PageData = {build: {- props: Array.from(props.entries()),+ props: pageData.build.props,},pages: pageData.pages,page: pageData.page,@@ -463,6 +463,7 @@ export const prebuild = async (options: {const rootInstanceId = pageData.page.rootInstanceId;const instances = new Map(pageData.build.instances);+ const props = new Map(pageData.build.props);const dataSources = new Map(pageData.build.dataSources);const utilsExport = generateUtilsExport({props,diff --git a/packages/react-sdk/src/hook.test.ts b/packages/react-sdk/src/hook.test.tsindex c7abeb344e..cad642bde6 100644--- a/packages/react-sdk/src/hook.test.ts+++ b/packages/react-sdk/src/hook.test.ts@@ -1,5 +1,5 @@import { expect, test } from "@jest/globals";-import { getClosestInstance, type InstancePath } from ".";+import { getClosestInstance, type InstancePath } from "./hook";test("get closest instance", () => {const instancePath: InstancePath = [diff --git a/packages/react-sdk/src/index.ts b/packages/react-sdk/src/index.tsindex 33da92be41..1bf45356de 100644--- a/packages/react-sdk/src/index.ts+++ b/packages/react-sdk/src/index.ts@@ -17,9 +17,9 @@ export {normalizeProps,useInstanceProps,getPropsByInstanceId,- usePropUrl,getInstanceIdFromComponentProps,getIndexWithinAncestorFromComponentProps,+ usePages,} from "./props";export { type Params, ReactSdkContext } from "./context";export {diff --git a/packages/react-sdk/src/props.test.ts b/packages/react-sdk/src/props.test.tsindex 825cd81ad2..1caf2dde49 100644--- a/packages/react-sdk/src/props.test.ts+++ b/packages/react-sdk/src/props.test.ts@@ -1,13 +1,6 @@-import { describe, test, expect } from "@jest/globals";-import type { Page, Prop, Asset, Assets } from "@webstudio-is/sdk";-import {- resolveUrlProp,- type Pages,- type PropsByInstanceId,- normalizeProps,-} from "./props";--const unique = () => Math.random().toString();+import { test, expect } from "@jest/globals";+import type { Prop } from "@webstudio-is/sdk";+import { normalizeProps } from "./props";test("normalize asset prop into string", () => {expect(@@ -38,6 +31,7 @@ test("normalize asset prop into string", () => {},],]),+ pages: new Map(),})).toEqual([{@@ -50,189 +44,92 @@ test("normalize asset prop into string", () => {]);});-describe("resolveUrlProp", () => {- const instanceId = unique();- const projectId = unique();-- const page1: Page = {- id: unique(),- path: `/${unique()}`,- name: "",- title: "",- meta: {},- rootInstanceId: "0",- };-- const page2: Page = {- id: unique(),- path: `/${unique()}`,- name: "",- title: "",- meta: {},- rootInstanceId: "0",- };-- const asset1: Asset = {- id: unique(),- name: unique(),- type: "image",- projectId,- format: "png",- size: 100000,- createdAt: new Date().toISOString(),- description: null,- meta: { width: 128, height: 180 },- };-- const assetProp: Prop = {- type: "asset",- id: unique(),- instanceId,- name: unique(),- value: asset1.id,- };-- const pageByIdProp: Prop = {- type: "page",- id: unique(),- instanceId,- name: unique(),- value: page1.id,- };+test("normalize page prop with path into string", () => {+ expect(+ normalizeProps({+ props: [+ {+ id: "prop1",+ instanceId: "instance1",+ name: "href",+ type: "page",+ value: "page1Id",+ },+ ],+ assetBaseUrl: "",+ assets: new Map(),+ pages: new Map([+ [+ "page1Id",+ {+ id: "page1Id",+ path: "page1",+ rootInstanceId: "",+ name: "",+ title: "",+ meta: {},+ },+ ],+ ]),+ })+ ).toEqual([+ {+ id: "prop1",+ instanceId: "instance1",+ name: "href",+ type: "string",+ value: "/page1",+ },+ ]);+});- const instnaceIdProp: Prop = {- type: "string",- id: unique(),- instanceId: unique(),+test("normalize page prop with path and hash into string", () => {+ const idProp: Prop = {+ id: "prop1",+ instanceId: "instance1",name: "id",- value: unique(),- };-- const pageSectionProp: Prop = {- type: "page",- id: unique(),- instanceId,- name: unique(),- value: { pageId: page1.id, instanceId: instnaceIdProp.instanceId },- };-- const pageByPathProp: Prop = {type: "string",- id: unique(),- instanceId,- name: unique(),- value: page2.path,+ value: "my anchor",};-- const arbitraryUrlProp: Prop = {- type: "string",- id: unique(),- instanceId,- name: unique(),- value: unique(),- };-- const duplicatePropName = unique();-- const duplicateUrlPropFirst: Prop = {- type: "string",- id: unique(),- instanceId,- name: duplicatePropName,- value: unique(),- };-- const duplicateUrlPropSecond: Prop = {- type: "string",- id: unique(),- instanceId,- name: duplicatePropName,- value: unique(),- };-- const props: PropsByInstanceId = new Map([- [- instanceId,- [- pageByIdProp,- pageByPathProp,- arbitraryUrlProp,- assetProp,- pageSectionProp,- duplicateUrlPropFirst,- duplicateUrlPropSecond,+ expect(+ normalizeProps({+ props: [+ {+ id: "prop1",+ instanceId: "instance1",+ name: "href",+ type: "page",+ value: {+ pageId: "page1Id",+ instanceId: "instance1",+ },+ },+ idProp,],- ],- [instnaceIdProp.instanceId, [instnaceIdProp]],- ]);-- const pages: Pages = new Map([- [page1.id, page1],- [page2.id, page2],- ]);-- const assets: Assets = new Map([[asset1.id, asset1]]);-- const stores = {- assetBaseUrl: "/assets/",- props,- pages,- assets,- };-- test("if instanceId is unknown returns undefined", () => {- expect(- resolveUrlProp("unknown", pageByIdProp.name, stores)- ).toBeUndefined();- });-- test("if prop name is unknown returns undefined", () => {- expect(resolveUrlProp(instanceId, "unknown", stores)).toBeUndefined();- });-- test("asset by id", () => {- expect(resolveUrlProp(instanceId, assetProp.name, stores)).toEqual({- type: "string",- url: `/assets/${asset1.name}`,- });- });-- test("page by id", () => {- expect(resolveUrlProp(instanceId, pageByIdProp.name, stores)).toEqual({- type: "page",- page: page1,- });- });-- test("page by path", () => {- expect(resolveUrlProp(instanceId, pageByPathProp.name, stores)).toEqual({- type: "page",- page: page2,- });- });-- test("section on a page", () => {- expect(resolveUrlProp(instanceId, pageSectionProp.name, stores)).toEqual({- type: "page",- page: page1,- instanceId: instnaceIdProp.instanceId,- hash: instnaceIdProp.value,- });- });-- test("arbitrary url", () => {- expect(resolveUrlProp(instanceId, arbitraryUrlProp.name, stores)).toEqual({- type: "string",- url: arbitraryUrlProp.value,- });- });-- // We had a bug that some props were duplicated https://github.com/webstudio-is/webstudio/pull/2170- // Use the latest prop to ensure consistency with the builder settings panel.- test("duplicate prop name", () => {- expect(resolveUrlProp(instanceId, duplicatePropName, stores)).toEqual({+ assetBaseUrl: "",+ assets: new Map(),+ pages: new Map([+ [+ "page1Id",+ {+ id: "page1Id",+ path: "page1",+ rootInstanceId: "",+ name: "",+ title: "",+ meta: {},+ },+ ],+ ]),+ })+ ).toEqual([+ {+ id: "prop1",+ instanceId: "instance1",+ name: "href",type: "string",- url: duplicateUrlPropSecond.value,- });- });+ value: "/page1#my%20anchor",+ },+ idProp,+ ]);});diff --git a/packages/react-sdk/src/props.ts b/packages/react-sdk/src/props.tsindex 6662744658..2f3d260937 100644--- a/packages/react-sdk/src/props.ts+++ b/packages/react-sdk/src/props.ts@@ -9,14 +9,22 @@ export type PropsByInstanceId = Map<Instance["id"], Prop[]>;export type Pages = Map<Page["id"], Page>;+export const usePages = (): Pages => {+ const { pagesStore } = useContext(ReactSdkContext);+ const pages = useStore(pagesStore);+ return pages;+};+export const normalizeProps = ({props,assetBaseUrl,assets,+ pages,}: {props: Prop[];assetBaseUrl: string;assets: Assets;+ pages: Pages;}) => {const newProps: Prop[] = [];for (const prop of props) {@@ -36,6 +44,41 @@ export const normalizeProps = ({});continue;}++ if (prop.type === "page") {+ let page: undefined | Page;+ let idProp: undefined | Prop;+ if (typeof prop.value === "string") {+ const pageId = prop.value;+ page = pages.get(pageId);+ } else {+ const { pageId, instanceId } = prop.value;+ page = pages.get(pageId);+ idProp = props.find(+ (prop) => prop.instanceId === instanceId && prop.name === "id"+ );+ }+ if (page === undefined) {+ continue;+ }+ const url = new URL(page.path, "https://any-valid.url");+ let value = url.pathname;+ if (idProp?.type === "string") {+ const hash = idProp.value;+ url.hash = encodeURIComponent(hash);+ value = `${url.pathname}${url.hash}`;+ }+ newProps.push({+ id: prop.id,+ name: prop.name,+ required: prop.required,+ instanceId: prop.instanceId,+ type: "string",+ value,+ });+ continue;+ }+newProps.push(prop);}return newProps;@@ -60,15 +103,13 @@ export const useInstanceProps = (instanceId: Instance["id"]) => {const {propsByInstanceIdStore,dataSourcesLogicStore,- assetBaseUrl,- assetsStore,indexesWithinAncestors,} = useContext(ReactSdkContext);const index = indexesWithinAncestors.get(instanceId);const instancePropsObjectStore = useMemo(() => {return computed(- [propsByInstanceIdStore, dataSourcesLogicStore, assetsStore],- (propsByInstanceId, dataSourcesLogic, assets) => {+ [propsByInstanceIdStore, dataSourcesLogicStore],+ (propsByInstanceId, dataSourcesLogic) => {const instancePropsObject: Record<Prop["name"], unknown> = {};if (index !== undefined) {instancePropsObject[indexAttribute] = index.toString();@@ -77,14 +118,8 @@ export const useInstanceProps = (instanceId: Instance["id"]) => {if (instanceProps === undefined) {return instancePropsObject;}- const normalizedProps = normalizeProps({- props: instanceProps,- assetBaseUrl,- assets,- });- for (const prop of normalizedProps) {- // asset is normalized to string- // page is handled internally+ for (const prop of instanceProps) {+ // asset and page are normalized to stringif (prop.type === "asset" || prop.type === "page") {continue;}@@ -108,135 +143,11 @@ export const useInstanceProps = (instanceId: Instance["id"]) => {return instancePropsObject;});- }, [- propsByInstanceIdStore,- assetsStore,- dataSourcesLogicStore,- instanceId,- index,- assetBaseUrl,- ]);+ }, [propsByInstanceIdStore, dataSourcesLogicStore, instanceId, index]);const instancePropsObject = useStore(instancePropsObjectStore);return instancePropsObject;};-export const resolveUrlProp = (- instanceId: Instance["id"],- name: string,- {- assetBaseUrl,- props,- pages,- assets,- }: {- assetBaseUrl: string;- props: PropsByInstanceId;- pages: Pages;- assets: Assets;- }-):- | {- type: "page";- page: Page;- instanceId?: Instance["id"];- hash?: string;- }- | { type: "string"; url: string }- | undefined => {- const instanceProps = props.get(instanceId);- if (instanceProps === undefined) {- return;- }-- let prop = undefined;-- const normalizedProps = normalizeProps({- props: instanceProps,- assetBaseUrl,- assets,- });-- // We had a bug that some props were duplicated https://github.com/webstudio-is/webstudio/pull/2170- // Use the latest prop to ensure consistency with the builder settings panel.- for (const instanceProp of normalizedProps) {- if (instanceProp.name !== name) {- continue;- }- prop = instanceProp;- }-- if (prop === undefined) {- return;- }-- if (prop.type === "page") {- if (typeof prop.value === "string") {- const page = pages.get(prop.value);- return page && { type: "page", page };- }-- const { instanceId, pageId } = prop.value;-- const page = pages.get(pageId);-- if (page === undefined) {- return;- }-- const idProp = props.get(instanceId)?.find((prop) => prop.name === "id");-- return {- type: "page",- page,- instanceId,- hash:- idProp === undefined || idProp.type !== "string"- ? undefined- : idProp.value,- };- }-- if (prop.type === "string") {- for (const page of pages.values()) {- if (page.path === prop.value) {- return { type: "page", page };- }- }- return { type: "string", url: prop.value };- }-- return;-};--// this utility is used for link component in both builder and preview-// so need to optimize rerenders with computed-export const usePropUrl = (instanceId: Instance["id"], name: string) => {- const { assetBaseUrl, propsByInstanceIdStore, pagesStore, assetsStore } =- useContext(ReactSdkContext);- const store = useMemo(- () =>- computed(- [propsByInstanceIdStore, pagesStore, assetsStore],- (props, pages, assets) =>- resolveUrlProp(instanceId, name, {- assetBaseUrl,- props,- pages,- assets,- })- ),- [- propsByInstanceIdStore,- pagesStore,- assetsStore,- instanceId,- name,- assetBaseUrl,- ]- );- return useStore(store);-};-export const getInstanceIdFromComponentProps = (props: Record<string, unknown>) => {diff --git a/packages/sdk-components-react-remix/src/shared/remix-link.tsx b/packages/sdk-components-react-remix/src/shared/remix-link.tsxindex cafbc9fb96..07338f888c 100644--- a/packages/sdk-components-react-remix/src/shared/remix-link.tsx+++ b/packages/sdk-components-react-remix/src/shared/remix-link.tsx@@ -1,9 +1,6 @@import { forwardRef, type ComponentPropsWithoutRef } from "react";import { NavLink as RemixLink } from "@remix-run/react";-import {- usePropUrl,- getInstanceIdFromComponentProps,-} from "@webstudio-is/react-sdk";+import { usePages } from "@webstudio-is/react-sdk";import type { Link } from "@webstudio-is/sdk-components-react";type Props = Omit<ComponentPropsWithoutRef<typeof Link>, "target"> & {@@ -19,19 +16,17 @@ type Props = Omit<ComponentPropsWithoutRef<typeof Link>, "target"> & {export const wrapLinkComponent = (BaseLink: typeof Link) => {const Component = forwardRef<HTMLAnchorElement, Props>((props, ref) => {- const href = usePropUrl(getInstanceIdFromComponentProps(props), "href");-- if (href?.type === "page") {- let to = href.page.path === "" ? "/" : href.page.path;- const urlTo = new URL(to, "https://any-valid.url");- to = urlTo.pathname;-- if (href.hash !== undefined) {- urlTo.hash = encodeURIComponent(href.hash);- to = `${urlTo.pathname}${urlTo.hash}`;+ const pages = usePages();+ const href = props.href;++ // use remix link when url references webstudio page+ if (href !== undefined) {+ const url = new URL(href, "https://any-valid.url");+ for (const page of pages.values()) {+ if (page.path === url.pathname) {+ return <RemixLink {...props} to={href} ref={ref} />;+ }}-- return <RemixLink {...props} to={to} ref={ref} />;}const { prefetch, reloadDocument, replace, preventScrollReset, ...rest } =diff --git a/packages/sdk-components-react/src/link.tsx b/packages/sdk-components-react/src/link.tsxindex f8209a9d16..c2dcc0ed90 100644--- a/packages/sdk-components-react/src/link.tsx+++ b/packages/sdk-components-react/src/link.tsx@@ -1,8 +1,4 @@import { forwardRef, type ComponentProps } from "react";-import {- usePropUrl,- getInstanceIdFromComponentProps,-} from "@webstudio-is/react-sdk";export const defaultTag = "a";@@ -12,27 +8,7 @@ type Props = Omit<ComponentProps<"a">, "target"> & {};export const Link = forwardRef<HTMLAnchorElement, Props>((props, ref) => {- const href = usePropUrl(getInstanceIdFromComponentProps(props), "href");-- let url = "#";-- switch (href?.type) {- case "page": {- url = href.page.path === "" ? "/" : href.page.path;- const urlTo = new URL(url, "https://any-valid.url");- url = urlTo.pathname;-- if (href.hash !== undefined) {- urlTo.hash = encodeURIComponent(href.hash);- url = `${urlTo.pathname}${urlTo.hash}`;- }- break;- }- case "string":- url = href.url;- }-- return <a {...props} href={url} ref={ref} />;+ return <a {...props} href={props.href ?? "#"} ref={ref} />;});Link.displayName = "Link";