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
refactor: support nanostores as sync objects (#4454)
Bogdan Chadkin524f83203e16
diff --git a/apps/builder/app/builder/builder.tsx b/apps/builder/app/builder/builder.tsxindex f3c1418724..ff36de8775 100644--- a/apps/builder/app/builder/builder.tsx+++ b/apps/builder/app/builder/builder.tsx@@ -283,7 +283,7 @@ export const Builder = ({$publisher.set({ publish });}, [publish]);- useBuilderStore(publish);+ useBuilderStore();useSyncServer({projectId: project.id,authPermit,diff --git a/apps/builder/app/builder/features/settings-panel/shared.tsx b/apps/builder/app/builder/features/settings-panel/shared.tsxindex 3a5668d974..cf4066183b 100644--- a/apps/builder/app/builder/features/settings-panel/shared.tsx+++ b/apps/builder/app/builder/features/settings-panel/shared.tsx@@ -351,11 +351,13 @@ export const updateExpressionValue = (expression: string, value: unknown) => {}};+type BindingState = {+ overwritable: boolean;+ variant: BindingVariant;+};+export const useBindingState = (expression: undefined | string) => {- const $bindingState = useMemo((): ReadableAtom<{- overwritable: boolean;- variant: BindingVariant;- }> => {+ const $bindingState = useMemo((): ReadableAtom<BindingState> => {if (expression === undefined) {// value is not bound to expression and can be updatedreturn atom({ overwritable: true, variant: "default" });@@ -368,7 +370,7 @@ export const useBindingState = (expression: undefined | string) => {}return computed([$dataSources, $dataSourceVariables],- (dataSources, dataSourceVariables) => {+ (dataSources, dataSourceVariables): BindingState => {const dataSource = dataSources.get(potentialVariableId);// resources and parameters cannot be updatedif (dataSource?.type !== "variable") {diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex c5d044fa1f..95c416051c 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -227,7 +227,7 @@ type CanvasProps = {};export const Canvas = ({ params, imageLoader }: CanvasProps) => {- useCanvasStore(publish);+ useCanvasStore();const isDesignMode = useStore($isDesignMode);const isContentMode = useStore($isContentMode);diff --git a/apps/builder/app/shared/breakpoints/group-breakpoints.ts b/apps/builder/app/shared/breakpoints/group-breakpoints.tsindex 28c5f245a0..6f8601ccc6 100644--- a/apps/builder/app/shared/breakpoints/group-breakpoints.ts+++ b/apps/builder/app/shared/breakpoints/group-breakpoints.ts@@ -1,5 +1,5 @@import { compareMedia } from "@webstudio-is/css-engine";-import { isBaseBreakpoint } from "./is-base-breakpoint";+import { isBaseBreakpoint } from "../nano-states";// We group in 3 groups: min-width, base (no min/max), max-width conditionsexport const groupBreakpoints = <diff --git a/apps/builder/app/shared/breakpoints/index.ts b/apps/builder/app/shared/breakpoints/index.tsindex 3092511538..0f2d89b0af 100644--- a/apps/builder/app/shared/breakpoints/index.ts+++ b/apps/builder/app/shared/breakpoints/index.ts@@ -1,4 +1,4 @@-export * from "./is-base-breakpoint";+export { isBaseBreakpoint } from "~/shared/nano-states/breakpoints";export * from "./select-breakpoint-by-order";export * from "./group-breakpoints";export * from "./constants";diff --git a/apps/builder/app/shared/breakpoints/is-base-breakpoint.ts b/apps/builder/app/shared/breakpoints/is-base-breakpoint.tsdeleted file mode 100644index 9efe78db9c..0000000000--- a/apps/builder/app/shared/breakpoints/is-base-breakpoint.ts+++ /dev/null@@ -1,4 +0,0 @@-export const isBaseBreakpoint = (breakpoint: {- minWidth?: number;- maxWidth?: number;-}) => breakpoint.minWidth === undefined && breakpoint.maxWidth === undefined;diff --git a/apps/builder/app/shared/nano-states/breakpoints.ts b/apps/builder/app/shared/nano-states/breakpoints.tsindex bf9900a178..86662d71c0 100644--- a/apps/builder/app/shared/nano-states/breakpoints.ts+++ b/apps/builder/app/shared/nano-states/breakpoints.ts@@ -1,6 +1,10 @@import { atom, computed } from "nanostores";import type { Breakpoint, Breakpoints } from "@webstudio-is/sdk";-import { isBaseBreakpoint } from "../breakpoints";++export const isBaseBreakpoint = (breakpoint: {+ minWidth?: number;+ maxWidth?: number;+}) => breakpoint.minWidth === undefined && breakpoint.maxWidth === undefined;export const $breakpoints = atom<Breakpoints>(new Map());@@ -28,7 +32,3 @@ export const $selectedBreakpoint = computed();});--export const $synchronizedBreakpoints = [- ["selectedBreakpointId", $selectedBreakpointId],-] as const;diff --git a/apps/builder/app/shared/nano-states/canvas.ts b/apps/builder/app/shared/nano-states/canvas.tsindex ffecc3c38c..26d5ddfaeb 100644--- a/apps/builder/app/shared/nano-states/canvas.ts+++ b/apps/builder/app/shared/nano-states/canvas.ts@@ -63,14 +63,6 @@ export const $collaborativeInstanceSelector = atom<export const $collaborativeInstanceRect = atom<undefined | DOMRect>(undefined);-export const synchronizedCanvasStores = [- ["textToolbar", $textToolbar],- ["selectedInstanceOutline", $selectedInstanceOutline],- ["hoveredInstanceOutline", $hoveredInstanceOutline],- ["$collaborativeInstanceSelector", $collaborativeInstanceSelector],- ["$collaborativeInstanceRect", $collaborativeInstanceRect],-] as const;-export const $canvasIframeState = atom<"idle" | "ready">("idle");export const $detectedFontsWeights = atom<Map<string, Array<FontWeight>>>(diff --git a/apps/builder/app/shared/nano-states/components.ts b/apps/builder/app/shared/nano-states/components.tsindex 17a2d3308f..29ee90ff7e 100644--- a/apps/builder/app/shared/nano-states/components.ts+++ b/apps/builder/app/shared/nano-states/components.ts@@ -241,8 +241,3 @@ export const registerComponentLibrary = ({}$registeredComponentPropsMetas.set(nextPropsMetas);};--export const synchronizedComponentsMetaStores = [- ["registeredComponentMetas", $registeredComponentMetas],- ["registeredComponentPropsMetas", $registeredComponentPropsMetas],-] as const;diff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.tsindex 9e867d7ce7..352757e04f 100644--- a/apps/builder/app/shared/nano-states/instances.ts+++ b/apps/builder/app/shared/nano-states/instances.ts@@ -32,8 +32,3 @@ export const $textEditingInstanceSelector = atom<>();export const $instances = atom<Instances>(new Map());--export const $synchronizedInstances = [- ["textEditingInstanceSelector", $textEditingInstanceSelector],- ["isResizingCanvas", $isResizingCanvas],-] as const;diff --git a/apps/builder/app/shared/store-utils.ts b/apps/builder/app/shared/store-utils.tsindex b0d1670596..848d5ffbbe 100644--- a/apps/builder/app/shared/store-utils.ts+++ b/apps/builder/app/shared/store-utils.ts@@ -1,4 +1,9 @@-import { type AnyStore, type StoreValue, computed } from "nanostores";+import {+ type AnyStore,+ type ReadableAtom,+ type StoreValue,+ computed,+} from "nanostores";import { shallowEqual } from "shallow-equal";// https://github.com/nanostores/nanostores/blob/0d27b0d18d0f471ca0ac5439137d3dac71d01f08/computed/index.d.ts@@ -10,15 +15,17 @@ type StoreValues<Stores extends AnyStore[]> = {// eslint-disable-next-line @typescript-eslint/no-explicit-anytype Comparable = Record<string, any> | any[] | null | undefined;-export const shallowComputed = <- Value extends Comparable,- OriginStores extends AnyStore[],->(- stores: [...OriginStores],- cb: (...values: StoreValues<OriginStores>) => Value-) => {- let prevComputed: Value;- return computed<Value, OriginStores>(stores, (...values) => {+interface Computed {+ <Value extends Comparable, OriginStores extends AnyStore[]>(+ stores: [...OriginStores],+ cb: (...values: StoreValues<OriginStores>) => Value+ ): ReadableAtom<Value>;+}++export const shallowComputed: Computed = (stores, cb) => {+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ let prevComputed: any;+ return (computed as Computed)(stores, (...values) => {const nextComputed = cb(...values);if (shallowEqual(prevComputed, nextComputed)) {return prevComputed;diff --git a/apps/builder/app/shared/sync-client.test.ts b/apps/builder/app/shared/sync-client.test.tsindex 81b606b0ea..56192b14cb 100644--- a/apps/builder/app/shared/sync-client.test.ts+++ b/apps/builder/app/shared/sync-client.test.ts@@ -1,9 +1,15 @@-import { expect, test } from "vitest";+import { describe, expect, test } from "vitest";import { createNanoEvents } from "nanoevents";import { atom } from "nanostores";import { Store } from "immerhin";import { enableMapSet } from "immer";-import { ImmerhinSyncObject, SyncClient, SyncObjectPool } from "./sync-client";+import {+ ImmerhinSyncObject,+ NanostoresSyncObject,+ SyncClient,+ SyncObjectPool,+ type Transaction,+} from "./sync-client";enableMapSet();@@ -211,3 +217,57 @@ test("support pool of objects", () => {new Map([["mark", "Mark Grayson"]]));});++describe("nanostores sync object", () => {+ test("sync initial state and exchange transactions", () => {+ const emitter = createNanoEvents();+ const $leader = atom(1);+ const $follower = atom(2);+ new SyncClient({+ role: "leader",+ object: new NanostoresSyncObject("my-data", $leader),+ emitter,+ }).connect({ signal: new AbortController().signal });+ new SyncClient({+ role: "follower",+ object: new NanostoresSyncObject("my-data", $follower),+ emitter,+ }).connect({ signal: new AbortController().signal });+ expect($leader.get()).toEqual(1);+ expect($follower.get()).toEqual(1);+ $leader.set(3);+ expect($leader.get()).toEqual(3);+ expect($follower.get()).toEqual(3);+ $follower.set(5);+ expect($leader.get()).toEqual(5);+ expect($follower.get()).toEqual(5);+ });++ test("prevent sending back state", () => {+ const $store = atom(1);+ const object = new NanostoresSyncObject("nanostores", $store);+ const transactions: Transaction[] = [];+ object.subscribe((transaction) => {+ transactions.push(transaction);+ }, new AbortController().signal);+ expect(transactions).toEqual([]);+ object.setState(2);+ expect(transactions).toEqual([]);+ });++ test("prevent sending back transactions", () => {+ const $store = atom(1);+ const object = new NanostoresSyncObject("nanostores", $store);+ const transactions: Transaction[] = [];+ object.subscribe((transaction) => {+ transactions.push(transaction);+ }, new AbortController().signal);+ expect(transactions).toEqual([]);+ object.addTransaction({+ id: "my-transaction",+ object: "nanostores",+ payload: 2,+ });+ expect(transactions).toEqual([]);+ });+});diff --git a/apps/builder/app/shared/sync-client.ts b/apps/builder/app/shared/sync-client.tsindex 342e410e25..3abc319978 100644--- a/apps/builder/app/shared/sync-client.ts+++ b/apps/builder/app/shared/sync-client.ts@@ -1,18 +1,31 @@import { nanoid } from "nanoid";import { createNanoEvents, type Emitter } from "nanoevents";import type { Change, Store } from "immerhin";+import type { WritableAtom } from "nanostores";-type Transaction = {+export type Transaction<Payload = unknown> = {id: string;object: string;- changes: Change[];+ payload: Payload;};-type RevertedTransaction = {+export type RevertedTransaction = {id: string;object: string;};+interface SyncObject {+ name: string;+ getState(): unknown;+ setState(state: unknown): void;+ addTransaction(transaction: Transaction): void;+ revertTransaction(transaction: RevertedTransaction): void;+ subscribe(+ callback: (transaction: Transaction) => void,+ signal: AbortSignal+ ): void;+}+export class ImmerhinSyncObject implements SyncObject {name: string;store: Store;@@ -34,18 +47,58 @@ export class ImmerhinSyncObject implements SyncObject {$store.set(structuredClone(state.get(namespace)));}}- addTransaction(transaction: Transaction) {- this.store.addTransaction(transaction.id, transaction.changes, "remote");+ addTransaction(transaction: Transaction<Change[]>) {+ this.store.addTransaction(transaction.id, transaction.payload, "remote");}revertTransaction(transaction: RevertedTransaction) {this.store.revertTransaction(transaction.id);}- subscribe(callback: (transaction: Transaction) => void, signal: AbortSignal) {- const unsubscribe = this.store.subscribe((id, changes, source) => {+ subscribe(+ callback: (transaction: Transaction<Change[]>) => void,+ signal: AbortSignal+ ) {+ const unsubscribe = this.store.subscribe((id, payload, source) => {if (source === "remote") {return;}- callback({ id, object: this.name, changes });+ callback({ id, object: this.name, payload });+ });+ signal.addEventListener("abort", unsubscribe);+ }+}++export class NanostoresSyncObject implements SyncObject {+ name: string;+ store: WritableAtom<unknown>;+ // track the source of "store.set" to avoid cyclic updates+ operation: "local" | "state" | "add" = "local";+ constructor(name: string, store: WritableAtom<unknown>) {+ this.name = name;+ this.store = store;+ }+ getState() {+ return this.store.get();+ }+ setState(state: unknown) {+ this.operation = "state";+ this.store.set(state);+ this.operation = "local";+ }+ addTransaction(transaction: Transaction) {+ this.operation = "add";+ this.store.set(transaction.payload);+ this.operation = "local";+ }+ revertTransaction(_transaction: RevertedTransaction) {+ // @todo store the list of transactions+ }+ subscribe(callback: (transaction: Transaction) => void, signal: AbortSignal) {+ const unsubscribe = this.store.listen((payload) => {+ if (this.operation !== "local") {+ return;+ }+ const transaction = { id: nanoid(), object: this.name, payload };+ callback(transaction);});signal.addEventListener("abort", unsubscribe);}@@ -86,7 +139,7 @@ export class SyncObjectPool implements SyncObject {type SyncMessage =| { type: "connect"; clientId: string }- | { type: "state"; clientId: string; state: Map<string, unknown> }+ | { type: "state"; clientId: string; state: unknown }| { type: "commit"; clientId: string; transaction: Transaction }| { type: "revert"; clientId: string; transaction: RevertedTransaction };@@ -100,18 +153,6 @@ type SyncClientOptions = {emitter?: SyncEmitter;};-interface SyncObject {- name: string;- getState(): Map<string, unknown>;- setState(state: Map<string, unknown>): void;- addTransaction(transaction: Transaction): void;- revertTransaction(transaction: RevertedTransaction): void;- subscribe(- callback: (transaction: Transaction) => void,- signal: AbortSignal- ): void;-}-export class SyncClient {clientId = nanoid();role: SyncClientOptions["role"];diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex d286e5d1a8..f518421153 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -1,9 +1,6 @@-import { nanoid } from "nanoid";import { Store } from "immerhin";import { enableMapSet, setAutoFreeze } from "immer";-import type { WritableAtom } from "nanostores";import { useEffect } from "react";-import { type Publish, subscribe } from "~/shared/pubsub";import {$project,$pages,@@ -24,12 +21,8 @@ import {$hoveredInstanceSelector,$authTokenPermissions,$toastErrors,- synchronizedCanvasStores,- $synchronizedInstances,- $synchronizedBreakpoints,$selectedStyleSources,$selectedStyleState,- synchronizedComponentsMetaStores,$dataSourceVariables,$dragAndDropState,$selectedInstanceStates,@@ -41,11 +34,22 @@ import {$memoryProps,$detectedFontsWeights,$builderMode,+ $selectedBreakpointId,+ $textEditingInstanceSelector,+ $isResizingCanvas,+ $collaborativeInstanceRect,+ $collaborativeInstanceSelector,+ $hoveredInstanceOutline,+ $selectedInstanceOutline,+ $textToolbar,+ $registeredComponentMetas,+ $registeredComponentPropsMetas,} from "~/shared/nano-states";import { $ephemeralStyles } from "~/canvas/stores";import { $awareness } from "../awareness";import {ImmerhinSyncObject,+ NanostoresSyncObject,SyncClient,SyncObjectPool,type SyncEmitter,@@ -55,31 +59,8 @@ enableMapSet();// safari structuredClone fixsetAutoFreeze(false);-const appId = nanoid();--type StoreData = {- namespace: string;- value: unknown;-};--type SyncEventSource = "canvas" | "builder";--declare module "~/shared/pubsub" {- export interface PubsubMap {- connect: { sourceAppId: string };- disconnect: { sourceAppId: string };- sendStoreData: {- // distinct source to avoid infinite loop- source: SyncEventSource;- data: StoreData[];- };- }-}-export const clientSyncStore = new Store();export const serverSyncStore = new Store();-const clientStores = new Map<string, WritableAtom<unknown>>();-const initializedStores = new Set<string>();export const registerContainers = () => {// synchronize patches@@ -94,126 +75,85 @@ export const registerContainers = () => {serverSyncStore.register("resources", $resources);serverSyncStore.register("assets", $assets);serverSyncStore.register("marketplaceProduct", $marketplaceProduct);- // synchronize whole states- clientStores.set("project", $project);- clientStores.set("dataSourceVariables", $dataSourceVariables);- clientStores.set("resourceValues", $resourceValues);- clientStores.set("selectedPageHash", $selectedPageHash);- clientStores.set("selectedInstanceSelector", $selectedInstanceSelector);- clientStores.set("awareness", $awareness);- clientStores.set(- "selectedInstanceBrowserStyle",- $selectedInstanceBrowserStyle- );- clientStores.set(- "$selectedInstanceIntanceToTag",- $selectedInstanceIntanceToTag- );- clientStores.set("$selectedInstanceUnitSizes", $selectedInstanceUnitSizes);- clientStores.set(- "$selectedInstanceRenderState",- $selectedInstanceRenderState- );- clientStores.set("hoveredInstanceSelector", $hoveredInstanceSelector);- clientStores.set("builderMode", $builderMode);- clientStores.set("authTokenPermissions", $authTokenPermissions);- clientStores.set("toastErrors", $toastErrors);-- clientStores.set("selectedStyleSources", $selectedStyleSources);- clientStores.set("selectedStyleState", $selectedStyleState);- clientStores.set("dragAndDropState", $dragAndDropState);- clientStores.set("ephemeralStyles", $ephemeralStyles);- clientStores.set("selectedInstanceStates", $selectedInstanceStates);- clientStores.set("canvasIframeState", $canvasIframeState);- clientStores.set("uploadingFilesDataStore", $uploadingFilesDataStore);- clientStores.set("memoryProps", $memoryProps);- clientStores.set("detectedFontsWeights", $detectedFontsWeights);-- for (const [name, store] of $synchronizedBreakpoints) {- clientStores.set(name, store);- }- for (const [name, store] of $synchronizedInstances) {- clientStores.set(name, store);- }- for (const [name, store] of synchronizedCanvasStores) {- clientStores.set(name, store);- }- for (const [name, store] of synchronizedComponentsMetaStores) {- clientStores.set(name, store);- }-- // use listen to not invoke initially- for (const [name, store] of clientStores) {- // here we rely on the fact registerContainers is called before any store.set- // is called to find which store is initialized to send its data to the other realm- // this can help to find the direction between builder and canvas- // so canvas could send initial data to builder without builder overriding it- // with default store value- const unsubscribe = store.listen(() => {- initializedStores.add(name);- unsubscribe();- });- }};-const syncStoresState = (name: SyncEventSource, publish: Publish) => {- const latestData = new Map<string, unknown>();-- const unsubscribeRemoteChanges = subscribe(- "sendStoreData",- ({ source, data }) => {- /// prevent reapplying own changes- if (source === name) {- return;- }- for (const { namespace, value } of data) {- // apply state stores data- const $state = clientStores.get(namespace);- if ($state) {- // should be called before store set- // to be accessible in listen callback- latestData.set(namespace, value);- $state.set(value);- }- }- }- );-- const unsubscribes: Array<() => void> = [];- for (const [namespace, store] of clientStores) {- unsubscribes.push(- // use listen to not invoke initially- store.listen((value) => {- // nanostores cannot identify the source of change- // so we check the latest value applied to the store- // and do nothing if was set by synchronization logic- if (latestData.has(namespace) && latestData.get(namespace) === value) {- return;- }- latestData.set(namespace, value);-- publish({- type: "sendStoreData",- payload: {- source: name,- data: [- {- namespace,- value,- },- ],- },- });- })- );- }-- return () => {- unsubscribeRemoteChanges();- for (const unsubscribe of unsubscribes) {- unsubscribe();- }- };+const createObjectPool = () => {+ return new SyncObjectPool([+ new ImmerhinSyncObject("server", serverSyncStore),+ new ImmerhinSyncObject("client", clientSyncStore),+ new NanostoresSyncObject(+ "selectedInstanceSelector",+ $selectedInstanceSelector+ ),+ new NanostoresSyncObject("awareness", $awareness),+ new NanostoresSyncObject("project", $project),+ new NanostoresSyncObject("dataSourceVariables", $dataSourceVariables),+ new NanostoresSyncObject("resourceValues", $resourceValues),+ new NanostoresSyncObject("selectedPageHash", $selectedPageHash),+ new NanostoresSyncObject(+ "selectedInstanceBrowserStyle",+ $selectedInstanceBrowserStyle+ ),+ new NanostoresSyncObject(+ "$selectedInstanceIntanceToTag",+ $selectedInstanceIntanceToTag+ ),+ new NanostoresSyncObject(+ "$selectedInstanceUnitSizes",+ $selectedInstanceUnitSizes+ ),+ new NanostoresSyncObject(+ "$selectedInstanceRenderState",+ $selectedInstanceRenderState+ ),+ new NanostoresSyncObject(+ "hoveredInstanceSelector",+ $hoveredInstanceSelector+ ),+ new NanostoresSyncObject("builderMode", $builderMode),+ new NanostoresSyncObject("authTokenPermissions", $authTokenPermissions),+ new NanostoresSyncObject("toastErrors", $toastErrors),+ new NanostoresSyncObject("selectedStyleSources", $selectedStyleSources),+ new NanostoresSyncObject("selectedStyleState", $selectedStyleState),+ new NanostoresSyncObject("dragAndDropState", $dragAndDropState),+ new NanostoresSyncObject("ephemeralStyles", $ephemeralStyles),+ new NanostoresSyncObject("selectedInstanceStates", $selectedInstanceStates),+ new NanostoresSyncObject("canvasIframeState", $canvasIframeState),+ new NanostoresSyncObject(+ "uploadingFilesDataStore",+ $uploadingFilesDataStore+ ),+ new NanostoresSyncObject("memoryProps", $memoryProps),+ new NanostoresSyncObject("detectedFontsWeights", $detectedFontsWeights),+ new NanostoresSyncObject("selectedBreakpointId", $selectedBreakpointId),+ new NanostoresSyncObject(+ "textEditingInstanceSelector",+ $textEditingInstanceSelector+ ),+ new NanostoresSyncObject("isResizingCanvas", $isResizingCanvas),+ new NanostoresSyncObject("textToolbar", $textToolbar),+ new NanostoresSyncObject(+ "selectedInstanceOutline",+ $selectedInstanceOutline+ ),+ new NanostoresSyncObject("hoveredInstanceOutline", $hoveredInstanceOutline),+ new NanostoresSyncObject(+ "collaborativeInstanceSelector",+ $collaborativeInstanceSelector+ ),+ new NanostoresSyncObject(+ "collaborativeInstanceRect",+ $collaborativeInstanceRect+ ),+ new NanostoresSyncObject(+ "registeredComponentMetas",+ $registeredComponentMetas+ ),+ new NanostoresSyncObject(+ "registeredComponentPropsMetas",+ $registeredComponentPropsMetas+ ),+ ]);};declare global {@@ -231,107 +171,34 @@ const sharedSyncEmitter =? undefined: window.__webstudioSharedSyncEmitter__;-const objectPool = new SyncObjectPool([- new ImmerhinSyncObject("server", serverSyncStore),- new ImmerhinSyncObject("client", clientSyncStore),-]);--export const useCanvasStore = (publish: Publish) => {+export const useCanvasStore = () => {useEffect(() => {const canvasClient = new SyncClient({role: "follower",- object: objectPool,+ object: createObjectPool(),emitter: sharedSyncEmitter,});const controller = new AbortController();canvasClient.connect({ signal: controller.signal });- // 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(),- });- }- }- 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);-return () => {- publish({- type: "disconnect",- payload: { sourceAppId: appId },- });- unsubscribeStoresState();controller.abort();};- }, [publish]);+ }, []);};export const builderClient = new SyncClient({role: "leader",- object: objectPool,+ object: createObjectPool(),});-export const useBuilderStore = (publish: Publish) => {+export const useBuilderStore = () => {useEffect(() => {const controller = new AbortController();builderClient.connect({ signal: controller.signal });- let unsubscribeStoresState: 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);- // 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: "builder",- data,- },- });- });-- const unsubscribeDisconnect = subscribe("disconnect", () => {- unsubscribeStoresState?.();- });return () => {- unsubscribeConnect();- unsubscribeDisconnect();- unsubscribeStoresState?.();controller.abort();};- }, [publish]);+ }, []);};diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex cfbe4564c4..bb2a480f68 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -40,7 +40,7 @@"@lezer/common": "^1.2.3","@lezer/css": "^1.1.9","@lezer/highlight": "^1.2.1",- "@nanostores/react": "^0.7.1",+ "@nanostores/react": "^0.8.0","@radix-ui/react-select": "^2.1.2","@radix-ui/react-tooltip": "^1.1.3","@react-aria/interactions": "^3.22.4",@@ -96,7 +96,7 @@"micromark-extension-gfm": "^3.0.0","nanoevents": "^9.1.0","nanoid": "^5.0.8",- "nanostores": "^0.9.3",+ "nanostores": "^0.11.3","picocolors": "^1.1.0","pretty-bytes": "^6.1.1","react": "18.3.0-canary-14898b6a9-20240318",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 303ddeee88..65e6911dc2 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -188,8 +188,8 @@ importers:specifier: ^1.2.1version: 1.2.1'@nanostores/react':- specifier: ^0.7.1- version: 0.7.1([email protected])([email protected])+ specifier: ^0.8.0+ version: 0.8.0([email protected])([email protected])'@radix-ui/react-select':specifier: ^2.1.2version: 2.1.2(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])@@ -356,8 +356,8 @@ importers:specifier: ^5.0.8version: 5.0.8nanostores:- specifier: ^0.9.3- version: 0.9.3+ specifier: ^0.11.3+ version: 0.11.3picocolors:specifier: ^1.1.0version: 1.1.0@@ -3493,11 +3493,11 @@ packages:'@mdx-js/[email protected]':resolution: {integrity: sha512-jLuwRlz8DQfQNiUCJR50Y09CGPq3fLtmtUQfVrj79E0JWu3dvsVcxVIcfhR5h0iXu+/z++zDrYeiJqifRynJkA==}- '@nanostores/[email protected]':- resolution: {integrity: sha512-EXQg9N4MdI4eJQz/AZLIx3hxQ6BuBmV4Q55bCd5YCSgEOAW7tGTsIZxpRXxvxLXzflNvHTBvfrDNY38TlSVBkQ==}- engines: {node: ^16.0.0 || ^18.0.0 || >=20.0.0}+ '@nanostores/[email protected]':+ resolution: {integrity: sha512-MhbVB7NQLboq/Z9fRTDen9zib/YCffe6mn+3Xg5MOYByMX5Xx98SOZjk/Nd3yvOd/g7GjlQqwXj0KF2lPb6CEQ==}+ engines: {node: ^18.0.0 || >=20.0.0}peerDependencies:- nanostores: ^0.9.0+ nanostores: ^0.9.0 || ^0.10.0 || ^0.11.0react: 18.3.0-canary-14898b6a9-20240318'@netlify/[email protected]':@@ -7094,9 +7094,9 @@ packages:engines: {node: ^18 || >=20}hasBin: true- resolution: {integrity: sha512-KobZjcVyNndNrb5DAjfs0WG0lRcZu5Q1BOrfTOxokFLi25zFrWPjg+joXC6kuDqNfSt9fQwppyjUBkRPtsL+8w==}- engines: {node: ^16.0.0 || ^18.0.0 || >=20.0.0}+ resolution: {integrity: sha512-TUes3xKIX33re4QzdxwZ6tdbodjmn3tWXCEc1uokiEmo14sI1EaGYNs2k3bU2pyyGNmBqFGAVl6jAGWd06AVIg==}+ engines: {node: ^18.0.0 || >=20.0.0}resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}@@ -10033,9 +10033,9 @@ snapshots:transitivePeerDependencies:- supports-colordependencies:- nanostores: 0.9.3+ nanostores: 0.11.3react: 18.3.0-canary-14898b6a9-20240318'@netlify/[email protected]': {}@@ -14466,7 +14466,7 @@ snapshots:- [email protected]: {}+ [email protected]: {}