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: Preserve selection after instance deletion (#5879)
Oleg Isonendd99e49fbeda
diff --git a/apps/builder/app/shared/nano-states/instance-selection.ts b/apps/builder/app/shared/nano-states/instance-selection.tsindex 4f9dbca592..0bae3adf4a 100644--- a/apps/builder/app/shared/nano-states/instance-selection.ts+++ b/apps/builder/app/shared/nano-states/instance-selection.ts@@ -11,6 +11,12 @@ import {import { $instances } from "../sync/data-stores";export const $allSelectedInstanceSelectors = atom<InstanceSelector[]>([]);+// Instance pruning is derived from tree updates and must not be synchronized+// back as an explicit selection change.+export const $instanceSelectionUpdate = atom<{+ revision: number;+ origin: "explicit" | "instance-pruning";+}>({ revision: 0, origin: "explicit" });export const $selectedInstanceSelector = computed($allSelectedInstanceSelectors,@@ -21,18 +27,25 @@ export const $selectedInstanceSelector = computed(});-export const selectInstances = (instanceSelectors: InstanceSelector[]) => {+const setSelectedInstances = (+ instanceSelectors: InstanceSelector[],+ origin: "explicit" | "instance-pruning"+) => {const normalizedSelectors = normalizeInstanceSelectors(instanceSelectors);- if (- areSelectorListsEqual(- $allSelectedInstanceSelectors.get(),- normalizedSelectors- ) === false- ) {+ const selectedSelectors = $allSelectedInstanceSelectors.get();+ if (areSelectorListsEqual(selectedSelectors, normalizedSelectors) === false) {+ $instanceSelectionUpdate.set({+ revision: $instanceSelectionUpdate.get().revision + 1,+ origin,+ });$allSelectedInstanceSelectors.set(normalizedSelectors);}};+export const selectInstances = (instanceSelectors: InstanceSelector[]) => {+ setSelectedInstances(instanceSelectors, "explicit");+};+export const clearInstanceSelection = () => {selectInstances([]);};@@ -67,9 +80,10 @@ $instances.listen((instances) => {if (selectedSelectors.length === 0) {return;}- selectInstances(+ setSelectedInstances(selectedSelectors.filter((instanceSelector) =>canResolveInstanceSelector(instanceSelector, instances)- )+ ),+ "instance-pruning");});diff --git a/apps/builder/app/shared/sync/sync-stores.test.ts b/apps/builder/app/shared/sync/sync-stores.test.tsindex 0de7565aae..b3dd210e18 100644--- a/apps/builder/app/shared/sync/sync-stores.test.ts+++ b/apps/builder/app/shared/sync/sync-stores.test.ts@@ -1,4 +1,5 @@import { afterEach, describe, expect, test, vi } from "vitest";+import type { Instance } from "@webstudio-is/sdk";import {$allSelectedInstanceSelectors,$selectedInstanceOutlines,@@ -8,29 +9,130 @@ import {selectInstances,} from "../nano-states";import { __testing__, createObjectPool } from "./sync-stores";+import { $instances } from "./data-stores";const { SelectedPageAndInstanceSyncObject } = __testing__;+const subscriptionControllers: AbortController[] = [];const waitForBatchedStore = () =>new Promise<void>((resolve) => {setTimeout(resolve, 0);});+const setTestInstances = (...instanceIds: string[]) => {+ const instances = new Map<string, Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: instanceIds.map((value) => ({ type: "id", value })),+ },+ ],+ ]);+ for (const id of instanceIds) {+ instances.set(id, {+ type: "instance",+ id,+ component: "Box",+ children: [],+ });+ }+ $instances.set(instances);+};++const subscribeSelectionSync = async () => {+ const syncObject = new SelectedPageAndInstanceSyncObject();+ const sendTransaction = vi.fn();+ const controller = new AbortController();+ subscriptionControllers.push(controller);+ syncObject.subscribe(sendTransaction, controller.signal);+ await waitForBatchedStore();+ sendTransaction.mockClear();+ return { sendTransaction, syncObject };+};+afterEach(() => {+ for (const controller of subscriptionControllers.splice(0)) {+ controller.abort();+ }$selectedPageId.set(undefined);selectInstance(undefined);$allSelectedInstanceSelectors.set([]);$selectedInstanceOutlines.set([]);+ $instances.set(new Map());});describe("SelectedPageAndInstanceSyncObject", () => {- test("sends page and instance selector as one final transaction", async () => {- const syncObject = new SelectedPageAndInstanceSyncObject();- const sendTransaction = vi.fn();- syncObject.subscribe(sendTransaction, new AbortController().signal);+ test("does not publish selection pruned by an instance update", async () => {+ setTestInstances("box");+ selectInstance(["box", "body"]);+ const { sendTransaction } = await subscribeSelectionSync();++ setTestInstances();+ await waitForBatchedStore();++ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ expect(sendTransaction).not.toHaveBeenCalled();++ $selectedPageId.set("next-page");+ await waitForBatchedStore();++ expect(sendTransaction).toHaveBeenCalledWith({+ id: expect.any(String),+ object: "selectedPageAndInstance",+ payload: {+ selectedPageId: "next-page",+ selectedInstanceSelector: undefined,+ allSelectedInstanceSelectors: [],+ },+ });+ });++ test("publishes a page change batched with instance pruning", async () => {+ setTestInstances("box");+ selectInstance(["box", "body"]);+ const { sendTransaction } = await subscribeSelectionSync();+ setTestInstances();+ $selectedPageId.set("next-page");await waitForBatchedStore();- sendTransaction.mockClear();++ expect(sendTransaction).toHaveBeenCalledWith({+ id: expect.any(String),+ object: "selectedPageAndInstance",+ payload: {+ selectedPageId: "next-page",+ selectedInstanceSelector: undefined,+ allSelectedInstanceSelectors: [],+ },+ });+ });++ test("publishes an explicit fallback selected after instance pruning", async () => {+ setTestInstances("box", "heading");+ selectInstance(["box", "body"]);+ const { sendTransaction } = await subscribeSelectionSync();++ setTestInstances("heading");+ selectInstance(["heading", "body"]);+ await waitForBatchedStore();++ expect(sendTransaction).toHaveBeenCalledTimes(1);+ expect(sendTransaction).toHaveBeenCalledWith({+ id: expect.any(String),+ object: "selectedPageAndInstance",+ payload: {+ selectedPageId: undefined,+ selectedInstanceSelector: ["heading", "body"],+ allSelectedInstanceSelectors: [["heading", "body"]],+ },+ });+ });++ test("sends page and instance selector as one final transaction", async () => {+ const { sendTransaction } = await subscribeSelectionSync();$selectedPageId.set("page-a");selectInstance(["body-a"]);@@ -50,12 +152,7 @@ describe("SelectedPageAndInstanceSyncObject", () => {});test("applies page and instance selector without echoing transaction", async () => {- const syncObject = new SelectedPageAndInstanceSyncObject();- const sendTransaction = vi.fn();- syncObject.subscribe(sendTransaction, new AbortController().signal);-- await waitForBatchedStore();- sendTransaction.mockClear();+ const { sendTransaction, syncObject } = await subscribeSelectionSync();syncObject.applyTransaction({id: "selection",@@ -75,6 +172,35 @@ describe("SelectedPageAndInstanceSyncObject", () => {expect(sendTransaction).not.toHaveBeenCalled();});+ test("remote no-op does not suppress the next local transaction", async () => {+ $selectedPageId.set("page-a");+ selectInstance(["body-a"]);+ const { sendTransaction, syncObject } = await subscribeSelectionSync();++ syncObject.applyTransaction({+ id: "selection",+ object: "selectedPageAndInstance",+ payload: {+ selectedPageId: "page-a",+ selectedInstanceSelector: ["body-a"],+ allSelectedInstanceSelectors: [["body-a"]],+ },+ });+ selectInstance(["body-b"]);+ await waitForBatchedStore();++ expect(sendTransaction).toHaveBeenCalledTimes(1);+ expect(sendTransaction).toHaveBeenCalledWith({+ id: expect.any(String),+ object: "selectedPageAndInstance",+ payload: {+ selectedPageId: "page-a",+ selectedInstanceSelector: ["body-b"],+ allSelectedInstanceSelectors: [["body-b"]],+ },+ });+ });+test("applies undefined instance selector as cleared selection", async () => {const syncObject = new SelectedPageAndInstanceSyncObject();@@ -97,12 +223,7 @@ describe("SelectedPageAndInstanceSyncObject", () => {});test("sends undefined instance selector when multiple instances are selected", async () => {- const syncObject = new SelectedPageAndInstanceSyncObject();- const sendTransaction = vi.fn();- syncObject.subscribe(sendTransaction, new AbortController().signal);-- await waitForBatchedStore();- sendTransaction.mockClear();+ const { sendTransaction } = await subscribeSelectionSync();$selectedPageId.set("page-a");selectInstances([@@ -152,12 +273,7 @@ describe("SelectedPageAndInstanceSyncObject", () => {});test("malformed remote payload does not suppress next local transaction", async () => {- const syncObject = new SelectedPageAndInstanceSyncObject();- const sendTransaction = vi.fn();- syncObject.subscribe(sendTransaction, new AbortController().signal);-- await waitForBatchedStore();- sendTransaction.mockClear();+ const { sendTransaction, syncObject } = await subscribeSelectionSync();syncObject.applyTransaction({id: "selection",@@ -182,6 +298,28 @@ describe("SelectedPageAndInstanceSyncObject", () => {});});+ test("malformed remote payload does not echo a pending valid update", async () => {+ const { sendTransaction, syncObject } = await subscribeSelectionSync();++ syncObject.applyTransaction({+ id: "selection",+ object: "selectedPageAndInstance",+ payload: {+ selectedPageId: "page-a",+ selectedInstanceSelector: ["body-a"],+ allSelectedInstanceSelectors: [["body-a"]],+ },+ });+ syncObject.applyTransaction({+ id: "malformed-selection",+ object: "selectedPageAndInstance",+ payload: null,+ });+ await waitForBatchedStore();++ expect(sendTransaction).not.toHaveBeenCalled();+ });+test("malformed selection fields do not update stores", () => {const syncObject = new SelectedPageAndInstanceSyncObject();diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex 2d0c461b8c..8f8055438f 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -72,14 +72,19 @@ import { $pointerPosition } from "../awareness";import { $temporaryInstances } from "../nano-states";import {$allSelectedInstanceSelectors,+ $instanceSelectionUpdate,$selectedInstanceSelector,selectInstance,selectInstances,-} from "../nano-states/instances";+} from "../nano-states/instance-selection";import { $selectedPageId } from "../nano-states/pages";+import { areSelectorListsEqual } from "../instance-utils/selection";import { $systemDataByPage } from "../system";import { $resourcesCache } from "../resources";-import type { InstanceSelector } from "@webstudio-is/project-build/runtime/tree";+import {+ areInstanceSelectorsEqual,+ type InstanceSelector,+} from "@webstudio-is/project-build/runtime/tree";enableMapSet();// safari structuredClone fix@@ -131,44 +136,68 @@ type SelectedPageAndInstance = {allSelectedInstanceSelectors: InstanceSelector[];};+const isInstanceSelector = (value: unknown): value is InstanceSelector =>+ Array.isArray(value) && value.every((id) => typeof id === "string");++const isInstanceSelectorList = (value: unknown): value is InstanceSelector[] =>+ Array.isArray(value) && value.every(isInstanceSelector);++const areSelectedPageAndInstanceEqual = (+ left: SelectedPageAndInstance,+ right: SelectedPageAndInstance+) =>+ left.selectedPageId === right.selectedPageId &&+ (left.selectedInstanceSelector === undefined+ ? right.selectedInstanceSelector === undefined+ : right.selectedInstanceSelector !== undefined &&+ areInstanceSelectorsEqual(+ left.selectedInstanceSelector,+ right.selectedInstanceSelector+ )) &&+ areSelectorListsEqual(+ left.allSelectedInstanceSelectors,+ right.allSelectedInstanceSelectors+ );+const $selectedPageAndInstance = batched(- [$selectedPageId, $selectedInstanceSelector, $allSelectedInstanceSelectors],+ [+ $selectedPageId,+ $selectedInstanceSelector,+ $allSelectedInstanceSelectors,+ $instanceSelectionUpdate,+ ],(- selectedPageId,- selectedInstanceSelector,- allSelectedInstanceSelectors- ): SelectedPageAndInstance => ({selectedPageId,selectedInstanceSelector,allSelectedInstanceSelectors,+ selectionUpdate+ ) => ({+ state: {+ selectedPageId,+ selectedInstanceSelector,+ allSelectedInstanceSelectors,+ } satisfies SelectedPageAndInstance,+ selectionUpdate,}));class SelectedPageAndInstanceSyncObject {name = "selectedPageAndInstance";- operation: "local" | "state" | "add" = "local";- ignoreNextBatchedChange = false;+ private operation: "local" | "state" | "add" = "local";+ private stateToIgnore: SelectedPageAndInstance | undefined;+ private lastSelectionRevision = $instanceSelectionUpdate.get().revision;+ private lastSelectedPageId = $selectedPageId.get();getState() {- return $selectedPageAndInstance.get();+ return $selectedPageAndInstance.get().state;}setState(state: unknown) {- this.operation = "state";- this.ignoreNextBatchedChange = this.setSelectedPageAndInstance(state);- this.operation = "local";+ this.applyRemoteState(state, "state");}applyTransaction(transaction: Transaction) {- this.operation = "add";- try {- this.ignoreNextBatchedChange = this.setSelectedPageAndInstance(- structuredClone(transaction.payload)- );- } catch (error) {- console.error(error);- }- this.operation = "local";+ this.applyRemoteState(transaction.payload, "add");}revertTransaction(_transaction: RevertedTransaction) {@@ -179,22 +208,60 @@ class SelectedPageAndInstanceSyncObject {sendTransaction: (transaction: Transaction) => void,signal: AbortSignal) {- const unsubscribe = $selectedPageAndInstance.listen((payload) => {- if (this.ignoreNextBatchedChange) {- this.ignoreNextBatchedChange = false;- return;- }- if (this.operation !== "local") {- return;+ this.lastSelectionRevision = $instanceSelectionUpdate.get().revision;+ this.lastSelectedPageId = $selectedPageId.get();+ const unsubscribe = $selectedPageAndInstance.listen(+ ({ state, selectionUpdate }) => {+ const isDerivedPruning =+ selectionUpdate.revision !== this.lastSelectionRevision &&+ selectionUpdate.origin === "instance-pruning";+ const didSelectedPageChange =+ state.selectedPageId !== this.lastSelectedPageId;+ this.lastSelectionRevision = selectionUpdate.revision;+ this.lastSelectedPageId = state.selectedPageId;+ if (this.stateToIgnore !== undefined) {+ const shouldIgnore = areSelectedPageAndInstanceEqual(+ state,+ this.stateToIgnore+ );+ this.stateToIgnore = undefined;+ if (shouldIgnore) {+ return;+ }+ }+ if (+ this.operation !== "local" ||+ (isDerivedPruning && didSelectedPageChange === false)+ ) {+ return;+ }+ sendTransaction({ id: nanoid(), object: this.name, payload: state });}- sendTransaction({ id: nanoid(), object: this.name, payload });- });+ );signal.addEventListener("abort", unsubscribe);}- private setSelectedPageAndInstance(state: unknown) {+ private applyRemoteState(state: unknown, operation: "state" | "add") {+ this.operation = operation;+ try {+ const appliedState = this.setSelectedPageAndInstance(+ operation === "add" ? structuredClone(state) : state+ );+ if (appliedState !== undefined) {+ this.stateToIgnore = appliedState;+ }+ } catch (error) {+ console.error(error);+ } finally {+ this.operation = "local";+ }+ }++ private setSelectedPageAndInstance(+ state: unknown+ ): SelectedPageAndInstance | undefined {if (typeof state !== "object" || state === null) {- return false;+ return;}const {selectedPageId,@@ -202,34 +269,31 @@ class SelectedPageAndInstanceSyncObject {allSelectedInstanceSelectors,} = state as Partial<SelectedPageAndInstance>;if (selectedPageId !== undefined && typeof selectedPageId !== "string") {- return false;+ return;}if (selectedInstanceSelector !== undefined &&- (Array.isArray(selectedInstanceSelector) === false ||- selectedInstanceSelector.every((id) => typeof id === "string") ===- false)+ isInstanceSelector(selectedInstanceSelector) === false) {- return false;+ return;}if (allSelectedInstanceSelectors !== undefined &&- (Array.isArray(allSelectedInstanceSelectors) === false ||- allSelectedInstanceSelectors.every(- (selector) =>- Array.isArray(selector) &&- selector.every((id) => typeof id === "string")- ) === false)+ isInstanceSelectorList(allSelectedInstanceSelectors) === false) {- return false;+ return;}$selectedPageId.set(selectedPageId);if (allSelectedInstanceSelectors !== undefined) {selectInstances(allSelectedInstanceSelectors);- return true;+ } else {+ selectInstance(selectedInstanceSelector);}- selectInstance(selectedInstanceSelector);- return true;+ return {+ selectedPageId: $selectedPageId.get(),+ selectedInstanceSelector: $selectedInstanceSelector.get(),+ allSelectedInstanceSelectors: $allSelectedInstanceSelectors.get(),+ };}}