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
fix: sync commands after builder and canvas initialized (#2455)
Bogdan Chadkin3ce14f378435
diff --git a/apps/builder/app/builder/features/workspace/canvas-iframe.tsx b/apps/builder/app/builder/features/workspace/canvas-iframe.tsxindex 59e098408b..2bcb86f576 100644--- a/apps/builder/app/builder/features/workspace/canvas-iframe.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-iframe.tsx@@ -1,4 +1,4 @@-import { forwardRef } from "react";+import { forwardRef, useEffect, useState } from "react";import {type CSS,css,@@ -16,7 +16,17 @@ type CanvasIframeProps = {export const CanvasIframe = forwardRef<HTMLIFrameElement, CanvasIframeProps>(({ css, ...rest }, ref) => {- return <iframe {...rest} ref={ref} className={iframeStyle({ css })} />;+ // initialize canvas after builder is rendered+ // and synchronizatio is initialized+ const [isInitialized, setInitialized] = useState(false);+ useEffect(() => {+ setInitialized(true);+ }, []);+ return (+ isInitialized && (+ <iframe {...rest} ref={ref} className={iframeStyle({ css })} />+ )+ );});diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex 38e0cb4fab..109a364903 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -1,4 +1,4 @@-import { useMemo, useEffect } from "react";+import { useMemo, useEffect, useState } from "react";import { useStore } from "@nanostores/react";import { computed } from "nanostores";import { Scripts, ScrollRestoration } from "@remix-run/react";@@ -21,11 +21,7 @@ import * as radixComponentMetas from "@webstudio-is/sdk-components-react-radix/mimport * as radixComponentPropsMetas from "@webstudio-is/sdk-components-react-radix/props";import { hooks as radixComponentHooks } from "@webstudio-is/sdk-components-react-radix/hooks";import { $publisher, publish } from "~/shared/pubsub";-import {- handshakenStore,- registerContainers,- useCanvasStore,-} from "~/shared/sync";+import { registerContainers, useCanvasStore } from "~/shared/sync";import { useSharedShortcuts } from "~/shared/shortcuts";import { useCanvasShortcuts } from "./canvas-shortcuts";import { useManageDesignModeStyles, GlobalStyles } from "./shared/styles";@@ -172,7 +168,6 @@ export const Canvas = ({params,imageLoader,}: CanvasProps): JSX.Element | null => {- const handshaken = useStore(handshakenStore);useCanvasStore(publish);const isPreviewMode = useStore($isPreviewMode);@@ -233,6 +228,11 @@ export const Canvas = ({const instances = useStore(instancesStore);const elements = useElementsTree(components, instances, params, imageLoader);+ const [isInitialized, setInitialized] = useState(false);+ useEffect(() => {+ setInitialized(true);+ }, []);+if (components.size === 0 || instances.size === 0) {return (<body>@@ -250,7 +250,7 @@ export const Canvas = ({// Call hooks after render to ensure effects are last.// Helps improve outline calculations as all styles are then applied.}- {isPreviewMode === false && handshaken === true && (+ {isPreviewMode === false && isInitialized && (<DesignMode params={params} />)}</>diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex 6a10d714e4..02be6e3e55 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -1,6 +1,7 @@+import { nanoid } from "nanoid";import { Store, type Change } from "immerhin";import { enableMapSet } from "immer";-import { atom, type WritableAtom } from "nanostores";+import type { WritableAtom } from "nanostores";import { useEffect } from "react";import { type Publish, subscribe } from "~/shared/pubsub";import {@@ -34,6 +35,8 @@ import {enableMapSet();+const appId = nanoid();+type StoreData = {namespace: string;value: unknown;@@ -43,8 +46,8 @@ type SyncEventSource = "canvas" | "builder";declare module "~/shared/pubsub" {export interface PubsubMap {- handshake: { source: SyncEventSource };-+ connect: { sourceAppId: string };+ disconnect: { sourceAppId: string };sendStoreData: {// distinct source to avoid infinite loopsource: SyncEventSource;@@ -260,105 +263,60 @@ const syncStoresState = (name: SyncEventSource, publish: Publish) => {};};-export const handshakenStore = atom(false);--const handshakeAndSyncStores = (- source: SyncEventSource,- publish: Publish,- sync: (publish: Publish) => () => void-) => {- const actions: Parameters<typeof publish>[0][] = [];-- // Until builder is ready store action in local cache- const publishAction: typeof publish = (action) => {- const destinationReady = handshakenStore.get();- if (destinationReady) {- return publish(action);- }- actions.push({ payload: undefined, ...action });- };-- const unsubscribe = sync(publishAction);-- const handshakeAction = {- type: "handshake",- payload: {- source,- },- } as const;-- publish(handshakeAction);-- const destinationStoreReady = subscribe("handshake", (payload) => {- if (source === payload.source) {- return;- }-- const destinationReady = handshakenStore.get();- if (destinationReady) {- return;- }-- // We need to publish it here last time- publish(handshakeAction);-- for (const action of actions) {- publish(action);- }-- // cleanup- actions.length = 0;-- handshakenStore.set(true);-- destinationStoreReady();- });-- return () => {- destinationStoreReady();- unsubscribe();- };-};-export const useCanvasStore = (publish: Publish) => {useEffect(() => {- return handshakeAndSyncStores("canvas", publish, (publish) => {- const unsubscribeStoresState = syncStoresState("canvas", publish);- const unsubscribeStoresChanges = syncStoresChanges("canvas", publish);+ // connect to builder to get latest changes+ publish({+ type: "connect",+ payload: { sourceAppId: appId },+ });- // immerhin data is sent only initially so not part of syncStoresState- // expect data to be populated by the time effect is called- const data = [];- for (const [namespace, store] of clientStores) {- if (initializedStores.has(namespace)) {- data.push({- namespace,- value: store.get(),- });- }+ // immerhin data is sent only initially so not part of syncStoresState+ // expect data to be populated by the time effect is called+ const data = [];+ for (const [namespace, store] of clientStores) {+ if (initializedStores.has(namespace)) {+ data.push({+ namespace,+ value: store.get(),+ });}+ }+ publish({+ type: "sendStoreData",+ payload: {+ source: "canvas",+ data,+ },+ });++ // subscribe stores after connect even so builder is ready to receive+ // changes from immerhin queue+ const unsubscribeStoresState = syncStoresState("canvas", publish);+ const unsubscribeStoresChanges = syncStoresChanges("canvas", publish);++ return () => {publish({- type: "sendStoreData",- payload: {- source: "canvas",- data,- },+ type: "disconnect",+ payload: { sourceAppId: appId },});-- return () => {- unsubscribeStoresState();- unsubscribeStoresChanges();- };- });+ unsubscribeStoresState();+ unsubscribeStoresChanges();+ };}, [publish]);};export const useBuilderStore = (publish: Publish) => {useEffect(() => {- return handshakeAndSyncStores("builder", publish, (publish) => {- const unsubscribeStoresState = syncStoresState("builder", publish);- const unsubscribeStoresChanges = syncStoresChanges("builder", publish);-+ let unsubscribeStoresState: undefined | (() => void);+ let unsubscribeStoresChanges: undefined | (() => void);+ const unsubscribeConnect = subscribe("connect", () => {+ // subscribe stores after connection so canvas is ready to receive+ // changes from immerhin queue+ // @todo subscribe prematurely and compute initial changes+ // from current state whenever new app is connected+ unsubscribeStoresState = syncStoresState("builder", publish);+ unsubscribeStoresChanges = syncStoresChanges("builder", publish);// immerhin data is sent only initially so not part of syncStoresState// expect data to be populated by the time effect is calledconst data = [];@@ -383,17 +341,18 @@ export const useBuilderStore = (publish: Publish) => {data,},});+ });- return () => {- unsubscribeStoresState();- unsubscribeStoresChanges();- };+ const unsubscribeDisconnect = subscribe("disconnect", () => {+ unsubscribeStoresState?.();+ unsubscribeStoresChanges?.();});- }, [publish]);- useEffect(() => {return () => {- handshakenStore.set(false);+ unsubscribeConnect();+ unsubscribeDisconnect();+ unsubscribeStoresState?.();+ unsubscribeStoresChanges?.();};- }, []);+ }, [publish]);};