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
feat: Multiselect (#5834)
Oleg Isonen2a77c2a8b585
diff --git a/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx b/apps/builder/app/builder/features/command-panel/groups/instances-group.tsxindex 41c1128475..3f058c2ac8 100644--- a/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/instances-group.tsx@@ -11,10 +11,7 @@ import { parseComponentName } from "@webstudio-is/sdk";import type { Instance } from "@webstudio-is/sdk";import { $instances, $pages } from "~/shared/sync/data-stores";import { getInstanceLabel } from "~/builder/shared/instance-label";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils/lookup";import {closeCommandPanel,@@ -98,7 +95,7 @@ export const InstancesGroup = ({ options }: { options: InstanceOption[] }) => {);if (awareness) {$selectedPageId.set(awareness.pageId);- $selectedInstanceSelector.set(awareness.instanceSelector);+ selectInstance(awareness.instanceSelector);setActiveSidebarPanel("auto");}}diff --git a/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx b/apps/builder/app/builder/features/command-panel/shared/instance-list.tsxindex 609ba9b962..cd426fea63 100644--- a/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx+++ b/apps/builder/app/builder/features/command-panel/shared/instance-list.tsx@@ -20,10 +20,7 @@ import { buildInstancePath } from "~/shared/instance-utils/lookup";import { $commandContent } from "~/builder/features/command-panel/command-state";import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils/lookup";import { $activeInspectorPanel } from "~/builder/shared/nano-states";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";import { useAutoSelectFirstItem } from "./auto-select";import { InstancePathFooter } from "./instance-path-footer";@@ -167,7 +164,7 @@ export const showInstance = (instanceId);$selectedPageId.set(pageId);- $selectedInstanceSelector.set(instanceSelector);+ selectInstance(instanceSelector);if (panel !== undefined) {$activeInspectorPanel.set(panel);}diff --git a/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.test.ts b/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.test.tsnew file mode 100644index 0000000000..03283fc58d--- /dev/null+++ b/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.test.ts@@ -0,0 +1,51 @@+import { describe, expect, test } from "vitest";+import { __testing__ } from "./keyboard-shortcuts-dialog";++const { additionalShortcuts, getShortcutCategoryColumns } = __testing__;++describe("keyboard shortcuts dialog", () => {+ test("keeps semantic category groups in expected columns", () => {+ const { leftCategories, rightCategories } = getShortcutCategoryColumns([+ "General",+ "Top bar",+ "Navigator",+ "Panels",+ "Style panel",+ ]);++ expect(leftCategories).toEqual([+ "General",+ "Top bar",+ "Panels",+ "Style panel",+ ]);+ expect(rightCategories).toEqual(["Navigator"]);+ });++ test("lists navigator multi-selection shortcuts", () => {+ expect(additionalShortcuts).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "toggleNavigatorSelection",+ defaultHotkeys: ["meta+click", "ctrl+click"],+ }),+ expect.objectContaining({+ name: "rangeNavigatorSelection",+ defaultHotkeys: ["shift+click"],+ }),+ expect.objectContaining({+ name: "extendNavigatorSelectionUp",+ defaultHotkeys: ["shift+arrowup"],+ }),+ expect.objectContaining({+ name: "extendNavigatorSelectionDown",+ defaultHotkeys: ["shift+arrowdown"],+ }),+ expect.objectContaining({+ name: "selectNavigatorSiblings",+ defaultHotkeys: ["meta+a", "ctrl+a"],+ }),+ ])+ );+ });+});diff --git a/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.tsx b/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.tsxindex a7214f1790..69e12d1144 100644--- a/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.tsx+++ b/apps/builder/app/builder/features/keyboard-shortcuts-dialog/keyboard-shortcuts-dialog.tsx@@ -37,6 +37,41 @@ const additionalShortcuts = [category: "Navigator",defaultHotkeys: ["←"],},+ {+ name: "toggleNavigatorSelection",+ label: "Toggle Navigator selection",+ description: "Add or remove an item from Navigator selection",+ category: "Navigator",+ defaultHotkeys: ["meta+click", "ctrl+click"],+ },+ {+ name: "rangeNavigatorSelection",+ label: "Range-select Navigator items",+ description: "Select a range of Navigator items",+ category: "Navigator",+ defaultHotkeys: ["shift+click"],+ },+ {+ name: "extendNavigatorSelectionUp",+ label: "Extend Navigator selection up",+ description: "Extend Navigator selection up",+ category: "Navigator",+ defaultHotkeys: ["shift+arrowup"],+ },+ {+ name: "extendNavigatorSelectionDown",+ label: "Extend Navigator selection down",+ description: "Extend Navigator selection down",+ category: "Navigator",+ defaultHotkeys: ["shift+arrowdown"],+ },+ {+ name: "selectNavigatorSiblings",+ label: "Select Navigator siblings",+ description: "Select sibling Navigator items",+ category: "Navigator",+ defaultHotkeys: ["meta+a", "ctrl+a"],+ },{name: "expandAllNavigatorNodes",label: "Expand all items",@@ -53,6 +88,29 @@ const additionalShortcuts = [},];+const leftCategoryOrder = ["General", "Top bar", "Panels", "Style panel"];+const rightCategoryOrder = ["Navigator"];++const getShortcutCategoryColumns = (categories: string[]) => {+ const orderedCategories = new Set([+ ...leftCategoryOrder,+ ...rightCategoryOrder,+ ]);+ const remainingCategories = categories.filter(+ (category) => orderedCategories.has(category) === false+ );+ return {+ leftCategories: [+ ...leftCategoryOrder.filter((category) => categories.includes(category)),+ ...remainingCategories.filter((_, index) => index % 2 === 0),+ ],+ rightCategories: [+ ...rightCategoryOrder.filter((category) => categories.includes(category)),+ ...remainingCategories.filter((_, index) => index % 2 === 1),+ ],+ };+};+export const KeyboardShortcutsDialog = () => {const isOpen = useStore($isKeyboardShortcutsOpen);const commandMetas = useStore($commandMetas);@@ -86,24 +144,45 @@ export const KeyboardShortcutsDialog = () => {// Define popularity order for shortcuts within each categoryconst shortcutOrder: Record<string, ValidCommandName[]> = {General: [- "cancelCurrentDrag","openCommandPanel",+ "undo",+ "redo",+ "save","toggleUiHidden",+ "cancelCurrentDrag","openPublishDialog","openExportDialog","openKeyboardShortcuts",],- "Top bar": ["toggleDesignMode", "togglePreviewMode", "toggleContentMode"],+ "Top bar": [+ "toggleDesignMode",+ "toggleContentMode",+ "togglePreviewMode",+ "switchBreakpoint",+ "openPublishDialog",+ ],Navigator: [+ "expandNavigatorItem",+ "collapseNavigatorItem",+ "expandAllNavigatorNodes",+ "selectNavigatorSiblings",+ "toggleNavigatorSelection",+ "rangeNavigatorSelection",+ "extendNavigatorSelectionUp",+ "extendNavigatorSelectionDown","copy","cut","paste","duplicateInstance",+ "deleteInstanceBuilder",+ "moveInstanceUp",+ "moveInstanceDown",+ "moveInstanceOut",+ "moveInstanceIntoPreviousSibling",+ "editInstanceLabel",+ "toggleShow","wrap","unwrap",- "expandNavigatorItem",- "collapseNavigatorItem",- "expandAllNavigatorNodes",],Panels: ["toggleComponentsPanel",@@ -172,6 +251,56 @@ export const KeyboardShortcutsDialog = () => {return 0;});+ const { leftCategories, rightCategories } =+ getShortcutCategoryColumns(sortedCategories);++ const renderCategory = (category: ValidCategory) => {+ const categoryCommands = groupedCommands[category];+ return (+ <Box key={category}>+ <Text variant="titles" color="main" css={{ mb: theme.spacing[5] }}>+ {category}+ </Text>+ <Grid gap={3} align="center" css={{ gridTemplateColumns: "10ch 1fr" }}>+ {categoryCommands.map((command) => {+ const hotkey = command.defaultHotkeys+ ? filterHotkeyByOs(command.defaultHotkeys)+ : undefined;++ if (!hotkey) {+ return;+ }++ return (+ <Fragment key={command.name}>+ <Box css={{ textAlign: "right" }}>+ <Box+ as="span"+ css={{+ paddingInline: 4,+ border: `1px solid ${theme.colors.borderNeutral}`,+ borderRadius: theme.borderRadius[2],+ }}+ >+ <Kbd+ value={hotkey.split("+") as string[]}+ color="moreSubtle"+ />+ </Box>+ </Box>+ <Text variant="regular" color="subtle">+ {("description" in command && command.description) ||+ command.label ||+ command.name}+ </Text>+ </Fragment>+ );+ })}+ </Grid>+ </Box>+ );+ };+return (<Dialogopen={isOpen}@@ -187,64 +316,16 @@ export const KeyboardShortcutsDialog = () => {<DialogTitle>Keyboard shortcuts</DialogTitle><ScrollArea><Grid columns={2} gap={3} css={{ padding: theme.panel.padding }}>- {sortedCategories.map((category) => {- const categoryCommands = groupedCommands[category];- return (- <Box key={category}>- <Text- variant="titles"- color="main"- css={{ mb: theme.spacing[5] }}- >- {category}- </Text>- <Grid- gap={3}- align="center"- css={{ gridTemplateColumns: "10ch 1fr" }}- >- {categoryCommands.map((command) => {- const hotkey = command.defaultHotkeys- ? filterHotkeyByOs(command.defaultHotkeys)- : undefined;-- if (!hotkey) {- return;- }-- return (- <Fragment key={command.name}>- <Box css={{ textAlign: "right" }}>- <Box- as="span"- css={{- paddingInline: 4,- border: `1px solid ${theme.colors.borderNeutral}`,- borderRadius: theme.borderRadius[2],- }}- >- <Kbd- value={hotkey.split("+") as string[]}- color="moreSubtle"- />- </Box>- </Box>- <Text variant="regular" color="subtle">- {("description" in command &&- command.description) ||- command.label ||- command.name}- </Text>- </Fragment>- );- })}- </Grid>- </Box>- );- })}+ <Grid gap={5}>{leftCategories.map(renderCategory)}</Grid>+ <Grid gap={5}>{rightCategories.map(renderCategory)}</Grid></Grid></ScrollArea></DialogContent></Dialog>);};++export const __testing__ = {+ additionalShortcuts,+ getShortcutCategoryColumns,+};diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.test.ts b/apps/builder/app/builder/features/navigator/navigator-tree.test.tsnew file mode 100644index 0000000000..8a8426d667--- /dev/null+++ b/apps/builder/app/builder/features/navigator/navigator-tree.test.ts@@ -0,0 +1,305 @@+import { beforeEach, describe, expect, test } from "vitest";+import { __testing__ } from "./navigator-tree";+import {+ $allSelectedInstanceSelectors,+ selectInstances,+} from "~/shared/nano-states";++const {+ getFocusSelectionSkipCountAfterPointerDown,+ getNavigatorKeyboardSelectionUpdate,+ getNavigatorSelectionUpdate,+ getNavigatorSiblingSelectionUpdate,+ shouldClearNavigatorMultiSelectionOnEscape,+ shouldSelectOnPointerDown,+} = __testing__;++describe("getNavigatorSelectionUpdate", () => {+ beforeEach(() => {+ selectInstances([]);+ });++ const flatSelectors = [+ ["body"],+ ["section", "body"],+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ["footer", "body"],+ ];++ test("selects one instance on normal click and updates anchor", () => {+ expect(+ getNavigatorSelectionUpdate({+ selectedSelectors: [["box", "section", "body"]],+ clickedSelector: ["heading", "section", "body"],+ flatSelectors,+ anchorSelector: ["box", "section", "body"],+ isToggle: false,+ isRange: false,+ })+ ).toEqual({+ selectedSelectors: [["heading", "section", "body"]],+ anchorSelector: ["heading", "section", "body"],+ });+ });++ test("toggles clicked instance and updates anchor", () => {+ expect(+ getNavigatorSelectionUpdate({+ selectedSelectors: [["heading", "section", "body"]],+ clickedSelector: ["box", "section", "body"],+ flatSelectors,+ anchorSelector: ["heading", "section", "body"],+ isToggle: true,+ isRange: false,+ })+ ).toEqual({+ selectedSelectors: [+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ],+ anchorSelector: ["box", "section", "body"],+ });++ expect(+ getNavigatorSelectionUpdate({+ selectedSelectors: [+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ],+ clickedSelector: ["box", "section", "body"],+ flatSelectors,+ anchorSelector: ["heading", "section", "body"],+ isToggle: true,+ isRange: false,+ }).selectedSelectors+ ).toEqual([["heading", "section", "body"]]);+ });++ test("treats range click without anchor as normal click", () => {+ expect(+ getNavigatorSelectionUpdate({+ selectedSelectors: [["box", "section", "body"]],+ clickedSelector: ["heading", "section", "body"],+ flatSelectors,+ anchorSelector: undefined,+ isToggle: false,+ isRange: true,+ })+ ).toEqual({+ selectedSelectors: [["heading", "section", "body"]],+ anchorSelector: ["heading", "section", "body"],+ });+ });++ test("selects visible range and keeps unrelated selected instances", () => {+ expect(+ getNavigatorSelectionUpdate({+ selectedSelectors: [["footer", "body"]],+ clickedSelector: ["heading", "section", "body"],+ flatSelectors,+ anchorSelector: ["section", "body"],+ isToggle: false,+ isRange: true,+ })+ ).toEqual({+ selectedSelectors: [+ ["section", "body"],+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ["footer", "body"],+ ],+ anchorSelector: ["heading", "section", "body"],+ });+ });++ test("normalizes range selection through the selection store", () => {+ const nextSelection = getNavigatorSelectionUpdate({+ selectedSelectors: [],+ clickedSelector: ["footer", "body"],+ flatSelectors,+ anchorSelector: ["section", "body"],+ isToggle: false,+ isRange: true,+ });++ selectInstances(nextSelection.selectedSelectors);++ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["section", "body"],+ ["footer", "body"],+ ]);+ });++ test("handles multi-select gestures on pointer down before drag can consume click", () => {+ expect(+ shouldSelectOnPointerDown({+ button: 0,+ metaKey: true,+ ctrlKey: false,+ shiftKey: false,+ })+ ).toBe(true);+ expect(+ shouldSelectOnPointerDown({+ button: 0,+ metaKey: false,+ ctrlKey: true,+ shiftKey: false,+ })+ ).toBe(true);+ expect(+ shouldSelectOnPointerDown({+ button: 0,+ metaKey: false,+ ctrlKey: false,+ shiftKey: true,+ })+ ).toBe(true);++ expect(+ shouldSelectOnPointerDown({+ button: 0,+ metaKey: false,+ ctrlKey: false,+ shiftKey: false,+ })+ ).toBe(false);+ expect(+ shouldSelectOnPointerDown({+ button: 2,+ metaKey: true,+ ctrlKey: false,+ shiftKey: false,+ })+ ).toBe(false);+ });++ test("skips focus selection through context menu open and close", () => {+ expect(getFocusSelectionSkipCountAfterPointerDown({ button: 2 })).toBe(2);+ expect(getFocusSelectionSkipCountAfterPointerDown({ button: 0 })).toBe(1);+ });++ test("consumes escape only when navigator has multi-selection to clear", () => {+ expect(+ shouldClearNavigatorMultiSelectionOnEscape({+ key: "Escape",+ selectedSelectors: [+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ],+ })+ ).toBe(true);++ expect(+ shouldClearNavigatorMultiSelectionOnEscape({+ key: "Escape",+ selectedSelectors: [["box", "section", "body"]],+ })+ ).toBe(false);++ expect(+ shouldClearNavigatorMultiSelectionOnEscape({+ key: "Enter",+ selectedSelectors: [+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ],+ })+ ).toBe(false);+ });++ test("extends selection with keyboard in visible order", () => {+ expect(+ getNavigatorKeyboardSelectionUpdate({+ selectedSelectors: [["box", "section", "body"]],+ focusedSelector: ["box", "section", "body"],+ flatSelectors,+ anchorSelector: undefined,+ direction: "next",+ })+ ).toEqual({+ selectedSelectors: [+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ],+ anchorSelector: ["box", "section", "body"],+ });++ expect(+ getNavigatorKeyboardSelectionUpdate({+ selectedSelectors: [+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ],+ focusedSelector: ["heading", "section", "body"],+ flatSelectors,+ anchorSelector: ["box", "section", "body"],+ direction: "next",+ })+ ).toEqual({+ selectedSelectors: [+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ["footer", "body"],+ ],+ anchorSelector: ["box", "section", "body"],+ });+ });++ test("does not change selection when keyboard extension reaches an edge", () => {+ expect(+ getNavigatorKeyboardSelectionUpdate({+ selectedSelectors: [["body"]],+ focusedSelector: ["body"],+ flatSelectors,+ anchorSelector: ["body"],+ direction: "previous",+ })+ ).toBeUndefined();+ });++ test("selects all visible siblings of focused instance", () => {+ expect(+ getNavigatorSiblingSelectionUpdate({+ focusedSelector: ["box", "section", "body"],+ flatSelectors,+ })+ ).toEqual({+ selectedSelectors: [+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ],+ anchorSelector: ["box", "section", "body"],+ });++ expect(+ getNavigatorSiblingSelectionUpdate({+ focusedSelector: ["section", "body"],+ flatSelectors,+ })+ ).toEqual({+ selectedSelectors: [+ ["section", "body"],+ ["footer", "body"],+ ],+ anchorSelector: ["section", "body"],+ });+ });++ test("does not select siblings when focused selector is not selectable", () => {+ expect(+ getNavigatorSiblingSelectionUpdate({+ focusedSelector: ["body"],+ flatSelectors,+ })+ ).toBeUndefined();++ expect(+ getNavigatorSiblingSelectionUpdate({+ focusedSelector: ["missing", "body"],+ flatSelectors,+ })+ ).toBeUndefined();+ });+});diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.tsx b/apps/builder/app/builder/features/navigator/navigator-tree.tsxindex 2a12bd804d..6c6b7bed36 100644--- a/apps/builder/app/builder/features/navigator/navigator-tree.tsx+++ b/apps/builder/app/builder/features/navigator/navigator-tree.tsx@@ -3,7 +3,7 @@ import {setInstanceLabelMutable,toggleInstanceShow,} from "~/shared/instance-utils/mutation";-import { useEffect, useRef } from "react";+import { useEffect, useMemo, useRef } from "react";import { atom, computed } from "nanostores";import { mergeRefs } from "@react-aria/utils";import { useStore } from "@nanostores/react";@@ -41,6 +41,7 @@ import {InfoCircleIcon,} from "@webstudio-is/icons";import {+ $allSelectedInstanceSelectors,$dragAndDropState,$blockChildOutline,$editingItemSelector,@@ -49,24 +50,30 @@ import {$propsIndex,$propValuesByInstanceSelector,$registeredComponentMetas,+ $selectedInstanceSelector,+ $selectedPage,+ clearInstanceSelection,getIndexedInstanceId,+ getInstanceKey,+ selectInstance,+ selectInstances,type ItemDropTarget,$propValuesByInstanceSelectorWithMemoryProps,} from "~/shared/nano-states";+import {+ getContextMenuSelectedInstanceSelectors,+ getInstanceSelectionUpdate,+} from "~/shared/instance-utils/selection";import { $instances, $props } from "~/shared/sync/data-stores";+import { suppressCommandsForEvent } from "~/shared/commands-emitter";import {+ areInstanceSelectorsEqual,isDescendantOrSelf,type InstanceSelector,} from "~/shared/instance-utils/tree";import { serverSyncStore } from "~/shared/sync/sync-stores";import { emitCommand } from "~/builder/shared/commands";import { useContentEditable } from "~/shared/dom-hooks";-import {- $selectedInstanceSelector,- $selectedPage,- getInstanceKey,-} from "~/shared/nano-states";-import { selectInstance } from "~/shared/nano-states";import {findClosestContainer,isRichTextContent,@@ -97,6 +104,114 @@ type TreeItem = {dropTarget?: TreeDropTarget;};+function getSelectorKey(selector: InstanceSelector): string;+function getSelectorKey(selector: undefined): undefined;+function getSelectorKey(+ selector: undefined | InstanceSelector+): undefined | string;+function getSelectorKey(selector: undefined | InstanceSelector) {+ return selector === undefined ? undefined : JSON.stringify(selector);+}++const getNavigatorSelectionUpdate = ({+ flatSelectors,+ ...options+}: Omit<+ Parameters<typeof getInstanceSelectionUpdate>[0],+ "orderedSelectors"+> & {+ flatSelectors: InstanceSelector[];+}) =>+ getInstanceSelectionUpdate({+ ...options,+ orderedSelectors: flatSelectors,+ });++const getNavigatorKeyboardSelectionUpdate = ({+ selectedSelectors,+ focusedSelector,+ flatSelectors,+ anchorSelector,+ direction,+}: {+ selectedSelectors: InstanceSelector[];+ focusedSelector: InstanceSelector;+ flatSelectors: InstanceSelector[];+ anchorSelector: undefined | InstanceSelector;+ direction: "previous" | "next";+}) => {+ const focusedIndex = flatSelectors.findIndex((selector) =>+ areInstanceSelectorsEqual(selector, focusedSelector)+ );+ if (focusedIndex === -1) {+ return;+ }+ const nextIndex =+ direction === "previous" ? focusedIndex - 1 : focusedIndex + 1;+ const clickedSelector = flatSelectors[nextIndex];+ if (clickedSelector === undefined) {+ return;+ }+ const nextAnchorSelector = anchorSelector ?? focusedSelector;+ const nextSelection = getInstanceSelectionUpdate({+ selectedSelectors,+ clickedSelector,+ orderedSelectors: flatSelectors,+ anchorSelector: nextAnchorSelector,+ isToggle: false,+ isRange: true,+ });+ return {+ ...nextSelection,+ anchorSelector: nextAnchorSelector,+ };+};++const getNavigatorSiblingSelectionUpdate = ({+ focusedSelector,+ flatSelectors,+}: {+ focusedSelector: InstanceSelector;+ flatSelectors: InstanceSelector[];+}) => {+ const focusedIndex = flatSelectors.findIndex((selector) =>+ areInstanceSelectorsEqual(selector, focusedSelector)+ );+ if (focusedIndex === -1 || focusedSelector.length < 2) {+ return;+ }+ const parentSelector = focusedSelector.slice(1);+ const selectedSelectors = flatSelectors.filter(+ (selector) =>+ selector.length > 1 &&+ areInstanceSelectorsEqual(selector.slice(1), parentSelector)+ );+ return {+ selectedSelectors,+ anchorSelector: focusedSelector,+ };+};++const shouldSelectOnPointerDown = ({+ button,+ metaKey,+ ctrlKey,+ shiftKey,+}: Pick<React.PointerEvent, "button" | "metaKey" | "ctrlKey" | "shiftKey">) =>+ button === 0 && (metaKey || ctrlKey || shiftKey);++const getFocusSelectionSkipCountAfterPointerDown = ({+ button,+}: Pick<React.PointerEvent, "button">) => (button === 2 ? 2 : 1);++const shouldClearNavigatorMultiSelectionOnEscape = ({+ key,+ selectedSelectors,+}: {+ key: string;+ selectedSelectors: InstanceSelector[];+}) => key === "Escape" && selectedSelectors.length > 1;+const $expandedItems = atom(new Set<string>());const $dropTarget = computed(@@ -191,7 +306,7 @@ export const $flatTree = computed(}const level = treeItem.visibleAncestors.length - 1;if (level > 0 && instance.children.some((child) => child.type === "id")) {- treeItem.isExpanded = expandedItems.has(selector.join());+ treeItem.isExpanded = expandedItems.has(getSelectorKey(selector));}// always expand invisible itemsif (isVisible === false) {@@ -258,7 +373,7 @@ export const $flatTree = computed(const parentSelector = treeItem.visibleAncestors.at(-2)?.selector;if (dropTarget &&- parentSelector?.join() === dropTarget.itemSelector.join() &&+ areInstanceSelectorsEqual(parentSelector, dropTarget.itemSelector) &&dropTarget.placement.closestChildIndex === indexWithinChildren) {if (dropTarget.placement.indexAdjustment === 0) {@@ -285,7 +400,7 @@ const handleExpand = (item: TreeItem, isExpanded: boolean, all: boolean) => {const expandedItems = new Set($expandedItems.get());const instances = $instances.get();const traverse = (instanceId: Instance["id"], selector: InstanceSelector) => {- const key = selector.join();+ const key = getSelectorKey(selector);if (isExpanded) {expandedItems.add(key);} else {@@ -487,7 +602,7 @@ const canDrag = (instance: Instance, instanceSelector: InstanceSelector) => {}// Do not drag if the instance name is being edited- if ($editingItemSelector.get()?.join(",") === instanceSelector.join(",")) {+ if (areInstanceSelectorsEqual($editingItemSelector.get(), instanceSelector)) {return false;}@@ -567,10 +682,14 @@ const canDrop = (export const NavigatorTree = () => {const isContentMode = useStore($isContentMode);const flatTree = useStore($flatTree);+ const selectedInstanceSelectors = useStore($allSelectedInstanceSelectors);const selectedInstanceSelector = useStore($selectedInstanceSelector);- const selectedKey = selectedInstanceSelector?.join();+ const selectedKeys = useMemo(+ () => new Set(selectedInstanceSelectors.map(getSelectorKey)),+ [selectedInstanceSelectors]+ );const hoveredInstanceSelector = useStore($hoveredInstanceSelector);- const hoveredKey = hoveredInstanceSelector?.join();+ const hoveredKey = getSelectorKey(hoveredInstanceSelector);const propValuesByInstanceSelectorWithMemoryProps = useStore($propValuesByInstanceSelectorWithMemoryProps);@@ -579,8 +698,21 @@ export const NavigatorTree = () => {const metas = useStore($registeredComponentMetas);const editingItemSelector = useStore($editingItemSelector);const dragAndDropState = useStore($dragAndDropState);- const dropTargetKey = dragAndDropState.dropTarget?.itemSelector.join();+ const dropTargetKey = getSelectorKey(+ dragAndDropState.dropTarget?.itemSelector+ );const rootMeta = metas.get(rootComponent);+ const rangeAnchorSelectorRef = useRef<undefined | InstanceSelector>();+ const suppressFocusSelectionRef = useRef(false);+ const skipFocusSelectionCountRef = useRef(0);+ const skipNextClickSelectionRef = useRef(false);+ const flatSelectors = useMemo(() => {+ const selectors = flatTree.map((item) => item.selector);+ if (rootMeta && isContentMode === false) {+ return [[ROOT_INSTANCE_ID], ...selectors];+ }+ return selectors;+ }, [flatTree, isContentMode, rootMeta]);// expand selected instance ancestorsuseEffect(() => {@@ -589,7 +721,7 @@ export const NavigatorTree = () => {let expanded = 0;// do not expand the selected instance itself, start with parentfor (let index = 1; index < selectedInstanceSelector.length; index += 1) {- const key = selectedInstanceSelector.slice(index).join();+ const key = getSelectorKey(selectedInstanceSelector.slice(index));if (newExpandedItems.has(key) === false) {newExpandedItems.add(key);expanded += 1;@@ -602,9 +734,23 @@ export const NavigatorTree = () => {}}, [selectedInstanceSelector]);- const selectInstanceAndClearSelection = (- instanceSelector: undefined | Instance["id"][],- event: React.MouseEvent | React.FocusEvent+ useEffect(() => {+ const anchorSelector = rangeAnchorSelectorRef.current;+ if (anchorSelector === undefined) {+ return;+ }+ if (+ selectedInstanceSelectors.length === 0 ||+ flatSelectors.some((selector) =>+ areInstanceSelectorsEqual(selector, anchorSelector)+ ) === false+ ) {+ rangeAnchorSelectorRef.current = undefined;+ }+ }, [flatSelectors, selectedInstanceSelectors]);++ const clearTextSelection = (+ event: React.MouseEvent | React.FocusEvent | React.PointerEvent) => {if (event.currentTarget.querySelector("[contenteditable]") === null) {// Allow text selection and edits inside current TreeNode@@ -612,8 +758,167 @@ export const NavigatorTree = () => {// Otherwise user will cmd+c the text instead of copying the instance.window.getSelection()?.removeAllRanges();}+ };+ const selectInstanceOnFocus = (+ instanceSelector: undefined | Instance["id"][],+ event: React.MouseEvent | React.FocusEvent+ ) => {+ if (suppressFocusSelectionRef.current) {+ return;+ }+ if (skipFocusSelectionCountRef.current > 0) {+ skipFocusSelectionCountRef.current -= 1;+ return;+ }+ clearTextSelection(event);selectInstance(instanceSelector);+ rangeAnchorSelectorRef.current = instanceSelector;+ };++ const selectNavigatorInstance = (+ instanceSelector: InstanceSelector,+ event: React.MouseEvent | React.PointerEvent+ ) => {+ clearTextSelection(event);+ suppressFocusSelectionRef.current = false;+ const nextSelection = getInstanceSelectionUpdate({+ selectedSelectors: selectedInstanceSelectors,+ clickedSelector: instanceSelector,+ orderedSelectors: flatSelectors,+ anchorSelector: rangeAnchorSelectorRef.current,+ isToggle: event.metaKey || event.ctrlKey,+ isRange: event.shiftKey,+ });+ selectInstances(nextSelection.selectedSelectors);+ rangeAnchorSelectorRef.current = nextSelection.anchorSelector;+ };++ const handlePointerDown = (+ instanceSelector: InstanceSelector,+ event: React.PointerEvent+ ) => {+ skipFocusSelectionCountRef.current =+ getFocusSelectionSkipCountAfterPointerDown(event);+ if (shouldSelectOnPointerDown(event)) {+ event.preventDefault();+ event.stopPropagation();+ selectNavigatorInstance(instanceSelector, event);+ skipNextClickSelectionRef.current = true;+ return;+ }+ if (event.button !== 2) {+ return;+ }+ skipNextClickSelectionRef.current = true;+ if (selectedKeys.has(getSelectorKey(instanceSelector))) {+ return;+ }+ clearTextSelection(event);+ suppressFocusSelectionRef.current = false;+ selectInstances(+ getContextMenuSelectedInstanceSelectors({+ selectedSelectors: selectedInstanceSelectors,+ clickedSelector: instanceSelector,+ })+ );+ rangeAnchorSelectorRef.current = instanceSelector;+ };++ const handleClick = (+ instanceSelector: InstanceSelector,+ event: React.MouseEvent+ ) => {+ if (skipNextClickSelectionRef.current) {+ skipNextClickSelectionRef.current = false;+ return;+ }+ selectNavigatorInstance(instanceSelector, event);+ };++ const handleKeyDown = (+ instanceSelector: InstanceSelector,+ event: React.KeyboardEvent<HTMLButtonElement>+ ) => {+ if (+ shouldClearNavigatorMultiSelectionOnEscape({+ key: event.key,+ selectedSelectors: selectedInstanceSelectors,+ })+ ) {+ suppressCommandsForEvent(event.nativeEvent);+ event.preventDefault();+ event.stopPropagation();+ suppressFocusSelectionRef.current = false;+ clearInstanceSelection();+ rangeAnchorSelectorRef.current = undefined;+ return;+ }++ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "a") {+ suppressCommandsForEvent(event.nativeEvent);+ event.preventDefault();+ event.stopPropagation();+ suppressFocusSelectionRef.current = false;+ const nextSelection = getNavigatorSiblingSelectionUpdate({+ focusedSelector: instanceSelector,+ flatSelectors,+ });+ if (nextSelection === undefined) {+ return;+ }+ selectInstances(nextSelection.selectedSelectors);+ rangeAnchorSelectorRef.current = nextSelection.anchorSelector;+ return;+ }++ if (event.shiftKey === false) {+ suppressFocusSelectionRef.current = false;+ return;+ }+ const direction =+ event.key === "ArrowUp"+ ? "previous"+ : event.key === "ArrowDown"+ ? "next"+ : undefined;+ if (direction === undefined) {+ return;+ }+ suppressCommandsForEvent(event.nativeEvent);+ event.preventDefault();+ event.stopPropagation();+ const nextSelection = getNavigatorKeyboardSelectionUpdate({+ selectedSelectors: selectedInstanceSelectors,+ focusedSelector: instanceSelector,+ flatSelectors,+ anchorSelector: rangeAnchorSelectorRef.current,+ direction,+ });+ if (nextSelection === undefined) {+ return;+ }+ suppressFocusSelectionRef.current = true;+ selectInstances(nextSelection.selectedSelectors);+ rangeAnchorSelectorRef.current = nextSelection.anchorSelector;++ const treeButtons = Array.from(+ event.currentTarget+ .closest("[data-navigator-tree]")+ ?.querySelectorAll<HTMLButtonElement>("[data-tree-button]") ?? []+ );+ const buttonIndex = treeButtons.indexOf(event.currentTarget);+ const nextFocusedButton =+ direction === "previous" ? buttonIndex - 1 : buttonIndex + 1;+ if (treeButtons[nextFocusedButton] !== undefined) {+ treeButtons[nextFocusedButton]?.focus({ preventScroll: true });+ }+ };++ const handleKeyUp = (event: React.KeyboardEvent<HTMLButtonElement>) => {+ if (event.key === "Shift" || event.shiftKey === false) {+ suppressFocusSelectionRef.current = false;+ }};return (@@ -627,181 +932,208 @@ export const NavigatorTree = () => {}}><TreeRoot>- {rootMeta && isContentMode === false && (- <TreeNode- level={0}- isSelected={selectedKey === ROOT_INSTANCE_ID}- buttonProps={{- onClick: (event) =>- selectInstanceAndClearSelection([ROOT_INSTANCE_ID], event),- onFocus: (event) =>- selectInstanceAndClearSelection([ROOT_INSTANCE_ID], event),- }}- action={- <Tooltip- variant="wrapped"- side="bottom"- disableHoverableContent={true}- content={- <Text>- Variables defined on Global root are available on every- instance on every page.- </Text>+ <Box data-navigator-tree>+ {rootMeta && isContentMode === false && (+ <TreeNode+ level={0}+ isSelected={selectedKeys.has(getSelectorKey([ROOT_INSTANCE_ID]))}+ buttonProps={{+ onPointerDown: (event) =>+ handlePointerDown([ROOT_INSTANCE_ID], event),+ onClick: (event) => handleClick([ROOT_INSTANCE_ID], event),+ onKeyDown: (event) => handleKeyDown([ROOT_INSTANCE_ID], event),+ onKeyUp: handleKeyUp,+ onFocus: (event) =>+ selectInstanceOnFocus([ROOT_INSTANCE_ID], event),+ }}+ action={+ <Tooltip+ variant="wrapped"+ side="bottom"+ disableHoverableContent={true}+ content={+ <Text>+ Variables defined on Global root are available on every+ instance on every page.+ </Text>+ }+ >+ <InfoCircleIcon />+ </Tooltip>+ }+ >+ <TreeNodeLabel+ prefix={+ <InstanceIcon instance={{ component: rootComponent }} />}>- <InfoCircleIcon />- </Tooltip>+ {rootMeta.label}+ </TreeNodeLabel>+ </TreeNode>+ )}++ {flatTree.map((item) => {+ const level = item.visibleAncestors.length - 1;+ const key = getSelectorKey(item.selector);+ const propValues = propValuesByInstanceSelectorWithMemoryProps.get(+ getInstanceKey(item.selector)+ );+ const show = Boolean(propValues?.get(showAttribute) ?? true);+ const isSelectedDescendantItem =+ selectedInstanceSelector !== undefined &&+ areInstanceSelectorsEqual(+ item.selector,+ selectedInstanceSelector+ ) === false &&+ isDescendantOrSelf(item.selector, selectedInstanceSelector);++ // Hook memory prop+ const isAnimationSelected =+ propValues?.get(animationCanPlayOnCanvasProperty) === true;++ const props = propsByInstanceId.get(item.instance.id);+ const actionProp = props?.find(+ (prop) => prop.type === "animationAction"+ );++ const isAnimationPinned = actionProp?.value?.isPinned === true;++ const isAnimating = isAnimationSelected || isAnimationPinned;++ const meta = metas.get(item.instance.component);++ if (meta === undefined) {+ return;}- >- <TreeNodeLabel- prefix={<InstanceIcon instance={{ component: rootComponent }} />}- >- {rootMeta.label}- </TreeNodeLabel>- </TreeNode>- )}-- {flatTree.map((item) => {- const level = item.visibleAncestors.length - 1;- const key = item.selector.join();- const propValues = propValuesByInstanceSelectorWithMemoryProps.get(- getInstanceKey(item.selector)- );- const show = Boolean(propValues?.get(showAttribute) ?? true);- const isSelectedDescendantItem =- selectedInstanceSelector !== undefined &&- item.selector.join() !== selectedInstanceSelector.join() &&- isDescendantOrSelf(item.selector, selectedInstanceSelector);-- // Hook memory prop- const isAnimationSelected =- propValues?.get(animationCanPlayOnCanvasProperty) === true;-- const props = propsByInstanceId.get(item.instance.id);- const actionProp = props?.find(- (prop) => prop.type === "animationAction"- );-- const isAnimationPinned = actionProp?.value?.isPinned === true;-- const isAnimating = isAnimationSelected || isAnimationPinned;-- const meta = metas.get(item.instance.component);-- if (meta === undefined) {- return;- }- return (- <TreeSortableItem- key={key}- level={level}- isExpanded={item.isExpanded}- isLastChild={item.isLastChild}- data={item}- canDrag={() => canDrag(item.instance, item.selector)}- dropTarget={item.dropTarget}- onDropTargetChange={(dropTarget, draggingItem) => {- const builderDropTarget = getBuilderDropTarget(- item,- dropTarget- );- if (- builderDropTarget &&- canDrop(draggingItem.selector, builderDropTarget)- ) {- $dragAndDropState.set({- ...$dragAndDropState.get(),- isDragging: true,- dragPayload: {- origin: "panel",- type: "reparent",- dragInstanceSelector: draggingItem.selector,- },- dropTarget: builderDropTarget,- });- } else {- $dragAndDropState.set({- ...$dragAndDropState.get(),- isDragging: false,- dropTarget: undefined,- });- }- }}- onDrop={(data) => {- const builderDropTarget = $dragAndDropState.get().dropTarget;- if (builderDropTarget) {- reparentInstance(data.selector, {- parentSelector: builderDropTarget.itemSelector,- position: builderDropTarget.indexWithinChildren,- });- }- $dragAndDropState.set({ isDragging: false });- }}- onExpand={(isExpanded) => handleExpand(item, isExpanded, false)}- >- <InstanceContextMenu>- <TreeNode- level={level}- isSelected={selectedKey === key}- isSelectedDescendant={isSelectedDescendantItem}- isHighlighted={hoveredKey === key || dropTargetKey === key}- isExpanded={item.isExpanded}- isActionVisible={isAnimating}- onExpand={(isExpanded, all) =>- handleExpand(item, isExpanded, all)+ return (+ <TreeSortableItem+ key={key}+ level={level}+ isExpanded={item.isExpanded}+ isLastChild={item.isLastChild}+ data={item}+ canDrag={() => canDrag(item.instance, item.selector)}+ dropTarget={item.dropTarget}+ onDropTargetChange={(dropTarget, draggingItem) => {+ const builderDropTarget = getBuilderDropTarget(+ item,+ dropTarget+ );+ if (+ builderDropTarget &&+ canDrop(draggingItem.selector, builderDropTarget)+ ) {+ $dragAndDropState.set({+ ...$dragAndDropState.get(),+ isDragging: true,+ dragPayload: {+ origin: "panel",+ type: "reparent",+ dragInstanceSelector: draggingItem.selector,+ },+ dropTarget: builderDropTarget,+ });+ } else {+ $dragAndDropState.set({+ ...$dragAndDropState.get(),+ isDragging: false,+ dropTarget: undefined,+ });}- nodeProps={{- style: {- opacity: item.isHidden ? 0.4 : undefined,- color: item.isReusable- ? rawTheme.colors.foregroundReusable- : undefined,- },- }}- buttonProps={{- onMouseEnter: () => {- $hoveredInstanceSelector.set(item.selector);- $blockChildOutline.set(undefined);- },- onMouseLeave: () => $hoveredInstanceSelector.set(undefined),- onClick: (event) =>- selectInstanceAndClearSelection(item.selector, event),- onFocus: (event) =>- selectInstanceAndClearSelection(item.selector, event),- onKeyDown: (event) => {- if (event.key === "Enter") {- emitCommand("editInstanceText");- }- },- }}- action={- <ShowToggle- instance={item.instance}- value={show}- isAnimating={isAnimating}- />+ }}+ onDrop={(data) => {+ const builderDropTarget = $dragAndDropState.get().dropTarget;+ if (builderDropTarget) {+ reparentInstance(data.selector, {+ parentSelector: builderDropTarget.itemSelector,+ position: builderDropTarget.indexWithinChildren,+ });}- >- <TreeNodeContent- instance={item.instance}- isEditing={- item.selector.join() === editingItemSelector?.join()+ $dragAndDropState.set({ isDragging: false });+ }}+ onExpand={(isExpanded) => handleExpand(item, isExpanded, false)}+ >+ <InstanceContextMenu>+ <TreeNode+ level={level}+ isSelected={selectedKeys.has(getSelectorKey(item.selector))}+ isSelectedDescendant={isSelectedDescendantItem}+ isHighlighted={hoveredKey === key || dropTargetKey === key}+ isExpanded={item.isExpanded}+ isActionVisible={isAnimating}+ onExpand={(isExpanded, all) =>+ handleExpand(item, isExpanded, all)}- onIsEditingChange={(isEditing) => {- $editingItemSelector.set(- isEditing === true ? item.selector : undefined- );+ nodeProps={{+ style: {+ opacity: item.isHidden ? 0.4 : undefined,+ color: item.isReusable+ ? rawTheme.colors.foregroundReusable+ : undefined,+ },}}- />- </TreeNode>- </InstanceContextMenu>- </TreeSortableItem>- );- })}+ buttonProps={{+ onPointerDown: (event) =>+ handlePointerDown(item.selector, event),+ onMouseEnter: () => {+ $hoveredInstanceSelector.set(item.selector);+ $blockChildOutline.set(undefined);+ },+ onMouseLeave: () =>+ $hoveredInstanceSelector.set(undefined),+ onClick: (event) => handleClick(item.selector, event),+ onFocus: (event) =>+ selectInstanceOnFocus(item.selector, event),+ onKeyDown: (event) => {+ handleKeyDown(item.selector, event);+ if (event.defaultPrevented) {+ return;+ }+ if (event.key === "Enter") {+ emitCommand("editInstanceText");+ }+ },+ onKeyUp: handleKeyUp,+ }}+ action={+ <ShowToggle+ instance={item.instance}+ value={show}+ isAnimating={isAnimating}+ />+ }+ >+ <TreeNodeContent+ instance={item.instance}+ isEditing={areInstanceSelectorsEqual(+ item.selector,+ editingItemSelector+ )}+ onIsEditingChange={(isEditing) => {+ $editingItemSelector.set(+ isEditing === true ? item.selector : undefined+ );+ }}+ />+ </TreeNode>+ </InstanceContextMenu>+ </TreeSortableItem>+ );+ })}+ </Box></TreeRoot>{/* space in the end of scroll area */}<Box css={{ height: theme.spacing[9] }}></Box></ScrollArea>);};++export const __testing__ = {+ getFocusSelectionSkipCountAfterPointerDown,+ getNavigatorKeyboardSelectionUpdate,+ getNavigatorSiblingSelectionUpdate,+ getNavigatorSelectionUpdate,+ shouldClearNavigatorMultiSelectionOnEscape,+ shouldSelectOnPointerDown,+};diff --git a/apps/builder/app/builder/features/publish/publish.tsx b/apps/builder/app/builder/features/publish/publish.tsxindex d10b305394..b388dd3e42 100644--- a/apps/builder/app/builder/features/publish/publish.tsx+++ b/apps/builder/app/builder/features/publish/publish.tsx@@ -41,7 +41,7 @@ import {SmallIconButton,} from "@webstudio-is/design-system";import { validateProjectDomain, type Project } from "@webstudio-is/project";-import { $selectedInstanceSelector } from "~/shared/nano-states";+import { selectInstance } from "~/shared/nano-states";import { $selectedPageId } from "~/shared/nano-states";import {$authTokenPermissions,@@ -810,9 +810,7 @@ const UpgradeBanner = ({ hasCustomDomains }: { hasCustomDomains: boolean }) => {type="button"onClick={() => {$selectedPageId.set(navigate.pageId);- $selectedInstanceSelector.set(- navigate.instanceSelector- );+ selectInstance(navigate.instanceSelector);if (view === "pageSettings") {setActiveSidebarPanel("pages");$editingPageId.set(navigate.pageId);diff --git a/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.stories.tsxindex f9f52e8309..4915d2b49e 100644--- a/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backdrop-filter/backdrop-filter.stories.tsx@@ -18,10 +18,7 @@ import {} from "~/shared/sync/data-stores";import { registerContainers } from "~/shared/sync/sync-stores";import { createDefaultPages } from "@webstudio-is/project-build";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";import { Section } from "./backdrop-filter";registerContainers();@@ -43,7 +40,7 @@ $pages.set(}));$selectedPageId.set("homePageId");-$selectedInstanceSelector.set(["box"]);+selectInstance(["box"]);const blurBackdropFilter: StyleDecl = {breakpointId: "base",diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsxindex 73fb8cbf96..4c5bc9dba1 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/background-content.stories.tsx@@ -18,10 +18,7 @@ import {} from "~/shared/sync/data-stores";import { registerContainers } from "~/shared/sync/sync-stores";import { BackgroundContent as BackgroundContentPanel } from "./background-content";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";import { useComputedStyleDecl } from "../../shared/model";import { setRepeatedStyleItem } from "../../shared/repeated-style";import { type StyleValue } from "@webstudio-is/css-engine";@@ -59,7 +56,7 @@ $styles.set();$selectedPageId.set("homePageId");-$selectedInstanceSelector.set(["box"]);+selectInstance(["box"]);const BackgroundStory = ({ styleValue }: { styleValue: StyleValue }) => {const backgroundImage = useComputedStyleDecl("background-image");diff --git a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsxindex 1283975334..b3d40aa53b 100644--- a/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/backgrounds/backgrounds.stories.tsx@@ -16,10 +16,7 @@ import {$styleSourceSelections,} from "~/shared/sync/data-stores";import { Section as SectionComponent } from "./backgrounds";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";const backgroundImage: StyleDecl = {breakpointId: "base",@@ -57,7 +54,7 @@ $instances.set(]));$selectedPageId.set("");-$selectedInstanceSelector.set(["box"]);+selectInstance(["box"]);const SingleLayerVariant = () => {useEffect(() => {diff --git a/apps/builder/app/builder/features/style-panel/sections/borders/borders.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/borders/borders.stories.tsxindex 23a96e2082..edad48a48d 100644--- a/apps/builder/app/builder/features/style-panel/sections/borders/borders.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/borders/borders.stories.tsx@@ -18,10 +18,7 @@ import {} from "~/shared/sync/data-stores";import { registerContainers } from "~/shared/sync/sync-stores";import { createDefaultPages } from "@webstudio-is/project-build";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";import { Section } from "./borders";registerContainers();@@ -43,7 +40,7 @@ $pages.set(}));$selectedPageId.set("homePageId");-$selectedInstanceSelector.set(["box"]);+selectInstance(["box"]);const solidBorderTop: StyleDecl = {breakpointId: "base",diff --git a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.stories.tsxindex 7f040ea826..4368bd3a7e 100644--- a/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/box-shadows/box-shadows.stories.tsx@@ -18,10 +18,7 @@ import {} from "~/shared/sync/data-stores";import { registerContainers } from "~/shared/sync/sync-stores";import { createDefaultPages } from "@webstudio-is/project-build";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";import { Section } from "./box-shadows";registerContainers();@@ -43,7 +40,7 @@ $pages.set(}));$selectedPageId.set("homePageId");-$selectedInstanceSelector.set(["box"]);+selectInstance(["box"]);const outerShadow: StyleDecl = {breakpointId: "base",diff --git a/apps/builder/app/builder/features/style-panel/sections/filter/filter.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/filter/filter.stories.tsxindex f4b3b7e1f5..f133030a0c 100644--- a/apps/builder/app/builder/features/style-panel/sections/filter/filter.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/filter/filter.stories.tsx@@ -18,10 +18,7 @@ import {} from "~/shared/sync/data-stores";import { registerContainers } from "~/shared/sync/sync-stores";import { createDefaultPages } from "@webstudio-is/project-build";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";import { Section } from "./filter";registerContainers();@@ -43,7 +40,7 @@ $pages.set(}));$selectedPageId.set("homePageId");-$selectedInstanceSelector.set(["box"]);+selectInstance(["box"]);const blurFilterStyle: StyleDecl = {breakpointId: "base",diff --git a/apps/builder/app/builder/features/style-panel/sections/outline/outline.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/outline/outline.stories.tsxindex e17cfb0cf0..cbdb73cc6d 100644--- a/apps/builder/app/builder/features/style-panel/sections/outline/outline.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/outline/outline.stories.tsx@@ -18,10 +18,7 @@ import {} from "~/shared/sync/data-stores";import { registerContainers } from "~/shared/sync/sync-stores";import { createDefaultPages } from "@webstudio-is/project-build";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";import { Section } from "./outline";registerContainers();@@ -43,7 +40,7 @@ $pages.set(}));$selectedPageId.set("homePageId");-$selectedInstanceSelector.set(["box"]);+selectInstance(["box"]);const solidOutline: StyleDecl = {breakpointId: "base",diff --git a/apps/builder/app/builder/features/style-panel/sections/position/inset-control.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/position/inset-control.stories.tsxindex af6317ff88..f011ab5bad 100644--- a/apps/builder/app/builder/features/style-panel/sections/position/inset-control.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/position/inset-control.stories.tsx@@ -12,10 +12,7 @@ import {$styleSources,$styleSourceSelections,} from "~/shared/sync/data-stores";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";const top: StyleDecl = {breakpointId: "base",@@ -92,7 +89,7 @@ $pages.set(}));$selectedPageId.set("homePageId");-$selectedInstanceSelector.set(["box"]);+selectInstance(["box"]);export const Inset = () => {return (diff --git a/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.stories.tsx b/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.stories.tsxindex c78a149a4e..c3c0d27f10 100644--- a/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/sections/transitions/transitions.stories.tsx@@ -10,10 +10,7 @@ import {} from "~/shared/sync/data-stores";import { registerContainers } from "~/shared/sync/sync-stores";import { Section } from "./transitions";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";import { createDefaultPages } from "@webstudio-is/project-build";const transitionProperty: StyleDecl = {@@ -57,7 +54,7 @@ $pages.set(}));$selectedPageId.set("homePageId");-$selectedInstanceSelector.set(["box"]);+selectInstance(["box"]);export const Transitions = () => (<StorySection title="Transitions">diff --git a/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts b/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.tsindex 1a06b2c195..874fa16bff 100644--- a/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts+++ b/apps/builder/app/builder/features/style-panel/shared/repeated-style.test.ts@@ -29,10 +29,7 @@ import {import { registerContainers } from "~/shared/sync/sync-stores";import { setProperty } from "./use-style-data";import type { ComputedStyleDecl } from "~/shared/style-object-model";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";setEnv("*");registerContainers();@@ -41,7 +38,7 @@ beforeEach(() => {$breakpoints.set(new Map([["base", { id: "base", label: "" }]]));$selectedBreakpointId.set("base");$selectedPageId.set("");- $selectedInstanceSelector.set(["box"]);+ selectInstance(["box"]);$instances.set(new Map([["box", { type: "instance", id: "box", component: "Box", children: [] }],diff --git a/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.ts b/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.tsindex c9fd416c6a..ec6eec2448 100644--- a/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.ts+++ b/apps/builder/app/builder/features/style-panel/shared/use-style-data.test.ts@@ -12,10 +12,7 @@ import {$styleSources,$styles,} from "~/shared/sync/data-stores";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";import { deleteProperty, setProperty } from "./use-style-data";import { getStyleDeclKey, type StyleDecl } from "@webstudio-is/sdk";@@ -37,7 +34,7 @@ const setupSelection = (styleSource: {]));$selectedPageId.set("");- $selectedInstanceSelector.set(["body"]);+ selectInstance(["body"]);$breakpoints.set(new Map([["base", { id: "base", label: "Base" }]]));$selectedBreakpointId.set("base");$styleSources.set(new Map([[styleSource.id, styleSource]]));diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.test.ts b/apps/builder/app/builder/features/style-panel/style-source-section.test.tsindex eeb71b30f0..1516e3a8e7 100644--- a/apps/builder/app/builder/features/style-panel/style-source-section.test.ts+++ b/apps/builder/app/builder/features/style-panel/style-source-section.test.ts@@ -9,10 +9,7 @@ import {$styles,} from "~/shared/sync/data-stores";import { addStyleSourceToInstance, __testing__ } from "./style-source-section";-import {- $selectedPageId,- $selectedInstanceSelector,-} from "~/shared/nano-states";+import { $selectedPageId, selectInstance } from "~/shared/nano-states";const { duplicateStyleSource, getComponentStates } = __testing__;@@ -158,7 +155,7 @@ test("add style source to instance", () => {]));$selectedPageId.set("");- $selectedInstanceSelector.set(["body"]);+ selectInstance(["body"]);$styleSources.set(new Map([["local1", { id: "local1", type: "local" }]]));$styleSourceSelections.set(new Map());$selectedStyleSources.set(new Map());@@ -195,7 +192,7 @@ test("duplicate locked style source creates an unlocked copy", () => {]));$selectedPageId.set("");- $selectedInstanceSelector.set(["body"]);+ selectInstance(["body"]);$styleSources.set(new Map([[diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-instance-context-menu.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-instance-context-menu.tsxindex 72c8c07161..bcb2356000 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/canvas-instance-context-menu.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/canvas-instance-context-menu.tsx@@ -1,7 +1,11 @@import { useStore } from "@nanostores/react";-import { $instanceContextMenu } from "~/shared/nano-states";import { useEffect, useRef } from "react";-import { selectInstance } from "~/shared/nano-states";+import {+ $allSelectedInstanceSelectors,+ $instanceContextMenu,+ selectInstances,+} from "~/shared/nano-states";+import { getContextMenuSelectedInstanceSelectors } from "~/shared/instance-utils/selection";import {ContextMenu,ContextMenuTrigger,@@ -19,7 +23,12 @@ export const CanvasInstanceContextMenu = () => {useEffect(() => {if (contextMenu && triggerRef.current && canvasRect) {- selectInstance(contextMenu.instanceSelector);+ selectInstances(+ getContextMenuSelectedInstanceSelectors({+ selectedSelectors: $allSelectedInstanceSelectors.get(),+ clickedSelector: contextMenu.instanceSelector,+ })+ );// Calculate the scaled and offset positionconst scaledPosition = applyScale(diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/outline.tsxindex 5b86fcb775..2a02751a99 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/outline.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/outline.tsx@@ -135,6 +135,7 @@ export const Outline = ({<>{propertyStyle}<div+ data-ws-outline={variant ?? "default"}className={`${baseStyle()} ${baseOutlineStyle({ variant, isLeftClamped, isRightClamped, isBottomClamped, isTopClamped })}`}style={style}>diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.test.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.test.tsxnew file mode 100644index 0000000000..0c19978089--- /dev/null+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.test.tsx@@ -0,0 +1,147 @@+import { createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { act } from "react-dom/test-utils";+import { afterEach, beforeEach, describe, expect, test } from "vitest";+import type { Instance } from "@webstudio-is/sdk";+import { $instances } from "~/shared/sync/data-stores";+import {+ $selectedInstanceOutlines,+ $textEditingInstanceSelector,+} from "~/shared/nano-states";+import {+ $canvasRect,+ $canvasScrollbarSize,+ $canvasWidth,+ $workspaceRect,+} from "~/builder/shared/nano-states";+import { $ephemeralStyles } from "~/canvas/stores";+import { SelectedInstanceOutline } from "./selected-instance-outline";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++let root: Root | undefined;++const createInstance = (id: Instance["id"]): Instance => ({+ type: "instance",+ id,+ component: "Box",+ children: [],+});++const rect = (left: number, top: number, width: number, height: number) =>+ ({ left, top, width, height }) as DOMRect;++const renderSelectedInstanceOutline = () => {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => {+ root?.render(createElement(SelectedInstanceOutline));+ });+ return {+ getOutlines: () => document.querySelectorAll("[data-ws-outline]"),+ };+};++beforeEach(() => {+ $instances.set(+ new Map([+ ["box1", createInstance("box1")],+ ["box2", createInstance("box2")],+ ])+ );+ $workspaceRect.set(rect(0, 0, 1000, 800));+ $canvasRect.set(rect(0, 0, 1000, 800));+ $canvasScrollbarSize.set({ width: 0, height: 0 });+ $canvasWidth.set(1000);+ $ephemeralStyles.set([]);+});++afterEach(() => {+ act(() => {+ root?.unmount();+ });+ root = undefined;+ document.body.innerHTML = "";+ $instances.set(new Map());+ $selectedInstanceOutlines.set([]);+ $textEditingInstanceSelector.set(undefined);+ $workspaceRect.set(undefined);+ $canvasRect.set(undefined);+ $canvasScrollbarSize.set(undefined);+ $canvasWidth.set(undefined);+ $ephemeralStyles.set([]);+});++describe("SelectedInstanceOutline", () => {+ test("renders an outline for every selected instance outline", () => {+ $selectedInstanceOutlines.set([+ {+ selector: ["box1", "body"],+ instanceId: "box1",+ rect: rect(10, 20, 100, 50),+ },+ {+ selector: ["box2", "body"],+ instanceId: "box2",+ rect: rect(40, 80, 120, 60),+ },+ ]);++ const { getOutlines } = renderSelectedInstanceOutline();++ expect(getOutlines()).toHaveLength(2);+ });++ test("renders multiple selected outlines when stale ephemeral styles exist", () => {+ $selectedInstanceOutlines.set([+ {+ selector: ["box1", "body"],+ instanceId: "box1",+ rect: rect(10, 20, 100, 50),+ },+ {+ selector: ["box2", "body"],+ instanceId: "box2",+ rect: rect(40, 80, 120, 60),+ },+ ]);+ $ephemeralStyles.set([+ {+ breakpointId: "base",+ styleSourceId: "style-source",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);++ const { getOutlines } = renderSelectedInstanceOutline();++ expect(getOutlines()).toHaveLength(2);+ });++ test("hides only the outline for the instance being text edited", () => {+ $selectedInstanceOutlines.set([+ {+ selector: ["box1", "body"],+ instanceId: "box1",+ rect: rect(10, 20, 100, 50),+ },+ {+ selector: ["box2", "body"],+ instanceId: "box2",+ rect: rect(40, 80, 120, 60),+ },+ ]);+ $textEditingInstanceSelector.set({+ selector: ["box1", "body"],+ reason: "enter",+ });++ const { getOutlines } = renderSelectedInstanceOutline();++ expect(getOutlines()).toHaveLength(1);+ });+});diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.tsx b/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.tsxindex d8292458f2..7f1e6aff9d 100644--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.tsx+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/selected-instance-outline.tsx@@ -1,8 +1,9 @@import { useStore } from "@nanostores/react";-import { $selectedInstanceOutlineAndInstance } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";-import { $textEditingInstanceSelector } from "~/shared/nano-states";-import { $selectedInstanceSelector } from "~/shared/nano-states";+import {+ $selectedInstanceOutlines,+ $textEditingInstanceSelector,+} from "~/shared/nano-states";import { isDescendantOrSelf } from "~/shared/instance-utils/tree";import { Outline } from "./outline";import { applyScale } from "../apply-scale";@@ -12,40 +13,49 @@ import { $ephemeralStyles } from "~/canvas/stores";export const SelectedInstanceOutline = () => {const instances = useStore($instances);- const selectedInstanceSelector = useStore($selectedInstanceSelector);const textEditingInstanceSelector = useStore($textEditingInstanceSelector);- const outline = useStore($selectedInstanceOutlineAndInstance);+ const outlines = useStore($selectedInstanceOutlines);const scale = useStore($scale);const ephemeralStyles = useStore($ephemeralStyles);const clampingRect = useStore($clampingRect);- if (selectedInstanceSelector === undefined) {+ if (clampingRect === undefined) {return;}- if (clampingRect === undefined) {+ if (outlines.length === 0) {return;}- const isEditingCurrentInstance =- textEditingInstanceSelector !== undefined &&- isDescendantOrSelf(- selectedInstanceSelector,- textEditingInstanceSelector.selector- );-- if (- isEditingCurrentInstance ||- outline === undefined ||- ephemeralStyles.length !== 0- ) {+ if (outlines.length === 1 && ephemeralStyles.length !== 0) {return;}- const variant = findClosestSlot(instances, selectedInstanceSelector)- ? "slot"- : "default";- const rect = applyScale(outline.rect, scale);-- return <Outline rect={rect} clampingRect={clampingRect} variant={variant} />;+ return (+ <>+ {outlines.map((outline) => {+ const isEditingCurrentInstance =+ textEditingInstanceSelector !== undefined &&+ isDescendantOrSelf(+ outline.selector,+ textEditingInstanceSelector.selector+ );+ if (isEditingCurrentInstance) {+ return;+ }+ const variant = findClosestSlot(instances, outline.selector)+ ? "slot"+ : "default";+ const rect = applyScale(outline.rect, scale);+ return (+ <Outline+ key={JSON.stringify(outline.selector)}+ rect={rect}+ clampingRect={clampingRect}+ variant={variant}+ />+ );+ })}+ </>+ );};diff --git a/apps/builder/app/builder/inspector.test.ts b/apps/builder/app/builder/inspector.test.tsnew file mode 100644index 0000000000..a3d8eeba13--- /dev/null+++ b/apps/builder/app/builder/inspector.test.ts@@ -0,0 +1,15 @@+import { describe, expect, test } from "vitest";+import { __testing__ } from "./inspector";++const { getInspectorEmptyStateMessage } = __testing__;++describe("getInspectorEmptyStateMessage", () => {+ test("describes empty and multi-selection states", () => {+ expect(getInspectorEmptyStateMessage(0)).toBe(+ "Select an instance on the canvas"+ );+ expect(getInspectorEmptyStateMessage(2)).toBe(+ "Multiple instances selected"+ );+ });+});diff --git a/apps/builder/app/builder/inspector.tsx b/apps/builder/app/builder/inspector.tsxindex edaa257740..12ed5ee61b 100644--- a/apps/builder/app/builder/inspector.tsx+++ b/apps/builder/app/builder/inspector.tsx@@ -28,6 +28,7 @@ import { NavigatorTree } from "~/builder/features/navigator";import type { Settings } from "~/builder/shared/client-settings";import { $activeInspectorPanel } from "~/builder/shared/nano-states";import {+ $allSelectedInstanceSelectors,$selectedInstance,$selectedInstanceKey,$selectedPage,@@ -59,9 +60,15 @@ const contentStyle = {const $isDragging = computed([$dragAndDropState], (state) => state.isDragging);+const getInspectorEmptyStateMessage = (selectedInstanceCount: number) =>+ selectedInstanceCount > 1+ ? "Multiple instances selected"+ : "Select an instance on the canvas";+export const Inspector = ({ navigatorLayout }: InspectorProps) => {const selectedInstance = useStore($selectedInstance);const selectedInstanceKey = useStore($selectedInstanceKey);+ const selectedInstanceSelectors = useStore($allSelectedInstanceSelectors);const tabsRef = useRef<HTMLDivElement>(null);const isDragging = useStore($isDragging);const metas = useStore($registeredComponentMetas);@@ -78,7 +85,9 @@ export const Inspector = ({ navigatorLayout }: InspectorProps) => {<Flex css={{ p: theme.spacing[9] }}>{/* @todo: use this space for something more usefull: a-la figma's no instance selected sate, maybe create an issue with a more specific proposal? */}<Card css={{ p: theme.spacing[9], width: "100%" }}>- <Text>Select an instance on the canvas</Text>+ <Text>+ {getInspectorEmptyStateMessage(selectedInstanceSelectors.length)}+ </Text></Card></Flex>);@@ -196,3 +205,7 @@ export const Inspector = ({ navigatorLayout }: InspectorProps) => {</EnhancedTooltipProvider>);};++export const __testing__ = {+ getInspectorEmptyStateMessage,+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-info.tsxindex 886e13ad33..87f9cf6725 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-info.tsx@@ -63,7 +63,7 @@ import { $assets } from "~/shared/sync/data-stores";import { $styleSourceSelections } from "~/shared/sync/data-stores";import { $openProjectSettings } from "~/shared/nano-states/project-settings";import { $styles } from "~/shared/sync/data-stores";-import { $selectedInstanceSelector } from "~/shared/nano-states";+import { selectInstance } from "~/shared/nano-states";import { selectPage } from "~/shared/nano-states";import { findPageAndSelectorByInstanceId } from "~/shared/instance-utils/lookup";import { $selectedPageId } from "~/shared/nano-states";@@ -274,7 +274,7 @@ const AssetUsagesList = ({ usages }: { usages: AssetUsage[] }) => {prop.instanceId);$selectedPageId.set(pageId);- $selectedInstanceSelector.set(instanceSelector);+ selectInstance(instanceSelector);setActiveSidebarPanel("auto");$activeInspectorPanel.set("settings");}}@@ -321,7 +321,7 @@ const AssetUsagesList = ({ usages }: { usages: AssetUsage[] }) => {styleInstanceId);$selectedPageId.set(pageId);- $selectedInstanceSelector.set(instanceSelector);+ selectInstance(instanceSelector);setActiveSidebarPanel("auto");$activeInspectorPanel.set("style");}}diff --git a/apps/builder/app/builder/shared/commands.test.ts b/apps/builder/app/builder/shared/commands.test.tsindex 2522907063..5311239ce2 100644--- a/apps/builder/app/builder/shared/commands.test.ts+++ b/apps/builder/app/builder/shared/commands.test.ts@@ -1,8 +1,14 @@-import { describe, expect, test } from "vitest";+import { afterEach, describe, expect, test, vi } from "vitest";import { createDefaultPages } from "@webstudio-is/project-build";-import type { Instance, PageTemplate } from "@webstudio-is/sdk";+import {+ blockTemplateComponent,+ type Instance,+ type PageTemplate,+} from "@webstudio-is/sdk";import type { Project } from "@webstudio-is/project";import {+ $allSelectedInstanceSelectors,+ $editingItemSelector,$editingPageId,$editingTemplateId,$folderIdToDelete,@@ -12,6 +18,7 @@ import {$selectedInstanceSelector,$templateIdToDelete,selectInstance,+ selectInstances,selectPage,} from "~/shared/nano-states";import {@@ -33,12 +40,22 @@ import {getPageActionTarget,} from "~/shared/page-action-target";import { expectSlotsShareFragment } from "~/shared/slot-test-utils";-import { __testing__, emitCommand } from "./commands";+import { __testing__, emitCommand, subscribeCommands } from "./commands";+import { $activeInspectorPanel } from "./nano-states";-const { canRunDesignModeCommand, guardDesignModeCommand } = __testing__;+const {+ canRunDesignModeCommand,+ canRunDesignOrContentModeCommand,+ guardDesignModeCommand,+ guardDesignOrContentModeCommand,+} = __testing__;registerContainers();+afterEach(() => {+ vi.unstubAllGlobals();+});+const resetPageActionStores = () => {$editingPageId.set(undefined);$editingTemplateId.set(undefined);@@ -135,6 +152,29 @@ describe("canRunDesignModeCommand", () => {});});+describe("canRunDesignOrContentModeCommand", () => {+ test("allows commands in design and content modes only", () => {+ expect(+ canRunDesignOrContentModeCommand({+ isContentMode: false,+ isDesignMode: true,+ })+ ).toBe(true);+ expect(+ canRunDesignOrContentModeCommand({+ isContentMode: true,+ isDesignMode: false,+ })+ ).toBe(true);+ expect(+ canRunDesignOrContentModeCommand({+ isContentMode: false,+ isDesignMode: false,+ })+ ).toBe(false);+ });+});+describe("guardDesignModeCommand", () => {test("allows design mode commands without showing a message", () => {const messages: string[] = [];@@ -163,7 +203,206 @@ describe("guardDesignModeCommand", () => {});});+describe("guardDesignOrContentModeCommand", () => {+ test("allows content mode commands without showing a message", () => {+ const messages: string[] = [];++ expect(+ guardDesignOrContentModeCommand({+ isContentMode: true,+ isDesignMode: false,+ message: "Blocked",+ toastInfo: (message) => messages.push(message),+ })+ ).toBe(true);+ expect(messages).toEqual([]);+ });++ test("blocks commands outside design and content modes", () => {+ const messages: string[] = [];++ expect(+ guardDesignOrContentModeCommand({+ isContentMode: false,+ isDesignMode: false,+ message: "Blocked",+ toastInfo: (message) => messages.push(message),+ })+ ).toBe(false);+ expect(messages).toEqual(["Blocked"]);+ });+});++describe("single-instance-only commands", () => {+ const setupMultiSelectionProject = () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ ],+ },+ ],+ [+ "box1",+ {+ type: "instance",+ id: "box1",+ component: "Box",+ children: [],+ },+ ],+ [+ "box2",+ {+ type: "instance",+ id: "box2",+ component: "Box",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstances([+ ["box1", "body"],+ ["box2", "body"],+ ]);+ };++ test("does not open settings or style source input for multi-selection", () => {+ setupMultiSelectionProject();+ $activeInspectorPanel.set("style");++ emitCommand("openSettingsPanel");+ emitCommand("focusStyleSources");++ expect($activeInspectorPanel.get()).toBe("style");+ });++ test("does not toggle visibility or edit label for multi-selection", () => {+ setupMultiSelectionProject();++ emitCommand("toggleShow");+ emitCommand("editInstanceLabel");++ expect($props.get()).toEqual(new Map());+ expect($editingItemSelector.get()).toBeUndefined();+ });+});++describe("cut", () => {+ test("cuts multiple selected sibling instances through command", async () => {+ resetDataStores();+ const writeText = vi.fn().mockResolvedValue(undefined);+ vi.stubGlobal("navigator", {+ ...navigator,+ clipboard: { writeText },+ });+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ ],+ },+ ],+ [+ "box1",+ {+ type: "instance",+ id: "box1",+ component: "Box",+ children: [],+ },+ ],+ [+ "box2",+ {+ type: "instance",+ id: "box2",+ component: "Box",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstances([+ ["box1", "body"],+ ["box2", "body"],+ ]);++ emitCommand("cut");+ await Promise.resolve();++ expect(JSON.parse(writeText.mock.calls[0]?.[0] ?? "")).toMatchObject({+ "@webstudio/instances/v0.1": {+ rootInstanceIds: ["box1", "box2"],+ },+ });+ expect($instances.get().get("body")?.children).toEqual([]);+ expect($instances.get().has("box1")).toBe(false);+ expect($instances.get().has("box2")).toBe(false);+ });+});+describe("duplicateInstance", () => {+ test("does nothing when no page item or instance is selected", () => {+ resetDataStores();+ $project.set({ id: "project-id" } as Project);+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [{ type: "id", value: "box" }],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ ]);+ $instances.set(instances);+ selectInstance(undefined);++ emitCommand("duplicateInstance");++ expect($instances.get()).toEqual(instances);+ expect($selectedInstanceSelector.get()).toBeUndefined();+ });+test("duplicates shared slot child in shared slot content", () => {resetDataStores();const instances = new Map<Instance["id"], Instance>([@@ -510,9 +749,499 @@ describe("duplicateInstance", () => {"body",]);});++ test("duplicates multiple selected sibling instances", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ ],+ },+ ],+ [+ "box1",+ {+ type: "instance",+ id: "box1",+ component: "Box",+ children: [],+ },+ ],+ [+ "box2",+ {+ type: "instance",+ id: "box2",+ component: "Box",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstances([+ ["box1", "body"],+ ["box2", "body"],+ ]);++ emitCommand("duplicateInstance");++ const bodyChildren = $instances.get().get("body")?.children;+ const duplicateIds = [bodyChildren?.[1]?.value, bodyChildren?.[3]?.value];+ expect(bodyChildren).toEqual([+ { type: "id", value: "box1" },+ { type: "id", value: expect.any(String) },+ { type: "id", value: "box2" },+ { type: "id", value: expect.any(String) },+ ]);+ expect(duplicateIds[0]).not.toBe("box1");+ expect(duplicateIds[1]).not.toBe("box2");+ expect($allSelectedInstanceSelectors.get()).toEqual([+ [duplicateIds[0], "body"],+ [duplicateIds[1], "body"],+ ]);+ });++ test("duplicates multiple selected sibling instances through keyboard shortcut", () => {+ resetDataStores();+ const unsubscribe = subscribeCommands();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ ],+ },+ ],+ [+ "box1",+ {+ type: "instance",+ id: "box1",+ component: "Box",+ children: [],+ },+ ],+ [+ "box2",+ {+ type: "instance",+ id: "box2",+ component: "Box",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstances([+ ["box1", "body"],+ ["box2", "body"],+ ]);++ document.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "d",+ metaKey: true,+ bubbles: true,+ cancelable: true,+ })+ );++ const bodyChildren = $instances.get().get("body")?.children;+ const duplicateIds = [bodyChildren?.[1]?.value, bodyChildren?.[3]?.value];+ expect(bodyChildren).toEqual([+ { type: "id", value: "box1" },+ { type: "id", value: expect.any(String) },+ { type: "id", value: "box2" },+ { type: "id", value: expect.any(String) },+ ]);+ expect(duplicateIds[0]).not.toBe("box1");+ expect(duplicateIds[1]).not.toBe("box2");+ unsubscribe();+ });++ test("duplicates only detachable roots when multi-selection includes non-detachable roots", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "template" },+ { type: "id", value: "box" },+ ],+ },+ ],+ [+ "template",+ {+ type: "instance",+ id: "template",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstances([+ ["template", "body"],+ ["box", "body"],+ ]);++ emitCommand("duplicateInstance");++ const bodyChildren = $instances.get().get("body")?.children;+ const duplicateId = bodyChildren?.[2]?.value;+ expect(bodyChildren).toEqual([+ { type: "id", value: "template" },+ { type: "id", value: "box" },+ { type: "id", value: expect.any(String) },+ ]);+ expect(duplicateId).not.toBe("template");+ expect(duplicateId).not.toBe("box");+ expect($instances.get().get("template")).toEqual(instances.get("template"));+ expect($selectedInstanceSelector.get()).toEqual([duplicateId, "body"]);+ });++ test("does not duplicate when no multi-selected root is detachable", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "template1" },+ { type: "id", value: "template2" },+ ],+ },+ ],+ [+ "template1",+ {+ type: "instance",+ id: "template1",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ [+ "template2",+ {+ type: "instance",+ id: "template2",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ]);+ const pages = createDefaultPages({+ homePageId: "page-id",+ rootInstanceId: "body",+ });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $project.set({ id: "project-id" } as Project);+ $instances.set(instances);+ selectInstances([+ ["template1", "body"],+ ["template2", "body"],+ ]);++ emitCommand("duplicateInstance");++ expect($instances.get()).toEqual(instances);+ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["template1", "body"],+ ["template2", "body"],+ ]);+ });+});++describe("deleteInstanceBuilder", () => {+ test("does nothing when no page item or instance is selected", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [{ type: "id", value: "box" }],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ ]);+ $instances.set(instances);+ selectInstance(undefined);++ emitCommand("deleteInstanceBuilder");++ expect($instances.get()).toEqual(instances);+ expect($selectedInstanceSelector.get()).toBeUndefined();+ });++ test("deletes multiple selected sibling instances", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ ],+ },+ ],+ [+ "box1",+ {+ type: "instance",+ id: "box1",+ component: "Box",+ children: [],+ },+ ],+ [+ "box2",+ {+ type: "instance",+ id: "box2",+ component: "Box",+ children: [],+ },+ ],+ ]);+ $instances.set(instances);+ selectInstances([+ ["box1", "body"],+ ["box2", "body"],+ ]);++ emitCommand("deleteInstanceBuilder");++ expect($instances.get().get("body")?.children).toEqual([]);+ expect($instances.get().has("box1")).toBe(false);+ expect($instances.get().has("box2")).toBe(false);+ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ });++ test("deletes only detachable roots when multi-selection includes non-detachable roots", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "template" },+ { type: "id", value: "box" },+ ],+ },+ ],+ [+ "template",+ {+ type: "instance",+ id: "template",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ [+ "box",+ {+ type: "instance",+ id: "box",+ component: "Box",+ children: [],+ },+ ],+ ]);+ $instances.set(instances);+ selectInstances([+ ["template", "body"],+ ["box", "body"],+ ]);++ emitCommand("deleteInstanceBuilder");++ expect($instances.get().get("body")?.children).toEqual([+ { type: "id", value: "template" },+ ]);+ expect($instances.get().has("template")).toBe(true);+ expect($instances.get().has("box")).toBe(false);+ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ });++ test("does not delete when no multi-selected root is detachable", () => {+ resetDataStores();+ const instances = new Map<Instance["id"], Instance>([+ [+ "body",+ {+ type: "instance",+ id: "body",+ component: "Body",+ children: [+ { type: "id", value: "template1" },+ { type: "id", value: "template2" },+ ],+ },+ ],+ [+ "template1",+ {+ type: "instance",+ id: "template1",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ [+ "template2",+ {+ type: "instance",+ id: "template2",+ component: blockTemplateComponent,+ children: [],+ },+ ],+ ]);+ $instances.set(instances);+ selectInstances([+ ["template1", "body"],+ ["template2", "body"],+ ]);++ emitCommand("deleteInstanceBuilder");++ expect($instances.get()).toEqual(instances);+ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["template1", "body"],+ ["template2", "body"],+ ]);+ });});describe("move instance commands", () => {+ test("extends instance selection with shift arrows when navigator is not focused", () => {+ setupMoveInstanceProject();+ const unsubscribe = subscribeCommands();+ selectInstance(["box", "body"]);++ document.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ shiftKey: true,+ bubbles: true,+ cancelable: true,+ })+ );+ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ]);++ document.body.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowDown",+ shiftKey: true,+ bubbles: true,+ cancelable: true,+ })+ );+ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ["paragraph", "body"],+ ]);++ unsubscribe();+ });++ test("selects all siblings with command-a when navigator is not focused", () => {+ setupMoveInstanceProject();+ const unsubscribe = subscribeCommands();+ selectInstance(["heading", "body"]);++ document.body.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "a",+ metaKey: true,+ bubbles: true,+ cancelable: true,+ })+ );++ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ["paragraph", "body"],+ ]);+ unsubscribe();+ });+test("moves the selected instance above the previous sibling", () => {setupMoveInstanceProject();selectInstance(["heading", "body"]);diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex 4b2247528e..85ae2a1061 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -1,7 +1,9 @@import {unwrapInstance,+ deleteInstanceMutable,deleteSelectedInstance,reparentInstance,+ sortInstancePathsForChildMutation,} from "~/shared/instance-utils/mutation";import { toggleInstanceShow } from "~/shared/instance-utils/mutation";import {@@ -10,7 +12,13 @@ import {} from "~/shared/instance-utils/fragment";import { insertWebstudioFragmentAt } from "~/shared/instance-utils/insert";import { toast } from "@webstudio-is/design-system";-import { type Instance, type WebstudioFragment } from "@webstudio-is/sdk";+import {+ ROOT_INSTANCE_ID,+ isComponentDetachable,+ type Instance,+ type WebstudioFragment,+} from "@webstudio-is/sdk";+import type { Project } from "@webstudio-is/project";import {isAutoGridPlacement,resetGridChildPlacement,@@ -25,13 +33,14 @@ import {$editingItemSelector,$editingPageId,$folderIdToDelete,+ $isContentMode,$isDesignMode,$isPreviewMode,$pageIdToDelete,$templateIdToDelete,toggleBuilderMode,} from "~/shared/nano-states";-import { $project } from "~/shared/sync/data-stores";+import { $instances, $project } from "~/shared/sync/data-stores";// Declare command for type safetydeclare module "~/shared/pubsub" {@@ -44,7 +53,11 @@ import {$breakpointsMenuView,selectBreakpointByOrder,} from "~/shared/breakpoints";-import { updateWebstudioData } from "~/shared/instance-utils/data";+import {+ updateInstanceData,+ updateWebstudioData,+} from "~/shared/instance-utils/data";+import { canDeleteInstanceInContentMode } from "~/shared/instance-utils/data";import { serverSyncStore } from "~/shared/sync/sync-stores";import { $publisher } from "~/shared/pubsub";import {@@ -54,8 +67,16 @@ import {setActiveSidebarPanel,toggleActiveSidebarPanel,} from "./nano-states";-import { $selectedInstancePath } from "~/shared/nano-states";-import { selectInstance, selectPage } from "~/shared/nano-states";+import {+ $allSelectedInstanceSelectors,+ $selectedInstancePath,+ clearInstanceSelection,+ getInstancePath,+ selectInstance,+ selectInstances,+ selectPage,+ type InstancePath,+} from "~/shared/nano-states";import { openCommandPanel } from "../features/command-panel";import { showWrapComponentsList } from "../features/command-panel/groups/wrap-group";import { showConvertComponentsList } from "../features/command-panel/groups/convert-group";@@ -87,6 +108,8 @@ import {getDirectSharedSlotChildBoundary,normalizeLegacySlotInstancePathMutable,} from "~/shared/instance-utils/slot";+import type { InstanceSelector } from "~/shared/instance-utils/tree";+import { areInstanceSelectorsEqual } from "~/shared/instance-utils/tree";const makeBreakpointCommand = <CommandName extends string>(name: CommandName,@@ -113,6 +136,14 @@ const exitPreviewModeFromNonCanvasSource = (source: string) => {const canRunDesignModeCommand = ({ isDesignMode }: { isDesignMode: boolean }) =>isDesignMode;+const canRunDesignOrContentModeCommand = ({+ isContentMode,+ isDesignMode,+}: {+ isContentMode: boolean;+ isDesignMode: boolean;+}) => isDesignMode || isContentMode;+const guardDesignModeCommand = ({isDesignMode,message,@@ -129,6 +160,27 @@ const guardDesignModeCommand = ({return false;};+const guardDesignOrContentModeCommand = ({+ isContentMode,+ isDesignMode,+ message,+ toastInfo = builderApi.toast.info,+}: {+ isContentMode: boolean;+ isDesignMode: boolean;+ message: string;+ toastInfo?: (message: string) => void;+}) => {+ if (canRunDesignOrContentModeCommand({ isContentMode, isDesignMode })) {+ return true;+ }+ toastInfo(message);+ return false;+};++const hasMultiInstanceSelection = () =>+ $allSelectedInstanceSelectors.get().length > 1;+const copyPageActionTarget = () => {if ($isDesignMode.get() === false) {return false;@@ -176,7 +228,9 @@ const duplicatePageActionTarget = () => {};export const __testing__ = {+ canRunDesignOrContentModeCommand,canRunDesignModeCommand,+ guardDesignOrContentModeCommand,guardDesignModeCommand,};@@ -210,6 +264,233 @@ const getIdChildIndex = (children: Instance["children"], instanceId: string) =>(child) => child.type === "id" && child.value === instanceId);+type SelectedInstancePath = {+ index: number;+ instancePath: InstancePath;+ instanceSelector: InstanceSelector;+};++const getAllSelectedInstancePaths = () => {+ const instances = $instances.get();+ const selectedInstanceSelectors = $allSelectedInstanceSelectors.get();+ const selectedInstancePaths: SelectedInstancePath[] = [];+ selectedInstanceSelectors.forEach((instanceSelector, index) => {+ if (instanceSelector[0] === ROOT_INSTANCE_ID) {+ return;+ }+ const instancePath = getInstancePath(instanceSelector, instances);+ if (instancePath === undefined || instancePath.length === 1) {+ return;+ }+ selectedInstancePaths.push({ index, instancePath, instanceSelector });+ });+ return selectedInstancePaths;+};++const getSiblingSelection = (selectedInstancePaths: SelectedInstancePath[]) => {+ const [firstSelectedPath] = selectedInstancePaths;+ const parentItem = firstSelectedPath?.instancePath[1];+ if (parentItem === undefined) {+ return;+ }+ const parentSelector = parentItem.instanceSelector;+ if (+ selectedInstancePaths.every(({ instancePath }) =>+ areInstanceSelectorsEqual(+ instancePath[1]?.instanceSelector,+ parentSelector+ )+ ) === false+ ) {+ return;+ }+ const siblingIds = parentItem.instance.children.flatMap((child) =>+ child.type === "id" ? [child.value] : []+ );+ const selectedIndexes = selectedInstancePaths+ .map(({ instancePath }) => siblingIds.indexOf(instancePath[0].instance.id))+ .filter((index) => index !== -1);+ if (selectedIndexes.length === 0) {+ return;+ }+ return { parentSelector, selectedIndexes, siblingIds };+};++const selectAdjacentSibling = (direction: "previous" | "next") => {+ const selectedInstancePaths = getAllSelectedInstancePaths();+ if (selectedInstancePaths.length === 0) {+ return;+ }+ const siblingSelection = getSiblingSelection(selectedInstancePaths);+ if (siblingSelection === undefined) {+ return;+ }+ const { parentSelector, selectedIndexes, siblingIds } = siblingSelection;+ const nextIndex =+ direction === "previous"+ ? Math.min(...selectedIndexes) - 1+ : Math.max(...selectedIndexes) + 1;+ const nextSiblingId = siblingIds[nextIndex];+ if (nextSiblingId === undefined) {+ return;+ }+ const selectedSiblingIds = new Set(+ selectedInstancePaths.map(({ instancePath }) => instancePath[0].instance.id)+ );+ selectedSiblingIds.add(nextSiblingId);+ selectInstances(+ siblingIds+ .filter((instanceId) => selectedSiblingIds.has(instanceId))+ .map((instanceId) => [instanceId, ...parentSelector])+ );+};++const selectSiblingInstances = () => {+ const selectedInstancePaths = getAllSelectedInstancePaths();+ if (selectedInstancePaths.length === 0) {+ return;+ }+ const siblingSelection = getSiblingSelection(selectedInstancePaths);+ if (siblingSelection === undefined) {+ return;+ }+ const { parentSelector, siblingIds } = siblingSelection;+ selectInstances(+ siblingIds.map((instanceId) => [instanceId, ...parentSelector])+ );+};++const reportSkippedSelectedInstances = (+ operation: "duplicated" | "deleted"+) => {+ builderApi.toast.info(`Some selected instances could not be ${operation}.`);+};++const deleteSelectedInstances = () => {+ if ($isPreviewMode.get()) {+ return false;+ }+ const selectedInstancePaths = getAllSelectedInstancePaths();+ if (selectedInstancePaths.length < 2) {+ return false;+ }+ const instances = $instances.get();+ const isContentMode = $isContentMode.get();+ const actionableInstancePaths = selectedInstancePaths.filter(+ ({ instancePath, instanceSelector }) =>+ isComponentDetachable(instancePath[0].instance.component) &&+ (isContentMode === false ||+ canDeleteInstanceInContentMode({ instanceSelector, instances }))+ );+ if (actionableInstancePaths.length === 0) {+ return true;+ }+ if (actionableInstancePaths.length < selectedInstancePaths.length) {+ reportSkippedSelectedInstances("deleted");+ }++ updateInstanceData((data) => {+ for (const { instancePath } of sortInstancePathsForChildMutation(+ actionableInstancePaths+ )) {+ deleteInstanceMutable(data, instancePath);+ }+ clearInstanceSelection();+ });+ return true;+};++const duplicateSelectedInstances = (project: Project) => {+ const selectedInstancePaths = getAllSelectedInstancePaths();+ if (selectedInstancePaths.length < 2) {+ return false;+ }+ const actionableInstancePaths = selectedInstancePaths.filter(+ ({ instancePath }) =>+ isComponentDetachable(instancePath[0].instance.component)+ );+ if (actionableInstancePaths.length === 0) {+ return true;+ }+ if (actionableInstancePaths.length < selectedInstancePaths.length) {+ reportSkippedSelectedInstances("duplicated");+ }+ const newInstanceSelectors = new Map<number, InstanceSelector>();++ updateWebstudioData((data) => {+ for (const { index, instancePath } of sortInstancePathsForChildMutation(+ actionableInstancePaths+ )) {+ const normalizedInstancePath = normalizeLegacySlotInstancePathMutable(+ data.instances,+ instancePath+ );+ const [selectedItem, parentItem] = normalizedInstancePath;+ if (parentItem === undefined) {+ continue;+ }+ const fragment = extractWebstudioFragment(data, selectedItem.instance.id);+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment,+ availableVariables: findAvailableVariables({+ ...data,+ startingInstanceId: parentItem.instanceSelector[0],+ }),+ projectId: project.id,+ });+ const newRootInstanceId = newInstanceIds.get(selectedItem.instance.id);+ if (newRootInstanceId === undefined) {+ continue;+ }++ if (+ isAutoGridPlacement({+ styles: data.styles,+ styleSources: data.styleSources,+ styleSourceSelections: data.styleSourceSelections,+ instanceId: selectedItem.instance.id,+ })+ ) {+ resetGridChildPlacement({+ styles: data.styles,+ styleSources: data.styleSources,+ styleSourceSelections: data.styleSourceSelections,+ instanceId: newRootInstanceId,+ });+ }++ const parentInstance = data.instances.get(parentItem.instance.id);+ if (parentInstance === undefined) {+ continue;+ }+ const indexWithinChildren = getIdChildIndex(+ parentInstance.children,+ selectedItem.instance.id+ );+ if (indexWithinChildren === -1) {+ continue;+ }+ parentInstance.children.splice(indexWithinChildren + 1, 0, {+ type: "id",+ value: newRootInstanceId,+ });+ newInstanceSelectors.set(index, [+ newRootInstanceId,+ ...parentItem.instanceSelector,+ ]);+ }+ });++ const sortedNewInstanceSelectors = [...newInstanceSelectors]+ .sort(([leftIndex], [rightIndex]) => leftIndex - rightIndex)+ .map(([, instanceSelector]) => instanceSelector);+ if (sortedNewInstanceSelectors.length > 0) {+ selectInstances(sortedNewInstanceSelectors);+ }+ return true;+};+const getOutdentMoveTarget = (instancePath: NonNullable<ReturnType<typeof $selectedInstancePath.get>>,positionRelativeToParent: "before" | "after"@@ -497,6 +778,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({category: "Style panel",defaultHotkeys: ["meta+enter", "ctrl+enter"],handler: () => {+ if (hasMultiInstanceSelection()) {+ return;+ }if ($isDesignMode.get() === false) {builderApi.toast.info("Style panel is only available in design mode."@@ -551,6 +835,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({category: "Panels",defaultHotkeys: ["d"],handler: () => {+ if (hasMultiInstanceSelection()) {+ return;+ }$activeInspectorPanel.set("settings");},disableOnInputLikeControls: true,@@ -566,7 +853,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({makeBreakpointCommand("selectBreakpoint9", 9),{name: "copy",- description: "Copy selected page or instance",+ description: "Copy selected page or instance(s)",category: "Navigator",handler: () => {if (copyPageActionTarget()) {@@ -577,13 +864,14 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({},{name: "paste",- description: "Paste copied instance",+ description: "Paste copied instance(s)",category: "Navigator",handler: () => {if (- guardDesignModeCommand({+ guardDesignOrContentModeCommand({+ isContentMode: $isContentMode.get(),isDesignMode: $isDesignMode.get(),- message: "Pasting is only allowed in design mode.",+ message: "Pasting is only allowed in design or content mode.",})) {void emitPaste();@@ -592,7 +880,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({},{name: "cut",- description: "Cut selected instance",+ description: "Cut selected instance(s)",category: "Navigator",handler: () => {if (@@ -618,6 +906,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({) {return;}+ if (hasMultiInstanceSelection()) {+ return;+ }const instancePath = $selectedInstancePath.get();if (instancePath?.[0]) {toggleInstanceShow(instancePath[0].instance.id);@@ -660,16 +951,43 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({disableOnInputLikeControls: true,handler: () => moveSelectedInstance("intoPreviousSibling"),},+ {+ name: "selectPreviousSibling",+ hidden: true,+ category: "Navigator",+ defaultHotkeys: ["shift+arrowup"],+ disableOnInputLikeControls: true,+ handler: () => selectAdjacentSibling("previous"),+ },+ {+ name: "selectNextSibling",+ hidden: true,+ category: "Navigator",+ defaultHotkeys: ["shift+arrowdown"],+ disableOnInputLikeControls: true,+ handler: () => selectAdjacentSibling("next"),+ },+ {+ name: "selectSiblingInstances",+ hidden: true,+ category: "Navigator",+ defaultHotkeys: ["meta+a", "ctrl+a"],+ disableOnInputLikeControls: true,+ handler: selectSiblingInstances,+ },{name: "deleteInstanceBuilder",label: "Delete",- description: "Delete selected page or instance",+ description: "Delete selected page or instance(s)",category: "Navigator",defaultHotkeys: ["backspace", "delete"],// See "deleteInstanceCanvas" for details on why the command is separated for the canvas and builder.disableHotkeyOutsideApp: true,disableOnInputLikeControls: true,handler: () => {+ if (deleteSelectedInstances()) {+ return;+ }if (requestSelectedPageItemDelete()) {return;}@@ -678,7 +996,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({},{name: "duplicateInstance",- description: "Duplicate selected page or instance",+ description: "Duplicate selected page or instance(s)",category: "Navigator",defaultHotkeys: ["meta+d", "ctrl+d"],handler: () => {@@ -694,6 +1012,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({) {return;}+ if (duplicateSelectedInstances(project)) {+ return;+ }if (duplicatePageActionTarget()) {return;}@@ -784,6 +1105,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({) {return;}+ if (hasMultiInstanceSelection()) {+ return;+ }const instancePath = $selectedInstancePath.get();if (instancePath === undefined) {return;@@ -808,6 +1132,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({) {return;}+ if (hasMultiInstanceSelection()) {+ return;+ }showWrapComponentsList();},},@@ -823,6 +1150,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({message: "Unwrapping is only allowed in design mode.",})) {+ if (hasMultiInstanceSelection()) {+ return;+ }unwrapInstance();}},@@ -842,6 +1172,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({) {return;}+ if (hasMultiInstanceSelection()) {+ return;+ }showConvertComponentsList();},},diff --git a/apps/builder/app/builder/shared/instance-context-menu.test.ts b/apps/builder/app/builder/shared/instance-context-menu.test.tsindex 3c888e6205..be317a72c7 100644--- a/apps/builder/app/builder/shared/instance-context-menu.test.ts+++ b/apps/builder/app/builder/shared/instance-context-menu.test.ts@@ -133,6 +133,148 @@ describe("getMenuPermissions", () => {});});+ test("keeps multi-selection actions and disables single-instance-only actions", () => {+ const bodyPath: InstancePath = [+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];+ const childPath: InstancePath = [+ {+ instance: createInstance("child"),+ instanceSelector: ["child", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];+ const siblingPath: InstancePath = [+ {+ instance: createInstance("sibling"),+ instanceSelector: ["sibling", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];++ expect(+ getMenuPermissions({+ instancePath: undefined,+ selectedInstancePaths: [childPath, siblingPath],+ isContentMode: false,+ isDesignMode: true,+ instances: emptyInstances,+ })+ ).toMatchObject({+ canCopy: true,+ canPaste: true,+ canCut: true,+ canDuplicate: true,+ canDelete: true,+ canHide: false,+ canRename: false,+ canWrap: false,+ canUnwrap: false,+ canConvert: false,+ canAddToken: false,+ canOpenSettings: false,+ });++ expect(+ getMenuPermissions({+ instancePath: undefined,+ selectedInstancePaths: [bodyPath, childPath],+ isContentMode: false,+ isDesignMode: true,+ instances: emptyInstances,+ })+ ).toMatchObject({+ canCopy: true,+ canCut: true,+ canDuplicate: true,+ canDelete: true,+ });+ });++ test("disables multi-selection actions when no selected path is actionable", () => {+ const rootPath: InstancePath = [+ {+ instance: createInstance(ROOT_INSTANCE_ID),+ instanceSelector: [ROOT_INSTANCE_ID],+ },+ ];+ const bodyPath: InstancePath = [+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];++ expect(+ getMenuPermissions({+ instancePath: undefined,+ selectedInstancePaths: [rootPath, bodyPath],+ isContentMode: false,+ isDesignMode: true,+ instances: emptyInstances,+ })+ ).toMatchObject({+ canCopy: false,+ canCut: false,+ canDuplicate: false,+ canDelete: false,+ canOpenSettings: false,+ });++ const templatePath: InstancePath = [+ {+ instance: createInstance("template", blockTemplateComponent),+ instanceSelector: ["template", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];++ expect(+ getMenuPermissions({+ instancePath: undefined,+ selectedInstancePaths: [templatePath],+ isContentMode: false,+ isDesignMode: true,+ instances: emptyInstances,+ })+ ).toMatchObject({+ canCopy: false,+ canCut: false,+ canDuplicate: false,+ canDelete: false,+ });+ });++ test("keeps single-instance actions disabled when part of a multi-selection cannot resolve", () => {+ const childPath: InstancePath = [+ {+ instance: createInstance("child"),+ instanceSelector: ["child", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];++ expect(+ getMenuPermissions({+ instancePath: undefined,+ selectedInstanceCount: 2,+ selectedInstancePaths: [childPath],+ isContentMode: false,+ isDesignMode: true,+ instances: emptyInstances,+ })+ ).toMatchObject({+ canCopy: true,+ canCut: true,+ canDuplicate: true,+ canDelete: true,+ canHide: false,+ canRename: false,+ canWrap: false,+ canUnwrap: false,+ canConvert: false,+ canAddToken: false,+ canOpenSettings: false,+ });+ });+test("disables design mutations outside of design and content modes", () => {const instancePath: InstancePath = [{@@ -238,8 +380,8 @@ describe("getMenuPermissions", () => {});expect(permissions).toMatchObject({- canCopy: false,- canPaste: false,+ canCopy: true,+ canPaste: true,canCut: false,canDuplicate: false,canHide: false,@@ -276,4 +418,67 @@ describe("getMenuPermissions", () => {}).canDelete).toBe(false);});++ test("content mode keeps multi-copy available but disables single-instance and mutation actions", () => {+ const instances: Instances = new Map([+ [+ "body",+ createInstance("body", "Body", [{ type: "id", value: "block" }]),+ ],+ [+ "block",+ createInstance("block", blockComponent, [+ { type: "id", value: "child" },+ { type: "id", value: "sibling" },+ ]),+ ],+ ["child", createInstance("child")],+ ["sibling", createInstance("sibling")],+ ]);+ const childPath: InstancePath = [+ {+ instance: createInstance("child"),+ instanceSelector: ["child", "block", "body"],+ },+ {+ instance: createInstance("block", blockComponent),+ instanceSelector: ["block", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];+ const siblingPath: InstancePath = [+ {+ instance: createInstance("sibling"),+ instanceSelector: ["sibling", "block", "body"],+ },+ {+ instance: createInstance("block", blockComponent),+ instanceSelector: ["block", "body"],+ },+ { instance: createInstance("body"), instanceSelector: ["body"] },+ ];++ expect(+ getMenuPermissions({+ instancePath: undefined,+ selectedInstancePaths: [childPath, siblingPath],+ isContentMode: true,+ isDesignMode: false,+ instances,+ })+ ).toMatchObject({+ canCopy: true,+ canPaste: true,+ canCut: false,+ canDuplicate: false,+ canHide: false,+ canRename: false,+ canWrap: false,+ canUnwrap: false,+ canConvert: false,+ canAddToken: false,+ canOpenSettings: false,+ canDelete: false,+ });+ });});diff --git a/apps/builder/app/builder/shared/instance-context-menu.tsx b/apps/builder/app/builder/shared/instance-context-menu.tsxindex 43e9c268fa..f72420cdec 100644--- a/apps/builder/app/builder/shared/instance-context-menu.tsx+++ b/apps/builder/app/builder/shared/instance-context-menu.tsx@@ -15,17 +15,23 @@ import {import { showAttribute } from "@webstudio-is/react-sdk";import { emitCommand } from "./commands";import {+ $allSelectedInstanceSelectors,$selectedInstancePath,$selectedPage,$isContentMode,$isDesignMode,+ $propValuesByInstanceSelector,+ getInstancePath,getInstanceKey,+ type InstancePath,} from "~/shared/nano-states";import { canDeleteInstanceInContentMode } from "~/shared/instance-utils/data";-import { $propValuesByInstanceSelector } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";-import { ROOT_INSTANCE_ID, type Instances } from "@webstudio-is/sdk";-import type { InstancePath } from "~/shared/nano-states";+import {+ isComponentDetachable,+ ROOT_INSTANCE_ID,+ type Instances,+} from "@webstudio-is/sdk";const canDeleteInContentMode = ({instancePath,@@ -43,26 +49,43 @@ const canDeleteInContentMode = ({const getMenuPermissions = ({instancePath,+ selectedInstancePaths = instancePath === undefined ? [] : [instancePath],+ selectedInstanceCount = selectedInstancePaths.length,isContentMode,isDesignMode,instances,}: {instancePath: InstancePath | undefined;+ selectedInstancePaths?: InstancePath[];+ selectedInstanceCount?: number;isContentMode: boolean;isDesignMode: boolean;instances: Instances;}) => {const instanceId = instancePath?.[0]?.instance.id;const rootInstanceId = $selectedPage.get()?.rootInstanceId;+ const isMultiSelection = selectedInstanceCount > 1;+ const canUseSingleSelectionActions = isMultiSelection === false;const isRoot = instanceId === ROOT_INSTANCE_ID;const isBody = instanceId === rootInstanceId;const isRootOrBody = isRoot || isBody;+ const hasActionableSelection = selectedInstancePaths.some((path) => {+ const selectedInstance = path[0]?.instance;+ const selectedInstanceId = selectedInstance?.id;+ return (+ selectedInstanceId !== undefined &&+ selectedInstanceId !== ROOT_INSTANCE_ID &&+ selectedInstanceId !== rootInstanceId &&+ selectedInstance !== undefined &&+ isComponentDetachable(selectedInstance.component)+ );+ });if (isContentMode) {return {- canCopy: false,- canPaste: false,+ canCopy: hasActionableSelection,+ canPaste: hasActionableSelection,canCut: false,canDuplicate: false,canHide: false,@@ -71,7 +94,7 @@ const getMenuPermissions = ({canUnwrap: false,canConvert: false,canAddToken: false,- canOpenSettings: true,+ canOpenSettings: canUseSingleSelectionActions,canDelete: canDeleteInContentMode({ instancePath, instances }),};}@@ -81,23 +104,25 @@ const getMenuPermissions = ({canMutateDesign && instancePath ? canUnwrapInstance(instancePath) : false;return {- canCopy: canMutateDesign && !isRootOrBody,+ canCopy: canMutateDesign && hasActionableSelection,canPaste: canMutateDesign && !isRoot,- canCut: canMutateDesign && !isRootOrBody,- canDuplicate: canMutateDesign && !isRootOrBody,- canHide: canMutateDesign && !isRoot,- canRename: canMutateDesign && !isRoot,- canWrap: canMutateDesign && !isRootOrBody,- canUnwrap,- canConvert: canMutateDesign && !isRootOrBody,- canAddToken: canMutateDesign,- canOpenSettings: true,- canDelete: canMutateDesign && !isRootOrBody,+ canCut: canMutateDesign && hasActionableSelection,+ canDuplicate: canMutateDesign && hasActionableSelection,+ canHide: canMutateDesign && !isRoot && canUseSingleSelectionActions,+ canRename: canMutateDesign && !isRoot && canUseSingleSelectionActions,+ canWrap: canMutateDesign && !isRootOrBody && canUseSingleSelectionActions,+ canUnwrap: canUnwrap && canUseSingleSelectionActions,+ canConvert:+ canMutateDesign && !isRootOrBody && canUseSingleSelectionActions,+ canAddToken: canMutateDesign && canUseSingleSelectionActions,+ canOpenSettings: canUseSingleSelectionActions,+ canDelete: canMutateDesign && hasActionableSelection,};};export const MenuItems = () => {const instancePath = useStore($selectedInstancePath);+ const selectedInstanceSelectors = useStore($allSelectedInstanceSelectors);const instances = useStore($instances);const propValues = useStore($propValuesByInstanceSelector);const isContentMode = useStore($isContentMode);@@ -114,10 +139,16 @@ export const MenuItems = () => {const permissions = getMenuPermissions({instancePath,+ selectedInstanceCount: selectedInstanceSelectors.length,+ selectedInstancePaths: selectedInstanceSelectors+ .map((instanceSelector) => getInstancePath(instanceSelector, instances))+ .filter((path): path is InstancePath => path !== undefined),isContentMode,isDesignMode,instances,});+ const shortcutColor = (isEnabled: boolean): "subtle" | "moreSubtle" =>+ isEnabled ? "subtle" : "moreSubtle";return (<Box css={{ width: theme.spacing[28] }}>@@ -129,7 +160,10 @@ export const MenuItems = () => {>Copy<ContextMenuItemRightSlot>- <Kbd value={["meta", "c"]} />+ <Kbd+ value={["meta", "c"]}+ color={shortcutColor(permissions.canCopy)}+ /></ContextMenuItemRightSlot></ContextMenuItem><ContextMenuItem@@ -140,7 +174,10 @@ export const MenuItems = () => {>Paste<ContextMenuItemRightSlot>- <Kbd value={["meta", "v"]} />+ <Kbd+ value={["meta", "v"]}+ color={shortcutColor(permissions.canPaste)}+ /></ContextMenuItemRightSlot></ContextMenuItem><ContextMenuItem@@ -151,7 +188,10 @@ export const MenuItems = () => {>Cut<ContextMenuItemRightSlot>- <Kbd value={["meta", "x"]} />+ <Kbd+ value={["meta", "x"]}+ color={shortcutColor(permissions.canCut)}+ /></ContextMenuItemRightSlot></ContextMenuItem><ContextMenuItem@@ -162,7 +202,10 @@ export const MenuItems = () => {>Duplicate<ContextMenuItemRightSlot>- <Kbd value={["meta", "d"]} />+ <Kbd+ value={["meta", "d"]}+ color={shortcutColor(permissions.canDuplicate)}+ /></ContextMenuItemRightSlot></ContextMenuItem><ContextMenuSeparator />@@ -182,7 +225,10 @@ export const MenuItems = () => {>Rename<ContextMenuItemRightSlot>- <Kbd value={["meta", "e"]} />+ <Kbd+ value={["meta", "e"]}+ color={shortcutColor(permissions.canRename)}+ /></ContextMenuItemRightSlot></ContextMenuItem><ContextMenuItem@@ -193,7 +239,10 @@ export const MenuItems = () => {>Wrap<ContextMenuItemRightSlot>- <Kbd value={["meta", "alt", "g"]} />+ <Kbd+ value={["meta", "alt", "g"]}+ color={shortcutColor(permissions.canWrap)}+ /></ContextMenuItemRightSlot></ContextMenuItem><ContextMenuItem@@ -204,7 +253,10 @@ export const MenuItems = () => {>Unwrap<ContextMenuItemRightSlot>- <Kbd value={["meta", "shift", "g"]} />+ <Kbd+ value={["meta", "shift", "g"]}+ color={shortcutColor(permissions.canUnwrap)}+ /></ContextMenuItemRightSlot></ContextMenuItem><ContextMenuItem@@ -216,30 +268,34 @@ export const MenuItems = () => {Convert</ContextMenuItem><ContextMenuSeparator />- {permissions.canAddToken && (- <ContextMenuItem- onSelect={() => {- emitCommand("focusStyleSources");- }}- >- Add token- <ContextMenuItemRightSlot>- <Kbd value={["meta", "enter"]} />- </ContextMenuItemRightSlot>- </ContextMenuItem>- )}- {permissions.canOpenSettings && (- <ContextMenuItem- onSelect={() => {- emitCommand("openSettingsPanel");- }}- >- Open settings- <ContextMenuItemRightSlot>- <Kbd value={["d"]} />- </ContextMenuItemRightSlot>- </ContextMenuItem>- )}+ <ContextMenuItem+ disabled={!permissions.canAddToken}+ onSelect={() => {+ emitCommand("focusStyleSources");+ }}+ >+ Add token+ <ContextMenuItemRightSlot>+ <Kbd+ value={["meta", "enter"]}+ color={shortcutColor(permissions.canAddToken)}+ />+ </ContextMenuItemRightSlot>+ </ContextMenuItem>+ <ContextMenuItem+ disabled={!permissions.canOpenSettings}+ onSelect={() => {+ emitCommand("openSettingsPanel");+ }}+ >+ Open settings+ <ContextMenuItemRightSlot>+ <Kbd+ value={["d"]}+ color={shortcutColor(permissions.canOpenSettings)}+ />+ </ContextMenuItemRightSlot>+ </ContextMenuItem><ContextMenuSeparator /><ContextMenuItemdisabled={!permissions.canDelete}@@ -250,7 +306,10 @@ export const MenuItems = () => {>Delete<ContextMenuItemRightSlot>- <Kbd value={["delete"]} />+ <Kbd+ value={["delete"]}+ color={shortcutColor(permissions.canDelete)}+ /></ContextMenuItemRightSlot></ContextMenuItem></Box>@@ -260,17 +319,7 @@ export const MenuItems = () => {export const InstanceContextMenu = ({ children }: { children: ReactNode }) => {return (<ContextMenu>- <ContextMenuTrigger- asChild- onPointerDown={(event) => {- if (!(event.target instanceof HTMLElement)) {- return;- }- event.target.closest<HTMLElement>("[data-tree-button]")?.click();- }}- >- {children}- </ContextMenuTrigger>+ <ContextMenuTrigger asChild>{children}</ContextMenuTrigger><ContextMenuContent><MenuItems /></ContextMenuContent>diff --git a/apps/builder/app/canvas/canvas.tsx b/apps/builder/app/canvas/canvas.tsxindex 0f4500ad86..7709f3ad7c 100644--- a/apps/builder/app/canvas/canvas.tsx+++ b/apps/builder/app/canvas/canvas.tsx@@ -62,7 +62,7 @@ import {} from "~/shared/copy-paste/copy-paste";import { inflateInstance, subscribeInflator } from "./inflator";import { useWindowResizeDebounced } from "~/shared/dom-hooks";-import { subscribeInstanceSelection } from "./instance-selection";+import { subscribeInstanceSelection } from "./instance-selection-events";import { subscribeInstanceHovering } from "./instance-hovering";import { useHashLinkSync } from "~/shared/pages";import { useMount } from "~/shared/hook-utils/use-mount";@@ -71,7 +71,7 @@ import { subscribeCommands } from "~/canvas/shared/commands";import { updateCollaborativeInstanceRect } from "./collaborative-instance";import { initCanvasApi } from "~/shared/canvas-api";import { subscribeFontLoadingDone } from "./shared/font-weight-support";-import { subscribeSelected } from "./instance-selected";+import { subscribeSelected } from "./selected-instance-effects";import { subscribeGridGuidesOnSelected } from "./grid-guide-utils";import { subscribeScrollNewInstanceIntoView } from "./shared/scroll-new-instance-into-view";import { $selectedPage } from "~/shared/nano-states";diff --git a/apps/builder/app/canvas/instance-selection-events.test.ts b/apps/builder/app/canvas/instance-selection-events.test.tsnew file mode 100644index 0000000000..217fde97cd--- /dev/null+++ b/apps/builder/app/canvas/instance-selection-events.test.ts@@ -0,0 +1,127 @@+import { afterEach, beforeEach, describe, expect, test } from "vitest";+import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";+import {+ $allSelectedInstanceSelectors,+ selectInstances,+} from "~/shared/nano-states";+import { subscribeInstanceSelection } from "./instance-selection-events";+import { $ephemeralStyles } from "./stores";++const createElement = (selector: string) => {+ const element = document.createElement("div");+ const [id] = selector.split(",");+ element.setAttribute(idAttribute, id);+ element.setAttribute(selectorIdAttribute, selector);+ document.body.appendChild(element);+ return element;+};++let abortController: AbortController;++beforeEach(() => {+ document.body.innerHTML = "";+ selectInstances([]);+ $ephemeralStyles.set([]);+ abortController = new AbortController();+ subscribeInstanceSelection({ signal: abortController.signal });+});++afterEach(() => {+ abortController.abort();+ $ephemeralStyles.set([]);+});++describe("canvas instance selection", () => {+ test("plain click selects one instance and replaces multi-selection", () => {+ const box = createElement("box,body");+ const heading = createElement("heading,body");++ box.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ heading.dispatchEvent(+ new MouseEvent("click", { bubbles: true, metaKey: true })+ );+ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ]);++ heading.dispatchEvent(new MouseEvent("click", { bubbles: true }));++ expect($allSelectedInstanceSelectors.get()).toEqual([["heading", "body"]]);+ });++ test("cmd-click toggles rendered instances without clearing existing selection", () => {+ const box = createElement("box,body");+ const heading = createElement("heading,body");++ box.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ heading.dispatchEvent(+ new MouseEvent("click", { bubbles: true, metaKey: true })+ );+ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ]);++ box.dispatchEvent(+ new MouseEvent("click", { bubbles: true, metaKey: true })+ );++ expect($allSelectedInstanceSelectors.get()).toEqual([["heading", "body"]]);+ });++ test("shift-click selects a rendered DOM-order range from the canvas anchor", () => {+ const box = createElement("box,body");+ createElement("heading,body");+ const footer = createElement("footer,body");++ box.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ footer.dispatchEvent(+ new MouseEvent("click", { bubbles: true, shiftKey: true })+ );++ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ["footer", "body"],+ ]);+ });++ test("does not reuse range anchor after subscription is recreated", () => {+ const box = createElement("box,body");+ createElement("heading,body");+ const footer = createElement("footer,body");++ box.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ abortController.abort();+ selectInstances([]);+ abortController = new AbortController();+ subscribeInstanceSelection({ signal: abortController.signal });++ footer.dispatchEvent(+ new MouseEvent("click", { bubbles: true, shiftKey: true })+ );++ expect($allSelectedInstanceSelectors.get()).toEqual([["footer", "body"]]);+ });++ test("clears stale ephemeral styles when canvas click creates multi-selection", () => {+ const box = createElement("box,body");+ const heading = createElement("heading,body");+ $ephemeralStyles.set([+ {+ breakpointId: "base",+ styleSourceId: "style-source",+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ]);++ box.dispatchEvent(new MouseEvent("click", { bubbles: true }));+ heading.dispatchEvent(+ new MouseEvent("click", { bubbles: true, metaKey: true })+ );++ expect($ephemeralStyles.get()).toEqual([]);+ });+});diff --git a/apps/builder/app/canvas/instance-selection.ts b/apps/builder/app/canvas/instance-selection-events.tssimilarity index 61%rename from apps/builder/app/canvas/instance-selection.tsrename to apps/builder/app/canvas/instance-selection-events.tsindex a764243f27..c557cd3ea2 100644--- a/apps/builder/app/canvas/instance-selection.ts+++ b/apps/builder/app/canvas/instance-selection-events.ts@@ -1,19 +1,32 @@import { getInstanceSelectorFromElement } from "~/shared/dom-utils";+import { selectorIdAttribute } from "@webstudio-is/react-sdk";import {+ $allSelectedInstanceSelectors,$hoveredInstanceOutline,$hoveredInstanceSelector,$isContentMode,$propsIndex,$registeredComponentMetas,+ $selectedInstanceSelector,+ $textEditingInstanceSelector,+ selectInstance,+ selectInstances,} from "~/shared/nano-states";+import { getInstanceSelectionUpdate } from "~/shared/instance-utils/selection";import { $props } from "~/shared/sync/data-stores";-import { $textEditingInstanceSelector } from "~/shared/nano-states";import { $instances } from "~/shared/sync/data-stores";+import { $ephemeralStyles } from "~/canvas/stores";import { emitCommand } from "./shared/commands";import { shallowEqual } from "shallow-equal";-import { $selectedInstanceSelector } from "~/shared/nano-states";-import { selectInstance } from "~/shared/nano-states";import { findClosestRichText } from "~/shared/content-model";+import {+ areInstanceSelectorsEqual,+ type InstanceSelector,+} from "~/shared/instance-utils/tree";++type SelectionAnchor = {+ current: undefined | InstanceSelector;+};const isElementBeingEdited = (element: Element) => {if (element.closest("[contenteditable=true]")) {@@ -23,7 +36,30 @@ const isElementBeingEdited = (element: Element) => {return false;};-const handleSelect = (event: MouseEvent) => {+const getRenderedInstanceSelectors = () => {+ const selectors: InstanceSelector[] = [];+ for (const element of document.querySelectorAll(`[${selectorIdAttribute}]`)) {+ const selectorId = element.getAttribute(selectorIdAttribute);+ const selector = selectorId?.split(",");+ if (selector === undefined || selector.length === 0) {+ continue;+ }+ if (+ selectors.some((selectedSelector) =>+ areInstanceSelectorsEqual(selectedSelector, selector)+ )+ ) {+ continue;+ }+ selectors.push(selector);+ }+ return selectors;+};++const handleSelect = (+ event: MouseEvent,+ rangeAnchorSelector: SelectionAnchor+) => {const element = event.target;if (!(element instanceof Element)) {@@ -45,13 +81,34 @@ const handleSelect = (event: MouseEvent) => {$textEditingInstanceSelector.set(undefined);}+ if (event.metaKey || event.ctrlKey || event.shiftKey) {+ const nextSelection = getInstanceSelectionUpdate({+ selectedSelectors: $allSelectedInstanceSelectors.get(),+ clickedSelector: instanceSelector,+ orderedSelectors: getRenderedInstanceSelectors(),+ anchorSelector: rangeAnchorSelector.current,+ isToggle: event.metaKey || event.ctrlKey,+ isRange: event.shiftKey,+ });+ selectInstances(nextSelection.selectedSelectors);+ if (nextSelection.selectedSelectors.length !== 1) {+ $ephemeralStyles.set([]);+ }+ rangeAnchorSelector.current = nextSelection.anchorSelector;+ return;+ }+// Prevent unnecessary updates (2 clicks are registered before a double click)if (!shallowEqual(instanceSelector, $selectedInstanceSelector.get())) {selectInstance(instanceSelector);}+ rangeAnchorSelector.current = instanceSelector;};-const handleEdit = (event: MouseEvent) => {+const handleEdit = (+ event: MouseEvent,+ rangeAnchorSelector: SelectionAnchor+) => {const element = event.target;if (!(element instanceof Element)) {@@ -106,6 +163,7 @@ const handleEdit = (event: MouseEvent) => {if (!shallowEqual(instanceSelector, $selectedInstanceSelector.get())) {selectInstance(instanceSelector);}+ rangeAnchorSelector.current = instanceSelector;return;}@@ -116,6 +174,7 @@ const handleEdit = (event: MouseEvent) => {) {selectInstance(editableInstanceSelector);}+ rangeAnchorSelector.current = editableInstanceSelector;$hoveredInstanceOutline.set(undefined);$hoveredInstanceSelector.set(undefined);@@ -133,17 +192,19 @@ export const subscribeInstanceSelection = ({}: {signal: AbortSignal;}) => {+ const rangeAnchorSelector: SelectionAnchor = { current: undefined };+addEventListener("click",(event) => {emitCommand("clickCanvas");if ($isContentMode.get()) {- handleEdit(event);+ handleEdit(event, rangeAnchorSelector);return;}- handleSelect(event);+ handleSelect(event, rangeAnchorSelector);},{ passive: true, signal });@@ -151,7 +212,7 @@ export const subscribeInstanceSelection = ({addEventListener("dblclick",(event) => {- handleEdit(event);+ handleEdit(event, rangeAnchorSelector);},{ passive: true, signal });diff --git a/apps/builder/app/canvas/selected-instance-effects.test.ts b/apps/builder/app/canvas/selected-instance-effects.test.tsnew file mode 100644index 0000000000..3100c77257--- /dev/null+++ b/apps/builder/app/canvas/selected-instance-effects.test.ts@@ -0,0 +1,260 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { idAttribute, selectorIdAttribute } from "@webstudio-is/react-sdk";+import {+ $allSelectedInstanceSelectors,+ $selectedInstanceOutline,+ $selectedInstanceOutlines,+ selectInstances,+} from "~/shared/nano-states";+import { $instances, $styleSourceSelections } from "~/shared/sync/data-stores";+import { subscribeSelected } from "./selected-instance-effects";+import { subscribeInstanceSelection } from "./instance-selection-events";++const createInstance = (id: string) => ({+ type: "instance" as const,+ id,+ component: "Box",+ children: [],+});++const createElement = ({+ selector,+ rect,+ parent = document.body,+}: {+ selector: string;+ rect: { left: number; top: number; width: number; height: number };+ parent?: HTMLElement;+}) => {+ const element = document.createElement("div");+ const [id] = selector.split(",");+ element.setAttribute(idAttribute, id);+ element.setAttribute(selectorIdAttribute, selector);+ element.getBoundingClientRect = () =>+ new TestDOMRect(rect.left, rect.top, rect.width, rect.height) as DOMRect;+ parent.appendChild(element);+ return element;+};++class ResizeObserver {+ observe() {}+ disconnect() {}+}++class TestDOMRect {+ left: number;+ top: number;+ width: number;+ height: number;+ x: number;+ y: number;+ right: number;+ bottom: number;++ constructor(x = 0, y = 0, width = 0, height = 0) {+ this.left = x;+ this.top = y;+ this.width = width;+ this.height = height;+ this.x = x;+ this.y = y;+ this.right = x + width;+ this.bottom = y + height;+ }++ static fromRect(rect: Partial<globalThis.DOMRectReadOnly>) {+ return new TestDOMRect(rect.x, rect.y, rect.width, rect.height);+ }++ toJSON() {+ return this;+ }+}++class TestDOMMatrix {+ inverse() {+ return this;+ }+}++class TestDOMPoint {+ x: number;+ y: number;++ constructor(x = 0, y = 0) {+ this.x = x;+ this.y = y;+ }++ matrixTransform() {+ return this;+ }+}++let unsubscribe = () => {};+let abortController: AbortController;++beforeEach(() => {+ vi.stubGlobal("ResizeObserver", ResizeObserver);+ vi.stubGlobal("DOMRect", TestDOMRect);+ vi.stubGlobal("DOMMatrix", TestDOMMatrix);+ vi.stubGlobal("DOMPoint", TestDOMPoint);+ vi.stubGlobal("requestAnimationFrame", () => 0);+ $instances.set(+ new Map([+ ["box", createInstance("box")],+ ["heading", createInstance("heading")],+ ])+ );+ $styleSourceSelections.set(new Map());+ $allSelectedInstanceSelectors.set([]);+ $selectedInstanceOutline.set(undefined);+ $selectedInstanceOutlines.set([]);+ document.body.innerHTML = "";+ abortController = new AbortController();+});++afterEach(() => {+ abortController.abort();+ unsubscribe();+ unsubscribe = () => {};+ vi.unstubAllGlobals();+ document.body.innerHTML = "";+ $instances.set(new Map());+ $allSelectedInstanceSelectors.set([]);+ $selectedInstanceOutline.set(undefined);+ $selectedInstanceOutlines.set([]);+});++describe("subscribeSelected", () => {+ test("creates both outline stores for one selected instance", () => {+ createElement({+ selector: "box,body",+ rect: { left: 10, top: 20, width: 100, height: 50 },+ });+ unsubscribe = subscribeSelected((callback) => callback());++ selectInstances([["box", "body"]]);++ expect($selectedInstanceOutlines.get()).toEqual([+ expect.objectContaining({+ selector: ["box", "body"],+ instanceId: "box",+ }),+ ]);+ expect(Object.keys($selectedInstanceOutlines.get()[0].rect)).toEqual([+ "top",+ "left",+ "width",+ "height",+ ]);+ expect($selectedInstanceOutline.get()).toEqual(+ expect.objectContaining({+ instanceId: "box",+ })+ );+ });++ test("creates an outline for every selected instance without single outline", () => {+ createElement({+ selector: "box,body",+ rect: { left: 10, top: 20, width: 100, height: 50 },+ });+ createElement({+ selector: "heading,body",+ rect: { left: 20, top: 40, width: 140, height: 70 },+ });+ unsubscribe = subscribeSelected((callback) => callback());++ selectInstances([+ ["box", "body"],+ ["heading", "body"],+ ]);++ expect(+ $selectedInstanceOutlines.get().map((outline) => outline.selector)+ ).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ]);+ expect($selectedInstanceOutline.get()).toBeUndefined();+ });++ test("does not fall back to parent rect for zero-size multi-selected instances", () => {+ const parent = createElement({+ selector: "parent,body",+ rect: { left: 5, top: 10, width: 500, height: 300 },+ });+ createElement({+ selector: "box,parent,body",+ rect: { left: 0, top: 0, width: 0, height: 0 },+ parent,+ });+ createElement({+ selector: "heading,parent,body",+ rect: { left: 20, top: 40, width: 140, height: 70 },+ parent,+ });+ unsubscribe = subscribeSelected((callback) => callback());++ selectInstances([+ ["box", "parent", "body"],+ ["heading", "parent", "body"],+ ]);++ expect($selectedInstanceOutlines.get()[0]).toEqual(+ expect.objectContaining({+ selector: ["box", "parent", "body"],+ rect: expect.objectContaining({+ left: 0,+ top: 0,+ width: 0,+ height: 0,+ }),+ })+ );+ expect(+ $selectedInstanceOutlines+ .get()+ .some(+ (outline) => outline.rect.width === 500 && outline.rect.height === 300+ )+ ).toBe(false);+ });++ test("creates outlines when instances are selected by canvas clicks", () => {+ const box = createElement({+ selector: "box,body",+ rect: { left: 10, top: 20, width: 100, height: 50 },+ });+ const heading = createElement({+ selector: "heading,body",+ rect: { left: 20, top: 40, width: 140, height: 70 },+ });+ unsubscribe = subscribeSelected((callback) => callback());+ subscribeInstanceSelection({ signal: abortController.signal });++ box.dispatchEvent(new MouseEvent("click", { bubbles: true }));++ expect(+ $selectedInstanceOutlines.get().map((outline) => outline.selector)+ ).toEqual([["box", "body"]]);+ expect($selectedInstanceOutline.get()).toEqual(+ expect.objectContaining({+ instanceId: "box",+ })+ );++ heading.dispatchEvent(+ new MouseEvent("click", { bubbles: true, metaKey: true })+ );++ expect(+ $selectedInstanceOutlines.get().map((outline) => outline.selector)+ ).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ]);+ expect($selectedInstanceOutline.get()).toBeUndefined();+ });+});diff --git a/apps/builder/app/canvas/instance-selected.ts b/apps/builder/app/canvas/selected-instance-effects.tssimilarity index 75%rename from apps/builder/app/canvas/instance-selected.tsrename to apps/builder/app/canvas/selected-instance-effects.tsindex b2f5e6b0ab..137149e31d 100644--- a/apps/builder/app/canvas/instance-selected.ts+++ b/apps/builder/app/canvas/selected-instance-effects.ts@@ -12,6 +12,7 @@ import {$stylesIndex,$propValuesByInstanceSelectorWithMemoryProps,$selectedInstanceStates,+ $allSelectedInstanceSelectors,type UnitSizes,type PropertySizes,} from "~/shared/nano-states";@@ -24,21 +25,69 @@ import {hasDoNotTrackMutationRecord,} from "~/shared/dom-utils";import { subscribeScrollState } from "~/canvas/shared/scroll-state";-import { $selectedInstanceOutline } from "~/shared/nano-states";+import {+ $selectedInstanceOutline,+ $selectedInstanceOutlines,+} from "~/shared/nano-states";import { $instances, $styles } from "~/shared/sync/data-stores";import { inflateInstance } from "~/canvas/inflator";-import type { InstanceSelector } from "~/shared/instance-utils/tree";-import { $selectedInstanceSelector } from "~/shared/nano-states";--const setOutline = (instanceId: Instance["id"], elements: HTMLElement[]) => {- $selectedInstanceOutline.set({+import {+ areInstanceSelectorsEqual,+ type InstanceSelector,+} from "~/shared/instance-utils/tree";++const toRect = (rect: DOMRect) => ({+ top: rect.top,+ left: rect.left,+ width: rect.width,+ height: rect.height,+});++const setOutline = (+ selector: InstanceSelector,+ instanceId: Instance["id"],+ elements: HTMLElement[],+ syncSingleOutline: boolean+) => {+ const outline = {+ selector,instanceId,- rect: getAllElementsBoundingBox(elements),- });+ rect: toRect(+ getAllElementsBoundingBox(elements, {+ fallbackToParent: syncSingleOutline,+ })+ ),+ };+ const outlines = $selectedInstanceOutlines.get();+ const index = outlines.findIndex((item) =>+ areInstanceSelectorsEqual(item.selector, selector)+ );+ if (index === -1) {+ $selectedInstanceOutlines.set([...outlines, outline]);+ } else {+ const nextOutlines = [...outlines];+ nextOutlines[index] = outline;+ $selectedInstanceOutlines.set(nextOutlines);+ }+ if (syncSingleOutline) {+ $selectedInstanceOutline.set(outline);+ }};-const hideOutline = () => {- $selectedInstanceOutline.set(undefined);+const hideOutline = (+ selector: InstanceSelector,+ syncSingleOutline: boolean+) => {+ $selectedInstanceOutlines.set(+ $selectedInstanceOutlines+ .get()+ .filter(+ (item) => areInstanceSelectorsEqual(item.selector, selector) === false+ )+ );+ if (syncSingleOutline) {+ $selectedInstanceOutline.set(undefined);+ }};const calculateUnitSizes = (element: HTMLElement): UnitSizes => {@@ -101,12 +150,14 @@ const calculatePropertySizes = (element: HTMLElement) => {const subscribeSelectedInstance = (selectedInstanceSelector: Readonly<InstanceSelector>,- debounceEffect: (callback: () => void) => void+ debounceEffect: (callback: () => void) => void,+ syncSingleSelectionStores: boolean) => {if (selectedInstanceSelector.length === 0) {return;}+ const selector = [...selectedInstanceSelector];const instanceId = selectedInstanceSelector[0];let visibleElements = getVisibleElementsByInstanceSelector(@@ -114,6 +165,9 @@ const subscribeSelectedInstance = ();const updateScroll = () => {+ if (syncSingleSelectionStores === false) {+ return;+ }const bbox = getAllElementsBoundingBox(visibleElements);if (visibleElements.length === 0) {return;@@ -157,13 +211,21 @@ const subscribeSelectedInstance = (if ($isResizingCanvas.get()) {return;}- setOutline(instanceId, visibleElements);+ setOutline(+ selector,+ instanceId,+ visibleElements,+ syncSingleSelectionStores+ );};// effect close to rendered element also catches dnd remounts// so actual state is always provided hereshowOutline();const updateStores = () => {+ if (syncSingleSelectionStores === false) {+ return;+ }const elements = getAllElementsByInstanceSelector(selectedInstanceSelector);if (elements.length === 0) {@@ -294,8 +356,8 @@ const subscribeSelectedInstance = (const unsubscribeIsResizingCanvas = $isResizingCanvas.subscribe((isResizing) => {- if (isResizing && $selectedInstanceOutline.get()) {- return hideOutline();+ if (isResizing) {+ return hideOutline(selector, syncSingleSelectionStores);}showOutline();}@@ -303,7 +365,7 @@ const subscribeSelectedInstance = (const unsubscribeScrollState = subscribeScrollState({onScrollStart() {- hideOutline();+ hideOutline(selector, syncSingleSelectionStores);},onScrollEnd() {showOutline();@@ -312,19 +374,23 @@ const subscribeSelectedInstance = (const unsubscribeWindowResize = subscribeWindowResize({onResizeStart() {- hideOutline();+ hideOutline(selector, syncSingleSelectionStores);},onResizeEnd() {showOutline();},});- $selectedInstanceRenderState.set("mounted");+ if (syncSingleSelectionStores) {+ $selectedInstanceRenderState.set("mounted");+ }return () => {clearTimeout(updateStoreTimeouHandle);- hideOutline();- $selectedInstanceRenderState.set("notMounted");+ hideOutline(selector, syncSingleSelectionStores);+ if (syncSingleSelectionStores) {+ $selectedInstanceRenderState.set("notMounted");+ }resizeObserver.disconnect();mutationObserver.disconnect();bodyStyleMutationObserver.disconnect();@@ -340,23 +406,35 @@ const subscribeSelectedInstance = (export const subscribeSelected = (debounceEffect: (callback: () => void) => void) => {- let previousSelectedInstance: readonly string[] | undefined = undefined;- let unsubscribeSelectedInstance = () => {};-- const unsubscribe = $selectedInstanceSelector.subscribe(- (instanceSelector) => {- if (instanceSelector !== previousSelectedInstance) {- unsubscribeSelectedInstance();- unsubscribeSelectedInstance =- subscribeSelectedInstance(instanceSelector ?? [], debounceEffect) ??- (() => {});- previousSelectedInstance = instanceSelector;+ let previousSelectedInstances: readonly InstanceSelector[] | undefined =+ undefined;+ let unsubscribeSelectedInstances = () => {};++ const unsubscribe = $allSelectedInstanceSelectors.subscribe(+ (instanceSelectors) => {+ if (instanceSelectors !== previousSelectedInstances) {+ unsubscribeSelectedInstances();+ $selectedInstanceOutline.set(undefined);+ $selectedInstanceOutlines.set([]);+ const unsubscribes = instanceSelectors.map((instanceSelector) =>+ subscribeSelectedInstance(+ instanceSelector,+ debounceEffect,+ instanceSelectors.length === 1+ )+ );+ unsubscribeSelectedInstances = () => {+ for (const unsubscribe of unsubscribes) {+ unsubscribe?.();+ }+ };+ previousSelectedInstances = instanceSelectors;}});return () => {unsubscribe();- unsubscribeSelectedInstance();+ unsubscribeSelectedInstances();};};diff --git a/apps/builder/app/canvas/shared/commands.test.ts b/apps/builder/app/canvas/shared/commands.test.tsnew file mode 100644index 0000000000..8fafe2cf34--- /dev/null+++ b/apps/builder/app/canvas/shared/commands.test.ts@@ -0,0 +1,77 @@+import { afterEach, describe, expect, test } from "vitest";+import {+ $allSelectedInstanceSelectors,+ $selectedInstanceSelector,+ $textEditingInstanceSelector,+ $textToolbar,+ selectInstance,+ selectInstances,+} from "~/shared/nano-states";+import { emitCommand } from "./commands";++afterEach(() => {+ selectInstance(undefined);+ $textEditingInstanceSelector.set(undefined);+ $textToolbar.set(undefined);+});++describe("escapeSelection", () => {+ test("closes text toolbar before exiting text editing or clearing selection", () => {+ selectInstance(["text", "body"]);+ $textEditingInstanceSelector.set({+ selector: ["text", "body"],+ reason: "enter",+ });+ $textToolbar.set({+ selectionRect: undefined,+ isBold: false,+ isItalic: false,+ isSuperscript: false,+ isSubscript: false,+ isLink: false,+ isSpan: false,+ });++ emitCommand("escapeSelection");++ expect($textToolbar.get()).toBeUndefined();+ expect($textEditingInstanceSelector.get()).toEqual({+ selector: ["text", "body"],+ reason: "enter",+ });+ expect($selectedInstanceSelector.get()).toEqual(["text", "body"]);+ });++ test("exits text editing before clearing selection", () => {+ selectInstance(["text", "body"]);+ $textEditingInstanceSelector.set({+ selector: ["text", "body"],+ reason: "enter",+ });++ emitCommand("escapeSelection");++ expect($textEditingInstanceSelector.get()).toBeUndefined();+ expect($selectedInstanceSelector.get()).toEqual(["text", "body"]);+ });++ test("clears selected instance when not editing text", () => {+ selectInstance(["box", "body"]);++ emitCommand("escapeSelection");++ expect($selectedInstanceSelector.get()).toBeUndefined();+ });++ test("clears multi-selection when not editing text", () => {+ selectInstances([+ ["box1", "body"],+ ["box2", "body"],+ ]);++ emitCommand("escapeSelection");++ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ expect($selectedInstanceSelector.get()).toBeUndefined();+ });+});diff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.tsindex ade1d79edf..fe583bbf0f 100644--- a/apps/builder/app/canvas/shared/commands.ts+++ b/apps/builder/app/canvas/shared/commands.ts@@ -4,21 +4,22 @@ import { createCommandsEmitter } from "~/shared/commands-emitter";import { getElementByInstanceSelector } from "~/shared/dom-utils";import { findAllEditableInstanceSelector } from "~/shared/instance-utils/lookup";import {+ $allSelectedInstanceSelectors,$registeredComponentMetas,$propsIndex,+ $selectedInstanceSelector,$textEditingInstanceSelector,$textToolbar,+ clearInstanceSelection,+ selectInstance,} from "~/shared/nano-states";-import { $instances } from "~/shared/sync/data-stores";-import { $props } from "~/shared/sync/data-stores";+import { $instances, $props } from "~/shared/sync/data-stores";import {CLEAR_FORMAT_COMMAND,TOGGLE_SPAN_COMMAND,getActiveEditor,hasSelectionFormat,} from "../features/text-editor/toolbar-connector";-import { $selectedInstanceSelector } from "~/shared/nano-states";-import { selectInstance } from "~/shared/nano-states";import {isDescendantOrSelf,type InstanceSelector,@@ -45,6 +46,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({"moveInstanceDown","moveInstanceOut","moveInstanceIntoPreviousSibling",+ "selectPreviousSibling",+ "selectNextSibling",+ "selectSiblingInstances",],commands: [{@@ -134,7 +138,6 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({// reset selection for canvas, but not for the builderdisableHotkeyOutsideApp: true,handler: () => {- const selectedInstanceSelector = $selectedInstanceSelector.get();const textEditingInstanceSelector = $textEditingInstanceSelector.get();const textToolbar = $textToolbar.get();@@ -150,9 +153,9 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({return;}- if (selectedInstanceSelector) {+ if ($allSelectedInstanceSelectors.get().length > 0) {// unselect both instance and style source- selectInstance(undefined);+ clearInstanceSelection();return;}},diff --git a/apps/builder/app/shared/awareness.test.tsx b/apps/builder/app/shared/awareness.test.tsxindex 601607fd1a..ea934bd134 100644--- a/apps/builder/app/shared/awareness.test.tsx+++ b/apps/builder/app/shared/awareness.test.tsx@@ -3,7 +3,8 @@ import { $awareness, startPointerTracking, __testing__ } from "./awareness";const { $pointerPosition, getUserAwareness } = __testing__;import { findPageAndSelectorByInstanceId } from "./instance-utils/lookup";-import { $selectedPageId } from "./nano-states/pages";+import { selectInstance, selectInstances } from "./nano-states/instances";+import { $selectedPageId } from "./nano-states";import { $user } from "./nano-states/misc";import { createDefaultPages } from "@webstudio-is/project-build";import { $, renderData } from "@webstudio-is/template";@@ -54,6 +55,7 @@ test("find awareness by instance inside of slot", () => {afterEach(async () => {vi.useRealTimers();$selectedPageId.set(undefined);+ selectInstance(undefined);$pointerPosition.set(undefined);$user.set(undefined);await Promise.resolve();@@ -110,6 +112,47 @@ test("awareness includes user identity", async () => {unsubscribe();});+test("awareness includes selected instance selector", async () => {+ const listener = vi.fn();+ const unsubscribe = $awareness.listen(listener);++ await Promise.resolve();+ listener.mockClear();++ $selectedPageId.set("homePageId");+ selectInstance(["boxId", "bodyId"]);+ await Promise.resolve();++ expect(listener.mock.calls[0]?.[0]).toMatchObject({+ pageId: "homePageId",+ selectedInstanceIds: ["boxId", "bodyId"],+ });++ unsubscribe();+});++test("awareness does not include multi-selected instance selectors", async () => {+ const listener = vi.fn();+ const unsubscribe = $awareness.listen(listener);++ await Promise.resolve();+ listener.mockClear();++ $selectedPageId.set("homePageId");+ selectInstances([+ ["boxId", "bodyId"],+ ["headingId", "bodyId"],+ ]);+ await Promise.resolve();++ expect(listener.mock.calls[0]?.[0]).toMatchObject({+ pageId: "homePageId",+ selectedInstanceIds: undefined,+ });++ unsubscribe();+});+test("awareness updates are coalesced into one microtask", async () => {const listener = vi.fn();const unsubscribe = $awareness.listen(listener);diff --git a/apps/builder/app/shared/commands-emitter.ts b/apps/builder/app/shared/commands-emitter.tsindex b7c2905659..fb47a2c657 100644--- a/apps/builder/app/shared/commands-emitter.ts+++ b/apps/builder/app/shared/commands-emitter.ts@@ -49,6 +49,12 @@ export type Command<CommandName extends string> = CommandMeta<CommandName> & {export const $commandMetas = atom(new Map<string, CommandMeta<string>>());clientSyncStore.register("commandMetas", $commandMetas);+const suppressedCommandEvents = new WeakSet<KeyboardEvent>();++export const suppressCommandsForEvent = (event: KeyboardEvent) => {+ suppressedCommandEvents.add(event);+};+// Copied from https://github.com/ai/keyux/blob/main/hotkey.js#L1C1-L2C1// eslint-disable-next-line no-control-regexconst nonEnglishLayout = /^[^\x00-\x7F]$/;@@ -147,6 +153,9 @@ export const createCommandsEmitter = <CommandName extends string>({commandHandlers.get(name)?.(source);});const handleKeyDown = (event: KeyboardEvent) => {+ if (suppressedCommandEvents.has(event)) {+ return;+ }let emitted = false;let preventDefault = true;for (const commandMeta of findCommandsMatchingHotkeys(event)) {@@ -160,14 +169,15 @@ export const createCommandsEmitter = <CommandName extends string>({const { disableOnInputLikeControls } = commandMeta;if (disableOnInputLikeControls) {- const element = event.target as HTMLElement;+ const element = event.target;const isOnInputLikeControl =- ["input", "select", "textarea", "color-input"].includes(+ element instanceof HTMLElement &&+ (["input", "select", "textarea", "color-input"].includes(element.tagName.toLowerCase()) ||- element.isContentEditable ||- // Detect Radix select, dropdown and co.- element.getAttribute("role") === "option";+ element.isContentEditable ||+ // Detect Radix select, dropdown and co.+ element.getAttribute("role") === "option");if (isOnInputLikeControl) {continue;diff --git a/apps/builder/app/shared/copy-paste/copy-paste.test.ts b/apps/builder/app/shared/copy-paste/copy-paste.test.tsindex dc77617495..f32d4e0bf7 100644--- a/apps/builder/app/shared/copy-paste/copy-paste.test.ts+++ b/apps/builder/app/shared/copy-paste/copy-paste.test.ts@@ -1,7 +1,10 @@import { afterEach, expect, test, vi } from "vitest";import { enableMapSet } from "immer";import { createDefaultPages } from "@webstudio-is/project-build";-import type { Instance } from "@webstudio-is/sdk";+import { coreMetas, type Instance } from "@webstudio-is/sdk";+import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";+import type { Project } from "@webstudio-is/project";+import { initBuilderApi } from "../builder-api";import { registerContainers } from "../sync/sync-stores";import {$assets,@@ -9,17 +12,35 @@ import {$dataSources,$instances,$pages,+ $project,$props,$resources,$styleSourceSelections,$styleSources,$styles,} from "../sync/data-stores";-import { $authTokenPermissions } from "../nano-states";-import { copyPage } from "./copy-paste";+import {+ $authTokenPermissions,+ $selectedPageId,+ $textEditingInstanceSelector,+ $registeredComponentMetas,+ selectInstance,+ selectInstances,+} from "../nano-states";+import {+ copyInstance,+ copyPage,+ cutInstance,+ emitPaste,+ initCopyPaste,+ initCopyPasteForContentEditMode,+} from "./copy-paste";enableMapSet();registerContainers();+$registeredComponentMetas.set(+ new Map(Object.entries({ ...baseComponentMetas, ...coreMetas }))+);const resetStores = () => {$authTokenPermissions.set({@@ -28,6 +49,7 @@ const resetStores = () => {canPublish: false,});$instances.set(new Map());+ $project.set(undefined);$props.set(new Map());$dataSources.set(new Map());$resources.set(new Map());@@ -36,6 +58,8 @@ const resetStores = () => {$styleSources.set(new Map());$styles.set(new Map());$assets.set(new Map());+ $textEditingInstanceSelector.set(undefined);+ selectInstance(undefined);};const setupPage = () => {@@ -44,6 +68,7 @@ const setupPage = () => {rootInstanceId: "body-id",});$pages.set(pages);+ $selectedPageId.set(pages.homePageId);$instances.set(new Map<Instance["id"], Instance>([[@@ -59,6 +84,56 @@ const setupPage = () => {);};+const createClipboardEvent = (type: "copy" | "cut" | "paste") => {+ const data = new Map<string, string>();+ const clipboardData = {+ getData: (mimeType: string) => data.get(mimeType) ?? "",+ setData: (mimeType: string, value: string) => {+ data.set(mimeType, value);+ },+ } as DataTransfer;+ const event = new Event(type, {+ bubbles: true,+ cancelable: true,+ }) as ClipboardEvent;+ Object.defineProperty(event, "clipboardData", { value: clipboardData });+ return { clipboardData, event };+};++class TestDataTransfer {+ data = new Map<string, string>();++ getData(mimeType: string) {+ return this.data.get(mimeType) ?? "";+ }++ setData(mimeType: string, value: string) {+ this.data.set(mimeType, value);+ }+}++class TestClipboardEvent extends Event {+ clipboardData?: DataTransfer;++ constructor(+ type: string,+ options: EventInit & { clipboardData?: DataTransfer }+ ) {+ super(type, options);+ this.clipboardData = options.clipboardData;+ }+}++const setupToastInfo = () => {+ initBuilderApi();+ const toastInfo = vi.fn();+ window.__webstudio__$__builderApi.toast.info = toastInfo;+ return toastInfo;+};++const waitForClipboardEvent = () =>+ new Promise((resolve) => setTimeout(resolve, 0));+afterEach(() => {resetStores();vi.unstubAllGlobals();@@ -82,3 +157,705 @@ test("does not copy page to clipboard when copy permission is disabled", async (expect(writeText).not.toHaveBeenCalled();});++test("does not copy instance to clipboard when no instance is selected", async () => {+ resetStores();+ const writeText = vi.fn().mockResolvedValue(undefined);+ vi.stubGlobal("navigator", {+ ...navigator,+ clipboard: { writeText },+ });++ await copyInstance();++ expect(writeText).not.toHaveBeenCalled();+});++test("copies selected instance through clipboard event", () => {+ resetStores();+ const abortController = new AbortController();+ initCopyPaste({ signal: abortController.signal });+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [{ type: "id", value: "box-id" }],+ },+ ],+ [+ "box-id",+ {+ type: "instance",+ id: "box-id",+ component: "Box",+ children: [],+ },+ ],+ ])+ );+ selectInstance(["box-id", "body-id"]);+ const { clipboardData, event } = createClipboardEvent("copy");++ document.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(true);+ expect(clipboardData.getData("text/plain")).toContain(+ '"@webstudio/instance/v0.1"'+ );+ abortController.abort();+});++test("copies multi-selected instances through clipboard event", () => {+ resetStores();+ const abortController = new AbortController();+ initCopyPaste({ signal: abortController.signal });+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [+ { type: "id", value: "box-id" },+ { type: "id", value: "heading-id" },+ ],+ },+ ],+ [+ "box-id",+ {+ type: "instance",+ id: "box-id",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading-id",+ {+ type: "instance",+ id: "heading-id",+ component: "Heading",+ children: [],+ },+ ],+ ])+ );+ selectInstances([+ ["box-id", "body-id"],+ ["heading-id", "body-id"],+ ]);+ const { clipboardData, event } = createClipboardEvent("copy");++ document.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(true);+ expect(JSON.parse(clipboardData.getData("text/plain"))).toMatchObject({+ "@webstudio/instances/v0.1": {+ rootInstanceIds: ["box-id", "heading-id"],+ },+ });+ abortController.abort();+});++test("content mode copies selected instances through clipboard event", () => {+ resetStores();+ const abortController = new AbortController();+ const toastInfo = setupToastInfo();+ initCopyPasteForContentEditMode({ signal: abortController.signal });+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [{ type: "id", value: "box-id" }],+ },+ ],+ [+ "box-id",+ {+ type: "instance",+ id: "box-id",+ component: "Box",+ children: [],+ },+ ],+ ])+ );+ selectInstance(["box-id", "body-id"]);+ const { clipboardData, event } = createClipboardEvent("copy");++ document.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(true);+ expect(clipboardData.getData("text/plain")).toContain(+ '"@webstudio/instance/v0.1"'+ );+ expect(toastInfo).not.toHaveBeenCalled();+ abortController.abort();+});++test("content mode reports unsupported copy selection", () => {+ resetStores();+ const abortController = new AbortController();+ const toastInfo = setupToastInfo();+ initCopyPasteForContentEditMode({ signal: abortController.signal });+ const { event } = createClipboardEvent("copy");++ document.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(false);+ expect(toastInfo).toHaveBeenCalledWith(+ "This selection cannot be copied here."+ );+ abortController.abort();+});++test("content mode pastes instance clipboard data through clipboard event", async () => {+ resetStores();+ const abortController = new AbortController();+ const toastInfo = setupToastInfo();+ initCopyPasteForContentEditMode({ signal: abortController.signal });+ $project.set({ id: "project-id" } as Project);+ setupPage();+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [{ type: "id", value: "box-id" }],+ },+ ],+ [+ "box-id",+ {+ type: "instance",+ id: "box-id",+ component: "Box",+ children: [],+ },+ ],+ ])+ );+ selectInstance(["box-id", "body-id"]);+ const { clipboardData: copyData, event: copyEvent } =+ createClipboardEvent("copy");+ document.dispatchEvent(copyEvent);+ const clipboardText = copyData.getData("text/plain");+ selectInstance(["body-id"]);+ const { clipboardData, event } = createClipboardEvent("paste");+ clipboardData.setData("text/plain", clipboardText);++ document.dispatchEvent(event);+ await waitForClipboardEvent();++ expect(event.defaultPrevented).toBe(true);+ expect($instances.get().get("body-id")?.children).toEqual([+ { type: "id", value: "box-id" },+ { type: "id", value: expect.any(String) },+ ]);+ expect(toastInfo).not.toHaveBeenCalled();+ abortController.abort();+});++test("pastes multi-selected instance clipboard data through clipboard event", async () => {+ resetStores();+ const abortController = new AbortController();+ initCopyPaste({ signal: abortController.signal });+ $project.set({ id: "project-id" } as Project);+ setupPage();+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [+ { type: "id", value: "source-1" },+ { type: "id", value: "source-2" },+ { type: "id", value: "target" },+ ],+ },+ ],+ [+ "source-1",+ {+ type: "instance",+ id: "source-1",+ component: "Box",+ children: [],+ },+ ],+ [+ "source-2",+ {+ type: "instance",+ id: "source-2",+ component: "Heading",+ children: [],+ },+ ],+ [+ "target",+ {+ type: "instance",+ id: "target",+ component: "Box",+ children: [],+ },+ ],+ ])+ );+ selectInstances([+ ["source-1", "body-id"],+ ["source-2", "body-id"],+ ]);+ const { clipboardData: copyData, event: copyEvent } =+ createClipboardEvent("copy");+ document.dispatchEvent(copyEvent);+ const clipboardText = copyData.getData("text/plain");+ expect(JSON.parse(clipboardText)).toMatchObject({+ "@webstudio/instances/v0.1": {+ rootInstanceIds: ["source-1", "source-2"],+ },+ });++ selectInstance(["target", "body-id"]);+ const { clipboardData, event } = createClipboardEvent("paste");+ clipboardData.setData("text/plain", clipboardText);+ document.dispatchEvent(event);+ await waitForClipboardEvent();++ const targetChildren = $instances.get().get("target")?.children;+ expect(targetChildren).toEqual([+ { type: "id", value: expect.any(String) },+ { type: "id", value: expect.any(String) },+ ]);+ expect(targetChildren?.[0]?.value).not.toBe("source-1");+ expect(targetChildren?.[1]?.value).not.toBe("source-2");+ expect(+ $instances.get().get(targetChildren?.[0]?.value ?? "")?.component+ ).toBe("Box");+ expect(+ $instances.get().get(targetChildren?.[1]?.value ?? "")?.component+ ).toBe("Heading");+ abortController.abort();+});++test("cuts multi-selected instances through clipboard event", () => {+ resetStores();+ const abortController = new AbortController();+ initCopyPaste({ signal: abortController.signal });+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [+ { type: "id", value: "box-id" },+ { type: "id", value: "heading-id" },+ ],+ },+ ],+ [+ "box-id",+ {+ type: "instance",+ id: "box-id",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading-id",+ {+ type: "instance",+ id: "heading-id",+ component: "Heading",+ children: [],+ },+ ],+ ])+ );+ selectInstances([+ ["box-id", "body-id"],+ ["heading-id", "body-id"],+ ]);+ const { clipboardData, event } = createClipboardEvent("cut");++ document.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(true);+ expect(JSON.parse(clipboardData.getData("text/plain"))).toMatchObject({+ "@webstudio/instances/v0.1": {+ rootInstanceIds: ["box-id", "heading-id"],+ },+ });+ expect($instances.get().get("body-id")?.children).toEqual([]);+ expect($instances.get().has("box-id")).toBe(false);+ expect($instances.get().has("heading-id")).toBe(false);+ abortController.abort();+});++test("content mode blocks cut through clipboard event", () => {+ resetStores();+ const abortController = new AbortController();+ const toastInfo = setupToastInfo();+ initCopyPasteForContentEditMode({ signal: abortController.signal });+ const { event } = createClipboardEvent("cut");++ document.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(false);+ expect(toastInfo).toHaveBeenCalledWith(+ "Cutting is allowed in design mode only."+ );+ abortController.abort();+});++test("content mode reports unsupported paste clipboard data", async () => {+ resetStores();+ const abortController = new AbortController();+ const toastInfo = setupToastInfo();+ initCopyPasteForContentEditMode({ signal: abortController.signal });+ const { clipboardData, event } = createClipboardEvent("paste");+ clipboardData.setData("text/plain", "plain text");++ document.dispatchEvent(event);+ await waitForClipboardEvent();++ expect(event.defaultPrevented).toBe(true);+ expect(toastInfo).toHaveBeenCalledWith(+ "This clipboard data cannot be pasted here."+ );+ abortController.abort();+});++test("does not intercept native copy from inputs", () => {+ resetStores();+ const abortController = new AbortController();+ initCopyPaste({ signal: abortController.signal });+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [{ type: "id", value: "box-id" }],+ },+ ],+ [+ "box-id",+ {+ type: "instance",+ id: "box-id",+ component: "Box",+ children: [],+ },+ ],+ ])+ );+ selectInstance(["box-id", "body-id"]);+ const input = document.createElement("input");+ document.body.appendChild(input);+ const { clipboardData, event } = createClipboardEvent("copy");++ input.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(false);+ expect(clipboardData.getData("text/plain")).toBe("");+ input.remove();+ abortController.abort();+});++test("does not intercept native copy while editing canvas text", () => {+ resetStores();+ const abortController = new AbortController();+ initCopyPaste({ signal: abortController.signal });+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [{ type: "id", value: "text-id" }],+ },+ ],+ [+ "text-id",+ {+ type: "instance",+ id: "text-id",+ component: "Text",+ children: [],+ },+ ],+ ])+ );+ selectInstance(["text-id", "body-id"]);+ $textEditingInstanceSelector.set({+ selector: ["text-id", "body-id"],+ reason: "enter",+ });+ const { clipboardData, event } = createClipboardEvent("copy");++ document.dispatchEvent(event);++ expect(event.defaultPrevented).toBe(false);+ expect(clipboardData.getData("text/plain")).toBe("");+ abortController.abort();+});++test("copies selected instance to clipboard", async () => {+ resetStores();+ const writeText = vi.fn().mockResolvedValue(undefined);+ vi.stubGlobal("navigator", {+ ...navigator,+ clipboard: { writeText },+ });+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [{ type: "id", value: "box-id" }],+ },+ ],+ [+ "box-id",+ {+ type: "instance",+ id: "box-id",+ component: "Box",+ children: [],+ },+ ],+ ])+ );+ selectInstance(["box-id", "body-id"]);++ await copyInstance();++ expect(writeText).toHaveBeenCalledWith(+ expect.stringContaining('"@webstudio/instance/v0.1"')+ );+});++test("copies multi-selected instances to clipboard and emits paste for every root", async () => {+ resetStores();+ const abortController = new AbortController();+ initCopyPaste({ signal: abortController.signal });+ let clipboardText = "";+ vi.stubGlobal("navigator", {+ ...navigator,+ clipboard: {+ writeText: vi.fn(async (text: string) => {+ clipboardText = text;+ }),+ readText: vi.fn(async () => clipboardText),+ },+ });+ vi.stubGlobal("DataTransfer", TestDataTransfer);+ vi.stubGlobal("ClipboardEvent", TestClipboardEvent);+ $project.set({ id: "project-id" } as Project);+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [+ { type: "id", value: "source-1" },+ { type: "id", value: "source-2" },+ { type: "id", value: "target" },+ ],+ },+ ],+ [+ "source-1",+ {+ type: "instance",+ id: "source-1",+ component: "Box",+ children: [],+ },+ ],+ [+ "source-2",+ {+ type: "instance",+ id: "source-2",+ component: "Heading",+ children: [],+ },+ ],+ [+ "target",+ {+ type: "instance",+ id: "target",+ component: "Box",+ children: [],+ },+ ],+ ])+ );+ selectInstances([+ ["source-1", "body-id"],+ ["source-2", "body-id"],+ ]);++ await copyInstance();+ expect(JSON.parse(clipboardText)).toMatchObject({+ "@webstudio/instances/v0.1": {+ rootInstanceIds: ["source-1", "source-2"],+ },+ });++ selectInstance(["target", "body-id"]);+ await emitPaste();+ await waitForClipboardEvent();++ expect($instances.get().get("target")?.children).toEqual([+ { type: "id", value: expect.any(String) },+ { type: "id", value: expect.any(String) },+ ]);+ abortController.abort();+});++test("does not cut instance to clipboard when no instance is selected", async () => {+ resetStores();+ const writeText = vi.fn().mockResolvedValue(undefined);+ vi.stubGlobal("navigator", {+ ...navigator,+ clipboard: { writeText },+ });++ await cutInstance();++ expect(writeText).not.toHaveBeenCalled();+});++test("cuts selected instance to clipboard and removes it", async () => {+ resetStores();+ const writeText = vi.fn().mockResolvedValue(undefined);+ vi.stubGlobal("navigator", {+ ...navigator,+ clipboard: { writeText },+ });+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [{ type: "id", value: "box-id" }],+ },+ ],+ [+ "box-id",+ {+ type: "instance",+ id: "box-id",+ component: "Box",+ children: [],+ },+ ],+ ])+ );+ selectInstance(["box-id", "body-id"]);++ await cutInstance();++ expect(writeText).toHaveBeenCalledWith(+ expect.stringContaining('"@webstudio/instance/v0.1"')+ );+ expect($instances.get().get("body-id")?.children).toEqual([]);+ expect($instances.get().has("box-id")).toBe(false);+});++test("cuts multi-selected instances to clipboard and removes every root", async () => {+ resetStores();+ const writeText = vi.fn().mockResolvedValue(undefined);+ vi.stubGlobal("navigator", {+ ...navigator,+ clipboard: { writeText },+ });+ $instances.set(+ new Map<Instance["id"], Instance>([+ [+ "body-id",+ {+ type: "instance",+ id: "body-id",+ component: "Body",+ children: [+ { type: "id", value: "box-id" },+ { type: "id", value: "heading-id" },+ ],+ },+ ],+ [+ "box-id",+ {+ type: "instance",+ id: "box-id",+ component: "Box",+ children: [],+ },+ ],+ [+ "heading-id",+ {+ type: "instance",+ id: "heading-id",+ component: "Heading",+ children: [],+ },+ ],+ ])+ );+ selectInstances([+ ["box-id", "body-id"],+ ["heading-id", "body-id"],+ ]);++ await cutInstance();++ expect(JSON.parse(writeText.mock.calls[0]?.[0] ?? "")).toMatchObject({+ "@webstudio/instances/v0.1": {+ rootInstanceIds: ["box-id", "heading-id"],+ },+ });+ expect($instances.get().get("body-id")?.children).toEqual([]);+ expect($instances.get().has("box-id")).toBe(false);+ expect($instances.get().has("heading-id")).toBe(false);+});diff --git a/apps/builder/app/shared/copy-paste/copy-paste.ts b/apps/builder/app/shared/copy-paste/copy-paste.tsindex 58f36c8c6d..a17cba660c 100644--- a/apps/builder/app/shared/copy-paste/copy-paste.ts+++ b/apps/builder/app/shared/copy-paste/copy-paste.ts@@ -155,21 +155,68 @@ export const initCopyPasteForContentEditMode = ({}: {signal: AbortSignal;}) => {- const handleClipboard = (event: ClipboardEvent) => {+ const showUnsupportedCopyMessage = () => {+ builderApi.toast.info("This selection cannot be copied here.");+ };++ const showUnsupportedPasteMessage = () => {+ builderApi.toast.info("This clipboard data cannot be pasted here.");+ };++ const showCutDesignModeOnlyMessage = () => {+ builderApi.toast.info("Cutting is allowed in design mode only.");+ };++ const handleCopy = (event: ClipboardEvent) => {if (validateClipboardEvent(event) === false) {return;}+ const data = instanceText.onCopy?.();+ if (data) {+ event.preventDefault();+ event.clipboardData?.setData(instanceText.mimeType, data);+ return;+ }+ showUnsupportedCopyMessage();+ };- builderApi.toast.info(- "Copying and pasting is allowed in design mode only."- );+ const handlePaste = async (event: ClipboardEvent) => {+ if (validateClipboardEvent(event) === false) {+ return;+ }+ const jsonData = event.clipboardData?.getData(instanceJson.mimeType).trim();+ if (jsonData) {+ event.preventDefault();+ if (await instanceJson.onPaste?.(jsonData)) {+ return;+ }+ showUnsupportedPasteMessage();+ return;+ }+ const textData = event.clipboardData?.getData(instanceText.mimeType).trim();+ if (textData) {+ event.preventDefault();+ if (await instanceText.onPaste?.(textData)) {+ return;+ }+ showUnsupportedPasteMessage();+ return;+ }+ showUnsupportedPasteMessage();};- document.addEventListener("copy", handleClipboard, { signal });- document.addEventListener("cut", handleClipboard, { signal });+ const handleCut = (event: ClipboardEvent) => {+ if (validateClipboardEvent(event) === false) {+ return;+ }+ showCutDesignModeOnlyMessage();+ };++ document.addEventListener("copy", handleCopy, { signal });+ document.addEventListener("cut", handleCut, { signal });// Capture is required so we get the element before content-editable removes it// This way we can detect when we are inside content-editable and ignore the event- document.addEventListener("paste", handleClipboard, {+ document.addEventListener("paste", handlePaste, {capture: true,signal,});diff --git a/apps/builder/app/shared/copy-paste/plugin-html.test.tsx b/apps/builder/app/shared/copy-paste/plugin-html.test.tsxindex 7a0e076392..d76c5c3454 100644--- a/apps/builder/app/shared/copy-paste/plugin-html.test.tsx+++ b/apps/builder/app/shared/copy-paste/plugin-html.test.tsx@@ -11,7 +11,7 @@ import { $pages, $project } from "~/shared/sync/data-stores";import {$registeredComponentMetas,$selectedPageId,- $selectedInstanceSelector,+ selectInstance,} from "../nano-states";import { html } from "./plugin-html";@@ -33,7 +33,7 @@ test("paste html fragment", async () => {createDefaultPages({ rootInstanceId: "bodyId", homePageId: "pageId" }));$selectedPageId.set("pageId");- $selectedInstanceSelector.set(["divId", "bodyId"]);+ selectInstance(["divId", "bodyId"]);expect(await html.onPaste?.(`<section>@@ -71,7 +71,7 @@ test("ignore html without any tags", async () => {createDefaultPages({ rootInstanceId: "bodyId", homePageId: "pageId" }));$selectedPageId.set("pageId");- $selectedInstanceSelector.set(["divId", "bodyId"]);+ selectInstance(["divId", "bodyId"]);expect(await html.onPaste?.(`It works`)).toEqual(false);expect($instances.get()).toEqual(data.instances);});@@ -88,7 +88,7 @@ test("skip whitespace-only text nodes between element siblings", async () => {createDefaultPages({ rootInstanceId: "bodyId", homePageId: "pageId" }));$selectedPageId.set("pageId");- $selectedInstanceSelector.set(["divId", "bodyId"]);+ selectInstance(["divId", "bodyId"]);// Regression test: whitespace between elements should not create separate text nodes// but the space should be preserved as part of one of the adjacent span instancesdiff --git a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts b/apps/builder/app/shared/copy-paste/plugin-instance.test.tsindex 33168cb1dc..11c9319593 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.test.ts@@ -1,4 +1,4 @@-import { describe, test, expect, vi, beforeAll } from "vitest";+import { describe, test, expect } from "vitest";import { enableMapSet } from "immer";import type {Instance,@@ -15,6 +15,7 @@ import {collectionComponent,coreMetas,elementComponent,+ blockTemplateComponent,portalComponent,} from "@webstudio-is/sdk";import type { Project } from "@webstudio-is/project";@@ -31,9 +32,9 @@ import {} from "~/shared/sync/data-stores";import { instanceText } from "./plugin-instance";import { createDefaultPages } from "@webstudio-is/project-build";-import { selectInstance } from "~/shared/nano-states";+import { selectInstance, selectInstances } from "~/shared/nano-states";+import { $allSelectedInstanceSelectors } from "~/shared/nano-states";import { $selectedPageId } from "../nano-states/pages";-import * as instanceFragmentUtils from "../instance-utils/fragment";import * as instanceMutationUtils from "../instance-utils/mutation";import {expectSlotTreeIntegrity,@@ -45,14 +46,6 @@ const expectString = expect.any(String) as unknown as string;enableMapSet();registerContainers();-// Mock detectFragmentTokenConflicts to always return no conflicts-beforeAll(() => {- vi.spyOn(- instanceFragmentUtils,- "detectFragmentTokenConflicts"- ).mockReturnValue([]);-});-$registeredComponentMetas.set(new Map(Object.entries({ ...baseComponentMetas, ...coreMetas })));@@ -99,6 +92,274 @@ const getMapDifference = <Type extends Map<unknown, unknown>>(return difference;};+describe("copy and cut guards", () => {+ test("does not copy without a selected instance", () => {+ selectInstance(undefined);++ expect(instanceText.onCopy?.()).toBeUndefined();+ });++ test("does not cut without a selected instance", () => {+ selectInstance(undefined);++ expect(instanceText.onCut?.()).toBeUndefined();+ });++ test("does not copy or cut the selected root instance", () => {+ const instances: Instances = toMap([+ createInstance("body0", "Body", [{ type: "id", value: "box1" }]),+ createInstance("box1", "Box", []),+ ] satisfies Instance[]);+ $instances.set(instances);+ selectInstance(["body0"]);++ expect(instanceText.onCopy?.()).toBeUndefined();+ expect(instanceText.onCut?.()).toBeUndefined();+ expect($instances.get()).toEqual(instances);+ });++ test("copies multiple selected roots into one combined fragment", () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ ]),+ createInstance("box1", "Box", []),+ createInstance("box2", "Box", []),+ ] satisfies Instance[])+ );+ selectInstances([+ ["box1", "body0"],+ ["box2", "body0"],+ ]);++ const clipboardData = instanceText.onCopy?.();++ expect(JSON.parse(clipboardData ?? "")).toMatchObject({+ "@webstudio/instances/v0.1": {+ rootInstanceIds: ["box1", "box2"],+ fragment: {+ children: [+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ ],+ instances: [+ { id: "box1", type: "instance", component: "Box", children: [] },+ { id: "box2", type: "instance", component: "Box", children: [] },+ ],+ },+ },+ });+ });++ test("pastes multiple copied roots in order and selects pasted roots", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ ]),+ createInstance("box1", "Box", [{ type: "id", value: "child" }]),+ createInstance("child", "Box", []),+ createInstance("box2", "Box", []),+ ] satisfies Instance[])+ );+ selectInstances([+ ["box1", "body0"],+ ["box2", "body0"],+ ]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstance(["body0"]);++ expect(await instanceText.onPaste?.(clipboardData)).toBe(true);++ const bodyChildren = $instances.get().get("body0")?.children;+ const pastedRootIds = bodyChildren?.slice(2).map((child) => child.value);+ expect(bodyChildren).toEqual([+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ { type: "id", value: expect.any(String) },+ { type: "id", value: expect.any(String) },+ ]);+ expect(pastedRootIds?.[0]).not.toBe("box1");+ expect(pastedRootIds?.[1]).not.toBe("box2");+ expect($allSelectedInstanceSelectors.get()).toEqual([+ [pastedRootIds?.[0], "body0"],+ [pastedRootIds?.[1], "body0"],+ ]);+ });++ test("sanitizes multi-root clipboard root ids before paste", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ ]),+ createInstance("box1", "Box", []),+ createInstance("box2", "Box", []),+ ] satisfies Instance[])+ );+ selectInstances([+ ["box1", "body0"],+ ["box2", "body0"],+ ]);+ const clipboardData = JSON.parse(instanceText.onCopy?.() ?? "");+ clipboardData["@webstudio/instances/v0.1"].rootInstanceIds = [+ "box1",+ "child",+ "missing",+ "box1",+ ];+ selectInstance(["body0"]);++ expect(await instanceText.onPaste?.(JSON.stringify(clipboardData))).toBe(+ true+ );++ const bodyChildren = $instances.get().get("body0")?.children;+ expect(bodyChildren).toEqual([+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ { type: "id", value: expect.any(String) },+ ]);++ clipboardData["@webstudio/instances/v0.1"].rootInstanceIds = ["missing"];+ expect(await instanceText.onPaste?.(JSON.stringify(clipboardData))).toBe(+ false+ );+ expect($instances.get().get("body0")?.children).toEqual(bodyChildren);+ });++ test("writes only copyable roots when multi-copy skips selected roots", () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "box1" },+ { type: "id", value: "template" },+ ]),+ createInstance("box1", "Box", []),+ createInstance("template", blockTemplateComponent, []),+ ] satisfies Instance[])+ );+ selectInstances([+ ["template", "body0"],+ ["box1", "body0"],+ ]);++ const clipboardData = instanceText.onCopy?.();++ expect(JSON.parse(clipboardData ?? "")).toMatchObject({+ "@webstudio/instances/v0.1": {+ rootInstanceIds: ["box1"],+ },+ });+ });++ test("does not copy when no multi-selected root is copyable", () => {+ const instances: Instances = toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "template1" },+ { type: "id", value: "template2" },+ ]),+ createInstance("template1", blockTemplateComponent, []),+ createInstance("template2", blockTemplateComponent, []),+ ] satisfies Instance[]);+ $instances.set(instances);+ selectInstances([+ ["template1", "body0"],+ ["template2", "body0"],+ ]);++ expect(instanceText.onCopy?.()).toBeUndefined();+ expect($instances.get()).toEqual(instances);+ });++ test("cuts multiple selected roots into one combined fragment and removes them", () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ ]),+ createInstance("box1", "Box", []),+ createInstance("box2", "Box", []),+ ] satisfies Instance[])+ );+ selectInstances([+ ["box1", "body0"],+ ["box2", "body0"],+ ]);++ const clipboardData = instanceText.onCut?.();++ expect(JSON.parse(clipboardData ?? "")).toMatchObject({+ "@webstudio/instances/v0.1": {+ rootInstanceIds: ["box1", "box2"],+ },+ });+ expect($instances.get().get("body0")?.children).toEqual([]);+ expect($instances.get().has("box1")).toBe(false);+ expect($instances.get().has("box2")).toBe(false);+ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ });++ test("cuts only copyable roots when multi-cut skips selected roots", () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "box1" },+ { type: "id", value: "template" },+ ]),+ createInstance("box1", "Box", []),+ createInstance("template", blockTemplateComponent, []),+ ] satisfies Instance[])+ );+ selectInstances([+ ["template", "body0"],+ ["box1", "body0"],+ ]);++ const clipboardData = instanceText.onCut?.();++ expect(JSON.parse(clipboardData ?? "")).toMatchObject({+ "@webstudio/instances/v0.1": {+ rootInstanceIds: ["box1"],+ },+ });+ expect($instances.get().get("body0")?.children).toEqual([+ { type: "id", value: "template" },+ ]);+ expect($instances.get().has("box1")).toBe(false);+ expect($instances.get().has("template")).toBe(true);+ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ });++ test("does not cut when no multi-selected root is copyable", () => {+ const instances: Instances = toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "template1" },+ { type: "id", value: "template2" },+ ]),+ createInstance("template1", blockTemplateComponent, []),+ createInstance("template2", blockTemplateComponent, []),+ ] satisfies Instance[]);+ $instances.set(instances);+ selectInstances([+ ["template1", "body0"],+ ["template2", "body0"],+ ]);++ expect(instanceText.onCut?.()).toBeUndefined();+ expect($instances.get()).toEqual(instances);+ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["template1", "body0"],+ ["template2", "body0"],+ ]);+ });+});+describe("paste target", () => {// body0// box1@@ -148,6 +409,127 @@ describe("paste target", () => {);});+ test("uses multi-selection paste target after the last selected sibling for old single-root clipboard data", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "source" },+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ { type: "id", value: "tail" },+ ]),+ createInstance("source", "Box", []),+ createInstance("box1", "Box", []),+ createInstance("box2", "Box", []),+ createInstance("tail", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["source", "body0"]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstances([+ ["box1", "body0"],+ ["box2", "body0"],+ ]);++ await instanceText.onPaste?.(clipboardData);++ const bodyChildren = $instances.get().get("body0")?.children;+ expect(bodyChildren).toEqual([+ { type: "id", value: "source" },+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ { type: "id", value: expect.any(String) },+ { type: "id", value: "tail" },+ ]);+ const pastedId = bodyChildren?.[3]?.value;+ expect(pastedId).not.toBe("source");+ expect($allSelectedInstanceSelectors.get()).toEqual([[pastedId, "body0"]]);+ });++ test("uses multi-selection paste target after the last selected sibling for multi-root clipboard data", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "source1" },+ { type: "id", value: "source2" },+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ { type: "id", value: "tail" },+ ]),+ createInstance("source1", "Box", []),+ createInstance("source2", "Box", []),+ createInstance("box1", "Box", []),+ createInstance("box2", "Box", []),+ createInstance("tail", "Box", []),+ ] satisfies Instance[])+ );+ selectInstances([+ ["source1", "body0"],+ ["source2", "body0"],+ ]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstances([+ ["box1", "body0"],+ ["box2", "body0"],+ ]);++ await instanceText.onPaste?.(clipboardData);++ const bodyChildren = $instances.get().get("body0")?.children;+ expect(bodyChildren).toEqual([+ { type: "id", value: "source1" },+ { type: "id", value: "source2" },+ { type: "id", value: "box1" },+ { type: "id", value: "box2" },+ { type: "id", value: expect.any(String) },+ { type: "id", value: expect.any(String) },+ { type: "id", value: "tail" },+ ]);+ });++ test("uses lowest common ancestor paste target for mixed-parent multi-selection", async () => {+ $instances.set(+ toMap([+ createInstance("body0", "Body", [+ { type: "id", value: "source" },+ { type: "id", value: "section" },+ { type: "id", value: "footer" },+ ]),+ createInstance("source", "Box", []),+ createInstance("section", "Box", [+ { type: "id", value: "group" },+ { type: "id", value: "aside" },+ { type: "id", value: "tail" },+ ]),+ createInstance("group", "Box", [{ type: "id", value: "box" }]),+ createInstance("box", "Box", []),+ createInstance("aside", "Box", []),+ createInstance("tail", "Box", []),+ createInstance("footer", "Box", []),+ ] satisfies Instance[])+ );+ selectInstance(["source", "body0"]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstances([+ ["box", "group", "section", "body0"],+ ["aside", "section", "body0"],+ ]);++ await instanceText.onPaste?.(clipboardData);++ expect($instances.get().get("section")?.children).toEqual([+ { type: "id", value: "group" },+ { type: "id", value: "aside" },+ { type: "id", value: "tail" },+ { type: "id", value: expect.any(String) },+ ]);+ expect($instances.get().get("body0")?.children).toEqual([+ { type: "id", value: "source" },+ { type: "id", value: "section" },+ { type: "id", value: "footer" },+ ]);+ });+test("pastes into shared slot content", async () => {$instances.set(toMap([@@ -581,7 +963,13 @@ describe("paste target", () => {);selectInstance(["box", "fragment", "slot1", "body0"]);- expect(instanceText.onCut?.()).toBeDefined();+ const clipboardData = instanceText.onCut?.();+ expect(JSON.parse(clipboardData ?? "")).toMatchObject({+ "@webstudio/instance/v0.1": {+ instanceSelector: ["box", "fragment", "slot1", "body0"],+ children: [{ type: "id", value: "box" }],+ },+ });expectSlotsShareFragment($instances.get(), ["slot1", "slot2"]);expect($instances.get().get("slot1")?.children).toEqual([@@ -615,7 +1003,13 @@ describe("paste target", () => {);selectInstance(["box", "slot1", "body0"]);- expect(instanceText.onCut?.()).toBeDefined();+ const clipboardData = instanceText.onCut?.();+ expect(JSON.parse(clipboardData ?? "")).toMatchObject({+ "@webstudio/instance/v0.1": {+ instanceSelector: ["box", "slot1", "body0"],+ children: [{ type: "id", value: "box" }],+ },+ });const fragmentId = expectSlotsShareFragment($instances.get(), ["slot1",@@ -649,7 +1043,13 @@ describe("paste target", () => {);selectInstance(["box", "div", "fragment", "slot1", "body0"]);- expect(instanceText.onCut?.()).toBeDefined();+ const clipboardData = instanceText.onCut?.();+ expect(JSON.parse(clipboardData ?? "")).toMatchObject({+ "@webstudio/instance/v0.1": {+ instanceSelector: ["box", "div", "fragment", "slot1", "body0"],+ children: [{ type: "id", value: "box" }],+ },+ });expect($instances.get().get("slot1")?.children).toEqual([{ type: "id", value: "fragment" },@@ -683,7 +1083,13 @@ describe("paste target", () => {);selectInstance(["box", "fragment", "slot1", "body0"]);- expect(instanceText.onCut?.()).toBeDefined();+ const clipboardData = instanceText.onCut?.();+ expect(JSON.parse(clipboardData ?? "")).toMatchObject({+ "@webstudio/instance/v0.1": {+ instanceSelector: ["box", "fragment", "slot1", "body0"],+ children: [{ type: "id", value: "box" }],+ },+ });expect($instances.get().get("slot1")?.children).toEqual([{ type: "id", value: "fragment" },@@ -1012,9 +1418,9 @@ test("prevent pasting portal into copy of it", async () => {createInstance("fragment", "Fragment", []),]);$instances.set(instances);- selectInstance(["box", "body"]);+ selectInstance(["portal1", "body"]);const clipboardData = instanceText.onCopy?.() ?? "";- selectInstance(["portal", "body"]);+ selectInstance(["portal2", "body"]);await instanceText.onPaste?.(clipboardData);expect($instances.get()).toEqual(instances);});@@ -1056,6 +1462,44 @@ test("insert portal into its sibling", async () => {);});+test("inserts multi-root clipboard into descendant of copied non-portal root", async () => {+ $instances.set(+ toMap([+ createInstance("body", "Body", [+ { type: "id", value: "portal" },+ { type: "id", value: "box" },+ ]),+ createInstance("portal", portalComponent, [+ { type: "id", value: "fragment" },+ ]),+ createInstance("fragment", "Fragment", []),+ createInstance("box", "Box", [{ type: "id", value: "target" }]),+ createInstance("target", "Box", []),+ ])+ );+ selectInstances([+ ["portal", "body"],+ ["box", "body"],+ ]);+ const clipboardData = instanceText.onCopy?.() ?? "";+ selectInstance(["target", "box", "body"]);++ await instanceText.onPaste?.(clipboardData);++ const targetChildren = $instances.get().get("target")?.children;+ const [pastedPortalId, pastedBoxId] =+ targetChildren?.map((child) => (child.type === "id" ? child.value : "")) ??+ [];+ expect(targetChildren).toEqual([+ { type: "id", value: expectString },+ { type: "id", value: expectString },+ ]);+ expect($instances.get().get(pastedPortalId ?? "")?.component).toBe(+ portalComponent+ );+ expect($instances.get().get(pastedBoxId ?? "")?.component).toBe("Box");+});+test("insert into portal fragment when portal is a target", async () => {$instances.set(toMap([@@ -1094,6 +1538,7 @@ test("insert into portal fragment when portal is a target", async () => {);// fragment already exists+ selectInstance(["portal", "body"]);await instanceText.onPaste?.(clipboardData);expect($instances.get()).toEqual(toMap([diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex 30a8af1270..047b9e6770 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -19,6 +19,7 @@ import { toast } from "@webstudio-is/design-system";import {type Instance,type Instances,+ type WebstudioFragment,webstudioFragment,findTreeInstanceIdsExcludingSlotDescendants,isComponentDetachable,@@ -26,10 +27,17 @@ import {} from "@webstudio-is/sdk";import { $instances, $project } from "~/shared/sync/data-stores";import type { InstanceSelector } from "../instance-utils/tree";-import { deleteInstanceMutable } from "../instance-utils/mutation";import {+ deleteInstanceMutable,+ sortInstancePathsForChildMutation,+} from "../instance-utils/mutation";+import {+ $allSelectedInstanceSelectors,+ clearInstanceSelection,+ getInstancePath,$selectedInstancePath,$selectedInstanceSelector,+ selectInstances,} from "~/shared/nano-states";import { findAvailableVariables } from "../data-variables";import { builderApi } from "../builder-api";@@ -37,6 +45,7 @@ import type { Plugin } from "./copy-paste";import { breakpointPasteLimitWarning } from "../breakpoints";const version = "@webstudio/instance/v0.1";+const multiRootVersion = "@webstudio/instances/v0.1";const instanceData = webstudioFragment.extend({instanceSelector: z.array(z.string()),@@ -44,14 +53,26 @@ const instanceData = webstudioFragment.extend({type InstanceData = z.infer<typeof instanceData>;-const getTreeData = (instanceSelector: InstanceSelector) => {+const multiRootInstanceData = z.object({+ rootInstanceIds: z.array(z.string()),+ fragment: webstudioFragment,+});++type MultiRootInstanceData = z.infer<typeof multiRootInstanceData>;++const getTreeData = (+ instanceSelector: InstanceSelector,+ { showToast = true }: { showToast?: boolean } = {}+) => {const instances = $instances.get();const [targetInstanceId] = instanceSelector;const instance = instances.get(targetInstanceId);if (instance && !isComponentDetachable(instance.component)) {- toast.error(- "This instance can not be moved outside of its parent component."- );+ if (showToast) {+ toast.error(+ "This instance can not be moved outside of its parent component."+ );+ }return;}@@ -70,7 +91,22 @@ const stringify = (data: InstanceData) => {return JSON.stringify({ [version]: data });};+const stringifyMultiRoot = (data: MultiRootInstanceData) => {+ return JSON.stringify({ [multiRootVersion]: data });+};++const stringifyMultiRootSelection = (selectedData: InstanceData[]) => {+ const rootInstanceIds = selectedData.map((data) => data.instanceSelector[0]);+ return stringifyMultiRoot({+ rootInstanceIds,+ fragment: mergeWebstudioFragments(rootInstanceIds, selectedData),+ });+};+const clipboard = z.object({ [version]: instanceData });+const multiRootClipboard = z.object({+ [multiRootVersion]: multiRootInstanceData,+});const parse = (clipboardData: string): InstanceData | undefined => {try {@@ -81,6 +117,79 @@ const parse = (clipboardData: string): InstanceData | undefined => {}};+const parseMultiRoot = (+ clipboardData: string+): MultiRootInstanceData | undefined => {+ try {+ const data = multiRootClipboard.parse(JSON.parse(clipboardData));+ return data[multiRootVersion];+ } catch {+ return;+ }+};++const getPasteRootInstanceIds = ({+ rootInstanceIds,+ fragment,+}: MultiRootInstanceData) => {+ const instanceIds = new Set(+ fragment.instances.map((instance) => instance.id)+ );+ const fragmentRootIds = new Set<Instance["id"]>();+ for (const child of fragment.children) {+ if (child.type === "id") {+ fragmentRootIds.add(child.value);+ }+ }+ const seen = new Set<Instance["id"]>();+ return rootInstanceIds.filter((instanceId) => {+ if (+ instanceIds.has(instanceId) === false ||+ fragmentRootIds.has(instanceId) === false ||+ seen.has(instanceId)+ ) {+ return false;+ }+ seen.add(instanceId);+ return true;+ });+};++const mergeById = <Item extends { id: string }>(items: Item[]) =>+ Array.from(new Map(items.map((item) => [item.id, item])).values());++const mergeUniqueByJson = <Item>(items: Item[]) =>+ Array.from(+ new Map(items.map((item) => [JSON.stringify(item), item])).values()+ );++const mergeWebstudioFragments = (+ rootInstanceIds: Instance["id"][],+ fragments: WebstudioFragment[]+): WebstudioFragment => ({+ children: rootInstanceIds.map((instanceId) => ({+ type: "id" as const,+ value: instanceId,+ })),+ instances: mergeById(fragments.flatMap((fragment) => fragment.instances)),+ styleSourceSelections: mergeUniqueByJson(+ fragments.flatMap((fragment) => fragment.styleSourceSelections)+ ),+ styleSources: mergeById(+ fragments.flatMap((fragment) => fragment.styleSources)+ ),+ breakpoints: mergeById(fragments.flatMap((fragment) => fragment.breakpoints)),+ styles: mergeUniqueByJson(fragments.flatMap((fragment) => fragment.styles)),+ dataSources: mergeById(fragments.flatMap((fragment) => fragment.dataSources)),+ resources: mergeById(fragments.flatMap((fragment) => fragment.resources)),+ props: mergeById(fragments.flatMap((fragment) => fragment.props)),+ assets: mergeById(fragments.flatMap((fragment) => fragment.assets)),+});++const reportSkippedSelectedInstances = (operation: "copied" | "cut") => {+ builderApi.toast.info(`Some selected instances could not be ${operation}.`);+};+const getPortalFragmentSelector = (instances: Instances,instanceSelector: InstanceSelector@@ -97,53 +206,134 @@ const getPortalFragmentSelector = (return [instance.children[0].value, ...instanceSelector];};-const findPasteTarget = (data: InstanceData): undefined | Insertable => {- const instances = $instances.get();+const getIdChildIndex = (+ children: Instance["children"],+ instanceId: Instance["id"]+) =>+ children.findIndex(+ (child) => child.type === "id" && child.value === instanceId+ );- const instanceSelector = $selectedInstanceSelector.get();+const getCommonAncestorSelector = (+ instanceSelectors: InstanceSelector[]+): undefined | InstanceSelector => {+ const [firstSelector] = instanceSelectors;+ if (firstSelector === undefined) {+ return;+ }+ const ancestorSelector: InstanceSelector = [];+ for (let index = 1; index <= firstSelector.length; index += 1) {+ const ancestorId = firstSelector[firstSelector.length - index];+ if (+ instanceSelectors.every(+ (selector) => selector[selector.length - index] === ancestorId+ )+ ) {+ ancestorSelector.unshift(ancestorId);+ continue;+ }+ break;+ }+ return ancestorSelector.length > 0 ? ancestorSelector : undefined;+};- // paste after selected instance- if (- instanceSelector &&- shallowEqual(instanceSelector, data.instanceSelector)- ) {- // body is not allowed to copy- // so clipboard always have at least two level instance selector- const [currentInstanceId, parentInstanceId] = instanceSelector;- const parentInstance = instances.get(parentInstanceId);+const findMultiSelectionInsertable = (+ fragment: WebstudioFragment+): undefined | Insertable => {+ const selectedInstanceSelectors = $allSelectedInstanceSelectors.get();+ if (selectedInstanceSelectors.length < 2) {+ return;+ }+ const instances = $instances.get();+ const selectedPaths = selectedInstanceSelectors+ .map((instanceSelector) => getInstancePath(instanceSelector, instances))+ .filter((path): path is NonNullable<typeof path> => path !== undefined);+ if (selectedPaths.length < 2) {+ return;+ }++ const directParentSelector = selectedPaths[0][1]?.instanceSelector;+ const hasSameDirectParent =+ directParentSelector !== undefined &&+ selectedPaths.every((path) =>+ shallowEqual(path[1]?.instanceSelector, directParentSelector)+ );+ if (hasSameDirectParent) {+ const parentInstance = instances.get(directParentSelector[0]);if (parentInstance === undefined) {return;}- const indexWithinChildren = parentInstance.children.findIndex(- (child) => child.type === "id" && child.value === currentInstanceId+ const selectedSiblingIndexes = selectedPaths.map((path) =>+ getIdChildIndex(parentInstance.children, path[0].instance.id));- return {- parentSelector: instanceSelector.slice(1),- position: indexWithinChildren + 1,- };+ if (selectedSiblingIndexes.includes(-1)) {+ return;+ }+ const lastSelectedSiblingIndex = Math.max(...selectedSiblingIndexes);+ return findPasteTargetForFragment(fragment, {+ parentSelector: directParentSelector,+ position: lastSelectedSiblingIndex + 1,+ });}- const insertable = findClosestInsertable(data);- if (insertable === undefined) {+ const commonAncestorSelector = getCommonAncestorSelector(+ selectedPaths.map((path) => path[0].instanceSelector)+ );+ if (commonAncestorSelector === undefined) {return;}+ return findPasteTargetForFragment(fragment, {+ parentSelector: commonAncestorSelector,+ position: "end",+ });+};++const findSelectionPasteTarget = (fragment: WebstudioFragment) =>+ findMultiSelectionInsertable(fragment) ??+ findPasteTargetForFragment(fragment);++const getCopiedRootInstanceIds = (fragment: WebstudioFragment) => {+ const newInstances: Instances = new Map(+ fragment.instances.map((instance) => [instance.id, instance])+ );+ const copiedRootInstanceIds = new Set<Instance["id"]>();+ for (const child of fragment.children) {+ if (child.type !== "id") {+ continue;+ }+ for (const instanceId of findTreeInstanceIdsExcludingSlotDescendants(+ newInstances,+ child.value+ )) {+ copiedRootInstanceIds.add(instanceId);+ }+ }+ return copiedRootInstanceIds;+};- if (data.instances.length === 0) {+const findPasteTargetForFragment = (+ fragment: WebstudioFragment,+ insertable?: Insertable+): undefined | Insertable => {+ const instances = $instances.get();++ insertable = findClosestInsertable(fragment, insertable);+ if (insertable === undefined) {return;}- const newInstances: Instances = new Map();- for (const instance of data.instances) {- newInstances.set(instance.id, instance);+ if (fragment.instances.length === 0) {+ return;}- const newInstanceIds = findTreeInstanceIdsExcludingSlotDescendants(- newInstances,- data.instances[0].id- );++ const copiedRootInstanceIds = getCopiedRootInstanceIds(fragment);const preservedChildIds = new Set<Instance["id"]>();- for (const instance of data.instances) {+ for (const instance of fragment.instances) {for (const child of instance.children) {- if (child.type === "id" && newInstanceIds.has(child.value) === false) {+ if (+ child.type === "id" &&+ copiedRootInstanceIds.has(child.value) === false+ ) {preservedChildIds.add(child.value);}}@@ -166,8 +356,107 @@ const findPasteTarget = (data: InstanceData): undefined | Insertable => {return insertable;};+const findPasteTarget = (data: InstanceData): undefined | Insertable => {+ const instances = $instances.get();++ const instanceSelector = $selectedInstanceSelector.get();++ // paste after selected instance+ if (+ instanceSelector &&+ shallowEqual(instanceSelector, data.instanceSelector)+ ) {+ // body is not allowed to copy+ // so clipboard always have at least two level instance selector+ const [currentInstanceId, parentInstanceId] = instanceSelector;+ const parentInstance = instances.get(parentInstanceId);+ if (parentInstance === undefined) {+ return;+ }+ const indexWithinChildren = parentInstance.children.findIndex(+ (child) => child.type === "id" && child.value === currentInstanceId+ );+ return {+ parentSelector: instanceSelector.slice(1),+ position: indexWithinChildren + 1,+ };+ }++ return findSelectionPasteTarget(data);+};++const resolveFragmentTokenConflicts = async (fragment: WebstudioFragment) => {+ const conflicts = detectFragmentTokenConflicts({ fragment });+ return conflicts.length > 0+ ? await builderApi.showTokenConflictDialog(conflicts)+ : "theirs";+};+const handlePasteInstance = async (clipboardData: string) => {const project = $project.get();+ const multiRootFragment = parseMultiRoot(clipboardData);+ if (multiRootFragment !== undefined) {+ if (project === undefined) {+ return false;+ }+ const pasteRootInstanceIds = getPasteRootInstanceIds(multiRootFragment);+ if (pasteRootInstanceIds.length === 0) {+ return false;+ }+ const pasteTarget = findSelectionPasteTarget(multiRootFragment.fragment);+ if (pasteTarget === undefined) {+ return false;+ }++ try {+ const conflictResolution = await resolveFragmentTokenConflicts(+ multiRootFragment.fragment+ );+ let didInsert = false;+ updateWebstudioData((data) => {+ const { newInstanceIds } = insertWebstudioFragmentCopy({+ data,+ fragment: multiRootFragment.fragment,+ availableVariables: findAvailableVariables({+ ...data,+ startingInstanceId: pasteTarget.parentSelector[0],+ }),+ projectId: project.id,+ conflictResolution,+ onBreakpointLimitMerge: () => {+ toast.warn(breakpointPasteLimitWarning);+ },+ });+ const children: Instance["children"] = [];+ const newSelectedSelectors: InstanceSelector[] = [];+ for (const rootInstanceId of pasteRootInstanceIds) {+ const newRootInstanceId = newInstanceIds.get(rootInstanceId);+ if (newRootInstanceId === undefined) {+ continue;+ }+ children.push({ type: "id", value: newRootInstanceId });+ newSelectedSelectors.push([+ newRootInstanceId,+ ...pasteTarget.parentSelector,+ ]);+ }+ if (children.length === 0) {+ return;+ }+ insertInstanceChildrenMutable(data, children, pasteTarget);+ selectInstances(newSelectedSelectors);+ didInsert = true;+ });+ if (didInsert === false) {+ return false;+ }+ } catch (error) {+ // User cancelled+ return false;+ }++ return true;+ }const fragment = parse(clipboardData);if (fragment === undefined || project === undefined) {return false;@@ -179,11 +468,8 @@ const handlePasteInstance = async (clipboardData: string) => {}try {- const conflicts = detectFragmentTokenConflicts({ fragment });- const conflictResolution =- conflicts.length > 0- ? await builderApi.showTokenConflictDialog(conflicts)- : "theirs";+ const conflictResolution = await resolveFragmentTokenConflicts(fragment);+ let didInsert = false;updateWebstudioData((data) => {const { newInstanceIds } = insertWebstudioFragmentCopy({data,@@ -206,7 +492,12 @@ const handlePasteInstance = async (clipboardData: string) => {{ type: "id", value: newRootInstanceId },];insertInstanceChildrenMutable(data, children, pasteTarget);+ selectInstances([[newRootInstanceId, ...pasteTarget.parentSelector]]);+ didInsert = true;});+ if (didInsert === false) {+ return false;+ }} catch (error) {// User cancelledreturn false;@@ -216,18 +507,75 @@ const handlePasteInstance = async (clipboardData: string) => {};const handleCopyInstance = () => {- const selectedInstanceSelector = $selectedInstanceSelector.get();- if (selectedInstanceSelector === undefined) {+ const selectedInstanceSelectors = $allSelectedInstanceSelectors.get();+ if (selectedInstanceSelectors.length === 0) {return;}- const data = getTreeData(selectedInstanceSelector);- if (data === undefined) {+ if (selectedInstanceSelectors.length === 1) {+ const data = getTreeData(selectedInstanceSelectors[0]);+ if (data === undefined) {+ return;+ }+ return stringify(data);+ }++ const selectedData = selectedInstanceSelectors+ .map((instanceSelector) =>+ getTreeData(instanceSelector, { showToast: false })+ )+ .filter((data): data is InstanceData => data !== undefined);+ if (selectedData.length === 0) {return;}- return stringify(data);+ if (selectedData.length < selectedInstanceSelectors.length) {+ reportSkippedSelectedInstances("copied");+ }+ return stringifyMultiRootSelection(selectedData);};const handleCutInstance = () => {+ const selectedInstanceSelectors = $allSelectedInstanceSelectors.get();+ if (selectedInstanceSelectors.length > 1) {+ const instances = $instances.get();+ const selectedPaths = selectedInstanceSelectors+ .map((instanceSelector) => {+ const data = getTreeData(instanceSelector, { showToast: false });+ const instancePath =+ data === undefined+ ? undefined+ : getInstancePath(data.instanceSelector, instances);+ if (data === undefined || instancePath === undefined) {+ return;+ }+ return { data, instancePath };+ })+ .filter(+ (+ item+ ): item is {+ data: InstanceData;+ instancePath: NonNullable<ReturnType<typeof getInstancePath>>;+ } => item !== undefined+ );+ if (selectedPaths.length === 0) {+ return;+ }+ const selectedPathData = selectedPaths.map(({ data }) => data);+ if (selectedPathData.length < selectedInstanceSelectors.length) {+ reportSkippedSelectedInstances("cut");+ }+ const clipboardData = stringifyMultiRootSelection(selectedPathData);+ updateInstanceData((data) => {+ for (const { instancePath } of sortInstancePathsForChildMutation(+ selectedPaths+ )) {+ deleteInstanceMutable(data, instancePath);+ }+ clearInstanceSelection();+ });+ return clipboardData;+ }+const instancePath = $selectedInstancePath.get();if (instancePath === undefined) {return;diff --git a/apps/builder/app/shared/copy-paste/plugin-page.test.ts b/apps/builder/app/shared/copy-paste/plugin-page.test.tsindex ae4aad4544..14a0bc1865 100644--- a/apps/builder/app/shared/copy-paste/plugin-page.test.ts+++ b/apps/builder/app/shared/copy-paste/plugin-page.test.ts@@ -25,7 +25,7 @@ import {import {$editingPageId,$editingTemplateId,- $selectedInstanceSelector,+ selectInstance,$selectedPageId,} from "../nano-states";import {@@ -51,7 +51,7 @@ const resetBuildStores = () => {$assets.set(new Map());$editingPageId.set(undefined);$editingTemplateId.set(undefined);- $selectedInstanceSelector.set(undefined);+ selectInstance(undefined);$selectedPageId.set(undefined);};@@ -70,7 +70,7 @@ test("copies the selected page root from the copy plugin", () => {page.name = "Selected Page";$pages.set(pages);$selectedPageId.set("source-page");- $selectedInstanceSelector.set(["source-root"]);+ selectInstance(["source-root"]);$instances.set(new Map<Instance["id"], Instance>([[diff --git a/apps/builder/app/shared/dom-utils.ts b/apps/builder/app/shared/dom-utils.tsindex 1692d0ed5a..a426150fe8 100644--- a/apps/builder/app/shared/dom-utils.ts+++ b/apps/builder/app/shared/dom-utils.ts@@ -133,9 +133,14 @@ const sumRects = (first: Rect, second: Rect) => {};};-export const getAllElementsBoundingBox = (+type BoundingBoxOptions = {+ fallbackToParent?: boolean;+};++const getElementsBoundingBox = (elements: Element[],- depth: number = 0+ options: BoundingBoxOptions,+ depth: number): DOMRect => {const rects: Rect[] = [];@@ -173,8 +178,9 @@ export const getAllElementsBoundingBox = (}if (element.children.length > 0) {- const childRect = getAllElementsBoundingBox(+ const childRect = getElementsBoundingBox([...element.children],+ options,depth + 1);if (childRect.width !== 0 || childRect.height !== 0) {@@ -184,7 +190,7 @@ export const getAllElementsBoundingBox = (}}- if (depth > 0) {+ if (depth > 0 || options.fallbackToParent === false) {continue;}@@ -193,7 +199,7 @@ export const getAllElementsBoundingBox = (if (parentElement === null) {continue;}- const parentRect = getAllElementsBoundingBox([parentElement]);+ const parentRect = getElementsBoundingBox([parentElement], {}, 0);if (parentRect.width !== 0 || parentRect.height !== 0) {const { top, right, bottom, left } = parentRect;@@ -217,6 +223,13 @@ export const getAllElementsBoundingBox = (});};+export const getAllElementsBoundingBox = (+ elements: Element[],+ options: BoundingBoxOptions = {}+): DOMRect => {+ return getElementsBoundingBox(elements, options, 0);+};+const doNotTrackMutationAttribute = "data-ws-do-not-track-mutation";export const doNotTrackMutation = (element: Element) => {diff --git a/apps/builder/app/shared/instance-utils/insert.test.tsx b/apps/builder/app/shared/instance-utils/insert.test.tsxindex ab6994e32d..22d0733aa4 100644--- a/apps/builder/app/shared/instance-utils/insert.test.tsx+++ b/apps/builder/app/shared/instance-utils/insert.test.tsx@@ -42,7 +42,7 @@ import {$resources,} from "~/shared/sync/data-stores";import { registerContainers } from "../sync/sync-stores";-import { $selectedInstanceSelector, getInstancePath } from "../nano-states";+import { getInstancePath } from "../nano-states";import { selectPage } from "../nano-states";import { selectInstance } from "../nano-states";import { $selectedPageId } from "../nano-states/pages";@@ -932,11 +932,7 @@ describe("find closest insertable", () => {}));$selectedPageId.set("homePageId");- $selectedInstanceSelector.set([- "collectionId[1]",- "collectionId",- "bodyId",- ]);+ selectInstance(["collectionId[1]", "collectionId", "bodyId"]);$registeredComponentMetas.set(defaultMetasMap);});diff --git a/apps/builder/app/shared/instance-utils/mutation.ts b/apps/builder/app/shared/instance-utils/mutation.tsindex de9e3ae5f2..fb3dab714e 100644--- a/apps/builder/app/shared/instance-utils/mutation.ts+++ b/apps/builder/app/shared/instance-utils/mutation.ts@@ -415,6 +415,39 @@ export const deleteInstanceMutable = (return true;};+const getIdChildIndex = (children: Instance["children"], instanceId: string) =>+ children.findIndex(+ (child) => child.type === "id" && child.value === instanceId+ );++const getInstancePathSiblingIndex = (instancePath: InstancePath) => {+ const selectedItem = instancePath[0];+ const parentItem = instancePath[1];+ if (parentItem === undefined) {+ return -1;+ }+ return getIdChildIndex(+ parentItem.instance.children,+ selectedItem.instance.id+ );+};++export const sortInstancePathsForChildMutation = <+ Item extends { instancePath: InstancePath },+>(+ items: Item[]+) =>+ [...items].sort((left, right) => {+ const depthDiff = right.instancePath.length - left.instancePath.length;+ if (depthDiff !== 0) {+ return depthDiff;+ }+ return (+ getInstancePathSiblingIndex(right.instancePath) -+ getInstancePathSiblingIndex(left.instancePath)+ );+ });+const cloneSharedSlotFragmentMutable = (data: Omit<WebstudioData, "pages">,slotId: Instance["id"],diff --git a/apps/builder/app/shared/instance-utils/selection.test.ts b/apps/builder/app/shared/instance-utils/selection.test.tsnew file mode 100644index 0000000000..aa86bea602--- /dev/null+++ b/apps/builder/app/shared/instance-utils/selection.test.ts@@ -0,0 +1,30 @@+import { describe, expect, test } from "vitest";+import { getContextMenuSelectedInstanceSelectors } from "./selection";++describe("getContextMenuSelectedInstanceSelectors", () => {+ test("preserves selected set when context menu opens on a selected instance", () => {+ const selectedSelectors = [+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ];++ expect(+ getContextMenuSelectedInstanceSelectors({+ selectedSelectors,+ clickedSelector: ["heading", "section", "body"],+ })+ ).toBe(selectedSelectors);+ });++ test("selects only the clicked instance when context menu opens on an unselected instance", () => {+ expect(+ getContextMenuSelectedInstanceSelectors({+ selectedSelectors: [+ ["box", "section", "body"],+ ["heading", "section", "body"],+ ],+ clickedSelector: ["footer", "body"],+ })+ ).toEqual([["footer", "body"]]);+ });+});diff --git a/apps/builder/app/shared/instance-utils/selection.ts b/apps/builder/app/shared/instance-utils/selection.tsnew file mode 100644index 0000000000..113959da07--- /dev/null+++ b/apps/builder/app/shared/instance-utils/selection.ts@@ -0,0 +1,215 @@+import { ROOT_INSTANCE_ID, type Instances } from "@webstudio-is/sdk";+import {+ areInstanceSelectorsEqual,+ isDescendantOrSelf,+ type InstanceSelector,+} from "./tree";++export const areSelectorListsEqual = (+ left: InstanceSelector[],+ right: InstanceSelector[]+) => {+ if (left.length !== right.length) {+ return false;+ }+ return left.every((selector, index) =>+ areInstanceSelectorsEqual(selector, right[index])+ );+};++const getSelectorKey = (selector: InstanceSelector) => JSON.stringify(selector);++const sortSelectorsByOrder = (+ selectors: InstanceSelector[],+ orderedSelectors: InstanceSelector[]+) => {+ const order = new Map(+ orderedSelectors.map((selector, index) => [getSelectorKey(selector), index])+ );+ return [...selectors].sort((left, right) => {+ const leftIndex = order.get(getSelectorKey(left)) ?? Infinity;+ const rightIndex = order.get(getSelectorKey(right)) ?? Infinity;+ return leftIndex - rightIndex;+ });+};++export const getInstanceSelectionUpdate = ({+ selectedSelectors,+ clickedSelector,+ orderedSelectors,+ anchorSelector,+ isToggle,+ isRange,+}: {+ selectedSelectors: InstanceSelector[];+ clickedSelector: InstanceSelector;+ orderedSelectors: InstanceSelector[];+ anchorSelector: undefined | InstanceSelector;+ isToggle: boolean;+ isRange: boolean;+}) => {+ if (isRange && anchorSelector !== undefined) {+ const anchorIndex = orderedSelectors.findIndex((selector) =>+ areInstanceSelectorsEqual(selector, anchorSelector)+ );+ const clickedIndex = orderedSelectors.findIndex((selector) =>+ areInstanceSelectorsEqual(selector, clickedSelector)+ );+ if (anchorIndex !== -1 && clickedIndex !== -1) {+ const start = Math.min(anchorIndex, clickedIndex);+ const end = Math.max(anchorIndex, clickedIndex);+ const rangeSelectors = orderedSelectors.slice(start, end + 1);+ return {+ selectedSelectors: sortSelectorsByOrder(+ [+ ...selectedSelectors.filter(+ (selector) =>+ rangeSelectors.some((rangeSelector) =>+ areInstanceSelectorsEqual(selector, rangeSelector)+ ) === false+ ),+ ...rangeSelectors,+ ],+ orderedSelectors+ ),+ anchorSelector: clickedSelector,+ };+ }+ }++ if (isToggle) {+ const isSelected = selectedSelectors.some((selector) =>+ areInstanceSelectorsEqual(selector, clickedSelector)+ );+ const nextSelectedSelectors = isSelected+ ? selectedSelectors.filter(+ (selector) =>+ areInstanceSelectorsEqual(selector, clickedSelector) === false+ )+ : [...selectedSelectors, clickedSelector];+ return {+ selectedSelectors: sortSelectorsByOrder(+ nextSelectedSelectors,+ orderedSelectors+ ),+ anchorSelector: clickedSelector,+ };+ }++ return {+ selectedSelectors: [clickedSelector],+ anchorSelector: clickedSelector,+ };+};++export const normalizeInstanceSelectors = (+ instanceSelectors: InstanceSelector[]+) => {+ const normalized: InstanceSelector[] = [];++ for (const instanceSelector of instanceSelectors) {+ if (normalized[0]?.[0] === ROOT_INSTANCE_ID) {+ continue;+ }++ if (+ instanceSelector.length === 1 &&+ instanceSelector[0] === ROOT_INSTANCE_ID+ ) {+ normalized.splice(0, normalized.length, instanceSelector);+ continue;+ }++ const hasSelectedAncestor = normalized.some((selectedSelector) =>+ isDescendantOrSelf(instanceSelector, selectedSelector)+ );+ if (hasSelectedAncestor) {+ continue;+ }++ let removedSelectedDescendant = false;+ for (let index = normalized.length - 1; index >= 0; index -= 1) {+ const selectedSelector = normalized[index];+ if (isDescendantOrSelf(selectedSelector, instanceSelector)) {+ normalized.splice(index, 1);+ removedSelectedDescendant = true;+ }+ }++ if (removedSelectedDescendant) {+ normalized.splice(0, normalized.length);+ }++ normalized.push(instanceSelector);+ }++ return normalized;+};++const indexedInstanceIdPattern = /^(.*)\[[^\]]+\]$/;++const getIndexedBaseInstanceId = (instanceId: InstanceSelector[number]) =>+ indexedInstanceIdPattern.exec(instanceId)?.[1];++const isKnownSelectorSegment = (+ instanceSelector: InstanceSelector,+ index: number,+ instances: Instances+) => {+ const instanceId = instanceSelector[index];+ if (instanceId === ROOT_INSTANCE_ID || instances.has(instanceId)) {+ return true;+ }+ const baseInstanceId = getIndexedBaseInstanceId(instanceId);+ return (+ baseInstanceId !== undefined &&+ instanceSelector[index + 1] === baseInstanceId &&+ instances.has(baseInstanceId)+ );+};++export const canResolveInstanceSelector = (+ instanceSelector: InstanceSelector,+ instances: Instances+) => {+ for (let index = 0; index < instanceSelector.length; index += 1) {+ if (isKnownSelectorSegment(instanceSelector, index, instances) === false) {+ return false;+ }++ const parentId = instanceSelector[index + 1];+ if (parentId === undefined) {+ continue;+ }++ const instanceId = instanceSelector[index];+ const baseInstanceId = getIndexedBaseInstanceId(instanceId);+ if (baseInstanceId !== undefined && parentId === baseInstanceId) {+ continue;+ }++ const parentInstance = instances.get(parentId);+ if (+ parentInstance?.children.some(+ (child) => child.type === "id" && child.value === instanceId+ ) !== true+ ) {+ return false;+ }+ }++ return true;+};++export const getContextMenuSelectedInstanceSelectors = ({+ selectedSelectors,+ clickedSelector,+}: {+ selectedSelectors: InstanceSelector[];+ clickedSelector: InstanceSelector;+}) => {+ const isClickedAlreadySelected = selectedSelectors.some((selector) =>+ areInstanceSelectorsEqual(selector, clickedSelector)+ );+ return isClickedAlreadySelected ? selectedSelectors : [clickedSelector];+};diff --git a/apps/builder/app/shared/instance-utils/tree.ts b/apps/builder/app/shared/instance-utils/tree.tsindex 7c3e9aa58a..7223831d03 100644--- a/apps/builder/app/shared/instance-utils/tree.ts+++ b/apps/builder/app/shared/instance-utils/tree.ts@@ -27,10 +27,12 @@ export const areInstanceSelectorsEqual = (left?: InstanceSelector,right?: InstanceSelector) => {- if (left === undefined || right === undefined) {- return false;- }- return left.join(",") === right.join(",");+ return (+ left !== undefined &&+ right !== undefined &&+ left.length === right.length &&+ left.every((instanceId, index) => instanceId === right[index])+ );};export const isDescendantOrSelf = (diff --git a/apps/builder/app/shared/nano-states/canvas.ts b/apps/builder/app/shared/nano-states/canvas.tsindex 7bdcab0968..135caf9785 100644--- a/apps/builder/app/shared/nano-states/canvas.ts+++ b/apps/builder/app/shared/nano-states/canvas.ts@@ -2,6 +2,7 @@ import { atom, computed } from "nanostores";import type { Instance, Instances } from "@webstudio-is/sdk";import { blockComponent, blockTemplateComponent } from "@webstudio-is/sdk";import type { FontWeight } from "@webstudio-is/fonts";+import type { Rect } from "@webstudio-is/design-system";import { $instances } from "../sync/data-stores";import type { InstanceSelector } from "../instance-utils/tree";@@ -19,7 +20,11 @@ export const $textToolbar = atom<undefined | TextToolbarState>(undefined);type InstanceOutline = {instanceId: Instance["id"];- rect: DOMRect;+ rect: Rect;+};++export type SelectedInstanceOutline = InstanceOutline & {+ selector: InstanceSelector;};export type BlockChildOutline = {@@ -50,6 +55,8 @@ export const $selectedInstanceOutline = atom<undefined | InstanceOutline>(undefined);+export const $selectedInstanceOutlines = atom<SelectedInstanceOutline[]>([]);+export const $selectedInstanceOutlineAndInstance = computed([$instances, $selectedInstanceOutline],getInstanceOutlineAndInstancediff --git a/apps/builder/app/shared/nano-states/instance-selection.test.ts b/apps/builder/app/shared/nano-states/instance-selection.test.tsnew file mode 100644index 0000000000..91f5052395--- /dev/null+++ b/apps/builder/app/shared/nano-states/instance-selection.test.ts@@ -0,0 +1,328 @@+import { beforeEach, describe, expect, test } from "vitest";+import type { Instance } from "@webstudio-is/sdk";+import { $instances, $pages } from "../sync/data-stores";+import {+ $allSelectedInstanceSelectors,+ $selectedInstance,+ $selectedInstanceKey,+ $selectedInstancePath,+ $selectedInstanceSelector,+ clearInstanceSelection,+ selectInstance,+ selectInstances,+ toggleSelectedInstance,+} from "./instances";+import { $selectedPageId } from "./pages";++const createInstance = (+ id: Instance["id"],+ children: Instance["children"] = []+): Instance => ({+ type: "instance",+ id,+ component: "Box",+ children,+});++beforeEach(() => {+ $instances.set(new Map());+ $pages.set(undefined);+ $selectedPageId.set(undefined);+ selectInstance(undefined);+});++describe("selectInstance", () => {+ test("selects and clears the selected instance selector through canonical state", () => {+ selectInstance(["box", "body"]);+ expect($allSelectedInstanceSelectors.get()).toEqual([["box", "body"]]);+ expect($selectedInstanceSelector.get()).toEqual(["box", "body"]);++ selectInstance(undefined);+ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ expect($selectedInstanceSelector.get()).toBeUndefined();+ });++ test("does not notify listeners when selecting the same selector", () => {+ const selections: Array<undefined | readonly Instance["id"][]> = [];+ const unsubscribe = $selectedInstanceSelector.listen((selector) => {+ selections.push(selector);+ });++ selectInstance(["box", "body"]);+ selectInstance(["box", "body"]);++ unsubscribe();+ expect(selections).toEqual([["box", "body"]]);+ });+});++describe("selectInstances", () => {+ test("stores all selected selectors and projects single selection only for one selected instance", () => {+ selectInstances([+ ["box", "body"],+ ["heading", "body"],+ ]);++ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ]);+ expect($selectedInstanceSelector.get()).toBeUndefined();++ selectInstances([["box", "body"]]);++ expect($selectedInstanceSelector.get()).toEqual(["box", "body"]);+ });++ test("clears with empty array and clear helper", () => {+ selectInstances([["box", "body"]]);++ selectInstances([]);+ expect($allSelectedInstanceSelectors.get()).toEqual([]);++ selectInstances([["box", "body"]]);+ clearInstanceSelection();+ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ });++ test("deduplicates selectors while preserving first occurrence order", () => {+ selectInstances([+ ["box", "body"],+ ["heading", "body"],+ ["box", "body"],+ ]);++ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ]);+ });++ test("does not treat selectors with comma-containing ids as duplicates", () => {+ selectInstances([+ ["a,b", "c"],+ ["a", "b,c"],+ ]);++ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["a,b", "c"],+ ["a", "b,c"],+ ]);+ });++ test("normalizes ancestor and descendant selections", () => {+ selectInstances([+ ["child", "parent", "body"],+ ["parent", "body"],+ ]);+ expect($allSelectedInstanceSelectors.get()).toEqual([["parent", "body"]]);++ selectInstances([+ ["parent", "body"],+ ["child", "parent", "body"],+ ]);+ expect($allSelectedInstanceSelectors.get()).toEqual([["parent", "body"]]);++ selectInstances([+ ["child", "parent", "body"],+ ["footer", "body"],+ ["parent", "body"],+ ]);+ expect($allSelectedInstanceSelectors.get()).toEqual([["parent", "body"]]);+ });++ test("collapses selection to a root selector when one is selected with other instances", () => {+ selectInstances([["box", "body"], [":root"]]);+ expect($allSelectedInstanceSelectors.get()).toEqual([[":root"]]);++ selectInstances([[":root"], ["box", "body"]]);+ expect($allSelectedInstanceSelectors.get()).toEqual([[":root"]]);+ });++ test("collapses selection to page body when selected with its descendants", () => {+ selectInstances([["box", "body"], ["heading", "body"], ["body"]]);+ expect($allSelectedInstanceSelectors.get()).toEqual([["body"]]);++ selectInstances([["body"], ["box", "body"]]);+ expect($allSelectedInstanceSelectors.get()).toEqual([["body"]]);+ });+});++describe("selection store invariants", () => {+ test("clears selection when selected page changes", () => {+ selectInstances([+ ["box", "body"],+ ["heading", "body"],+ ]);++ $selectedPageId.set("page-id");++ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ });++ test("prunes selected selectors that no longer resolve", () => {+ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ ],+ ["box", createInstance("box")],+ ["heading", createInstance("heading")],+ ])+ );+ selectInstances([+ ["box", "body"],+ ["heading", "body"],+ ]);++ $instances.set(+ new Map([+ ["body", createInstance("body", [{ type: "id", value: "heading" }])],+ ["heading", createInstance("heading")],+ ])+ );++ expect($allSelectedInstanceSelectors.get()).toEqual([["heading", "body"]]);+ });++ test("prunes selected selectors whose parent-child path no longer resolves", () => {+ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", [+ { type: "id", value: "section" },+ { type: "id", value: "footer" },+ ]),+ ],+ ["section", createInstance("section", [{ type: "id", value: "box" }])],+ ["footer", createInstance("footer")],+ ["box", createInstance("box")],+ ])+ );+ selectInstances([["box", "section", "body"]]);++ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", [+ { type: "id", value: "section" },+ { type: "id", value: "footer" },+ ]),+ ],+ ["section", createInstance("section")],+ ["footer", createInstance("footer", [{ type: "id", value: "box" }])],+ ["box", createInstance("box")],+ ])+ );++ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ });++ test("keeps virtual collection item selectors when their base instance still exists", () => {+ $instances.set(+ new Map([+ ["body", createInstance("body", [{ type: "id", value: "collection" }])],+ ["collection", createInstance("collection")],+ ])+ );+ selectInstances([["collection[1]", "collection", "body"]]);++ $instances.set(+ new Map([+ ["body", createInstance("body", [{ type: "id", value: "collection" }])],+ ["collection", createInstance("collection")],+ ])+ );++ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["collection[1]", "collection", "body"],+ ]);++ $instances.set(new Map([["body", createInstance("body")]]));++ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ });+});++describe("toggleSelectedInstance", () => {+ test("adds and removes selected selectors", () => {+ toggleSelectedInstance(["box", "body"]);+ expect($allSelectedInstanceSelectors.get()).toEqual([["box", "body"]]);++ toggleSelectedInstance(["heading", "body"]);+ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ]);++ toggleSelectedInstance(["box", "body"]);+ expect($allSelectedInstanceSelectors.get()).toEqual([["heading", "body"]]);++ toggleSelectedInstance(["heading", "body"]);+ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ });+});++describe("selected instance derived state", () => {+ test("derives selected instance, key, and path from selected selector", () => {+ $instances.set(+ new Map([+ ["body", createInstance("body", [{ type: "id", value: "box" }])],+ ["box", createInstance("box", [{ type: "id", value: "child" }])],+ ["child", createInstance("child")],+ ])+ );++ selectInstance(["child", "box", "body"]);++ expect($selectedInstance.get()?.id).toBe("child");+ expect($selectedInstanceKey.get()).toBe(+ JSON.stringify(["child", "box", "body"])+ );+ expect(+ $selectedInstancePath.get()?.map(({ instance }) => instance.id)+ ).toEqual(["child", "box", "body"]);+ });++ test("clears selected instance, key, and path when selection is cleared", () => {+ $instances.set(new Map([["box", createInstance("box")]]));++ selectInstance(["box"]);+ selectInstance(undefined);++ expect($selectedInstance.get()).toBeUndefined();+ expect($selectedInstanceKey.get()).toBeUndefined();+ expect($selectedInstancePath.get()).toBeUndefined();+ });++ test("does not derive a particular selected instance from multi-selection", () => {+ $instances.set(+ new Map([+ [+ "body",+ createInstance("body", [+ { type: "id", value: "box" },+ { type: "id", value: "heading" },+ ]),+ ],+ ["box", createInstance("box")],+ ["heading", createInstance("heading")],+ ])+ );++ selectInstances([+ ["box", "body"],+ ["heading", "body"],+ ]);++ expect($selectedInstance.get()).toBeUndefined();+ expect($selectedInstanceKey.get()).toBeUndefined();+ expect($selectedInstancePath.get()).toBeUndefined();+ });+});diff --git a/apps/builder/app/shared/nano-states/instance-selection.ts b/apps/builder/app/shared/nano-states/instance-selection.tsindex c841b3c247..e8d6aa839a 100644--- a/apps/builder/app/shared/nano-states/instance-selection.ts+++ b/apps/builder/app/shared/nano-states/instance-selection.ts@@ -1,16 +1,75 @@-import { atom } from "nanostores";-import type { InstanceSelector } from "../instance-utils/tree";+import { atom, computed } from "nanostores";+import {+ areInstanceSelectorsEqual,+ type InstanceSelector,+} from "../instance-utils/tree";+import {+ areSelectorListsEqual,+ canResolveInstanceSelector,+ normalizeInstanceSelectors,+} from "../instance-utils/selection";+import { $instances } from "../sync/data-stores";-export const $selectedInstanceSelector = atom<undefined | InstanceSelector>(- undefined+export const $allSelectedInstanceSelectors = atom<InstanceSelector[]>([]);++export const $selectedInstanceSelector = computed(+ $allSelectedInstanceSelectors,+ (instanceSelectors) => {+ if (instanceSelectors.length === 1) {+ return instanceSelectors[0];+ }+ });+export const selectInstances = (instanceSelectors: InstanceSelector[]) => {+ const normalizedSelectors = normalizeInstanceSelectors(instanceSelectors);+ if (+ areSelectorListsEqual(+ $allSelectedInstanceSelectors.get(),+ normalizedSelectors+ ) === false+ ) {+ $allSelectedInstanceSelectors.set(normalizedSelectors);+ }+};++export const clearInstanceSelection = () => {+ selectInstances([]);+};+export const selectInstance = (instanceSelector: undefined | InstanceSelector) => {- // prevent triggering select across the builder when selector is the same- // useful when click and focus events have to select instance- if ($selectedInstanceSelector.get()?.join() !== instanceSelector?.join()) {- $selectedInstanceSelector.set(instanceSelector);+ if (instanceSelector === undefined) {+ clearInstanceSelection();+ return;}+ selectInstances([instanceSelector]);};++export const toggleSelectedInstance = (instanceSelector: InstanceSelector) => {+ const selectedSelectors = $allSelectedInstanceSelectors.get();+ const selectedIndex = selectedSelectors.findIndex((selectedSelector) =>+ areInstanceSelectorsEqual(selectedSelector, instanceSelector)+ );+ if (selectedIndex === -1) {+ selectInstances([...selectedSelectors, instanceSelector]);+ return;+ }++ const nextSelectedSelectors = [...selectedSelectors];+ nextSelectedSelectors.splice(selectedIndex, 1);+ selectInstances(nextSelectedSelectors);+};++$instances.listen((instances) => {+ const selectedSelectors = $allSelectedInstanceSelectors.get();+ if (selectedSelectors.length === 0) {+ return;+ }+ selectInstances(+ selectedSelectors.filter((instanceSelector) =>+ canResolveInstanceSelector(instanceSelector, instances)+ )+ );+});diff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.tsindex 0bdd8114f9..c44b8232d0 100644--- a/apps/builder/app/shared/nano-states/instances.ts+++ b/apps/builder/app/shared/nano-states/instances.ts@@ -10,8 +10,12 @@ import type { InstanceSelector } from "../instance-utils/tree";import { $selectedPage } from "./pages";import { $selectedInstanceSelector } from "./instance-selection";export {+ $allSelectedInstanceSelectors,$selectedInstanceSelector,+ clearInstanceSelection,selectInstance,+ selectInstances,+ toggleSelectedInstance,} from "./instance-selection";export const $isResizingCanvas = atom(false);diff --git a/apps/builder/app/shared/nano-states/pages.test.ts b/apps/builder/app/shared/nano-states/pages.test.tsnew file mode 100644index 0000000000..093be6a725--- /dev/null+++ b/apps/builder/app/shared/nano-states/pages.test.ts@@ -0,0 +1,71 @@+import { beforeEach, describe, expect, test } from "vitest";+import { createDefaultPages } from "@webstudio-is/project-build";+import { $pages } from "../sync/data-stores";+import {+ $allSelectedInstanceSelectors,+ $selectedInstanceSelector,+ selectInstance,+ selectInstances,+} from "./instances";+import { $selectedPageId, selectPage } from "./pages";++beforeEach(() => {+ $pages.set(undefined);+ $selectedPageId.set(undefined);+ selectInstance(undefined);+});++describe("selectPage", () => {+ test("selects page by id and selects the page root instance", () => {+ const pages = createDefaultPages({+ homePageId: "home-page",+ rootInstanceId: "body-id",+ });+ $pages.set(pages);++ selectPage("home-page");++ expect($selectedPageId.get()).toBe("home-page");+ expect($selectedInstanceSelector.get()).toEqual(["body-id"]);+ });++ test("selects page by path and selects the page root instance", () => {+ const pages = createDefaultPages({+ homePageId: "home-page",+ rootInstanceId: "body-id",+ });+ $pages.set(pages);++ selectPage("/");++ expect($selectedPageId.get()).toBe("home-page");+ expect($selectedInstanceSelector.get()).toEqual(["body-id"]);+ });++ test("leaves current page and instance selection unchanged for unknown page", () => {+ const pages = createDefaultPages({+ homePageId: "home-page",+ rootInstanceId: "body-id",+ });+ $pages.set(pages);+ $selectedPageId.set("home-page");+ selectInstance(["box-id", "body-id"]);++ selectPage("missing-page");++ expect($selectedPageId.get()).toBe("home-page");+ expect($selectedInstanceSelector.get()).toEqual(["box-id", "body-id"]);+ });++ test("clears multi-selection when selected page id changes", () => {+ selectInstances([+ ["box-id", "body-id"],+ ["heading-id", "body-id"],+ ]);++ $selectedPageId.set("other-page");++ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ expect($selectedInstanceSelector.get()).toBeUndefined();+ });+});diff --git a/apps/builder/app/shared/nano-states/pages.ts b/apps/builder/app/shared/nano-states/pages.tsindex 747f02ca51..fde14e2d40 100644--- a/apps/builder/app/shared/nano-states/pages.ts+++ b/apps/builder/app/shared/nano-states/pages.ts@@ -9,12 +9,16 @@ import {isPage,} from "@webstudio-is/sdk";import { $pages } from "../sync/data-stores";-import { $selectedInstanceSelector } from "./instance-selection";+import { clearInstanceSelection, selectInstance } from "./instance-selection";export const $selectedPageId = atom<undefined | Page["id"] | PageTemplate["id"]>(undefined);+$selectedPageId.listen(() => {+ clearInstanceSelection();+});+export const $selectedPageHash = atom<{ hash: string }>({ hash: "" });export const $editingPageId = atom<undefined | Page["id"]>();@@ -68,5 +72,5 @@ export const selectPage = (pageId: Page["id"] | PageTemplate["id"]) => {return;}$selectedPageId.set(page.id);- $selectedInstanceSelector.set([page.rootInstanceId]);+ selectInstance([page.rootInstanceId]);};diff --git a/apps/builder/app/shared/sync/sync-stores.test.ts b/apps/builder/app/shared/sync/sync-stores.test.tsindex 690267e1ac..0de7565aae 100644--- a/apps/builder/app/shared/sync/sync-stores.test.ts+++ b/apps/builder/app/shared/sync/sync-stores.test.ts@@ -1,6 +1,13 @@import { afterEach, describe, expect, test, vi } from "vitest";-import { $selectedInstanceSelector, $selectedPageId } from "../nano-states";-import { __testing__ } from "./sync-stores";+import {+ $allSelectedInstanceSelectors,+ $selectedInstanceOutlines,+ $selectedInstanceSelector,+ $selectedPageId,+ selectInstance,+ selectInstances,+} from "../nano-states";+import { __testing__, createObjectPool } from "./sync-stores";const { SelectedPageAndInstanceSyncObject } = __testing__;@@ -11,7 +18,9 @@ const waitForBatchedStore = () =>afterEach(() => {$selectedPageId.set(undefined);- $selectedInstanceSelector.set(undefined);+ selectInstance(undefined);+ $allSelectedInstanceSelectors.set([]);+ $selectedInstanceOutlines.set([]);});describe("SelectedPageAndInstanceSyncObject", () => {@@ -24,7 +33,7 @@ describe("SelectedPageAndInstanceSyncObject", () => {sendTransaction.mockClear();$selectedPageId.set("page-a");- $selectedInstanceSelector.set(["body-a"]);+ selectInstance(["body-a"]);await waitForBatchedStore();@@ -35,6 +44,7 @@ describe("SelectedPageAndInstanceSyncObject", () => {payload: {selectedPageId: "page-a",selectedInstanceSelector: ["body-a"],+ allSelectedInstanceSelectors: [["body-a"]],},});});@@ -53,6 +63,7 @@ describe("SelectedPageAndInstanceSyncObject", () => {payload: {selectedPageId: "page-b",selectedInstanceSelector: ["body-b"],+ allSelectedInstanceSelectors: [["body-b"]],},});@@ -64,6 +75,82 @@ describe("SelectedPageAndInstanceSyncObject", () => {expect(sendTransaction).not.toHaveBeenCalled();});+ test("applies undefined instance selector as cleared selection", async () => {+ const syncObject = new SelectedPageAndInstanceSyncObject();++ $selectedPageId.set("page-before");+ selectInstance(["body-before"]);++ syncObject.applyTransaction({+ id: "selection",+ object: "selectedPageAndInstance",+ payload: {+ selectedPageId: "page-after",+ selectedInstanceSelector: undefined,+ allSelectedInstanceSelectors: [],+ },+ });++ expect($selectedPageId.get()).toBe("page-after");+ expect($selectedInstanceSelector.get()).toBeUndefined();+ expect($allSelectedInstanceSelectors.get()).toEqual([]);+ });++ 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();++ $selectedPageId.set("page-a");+ selectInstances([+ ["box-a", "body-a"],+ ["heading-a", "body-a"],+ ]);++ await waitForBatchedStore();++ expect(sendTransaction).toHaveBeenCalledTimes(1);+ expect(sendTransaction).toHaveBeenCalledWith({+ id: expect.any(String),+ object: "selectedPageAndInstance",+ payload: {+ selectedPageId: "page-a",+ selectedInstanceSelector: undefined,+ allSelectedInstanceSelectors: [+ ["box-a", "body-a"],+ ["heading-a", "body-a"],+ ],+ },+ });+ });++ test("applies multi-selection without needing a particular selected instance", () => {+ const syncObject = new SelectedPageAndInstanceSyncObject();++ syncObject.applyTransaction({+ id: "selection",+ object: "selectedPageAndInstance",+ payload: {+ selectedPageId: "page-b",+ selectedInstanceSelector: undefined,+ allSelectedInstanceSelectors: [+ ["box-b", "body-b"],+ ["heading-b", "body-b"],+ ],+ },+ });++ expect($selectedPageId.get()).toBe("page-b");+ expect($selectedInstanceSelector.get()).toBeUndefined();+ expect($allSelectedInstanceSelectors.get()).toEqual([+ ["box-b", "body-b"],+ ["heading-b", "body-b"],+ ]);+ });+test("malformed remote payload does not suppress next local transaction", async () => {const syncObject = new SelectedPageAndInstanceSyncObject();const sendTransaction = vi.fn();@@ -79,7 +166,7 @@ describe("SelectedPageAndInstanceSyncObject", () => {});$selectedPageId.set("page-c");- $selectedInstanceSelector.set(["body-c"]);+ selectInstance(["body-c"]);await waitForBatchedStore();@@ -90,6 +177,7 @@ describe("SelectedPageAndInstanceSyncObject", () => {payload: {selectedPageId: "page-c",selectedInstanceSelector: ["body-c"],+ allSelectedInstanceSelectors: [["body-c"]],},});});@@ -98,7 +186,7 @@ describe("SelectedPageAndInstanceSyncObject", () => {const syncObject = new SelectedPageAndInstanceSyncObject();$selectedPageId.set("page-before");- $selectedInstanceSelector.set(["body-before"]);+ selectInstance(["body-before"]);syncObject.applyTransaction({id: "selection",@@ -116,8 +204,47 @@ describe("SelectedPageAndInstanceSyncObject", () => {selectedInstanceSelector: [10],},});+ syncObject.applyTransaction({+ id: "selection",+ object: "selectedPageAndInstance",+ payload: {+ selectedPageId: "page-after",+ selectedInstanceSelector: undefined,+ allSelectedInstanceSelectors: [["box-after"], [10]],+ },+ });expect($selectedPageId.get()).toBe("page-before");expect($selectedInstanceSelector.get()).toEqual(["body-before"]);});});++describe("createObjectPool", () => {+ test("syncs selected instance outlines for builder canvas overlay", () => {+ const objectPool = createObjectPool();++ objectPool.applyTransaction({+ id: "selected-outlines",+ object: "selectedInstanceOutlines",+ payload: [+ {+ selector: ["box", "body"],+ instanceId: "box",+ rect: { left: 10, top: 20, width: 100, height: 50 },+ },+ {+ selector: ["heading", "body"],+ instanceId: "heading",+ rect: { left: 30, top: 40, width: 120, height: 60 },+ },+ ],+ });++ expect(+ $selectedInstanceOutlines.get().map((outline) => outline.selector)+ ).toEqual([+ ["box", "body"],+ ["heading", "body"],+ ]);+ });+});diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex a60a340e9c..a361eb62fa 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -36,6 +36,7 @@ import {$selectedInstanceRenderState,$hoveredInstanceSelector,$selectedInstanceOutline,+ $selectedInstanceOutlines,$hoveredInstanceOutline,} from "~/shared/nano-states";import { $marketplaceProduct } from "~/shared/sync/data-stores";@@ -66,7 +67,12 @@ import {} from "~/shared/sync/data-stores";import { $pointerPosition } from "../awareness";import { $temporaryInstances } from "../nano-states";-import { $selectedInstanceSelector } from "../nano-states/instances";+import {+ $allSelectedInstanceSelectors,+ $selectedInstanceSelector,+ selectInstance,+ selectInstances,+} from "../nano-states/instances";import { $selectedPageId } from "../nano-states/pages";import { $systemDataByPage } from "../system";import { $resourcesCache } from "../resources";@@ -118,13 +124,19 @@ export const registerContainers = () => {type SelectedPageAndInstance = {selectedPageId: string | undefined;selectedInstanceSelector: InstanceSelector | undefined;+ allSelectedInstanceSelectors: InstanceSelector[];};const $selectedPageAndInstance = batched(- [$selectedPageId, $selectedInstanceSelector],- (selectedPageId, selectedInstanceSelector): SelectedPageAndInstance => ({+ [$selectedPageId, $selectedInstanceSelector, $allSelectedInstanceSelectors],+ (+ selectedPageId,+ selectedInstanceSelector,+ allSelectedInstanceSelectors+ ): SelectedPageAndInstance => ({selectedPageId,selectedInstanceSelector,+ allSelectedInstanceSelectors,}));@@ -180,8 +192,11 @@ class SelectedPageAndInstanceSyncObject {if (typeof state !== "object" || state === null) {return false;}- const { selectedPageId, selectedInstanceSelector } =- state as Partial<SelectedPageAndInstance>;+ const {+ selectedPageId,+ selectedInstanceSelector,+ allSelectedInstanceSelectors,+ } = state as Partial<SelectedPageAndInstance>;if (selectedPageId !== undefined && typeof selectedPageId !== "string") {return false;}@@ -193,8 +208,23 @@ class SelectedPageAndInstanceSyncObject {) {return false;}+ if (+ allSelectedInstanceSelectors !== undefined &&+ (Array.isArray(allSelectedInstanceSelectors) === false ||+ allSelectedInstanceSelectors.every(+ (selector) =>+ Array.isArray(selector) &&+ selector.every((id) => typeof id === "string")+ ) === false)+ ) {+ return false;+ }$selectedPageId.set(selectedPageId);- $selectedInstanceSelector.set(selectedInstanceSelector);+ if (allSelectedInstanceSelectors !== undefined) {+ selectInstances(allSelectedInstanceSelectors);+ return true;+ }+ selectInstance(selectedInstanceSelector);return true;}}@@ -228,6 +258,10 @@ export const createObjectPool = () => {"selectedInstanceOutline",$selectedInstanceOutline),+ new NanostoresSyncObject(+ "selectedInstanceOutlines",+ $selectedInstanceOutlines+ ),new NanostoresSyncObject("hoveredInstanceOutline", $hoveredInstanceOutline),new NanostoresSyncObject("builderMode", $builderMode),new NanostoresSyncObject("authTokenPermissions", $authTokenPermissions),diff --git a/apps/builder/e2e/tests/slot-keyboard.e2e.ts b/apps/builder/e2e/tests/slot-keyboard.e2e.tsindex 9c3d5468ca..a32add3bb2 100644--- a/apps/builder/e2e/tests/slot-keyboard.e2e.ts+++ b/apps/builder/e2e/tests/slot-keyboard.e2e.ts@@ -16,6 +16,7 @@ let topChildFixture: SeededSlotKeyboardProject;let bottomChildFixture: SeededSlotKeyboardProject;let navigatorTopChildFixture: SeededSlotKeyboardProject;let navigatorBottomChildFixture: SeededSlotKeyboardProject;+let multiSelectFixture: SeededSlotKeyboardProject;const selector = (instanceSelector: string[]) =>`[data-ws-selector="${instanceSelector.join(",")}"]`;@@ -89,6 +90,11 @@ test.beforeAll(async () => {title: "Slot Keyboard Navigator Bottom Child E2E",builderToken: "slot-keyboard-navigator-bottom-child-e2e-builder-token",});+ multiSelectFixture = await createSlotKeyboardProject({+ email: "[email protected]",+ title: "Slot Keyboard Multi Select E2E",+ builderToken: "slot-keyboard-navigator-multi-select-e2e-builder-token",+ });});const expectCanvasInstancePrecedes = async ({@@ -137,6 +143,40 @@ const getFocusedTreeButtonText = async ({ page }: { page: Page }) => {});};+const getSelectedTreeButtonTexts = async ({ page }: { page: Page }) => {+ return await page+ .locator("[data-tree-button][aria-selected='true']")+ .evaluateAll((buttons) =>+ buttons.map((button) => button.textContent?.trim() ?? "")+ );+};++const expectSelectedTreeButtonTexts = async ({+ page,+ expectedTexts,+}: {+ page: Page;+ expectedTexts: string[];+}) => {+ await page.waitForFunction(+ (expected) => {+ const selectedTexts = Array.from(+ document.querySelectorAll("[data-tree-button][aria-selected='true']")+ ).map((button) => button.textContent?.trim() ?? "");+ return (+ selectedTexts.length === expected.length &&+ expected.every((expectedText) =>+ selectedTexts.some((selectedText) =>+ selectedText.includes(expectedText)+ )+ )+ );+ },+ expectedTexts,+ { timeout: 10_000 }+ );+};+test("Keyboard shortcut moves a shared slot child into the previous sibling", async () => {const { page, close } = await newIsolatedPage();@@ -246,6 +286,102 @@ test("Keyboard shortcut keeps Navigator arrows working after outdenting a row",}});+test("Shift+ArrowDown in Navigator selects exactly one additional row", async () => {+ const { page, close } = await newIsolatedPage();++ try {+ const canvas = await measure(+ "slot keyboard navigator multi-select open builder",+ async () => {+ return await openProjectBuilder({+ page,+ projectId: multiSelectFixture.projectId,+ authToken: multiSelectFixture.builderToken,+ });+ }+ );++ const slotADivSelector = [+ "slot-keyboard-div",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await canvasInstance({+ canvas,+ instanceSelector: slotADivSelector,+ }).click();+ await openNavigatorPanel({ page });+ await page.getByRole("button", { name: "Drop Div" }).first().click();+ await expectSelectedTreeButtonTexts({+ page,+ expectedTexts: ["Drop Div"],+ });++ await page.keyboard.press("Shift+ArrowDown");++ await expectSelectedTreeButtonTexts({+ page,+ expectedTexts: ["Drop Div", "Slot Heading"],+ });+ const focusedText = await getFocusedTreeButtonText({ page });+ if (focusedText?.includes("Slot Heading") !== true) {+ throw new Error(+ `Expected Shift+ArrowDown to focus Slot Heading, received ${focusedText}`+ );+ }+ } finally {+ await close();+ }+});++test("Control/Command+A after canvas selection selects sibling rows", async () => {+ const { page, close } = await newIsolatedPage();++ try {+ const canvas = await measure(+ "slot keyboard canvas multi-select open builder",+ async () => {+ return await openProjectBuilder({+ page,+ projectId: multiSelectFixture.projectId,+ authToken: multiSelectFixture.builderToken,+ });+ }+ );++ const slotAHeadingSelector = [+ "slot-keyboard-heading",+ "slot-keyboard-fragment",+ "slot-keyboard-slot-a",+ "slot-keyboard-wrapper",+ "slot-keyboard-body",+ ];+ await canvasInstance({+ canvas,+ instanceSelector: slotAHeadingSelector,+ }).click();++ await page.keyboard.press("Control+A");++ await openNavigatorPanel({ page });+ await expectSelectedTreeButtonTexts({+ page,+ expectedTexts: ["Drop Div", "Slot Heading"],+ });++ const selectedTexts = await getSelectedTreeButtonTexts({ page });+ if (selectedTexts.some((selectedText) => selectedText.includes("Slot A"))) {+ throw new Error(+ `Expected Command+A to select only siblings, received ${selectedTexts.join(", ")}`+ );+ }+ } finally {+ await close();+ }+});+test("Keyboard shortcut moves a direct shared slot child out of all slot occurrences", async () => {const { page, close } = await newIsolatedPage();diff --git a/packages/design-system/src/components/kbd.test.tsx b/packages/design-system/src/components/kbd.test.tsxnew file mode 100644index 0000000000..21b1e1d9d8--- /dev/null+++ b/packages/design-system/src/components/kbd.test.tsx@@ -0,0 +1,21 @@+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, test } from "vitest";+import { Kbd } from "./kbd";++describe("Kbd", () => {+ test("renders click shortcuts without plus separators", () => {+ expect(+ renderToStaticMarkup(<Kbd value={["alt", "click"]} />)+ ).not.toContain("+");+ expect(renderToStaticMarkup(<Kbd value={["click"]} />)).not.toContain("+");+ });++ test("renders arrow shortcuts as symbols", () => {+ expect(+ renderToStaticMarkup(<Kbd value={["shift", "arrowup"]} />)+ ).toContain("↑");+ expect(+ renderToStaticMarkup(<Kbd value={["shift", "arrowdown"]} />)+ ).toContain("↓");+ });+});diff --git a/packages/design-system/src/components/kbd.tsx b/packages/design-system/src/components/kbd.tsxindex 45b7dde554..5d4cacd425 100644--- a/packages/design-system/src/components/kbd.tsx+++ b/packages/design-system/src/components/kbd.tsx@@ -10,7 +10,11 @@ const shortcutSymbolMap: Record<string, string> = {backspace: "⌫",enter: "↵",tab: isMac ? "tab" : "Tab",- click: isMac ? "+click" : "+ Click",+ arrowup: "↑",+ arrowright: "→",+ arrowdown: "↓",+ arrowleft: "←",+ click: isMac ? "click" : "Click","click[0]": isMac ? "click" : "Click",};@@ -56,9 +60,10 @@ export const Kbd = ({color?: "subtle" | "moreSubtle" | "contrast";variant?: "regular";}) => {+ const separator = isMac && value.includes("click") === false ? "" : " ";return (<Text color={color} variant={variant} as="kbd">- {format(value).join(isMac ? "" : " ")}+ {format(value).join(separator)}</Text>);};