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: Convert instance to an instance of a different component (#5522)
Oleg Isonenff2e086632fb
diff --git a/apps/builder/app/builder/features/command-panel/groups/convert-group.tsx b/apps/builder/app/builder/features/command-panel/groups/convert-group.tsxnew file mode 100644index 0000000000..a12f14bfaf--- /dev/null+++ b/apps/builder/app/builder/features/command-panel/groups/convert-group.tsx@@ -0,0 +1,191 @@+import {+ CommandGroup,+ CommandGroupFooter,+ CommandIcon,+ CommandInput,+ CommandItem,+ CommandList,+ Flex,+ ScrollArea,+ Text,+} from "@webstudio-is/design-system";+import { matchSorter } from "match-sorter";+import { computed } from "nanostores";+import { elementComponent, tags } from "@webstudio-is/sdk";+import {+ $instances,+ $props,+ $registeredComponentMetas,+} from "~/shared/nano-states";+import { $selectedInstancePath } from "~/shared/awareness";+import {+ getInstanceLabel,+ InstanceIcon,+} from "~/builder/shared/instance-label";+import { canConvertInstance } from "~/shared/instance-utils";+import {+ $commandContent,+ $isCommandPanelOpen,+ closeCommandPanel,+ openCommandPanel,+} from "../command-state";+import { useState } from "react";+import { BackButton } from "../shared/back-button";+import { convertInstance } from "~/shared/instance-utils";++type ConvertOption = {+ component: string;+ tag?: string;+ label: string;+ category?: string;+ order?: number;+};++const $convertOptions = computed(+ [+ $isCommandPanelOpen,+ $selectedInstancePath,+ $instances,+ $props,+ $registeredComponentMetas,+ ],+ (isOpen, instancePath, instances, props, metas) => {+ const convertOptions: ConvertOption[] = [];+ if (!isOpen) {+ return convertOptions;+ }+ if (instancePath === undefined || instancePath.length === 1) {+ return convertOptions;+ }+ const [selectedItem] = instancePath;++ // Test all registered components+ for (const [componentName, meta] of metas) {+ // Skip the current component+ if (componentName === selectedItem.instance.component) {+ continue;+ }++ if (+ canConvertInstance(+ selectedItem.instance.id,+ selectedItem.instanceSelector,+ componentName,+ undefined,+ instances,+ props,+ metas+ )+ ) {+ const label = getInstanceLabel({ component: componentName });+ convertOptions.push({+ component: componentName,+ label,+ category: meta?.category,+ order: meta?.order,+ });+ }+ }++ // Test all valid HTML tags (for Element component)+ for (const tag of tags) {+ if (+ canConvertInstance(+ selectedItem.instance.id,+ selectedItem.instanceSelector,+ elementComponent,+ tag,+ instances,+ props,+ metas+ )+ ) {+ const label = getInstanceLabel({ component: elementComponent, tag });+ convertOptions.push({+ component: elementComponent,+ tag,+ label,+ });+ }+ }++ return convertOptions;+ }+);++const ConvertComponentsList = () => {+ const [search, setSearch] = useState("");+ const convertOptions = $convertOptions.get();++ let matches = convertOptions;+ if (search.trim().length > 0) {+ for (const word of search.trim().split(/\s+/)) {+ matches = matchSorter(matches, word, {+ keys: ["label"],+ });+ }+ }++ return (+ <>+ <CommandInput+ action="convert"+ placeholder="Search components to convert..."+ value={search}+ onValueChange={setSearch}+ onKeyDown={(event) => {+ if (event.key === "Backspace" && search === "") {+ event.preventDefault();+ $commandContent.set(undefined);+ }+ }}+ />+ <Flex direction="column" css={{ maxHeight: 300 }}>+ <ScrollArea>+ <CommandList>+ {matches.length === 0 ? (+ <Flex justify="center" align="center" css={{ minHeight: 100 }}>+ <Text color="subtle" align="center">+ No components found that this instance can be converted into+ </Text>+ </Flex>+ ) : (+ <CommandGroup name="convert-components" actions={["convert"]}>+ {matches.map(({ component, tag, label }) => {+ const key = tag ? `${component}:${tag}` : component;+ return (+ <CommandItem+ key={key}+ value={key}+ onSelect={() => {+ convertInstance(component, tag);+ closeCommandPanel();+ }}+ >+ <Flex gap={2}>+ <CommandIcon>+ <InstanceIcon instance={{ component, tag }} />+ </CommandIcon>+ <Text variant="labelsSentenceCase">{label}</Text>+ </Flex>+ </CommandItem>+ );+ })}+ </CommandGroup>+ )}+ </CommandList>+ </ScrollArea>+ </Flex>+ <CommandGroupFooter>+ <Flex grow>+ <BackButton />+ </Flex>+ </CommandGroupFooter>+ </>+ );+};++export const showConvertComponentsList = () => {+ openCommandPanel();+ $commandContent.set(<ConvertComponentsList />);+};diff --git a/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsxindex 755873da00..c4a11a83b4 100644--- a/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx+++ b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx@@ -37,7 +37,7 @@ import {} from "../command-state";import { useState } from "react";import { BackButton } from "../shared/back-button";-import { wrapIn } from "~/shared/instance-utils";+import { wrapInstance } from "~/shared/instance-utils";type WrapOption = {component: string;@@ -275,7 +275,7 @@ const WrapComponentsList = () => {key={key}value={key}onSelect={() => {- wrapIn(component, tag);+ wrapInstance(component, tag);closeCommandPanel();}}>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 f09c5e46dc..cd15a98877 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@@ -98,6 +98,8 @@ export const KeyboardShortcutsDialog = () => {"cut","paste","duplicateInstance",+ "wrap",+ "unwrap","expandNavigatorItem","collapseNavigatorItem","expandAllNavigatorNodes",diff --git a/apps/builder/app/builder/features/style-panel/style-panel.tsx b/apps/builder/app/builder/features/style-panel/style-panel.tsxindex 84c19bccea..59ff59af8e 100644--- a/apps/builder/app/builder/features/style-panel/style-panel.tsx+++ b/apps/builder/app/builder/features/style-panel/style-panel.tsx@@ -1,5 +1,5 @@import { useState } from "react";-import { computed, type WritableAtom } from "nanostores";+import { computed } from "nanostores";import { useStore } from "@nanostores/react";import {theme,@@ -119,11 +119,7 @@ export const ModeMenu = () => {);};-export const StylePanel = ({- $styleSourceInputElement,-}: {- $styleSourceInputElement: WritableAtom<HTMLInputElement | undefined>;-}) => {+export const StylePanel = () => {const { stylePanelMode } = useStore($settings);const selectedInstanceRenderState = useStore($selectedInstanceRenderState);const tag = useStore($selectedInstanceTag);@@ -184,9 +180,7 @@ export const StylePanel = ({<Text variant="titles" css={{ paddingBlock: theme.panel.paddingBlock }}>Style Sources</Text>- <StyleSourcesSection- $styleSourceInputElement={$styleSourceInputElement}- />+ <StyleSourcesSection /></Box><Separator /><ScrollArea>diff --git a/apps/builder/app/builder/features/style-panel/style-source-section.tsx b/apps/builder/app/builder/features/style-panel/style-source-section.tsxindex de59c8ad79..73fbb3c6a7 100644--- a/apps/builder/app/builder/features/style-panel/style-source-section.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source-section.tsx@@ -1,7 +1,7 @@-import { useState } from "react";+import { useState, useEffect } from "react";import { useStore } from "@nanostores/react";import { nanoid } from "nanoid";-import { computed, type WritableAtom } from "nanostores";+import { computed } from "nanostores";import { pseudoClassesByTag } from "@webstudio-is/html-data";import {type Instance,@@ -33,10 +33,18 @@ import {import { removeByMutable } from "~/shared/array-utils";import { cloneStyles } from "~/shared/tree-utils";import { serverSyncStore } from "~/shared/sync/sync-stores";+import { subscribe } from "~/shared/pubsub";import { $selectedInstance } from "~/shared/awareness";import { $instanceTags } from "./shared/model";import { humanizeString } from "~/shared/string-utils";+// Declare command for this module+declare module "~/shared/pubsub" {+ interface CommandRegistry {+ focusStyleSourceInput: undefined;+ }+}+const selectStyleSource = (styleSourceId: StyleSource["id"],state?: StyleDecl["state"]@@ -329,17 +337,25 @@ const $availableStyleSources = computed([$styleSources], (styleSources) => {return availableStylesSources;});-export const StyleSourcesSection = ({- $styleSourceInputElement,-}: {- $styleSourceInputElement: WritableAtom<HTMLInputElement | undefined>;-}) => {+export const StyleSourcesSection = () => {+ const [inputRef, setInputRef] = useState<HTMLInputElement | null>(null);const componentStates = useStore($componentStates);const availableStyleSources = useStore($availableStyleSources);const selectedInstanceStyleSources = useStore($selectedInstanceStyleSources);const selectedInstanceStatesByStyleSourceId = useStore($selectedInstanceStatesByStyleSourceId);++ // Subscribe to focusStyleSourceInput command+ useEffect(() => {+ const unsubscribe = subscribe("command:focusStyleSourceInput", () => {+ if (inputRef) {+ inputRef.focus();+ }+ });+ return unsubscribe;+ }, [inputRef]);+const value = selectedInstanceStyleSources.map((styleSource) =>convertToInputItem(styleSource,@@ -366,7 +382,7 @@ export const StyleSourcesSection = ({return (<><StyleSourceInput- $styleSourceInputElement={$styleSourceInputElement}+ inputRef={setInputRef}error={error}items={availableStyleSources}value={value}diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.stories.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.stories.tsxindex a24f21f8e1..274ca7d93e 100644--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.stories.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.stories.tsx@@ -2,7 +2,6 @@ import { nanoid } from "nanoid";import type { StoryFn } from "@storybook/react";import { useState } from "react";import { type ItemSelector, type ItemSource, StyleSourceInput } from ".";-import { atom } from "nanostores";export default {title: "Style Panel/Style Source Input",@@ -69,7 +68,7 @@ export const Basic: StoryFn<typeof StyleSourceInput> = () => {const [value, setValue] = useState([localItem, ...getItems()]);return (<StyleSourceInput- $styleSourceInputElement={atom()}+ inputRef={() => {}}css={{ width: 300 }}items={getItems()}value={value}@@ -101,7 +100,7 @@ export const WithTruncatedItem: StoryFn<typeof StyleSourceInput> = () => {]);return (<StyleSourceInput- $styleSourceInputElement={atom()}+ inputRef={() => {}}css={{ width: 300 }}items={getItems()}value={value}@@ -139,7 +138,7 @@ export const Complete: StoryFn<typeof StyleSourceInput> = () => {return (<StyleSourceInput- $styleSourceInputElement={atom()}+ inputRef={() => {}}css={{ width: 300 }}items={getItems()}value={value}diff --git a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsxindex 7aaca676d4..ec839004ec 100644--- a/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx+++ b/apps/builder/app/builder/features/style-panel/style-source/style-source-input.tsx@@ -62,7 +62,6 @@ import { StyleSourceBadge } from "./style-source-badge";import { humanizeString } from "~/shared/string-utils";import { $computedStyleDeclarations } from "../shared/model";import type { ComputedStyleDecl } from "~/shared/style-object-model";-import type { WritableAtom } from "nanostores";type IntermediateItem = {id: StyleSource["id"];@@ -279,7 +278,7 @@ const categories = [] satisfies ComponentState["category"][];type StyleSourceInputProps<Item extends IntermediateItem> = {- $styleSourceInputElement: WritableAtom<HTMLInputElement | undefined>;+ inputRef: (element: HTMLInputElement | null) => void;error?: StyleSourceError;items?: Array<Item>;value?: Array<Item>;@@ -565,9 +564,7 @@ export const StyleSourceInput = (<TextField// @todo inputProps is any which breaks all types passed to TextField{...inputProps}- inputRef={(element) =>- props.$styleSourceInputElement.set(element ?? undefined)- }+ inputRef={props.inputRef}error={props.error}renderStyleSourceMenuItems={(item, hasStyles) =>renderMenuItems({diff --git a/apps/builder/app/builder/inspector.tsx b/apps/builder/app/builder/inspector.tsxindex 362accfc23..9330b43540 100644--- a/apps/builder/app/builder/inspector.tsx+++ b/apps/builder/app/builder/inspector.tsx@@ -32,7 +32,6 @@ import {$selectedInstanceKey,$selectedPage,} from "~/shared/awareness";-import { $styleSourceInputElement } from "./shared/commands";import { InstanceIcon, getInstanceLabel } from "./shared/instance-label";const InstanceInfo = ({ instance }: { instance: Instance }) => {@@ -169,7 +168,7 @@ export const Inspector = ({ navigatorLayout }: InspectorProps) => {<InstanceInfo instance={selectedInstance} /><ModeMenu /></Flex>- <StylePanel $styleSourceInputElement={$styleSourceInputElement} />+ <StylePanel /></PanelTabsContent><PanelTabsContent value="settings" css={contentStyle} tabIndex={-1}><ScrollArea>diff --git a/apps/builder/app/builder/shared/commands.test.tsx b/apps/builder/app/builder/shared/commands.test.tsxdeleted file mode 100644index 46052ec0c4..0000000000--- a/apps/builder/app/builder/shared/commands.test.tsx+++ /dev/null@@ -1,191 +0,0 @@-import { describe, expect, test } from "vitest";-import { coreMetas, elementComponent } from "@webstudio-is/sdk";-import * as baseMetas from "@webstudio-is/sdk-components-react/metas";-import { createDefaultPages } from "@webstudio-is/project-build";-import { $, renderData, ws } from "@webstudio-is/template";-import {- $instances,- $pages,- $props,- $registeredComponentMetas,-} from "~/shared/nano-states";-import { registerContainers } from "~/shared/sync/sync-stores";-import { $awareness, selectInstance } from "~/shared/awareness";-import { deleteSelectedInstance, replaceWith } from "./commands";--registerContainers();--const metas = new Map(Object.entries({ ...coreMetas, ...baseMetas }));-$registeredComponentMetas.set(metas);-$pages.set(createDefaultPages({ rootInstanceId: "" }));-$awareness.set({ pageId: "" });--describe("deleteInstance", () => {- test("delete selected instance and select next one", () => {- $instances.set(- renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child1"></$.Box>- <$.Box ws:id="child2"></$.Box>- <$.Box ws:id="child3"></$.Box>- </$.Box>- </$.Body>- ).instances- );- selectInstance(["child2", "parent", "body"]);- deleteSelectedInstance();- expect($awareness.get()?.instanceSelector).toEqual([- "child3",- "parent",- "body",- ]);- });-- test("delete selected instance and select previous one", () => {- $instances.set(- renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child1"></$.Box>- <$.Box ws:id="child2"></$.Box>- <$.Box ws:id="child3"></$.Box>- </$.Box>- </$.Body>- ).instances- );- selectInstance(["child3", "parent", "body"]);- deleteSelectedInstance();- expect($awareness.get()?.instanceSelector).toEqual([- "child2",- "parent",- "body",- ]);- });-- test("delete selected instance and select parent one", () => {- $instances.set(- renderData(- <$.Body ws:id="body">- <$.Box ws:id="parent">- <$.Box ws:id="child1"></$.Box>- </$.Box>- </$.Body>- ).instances- );- selectInstance(["child1", "parent", "body"]);- deleteSelectedInstance();- expect($awareness.get()?.instanceSelector).toEqual(["parent", "body"]);- });-});--describe("replace with", () => {- test("replace legacy tag with element", () => {- const { instances, props } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box tag="article" ws:id="articleId"></$.Box>- </ws.element>- );- $instances.set(instances);- $props.set(props);- selectInstance(["articleId", "bodyId"]);- replaceWith(elementComponent);- const { instances: newInstances, props: newProps } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="article" ws:id="articleId"></ws.element>- </ws.element>- );- expect({ instances: $instances.get(), props: $props.get() }).toEqual({- instances: newInstances,- props: newProps,- });- });-- test("migrate legacy properties as well", () => {- const { instances, props } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box- ws:tag="div"- ws:id="divId"- className="my-class"- htmlFor="my-id"- ></$.Box>- </ws.element>- );- $instances.set(instances);- $props.set(props);- selectInstance(["divId", "bodyId"]);- replaceWith(elementComponent);- const { instances: newInstances, props: newProps } = renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element- ws:tag="div"- ws:id="divId"- class="my-class"- for="my-id"- ></ws.element>- </ws.element>- );- expect({ instances: $instances.get(), props: $props.get() }).toEqual({- instances: newInstances,- props: newProps,- });- });-- test("preserve currently specified tag", () => {- $instances.set(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:tag="article" ws:id="articleId"></$.Box>- </ws.element>- ).instances- );- selectInstance(["articleId", "bodyId"]);- replaceWith(elementComponent);- expect($instances.get()).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="article" ws:id="articleId"></ws.element>- </ws.element>- ).instances- );- });-- test("replace with first tag from presets", () => {- $instances.set(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Heading ws:id="headingId"></$.Heading>- </ws.element>- ).instances- );- selectInstance(["headingId", "bodyId"]);- replaceWith(elementComponent);- expect($instances.get()).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="h1" ws:id="headingId"></ws.element>- </ws.element>- ).instances- );- });-- test("fallback to div", () => {- $instances.set(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <$.Box ws:id="divId"></$.Box>- </ws.element>- ).instances- );- selectInstance(["divId", "bodyId"]);- replaceWith(elementComponent);- expect($instances.get()).toEqual(- renderData(- <ws.element ws:tag="body" ws:id="bodyId">- <ws.element ws:tag="div" ws:id="divId"></ws.element>- </ws.element>- ).instances- );- });-});diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.tsindex a631a2bdb6..b089edd776 100644--- a/apps/builder/app/builder/shared/commands.ts+++ b/apps/builder/app/builder/shared/commands.ts@@ -1,36 +1,31 @@-import {- blockTemplateComponent,- elementComponent,- isComponentDetachable,-} from "@webstudio-is/sdk";import { toast } from "@webstudio-is/design-system";import { createCommandsEmitter, type Command } from "~/shared/commands-emitter";import {$editingItemSelector,- $instances,- $textEditingInstanceSelector,$isDesignMode,toggleBuilderMode,- $isPreviewMode,- $isContentMode,- $registeredComponentMetas,- findBlockSelector,$project,} from "~/shared/nano-states";++// Declare command for type safety+declare module "~/shared/pubsub" {+ interface CommandRegistry {+ focusStyleSourceInput: undefined;+ }+}+import {$breakpointsMenuView,selectBreakpointByOrder,} from "~/shared/breakpoints";import {- deleteInstanceMutable,+ updateWebstudioData,+ unwrapInstance,+ deleteSelectedInstance,extractWebstudioFragment,insertWebstudioFragmentAt,insertWebstudioFragmentCopy,- updateWebstudioData,- unwrapInstanceMutable,- canUnwrapInstance,} from "~/shared/instance-utils";-import type { InstanceSelector } from "~/shared/tree-utils";import { serverSyncStore } from "~/shared/sync/sync-stores";import { $publisher } from "~/shared/pubsub";import {@@ -42,17 +37,13 @@ import {import { $selectedInstancePath, selectInstance } from "~/shared/awareness";import { openCommandPanel } from "../features/command-panel";import { showWrapComponentsList } from "../features/command-panel/groups/wrap-group";+import { showConvertComponentsList } from "../features/command-panel/groups/convert-group";import { builderApi } from "~/shared/builder-api";import { getSetting, setSetting } from "./client-settings";import { findAvailableVariables } from "~/shared/data-variables";-import { atom } from "nanostores";-import { isTreeSatisfyingContentModel } from "~/shared/content-model";import { generateFragmentFromHtml } from "~/shared/html";import { generateFragmentFromTailwind } from "~/shared/tailwind/tailwind";import { denormalizeSrcProps } from "~/shared/copy-paste/asset-upload";-import { getInstanceLabel } from "./instance-label";-import { $instanceTags } from "../features/style-panel/shared/model";-import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk";import { isSyncIdle } from "~/shared/sync/project-queue";import { openDeleteUnusedTokensDialog } from "~/builder/shared/style-source-utils";import { openDeleteUnusedDataVariablesDialog } from "~/builder/shared/data-variable-utils";@@ -65,8 +56,6 @@ import {} from "~/shared/copy-paste/init-copy-paste";import { toggleInstanceShow } from "~/shared/instance-utils";-export const $styleSourceInputElement = atom<HTMLInputElement | undefined>();-const makeBreakpointCommand = <CommandName extends string>(name: CommandName,number: number@@ -80,168 +69,6 @@ const makeBreakpointCommand = <CommandName extends string>(},});-export const deleteSelectedInstance = () => {- if ($isPreviewMode.get()) {- return;- }- const textEditingInstanceSelector = $textEditingInstanceSelector.get();- const instancePath = $selectedInstancePath.get();- // cannot delete instance while editing- if (textEditingInstanceSelector) {- return;- }- if (instancePath === undefined || instancePath.length === 1) {- return;- }- const [selectedItem, parentItem] = instancePath;- const selectedInstanceSelector = selectedItem.instanceSelector;- const instances = $instances.get();- if (!isComponentDetachable(selectedItem.instance.component)) {- toast.error(- "This instance can not be moved outside of its parent component."- );- return false;- }-- if ($isContentMode.get()) {- // In content mode we are allowing to delete childen of the editable block- const editableInstanceSelector = findBlockSelector(- selectedInstanceSelector,- instances- );- if (editableInstanceSelector === undefined) {- builderApi.toast.info("You can't delete this instance in conent mode.");- return;- }-- const isChildOfBlock =- selectedInstanceSelector.length - editableInstanceSelector.length === 1;-- const isTemplateInstance =- instances.get(selectedInstanceSelector[0])?.component ===- blockTemplateComponent;-- if (isTemplateInstance) {- builderApi.toast.info("You can't delete this instance in content mode.");- return;- }-- if (!isChildOfBlock) {- builderApi.toast.info("You can't delete this instance in content mode.");- return;- }- }-- // find next selected instance- let newSelectedInstanceSelector: undefined | InstanceSelector;- const parentInstanceSelector = parentItem.instanceSelector;- const siblingIds = parentItem.instance.children- .filter((child) => child.type === "id")- .map((child) => child.value);- const position = siblingIds.indexOf(selectedItem.instance.id);- const siblingId = siblingIds[position + 1] ?? siblingIds[position - 1];- if (siblingId) {- // select next or previous sibling if possible- newSelectedInstanceSelector = [siblingId, ...parentInstanceSelector];- } else {- // fallback to parent- newSelectedInstanceSelector = parentInstanceSelector;- }- updateWebstudioData((data) => {- if (deleteInstanceMutable(data, instancePath)) {- selectInstance(newSelectedInstanceSelector);- }- });-};--export const replaceWith = (component: string, tag?: string) => {- const instancePath = $selectedInstancePath.get();- // global root or body are selected- if (instancePath === undefined || instancePath.length === 1) {- return;- }- const [selectedItem] = instancePath;- const selectedInstance = selectedItem.instance;- const selectedInstanceSelector = selectedItem.instanceSelector;- const metas = $registeredComponentMetas.get();- const instanceTags = $instanceTags.get();- try {- updateWebstudioData((data) => {- const instance = data.instances.get(selectedInstance.id);- if (instance === undefined) {- return;- }- instance.component = component;- // replace with specified tag or with currently used- if (tag || component === elementComponent) {- instance.tag = tag ?? instanceTags.get(selectedInstance.id) ?? "div";- // delete legacy tag prop if specified- for (const prop of data.props.values()) {- if (prop.instanceId !== selectedInstance.id) {- continue;- }- if (prop.name === "tag") {- data.props.delete(prop.id);- continue;- }- const newName = reactPropsToStandardAttributes[prop.name];- if (newName) {- const newId = `${prop.instanceId}:${newName}`;- data.props.delete(prop.id);- data.props.set(newId, { ...prop, id: newId, name: newName });- }- }- }- const isSatisfying = isTreeSatisfyingContentModel({- instances: data.instances,- props: data.props,- metas,- instanceSelector: selectedInstanceSelector,- });- if (isSatisfying === false) {- const label = getInstanceLabel({ component, tag });- toast.error(`Cannot replace with ${label}`);- throw Error("Abort transaction");- }- });- } catch {- // do nothing- }-};--const unwrap = () => {- const instancePath = $selectedInstancePath.get();- if (instancePath === undefined || !canUnwrapInstance(instancePath)) {- return;- }-- const [selectedItem, parentItem] = instancePath;-- try {- updateWebstudioData((data) => {- const result = unwrapInstanceMutable({- instances: data.instances,- props: data.props,- metas: $registeredComponentMetas.get(),- selectedItem,- parentItem,- });-- if (!result.success) {- toast.error(result.error ?? "Cannot unwrap instance");- throw Error("Abort transaction");- }- });- // After unwrap, select the child that replaced the parent- selectInstance([- selectedItem.instance.id,- ...parentItem.instanceSelector.slice(1),- ]);- } catch {- // do nothing- }-};-export const { emitCommand, subscribeCommands } = createCommandsEmitter({source: "builder",externalCommands: [@@ -396,11 +223,20 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({}$activeInspectorPanel.set("style");requestAnimationFrame(() => {- $styleSourceInputElement.get()?.focus();+ emitCommand("focusStyleSourceInput");});},disableOnInputLikeControls: true,},+ {+ name: "focusStyleSourceInput",+ description: "Focus style source input",+ hidden: true,+ handler: () => {+ // This command is handled by the style panel component+ // It's emitted by openStylePanel command+ },+ },{name: "toggleStylePanelFocusMode",description: "Toggle style panel focus mode",@@ -564,6 +400,8 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({name: "wrap",label: "Wrap",description: "Wrap",+ category: "Navigator",+ defaultHotkeys: ["meta+alt+g", "ctrl+alt+g"],keepCommandPanelOpen: true,handler: () => {showWrapComponentsList();@@ -572,19 +410,19 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({{name: "unwrap",description: "Remove parent wrapper",- handler: () => unwrap(),- },- {- name: "replaceWithElement",- label: "Replace with an Element",- description: "Replace with element",- handler: () => replaceWith(elementComponent),+ category: "Navigator",+ defaultHotkeys: ["meta+shift+g", "ctrl+shift+g"],+ handler: () => unwrapInstance(),},{- name: "replaceWithLink",- label: "Replace with a Link",- description: "Replace with link",- handler: () => replaceWith(elementComponent, "a"),+ name: "convert",+ label: "Convert",+ description: "Convert component",+ category: "Navigator",+ keepCommandPanelOpen: true,+ handler: () => {+ showConvertComponentsList();+ },},{diff --git a/apps/builder/app/builder/shared/instance-context-menu.tsx b/apps/builder/app/builder/shared/instance-context-menu.tsxindex 14135ee1ff..3c0855866e 100644--- a/apps/builder/app/builder/shared/instance-context-menu.tsx+++ b/apps/builder/app/builder/shared/instance-context-menu.tsx@@ -41,6 +41,7 @@ const getMenuPermissions = (instancePath: InstancePath | undefined) => {canRename: !isRoot,canWrap: !isRootOrBody,canUnwrap,+ canConvert: !isRootOrBody,canDelete: !isRootOrBody,};};@@ -133,6 +134,9 @@ export const MenuItems = () => {}}>Wrap+ <ContextMenuItemRightSlot>+ <Kbd value={["meta", "alt", "g"]} />+ </ContextMenuItemRightSlot></ContextMenuItem><ContextMenuItemdisabled={!permissions.canUnwrap}@@ -141,6 +145,17 @@ export const MenuItems = () => {}}>Unwrap+ <ContextMenuItemRightSlot>+ <Kbd value={["meta", "shift", "g"]} />+ </ContextMenuItemRightSlot>+ </ContextMenuItem>+ <ContextMenuItem+ disabled={!permissions.canConvert}+ onSelect={() => {+ emitCommand("convert");+ }}+ >+ Convert</ContextMenuItem><ContextMenuSeparator /><ContextMenuItemdiff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.tsindex d06b78885e..ff1327ecdb 100644--- a/apps/builder/app/canvas/shared/commands.ts+++ b/apps/builder/app/canvas/shared/commands.ts@@ -19,7 +19,7 @@ import {} from "../features/text-editor/toolbar-connector";import { selectInstance } from "~/shared/awareness";import { isDescendantOrSelf, type InstanceSelector } from "~/shared/tree-utils";-import { deleteSelectedInstance } from "~/builder/shared/commands";+import { deleteSelectedInstance } from "~/shared/instance-utils";import { findClosestRichText } from "~/shared/content-model";export const { emitCommand, subscribeCommands } = createCommandsEmitter({diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsxindex 1f4c7659d7..2a0b6b938c 100644--- a/apps/builder/app/shared/instance-utils.test.tsx+++ b/apps/builder/app/shared/instance-utils.test.tsx@@ -41,10 +41,13 @@ import {insertWebstudioFragmentAt,insertWebstudioElementAt,buildInstancePath,- wrapIn,+ wrapInstance,toggleInstanceShow,unwrapInstanceMutable,canUnwrapInstance,+ canConvertInstance,+ convertInstance,+ deleteSelectedInstance,} from "./instance-utils";import type { InstancePath } from "./awareness";import {@@ -1031,7 +1034,7 @@ describe("wrap in", () => {).instances);selectInstance(["divId", "bodyId"]);- wrapIn(elementComponent, "a");+ wrapInstance(elementComponent, "a");expect($instances.get()).toEqual(renderData(<ws.element ws:tag="body" ws:id="bodyId">@@ -1052,7 +1055,7 @@ describe("wrap in", () => {).instances);selectInstance(["imageId", "bodyId"]);- wrapIn(elementComponent);+ wrapInstance(elementComponent);expect($instances.get()).toEqual(renderData(<ws.element ws:tag="body" ws:id="bodyId">@@ -1074,7 +1077,7 @@ describe("wrap in", () => {);$instances.set(instances);selectInstance(["textId", "bodyId"]);- wrapIn(elementComponent, "a");+ wrapInstance(elementComponent, "a");// nothing is changedexpect($instances.get()).toEqual(instances);});@@ -1089,7 +1092,7 @@ describe("wrap in", () => {);$instances.set(instances);selectInstance(["boldId", "textId", "bodyId"]);- wrapIn(elementComponent);+ wrapInstance(elementComponent);// nothing is changedexpect($instances.get()).toEqual(instances);});@@ -1104,7 +1107,7 @@ describe("wrap in", () => {);$instances.set(instances);selectInstance(["listItemId", "listId", "bodyId"]);- wrapIn(elementComponent);+ wrapInstance(elementComponent);// nothing is changedexpect($instances.get()).toEqual(instances);});@@ -2074,6 +2077,10 @@ describe("canUnwrapInstance", () => {instanceSelector: ["parent", "body"],instance: instances.get("parent")!,},+ {+ instanceSelector: ["body"],+ instance: instances.get("body")!,+ },] satisfies InstancePath;expect(canUnwrapInstance(instancePath)).toBe(true);@@ -2136,4 +2143,404 @@ describe("canUnwrapInstance", () => {expect(canUnwrapInstance(instancePath)).toBe(false);});++ test("returns true for Body > div > a scenario", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <ws.element ws:tag="div" ws:id="div">+ <ws.element ws:tag="a" ws:id="link">+ Link text+ </ws.element>+ </ws.element>+ </$.Body>+ );++ $instances.set(instances);+ $props.set(props);+ $registeredComponentMetas.set(defaultMetasMap);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $awareness.set({ pageId: pages.homePage.id });++ const instancePath = [+ {+ instanceSelector: ["link", "div", "body"],+ instance: instances.get("link")!,+ },+ {+ instanceSelector: ["div", "body"],+ instance: instances.get("div")!,+ },+ {+ instanceSelector: ["body"],+ instance: instances.get("body")!,+ },+ ] satisfies InstancePath;++ // Should be able to unwrap the link from the div+ expect(canUnwrapInstance(instancePath)).toBe(true);+ });++ test("unwrapInstanceMutable works for Body > div > a scenario", () => {+ const { instances, props } = renderData(+ <$.Body ws:id="body">+ <ws.element ws:tag="div" ws:id="div">+ <ws.element ws:tag="a" ws:id="link">+ Link text+ </ws.element>+ </ws.element>+ </$.Body>+ );++ const result = unwrapInstanceMutable({+ instances,+ props,+ metas: defaultMetasMap,+ selectedItem: {+ instanceSelector: ["link", "div", "body"],+ instance: instances.get("link")!,+ },+ parentItem: {+ instanceSelector: ["div", "body"],+ instance: instances.get("div")!,+ },+ });++ expect(result.success).toBe(true);++ // Verify the link is now a direct child of body+ const body = instances.get("body")!;+ expect(body.children).toContainEqual({ type: "id", value: "link" });++ // Verify the div was deleted since it has no more children+ expect(instances.has("div")).toBe(false);+ });+});++describe("canConvertInstance", () => {+ test("returns true for valid conversion", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="body">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ );++ const result = canConvertInstance(+ "box",+ ["box", "body"],+ elementComponent,+ "div",+ instances,+ props,+ defaultMetasMap+ );++ expect(result).toBe(true);+ });++ test("returns false for non-existent instance", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="body"></ws.element>+ );++ const result = canConvertInstance(+ "nonexistent",+ ["nonexistent", "body"],+ elementComponent,+ "div",+ instances,+ props,+ defaultMetasMap+ );++ expect(result).toBe(false);+ });++ test("returns true when converting Box to Heading", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="body">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ );++ const result = canConvertInstance(+ "box",+ ["box", "body"],+ "@webstudio-is/sdk-components-react:Heading",+ undefined,+ instances,+ props,+ defaultMetasMap+ );++ expect(result).toBe(true);+ });++ test("uses preset tag when available", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="body">+ <$.Box ws:id="box"></$.Box>+ </ws.element>+ );++ const result = canConvertInstance(+ "box",+ ["box", "body"],+ "@webstudio-is/sdk-components-react:Heading",+ undefined,+ instances,+ props,+ defaultMetasMap+ );++ expect(result).toBe(true);+ });+});++describe("convertInstance", () => {+ beforeEach(() => {+ $registeredComponentMetas.set(defaultMetasMap);+ });++ test("converts legacy tag to element", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box tag="article" ws:id="articleId"></$.Box>+ </ws.element>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["articleId", "bodyId"]);+ convertInstance(elementComponent);+ const { instances: newInstances, props: newProps } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="article" ws:id="articleId"></ws.element>+ </ws.element>+ );+ expect({ instances: $instances.get(), props: $props.get() }).toEqual({+ instances: newInstances,+ props: newProps,+ });+ });++ test("migrates legacy properties", () => {+ const { instances, props } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box+ ws:tag="div"+ ws:id="divId"+ className="my-class"+ htmlFor="my-id"+ ></$.Box>+ </ws.element>+ );+ $instances.set(instances);+ $props.set(props);+ selectInstance(["divId", "bodyId"]);+ convertInstance(elementComponent);+ const { instances: newInstances, props: newProps } = renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element+ ws:tag="div"+ ws:id="divId"+ class="my-class"+ for="my-id"+ ></ws.element>+ </ws.element>+ );+ expect({ instances: $instances.get(), props: $props.get() }).toEqual({+ instances: newInstances,+ props: newProps,+ });+ });++ test("preserves currently specified tag", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box ws:tag="article" ws:id="articleId"></$.Box>+ </ws.element>+ ).instances+ );+ selectInstance(["articleId", "bodyId"]);+ convertInstance(elementComponent);+ expect($instances.get()).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="article" ws:id="articleId"></ws.element>+ </ws.element>+ ).instances+ );+ });++ test("converts to first tag from presets", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Heading ws:id="headingId"></$.Heading>+ </ws.element>+ ).instances+ );+ selectInstance(["headingId", "bodyId"]);+ convertInstance(elementComponent);+ expect($instances.get()).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="h1" ws:id="headingId"></ws.element>+ </ws.element>+ ).instances+ );+ });++ test("falls back to div", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box ws:id="divId"></$.Box>+ </ws.element>+ ).instances+ );+ selectInstance(["divId", "bodyId"]);+ convertInstance(elementComponent);+ expect($instances.get()).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="div" ws:id="divId"></ws.element>+ </ws.element>+ ).instances+ );+ });++ test("converts with specific tag", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box ws:id="divId"></$.Box>+ </ws.element>+ ).instances+ );+ selectInstance(["divId", "bodyId"]);+ convertInstance(elementComponent, "a");+ expect($instances.get()).toEqual(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <ws.element ws:tag="a" ws:id="divId"></ws.element>+ </ws.element>+ ).instances+ );+ });++ test("converts between components", () => {+ $instances.set(+ renderData(+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box ws:id="boxId"></$.Box>+ </ws.element>+ ).instances+ );+ selectInstance(["boxId", "bodyId"]);+ convertInstance("@webstudio-is/sdk-components-react:Heading");+ const result = $instances.get();+ const boxInstance = result.get("boxId");+ expect(boxInstance?.component).toBe(+ "@webstudio-is/sdk-components-react:Heading"+ );+ });++ test("prevents converting root instance", () => {+ const initialInstances = renderData(+ <ws.element ws:tag="html" ws:id="rootId">+ <ws.element ws:tag="body" ws:id="bodyId"></ws.element>+ </ws.element>+ ).instances;+ $instances.set(initialInstances);+ selectInstance(["rootId"]);+ convertInstance(elementComponent, "div");+ // Should not change+ expect($instances.get()).toEqual(initialInstances);+ });++ test("prevents converting body instance", () => {+ const pages = createDefaultPages({ rootInstanceId: "bodyId" });+ $pages.set(pages);+ $awareness.set({ pageId: pages.homePage.id });++ const initialInstances = renderData(+ <ws.element ws:tag="html" ws:id="rootId">+ <ws.element ws:tag="body" ws:id="bodyId">+ <$.Box ws:id="boxId"></$.Box>+ </ws.element>+ </ws.element>+ ).instances;+ $instances.set(initialInstances);+ selectInstance(["bodyId", "rootId"]);+ convertInstance(elementComponent, "div");+ // Should not change+ expect($instances.get()).toEqual(initialInstances);+ });+});++describe("deleteSelectedInstance", () => {+ test("delete selected instance and select next one", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="parent">+ <$.Box ws:id="child1"></$.Box>+ <$.Box ws:id="child2"></$.Box>+ <$.Box ws:id="child3"></$.Box>+ </$.Box>+ </$.Body>+ );+ $instances.set(instances);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $awareness.set({ pageId: pages.homePage.id });+ selectInstance(["child2", "parent", "body"]);+ deleteSelectedInstance();+ expect($awareness.get()?.instanceSelector).toEqual([+ "child3",+ "parent",+ "body",+ ]);+ });++ test("delete selected instance and select previous one", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="parent">+ <$.Box ws:id="child1"></$.Box>+ <$.Box ws:id="child2"></$.Box>+ <$.Box ws:id="child3"></$.Box>+ </$.Box>+ </$.Body>+ );+ $instances.set(instances);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $awareness.set({ pageId: pages.homePage.id });+ selectInstance(["child3", "parent", "body"]);+ deleteSelectedInstance();+ expect($awareness.get()?.instanceSelector).toEqual([+ "child2",+ "parent",+ "body",+ ]);+ });++ test("delete selected instance and select parent one", () => {+ const { instances } = renderData(+ <$.Body ws:id="body">+ <$.Box ws:id="parent">+ <$.Box ws:id="child1"></$.Box>+ </$.Box>+ </$.Body>+ );+ $instances.set(instances);+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $awareness.set({ pageId: pages.homePage.id });+ selectInstance(["child1", "parent", "body"]);+ deleteSelectedInstance();+ expect($awareness.get()?.instanceSelector).toEqual(["parent", "body"]);+ });});diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex 6d67a34bf7..3c9c1f773d 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -1,6 +1,7 @@import { current, isDraft } from "immer";import { nanoid } from "nanoid";import { toast } from "@webstudio-is/design-system";+import { builderApi } from "~/shared/builder-api";import { equalMedia, type StyleValue } from "@webstudio-is/css-engine";import { showAttribute } from "@webstudio-is/react-sdk";import {@@ -33,6 +34,8 @@ import {Props,elementComponent,tags,+ blockTemplateComponent,+ isComponentDetachable,} from "@webstudio-is/sdk";import {$props,@@ -48,6 +51,10 @@ import {$resources,$registeredTemplates,$project,+ $isPreviewMode,+ $textEditingInstanceSelector,+ $isContentMode,+ findBlockSelector,} from "./nano-states";import {type DroppableTarget,@@ -84,6 +91,8 @@ import {} from "./content-model";import type { Project } from "@webstudio-is/project";import { getInstanceLabel } from "~/builder/shared/instance-label";+import { $instanceTags } from "~/builder/features/style-panel/shared/model";+import { reactPropsToStandardAttributes } from "@webstudio-is/react-sdk";/*** structuredClone can be invoked on draft and throw error@@ -627,15 +636,18 @@ export const unwrapInstanceMutable = ({};parentItem: { instanceSelector: InstanceSelector; instance: { id: string } };}): { success: boolean; error?: string } => {- const instanceSelector = findClosestNonTextualContainer({- metas,- props,- instances,- instanceSelector: parentItem.instanceSelector,- });- if (parentItem.instanceSelector.join() !== instanceSelector.join()) {+ // Check if the selected instance is rich text content (like Bold, Italic in Paragraph)+ if (+ isRichTextContent({+ instanceSelector: selectedItem.instanceSelector,+ instances,+ props,+ metas,+ })+ ) {return { success: false, error: "Cannot unwrap textual instance" };}+const parentInstance = instances.get(parentItem.instance.id);const selectedInstance = instances.get(selectedItem.instance.id);if (!parentInstance || !selectedInstance) {@@ -702,11 +714,12 @@ export const unwrapInstanceMutable = ({};export const canUnwrapInstance = (instancePath: InstancePath) => {- // global root or body are selected- if (instancePath.length < 2) {+ // Need at least 3 levels: selected, parent, and grandparent+ // Can't unwrap if there's no grandparent to move the selected instance to+ if (instancePath.length < 3) {return false;}- const [, parentItem] = instancePath;+ const [selectedItem, parentItem] = instancePath;// Prevent unwrapping if parent is the root instance (e.g., Body)const rootInstanceId = $selectedPage.get()?.rootInstanceId;@@ -717,19 +730,19 @@ export const canUnwrapInstance = (instancePath: InstancePath) => {return false;}- // Check if parent is inside a textual container+ // Check if the selected instance is rich text content (like Bold, Italic in Paragraph)const instances = $instances.get();const props = $props.get();const metas = $registeredComponentMetas.get();- const instanceSelector = findClosestNonTextualContainer({- metas,- props,- instances,- instanceSelector: parentItem.instanceSelector,- });-- if (parentItem.instanceSelector.join() !== instanceSelector.join()) {+ if (+ isRichTextContent({+ instanceSelector: selectedItem.instanceSelector,+ instances,+ props,+ metas,+ })+ ) {return false;}@@ -762,7 +775,7 @@ export const toggleInstanceShow = (instanceId: Instance["id"]) => {});};-export const wrapIn = (component: string, tag?: string) => {+export const wrapInstance = (component: string, tag?: string) => {const instancePath = $selectedInstancePath.get();// global root or body are selectedif (instancePath === undefined || instancePath.length === 1) {@@ -825,6 +838,215 @@ export const wrapIn = (component: string, tag?: string) => {}};+// Check if an instance can be converted to a specific component or tag+export const canConvertInstance = (+ selectedInstanceId: string,+ selectedInstanceSelector: string[],+ component: string,+ tag: string | undefined,+ instances: Instances,+ props: Props,+ metas: Map<Instance["component"], WsComponentMeta>+): boolean => {+ const selectedInstance = instances.get(selectedInstanceId);++ if (!selectedInstance) {+ return false;+ }++ // Create a test instance with the new component/tag+ const testInstance: Instance = {+ ...selectedInstance,+ component,+ };++ if (tag || component === elementComponent) {+ testInstance.tag = tag ?? "div";+ } else {+ // For components with presetStyle (like Heading, Box), infer default tag+ const meta = metas.get(component);+ const defaultTag = Object.keys(+ (meta as { presetStyle?: Record<string, unknown> })?.presetStyle ?? {}+ ).at(0);+ if (defaultTag) {+ testInstance.tag = defaultTag;+ }+ }++ const newInstances = new Map(instances);+ newInstances.set(testInstance.id, testInstance);++ // Validate the converted instance satisfies content model+ return isTreeSatisfyingContentModel({+ instances: newInstances,+ props,+ metas,+ instanceSelector: selectedInstanceSelector,+ });+};++export const convertInstance = (component: string, tag?: string) => {+ const instancePath = $selectedInstancePath.get();+ // global root or body are selected+ if (instancePath === undefined || instancePath.length === 1) {+ return;+ }+ const [selectedItem] = instancePath;+ const selectedInstance = selectedItem.instance;+ const selectedInstanceSelector = selectedItem.instanceSelector;+ const metas = $registeredComponentMetas.get();+ const instanceTags = $instanceTags.get();+ try {+ updateWebstudioData((data) => {+ const instance = data.instances.get(selectedInstance.id);+ if (instance === undefined) {+ return;+ }+ instance.component = component;+ // convert to specified tag or with currently used+ if (tag || component === elementComponent) {+ instance.tag = tag ?? instanceTags.get(selectedInstance.id) ?? "div";+ // delete legacy tag prop if specified+ for (const prop of data.props.values()) {+ if (prop.instanceId !== selectedInstance.id) {+ continue;+ }+ if (prop.name === "tag") {+ data.props.delete(prop.id);+ continue;+ }+ const newName = reactPropsToStandardAttributes[prop.name];+ if (newName) {+ const newId = `${prop.instanceId}:${newName}`;+ data.props.delete(prop.id);+ data.props.set(newId, { ...prop, id: newId, name: newName });+ }+ }+ }+ const isSatisfying = isTreeSatisfyingContentModel({+ instances: data.instances,+ props: data.props,+ metas,+ instanceSelector: selectedInstanceSelector,+ });+ if (isSatisfying === false) {+ const label = getInstanceLabel({ component, tag });+ toast.error(`Cannot convert to ${label}`);+ throw Error("Abort transaction");+ }+ });+ } catch {+ // do nothing+ }+};++export const unwrapInstance = () => {+ const instancePath = $selectedInstancePath.get();+ if (instancePath === undefined || !canUnwrapInstance(instancePath)) {+ return;+ }++ const [selectedItem, parentItem] = instancePath;++ try {+ updateWebstudioData((data) => {+ const result = unwrapInstanceMutable({+ instances: data.instances,+ props: data.props,+ metas: $registeredComponentMetas.get(),+ selectedItem,+ parentItem,+ });++ if (!result.success) {+ toast.error(result.error ?? "Cannot unwrap instance");+ throw Error("Abort transaction");+ }+ });+ // After unwrap, select the child that replaced the parent+ selectInstance([+ selectedItem.instance.id,+ ...parentItem.instanceSelector.slice(1),+ ]);+ } catch {+ // do nothing+ }+};++export const deleteSelectedInstance = () => {+ if ($isPreviewMode.get()) {+ return;+ }+ const textEditingInstanceSelector = $textEditingInstanceSelector.get();+ const instancePath = $selectedInstancePath.get();+ // cannot delete instance while editing+ if (textEditingInstanceSelector) {+ return;+ }+ if (instancePath === undefined || instancePath.length === 1) {+ return;+ }+ const [selectedItem, parentItem] = instancePath;+ const selectedInstanceSelector = selectedItem.instanceSelector;+ const instances = $instances.get();+ if (!isComponentDetachable(selectedItem.instance.component)) {+ toast.error(+ "This instance can not be moved outside of its parent component."+ );+ return false;+ }++ if ($isContentMode.get()) {+ // In content mode we are allowing to delete childen of the editable block+ const editableInstanceSelector = findBlockSelector(+ selectedInstanceSelector,+ instances+ );+ if (editableInstanceSelector === undefined) {+ builderApi.toast.info("You can't delete this instance in conent mode.");+ return;+ }++ const isChildOfBlock =+ selectedInstanceSelector.length - editableInstanceSelector.length === 1;++ const isTemplateInstance =+ instances.get(selectedInstanceSelector[0])?.component ===+ blockTemplateComponent;++ if (isTemplateInstance) {+ builderApi.toast.info("You can't delete this instance in content mode.");+ return;+ }++ if (!isChildOfBlock) {+ builderApi.toast.info("You can't delete this instance in content mode.");+ return;+ }+ }++ // find next selected instance+ let newSelectedInstanceSelector: undefined | InstanceSelector;+ const parentInstanceSelector = parentItem.instanceSelector;+ const siblingIds = parentItem.instance.children+ .filter((child) => child.type === "id")+ .map((child) => child.value);+ const position = siblingIds.indexOf(selectedItem.instance.id);+ const siblingId = siblingIds[position + 1] ?? siblingIds[position - 1];+ if (siblingId) {+ // select next or previous sibling if possible+ newSelectedInstanceSelector = [siblingId, ...parentInstanceSelector];+ } else {+ // fallback to parent+ newSelectedInstanceSelector = parentInstanceSelector;+ }+ updateWebstudioData((data) => {+ if (deleteInstanceMutable(data, instancePath)) {+ selectInstance(newSelectedInstanceSelector);+ }+ });+};+const traverseStyleValue = (value: StyleValue,callback: (value: StyleValue) => voiddiff --git a/apps/builder/app/shared/pubsub/create.test.ts b/apps/builder/app/shared/pubsub/create.test.tsnew file mode 100644index 0000000000..320fc5745e--- /dev/null+++ b/apps/builder/app/shared/pubsub/create.test.ts@@ -0,0 +1,696 @@+import { describe, test, expect, beforeEach, afterEach, vi } from "vitest";+import { createPubsub } from "./create";++type TestPublishMap = {+ testAction: { value: string };+ noPayloadAction: undefined;+ numberAction: number;+ storybook: string;+ command: { source: string; name: string };+ "command:testCommand": undefined;+ "command:anotherCommand": undefined;+};++// Helper to cast to Window type for test mocking+const asWindow = (obj: unknown) => obj as Window & typeof globalThis;++describe("createPubsub", () => {+ let postMessageSpy: ReturnType<typeof vi.fn>;+ let parentPostMessageSpy: ReturnType<typeof vi.fn>;+ let addEventListenerSpy: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ // Setup window and crypto+ if (!global.window) {+ (global as typeof globalThis).window = {} as Window & typeof globalThis;+ }++ // Mock crypto.getRandomValues+ global.window.crypto = {+ getRandomValues: vi.fn((arr: Uint8Array) => {+ for (let i = 0; i < arr.length; i++) {+ arr[i] = i;+ }+ return arr;+ }),+ } as unknown as Crypto;++ // Mock requestAnimationFrame - execute callbacks immediately+ global.requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {+ // Execute the callback immediately for testing+ setTimeout(() => callback(0), 0);+ return 0;+ }) as typeof requestAnimationFrame;++ postMessageSpy = vi.fn();+ parentPostMessageSpy = vi.fn();+ addEventListenerSpy = vi.fn();++ global.window.postMessage = postMessageSpy;+ global.window.addEventListener = addEventListenerSpy;+ global.window.parent = {+ postMessage: parentPostMessageSpy,+ } as unknown as Window;++ // Set NODE_ENV for consistent testing+ process.env.NODE_ENV = "test";+ });++ afterEach(() => {+ vi.clearAllMocks();+ delete (global.window as Window & { __webstudio__$__api_token?: string })+ .__webstudio__$__api_token;+ });++ describe("SSR environment", () => {+ test("should throw errors when used in SSR", () => {+ const originalWindow = global.window;+ (global as typeof globalThis).window = undefined as unknown as Window &+ typeof globalThis;++ const pubsub = createPubsub<TestPublishMap>();++ expect(() =>+ pubsub.publish({ type: "testAction", payload: { value: "test" } })+ ).toThrow("publish is not available in this environment");+ expect(() => pubsub.usePublish()).toThrow(+ "usePublish is not available in this environment"+ );+ expect(() => pubsub.useSubscribe("testAction", () => {})).toThrow(+ "useSubscribe is not available in this environment"+ );+ expect(() => pubsub.subscribe("testAction", () => {})).toThrow(+ "subscribe is not available in this environment"+ );++ global.window = originalWindow;+ });+ });++ describe("token generation and validation", () => {+ test("should generate random token when window.self === window.top", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ createPubsub<TestPublishMap>();++ expect(global.window.__webstudio__$__api_token).toBeDefined();+ });++ test("should use development token in non-production", () => {+ const originalNodeEnv = process.env.NODE_ENV;+ process.env.NODE_ENV = "development";++ global.window.self = asWindow({});+ global.window.top = asWindow(global.window);++ createPubsub<TestPublishMap>();++ // In development, token should be "development-token"+ expect(addEventListenerSpy).toHaveBeenCalledWith(+ "message",+ expect.any(Function),+ false+ );++ process.env.NODE_ENV = originalNodeEnv;+ });++ test("should read token from top window when not top", () => {+ const mockToken = "test-token";+ global.window.top = {+ __webstudio__$__api_token: mockToken,+ } as unknown as Window & typeof globalThis;+ global.window.self = asWindow({});++ createPubsub<TestPublishMap>();++ // Token should be reset to undefined on canvas+ expect(global.window.top.__webstudio__$__api_token).toBeUndefined();+ });+ });++ describe("publish (Canvas -> Builder)", () => {+ test("should publish action to parent and self", () => {+ global.window.self = asWindow({});+ global.window.top = asWindow(global.window);+ global.window.top.__webstudio__$__api_token = "test-token";++ const pubsub = createPubsub<TestPublishMap>();++ // Clear the token since it gets reset in createPubsub for Canvas context+ // Set it again after initialization+ global.window.top.__webstudio__$__api_token = "test-token";++ pubsub.publish({ type: "testAction", payload: { value: "hello" } });++ expect(parentPostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ action: { type: "testAction", payload: { value: "hello" } },+ }),+ "*"+ );+ expect(postMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ action: { type: "testAction", payload: { value: "hello" } },+ }),+ "*"+ );+ });++ test("should throw error when publish is called from Builder (self === top)", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ expect(() =>+ pubsub.publish({ type: "testAction", payload: { value: "test" } })+ ).toThrow("publish is not available in the Builder environment");+ });++ test("should handle action with no payload", () => {+ global.window.self = asWindow({});+ global.window.top = asWindow(global.window);+ global.window.top.__webstudio__$__api_token = "test-token";++ const pubsub = createPubsub<TestPublishMap>();++ // Set token again after initialization+ global.window.top.__webstudio__$__api_token = "test-token";++ pubsub.publish({ type: "noPayloadAction" });++ expect(parentPostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ action: { type: "noPayloadAction" },+ }),+ "*"+ );+ });+ });++ describe("usePublish (Builder -> Canvas)", () => {+ test("should be available when self === top", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ expect(pubsub.usePublish).toBeDefined();+ expect(typeof pubsub.usePublish).toBe("function");+ });++ test("should be available for iframe context", () => {+ global.window.self = asWindow({});+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ // usePublish hook itself is available, but publish will throw when called from Canvas+ expect(pubsub.usePublish).toBeDefined();+ });+ });++ describe("subscribe", () => {+ test("should subscribe to messages and call handler", async () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ pubsub.subscribe("testAction", handler);++ // Get the message handler that was registered+ const messageHandler = addEventListenerSpy.mock.calls[0][1];++ // Simulate a message event+ const mockEvent = {+ data: {+ action: { type: "testAction", payload: { value: "test" } },+ token: "development-token",+ },+ };++ messageHandler(mockEvent);++ // Wait for requestAnimationFrame callback to execute+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(handler).toHaveBeenCalledWith({ value: "test" });+ });++ test("should return unsubscribe function", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ const unsubscribe = pubsub.subscribe("testAction", handler);++ expect(typeof unsubscribe).toBe("function");++ unsubscribe();++ // Get the message handler+ const messageHandler = addEventListenerSpy.mock.calls[0][1];++ // Simulate a message event after unsubscribe+ const mockEvent = {+ data: {+ action: { type: "testAction", payload: { value: "test" } },+ token: "development-token",+ },+ };++ messageHandler(mockEvent);++ expect(handler).not.toHaveBeenCalled();+ });++ test("should handle multiple subscribers", async () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ // Create a fresh addEventListener spy for this test+ const localAddEventListenerSpy = vi.fn();+ global.window.addEventListener = localAddEventListenerSpy;++ const pubsub = createPubsub<TestPublishMap>();++ const handler1 = vi.fn();+ const handler2 = vi.fn();++ pubsub.subscribe("testAction", handler1);+ pubsub.subscribe("testAction", handler2);++ // Verify addEventListener was called+ expect(localAddEventListenerSpy).toHaveBeenCalledTimes(1);++ // Get the message handler from this pubsub instance+ const messageHandler = localAddEventListenerSpy.mock.calls[0][1];++ const mockEvent = {+ data: {+ action: { type: "testAction", payload: { value: "test" } },+ token: "development-token",+ },+ };++ // Call messageHandler and let it emit+ messageHandler(mockEvent);++ // Wait for requestAnimationFrame callback to execute+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(handler1).toHaveBeenCalledTimes(1);+ expect(handler1).toHaveBeenCalledWith({ value: "test" });+ expect(handler2).toHaveBeenCalledTimes(1);+ expect(handler2).toHaveBeenCalledWith({ value: "test" });+ });+ });++ describe("useSubscribe", () => {+ test("should be available as a hook function", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ expect(pubsub.useSubscribe).toBeDefined();+ expect(typeof pubsub.useSubscribe).toBe("function");+ });+ });++ describe("message unwrapping and validation", () => {+ test("should reject invalid payload (not an object)", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ pubsub.subscribe("testAction", handler);++ const messageHandler = addEventListenerSpy.mock.calls[0][1];++ // Mock console.error to avoid test output noise+ const consoleErrorSpy = vi+ .spyOn(console, "error")+ .mockImplementation(() => {});++ expect(() => {+ messageHandler({ data: "invalid" });+ }).toThrow("Invalid payload");++ expect(consoleErrorSpy).toHaveBeenCalledWith(+ "Invalid payload",+ "invalid"+ );+ consoleErrorSpy.mockRestore();+ });++ test("should reject payload without token", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ pubsub.subscribe("testAction", handler);++ const messageHandler = addEventListenerSpy.mock.calls[0][1];++ expect(() => {+ messageHandler({ data: { action: { type: "testAction" } } });+ }).toThrow("Invalid payload, not wrapped");+ });++ test("should reject payload with invalid token", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ pubsub.subscribe("testAction", handler);++ const messageHandler = addEventListenerSpy.mock.calls[0][1];++ expect(() => {+ messageHandler({+ data: {+ action: { type: "testAction" },+ token: "invalid-token",+ },+ });+ }).toThrow("Invalid token");+ });++ test("should reject payload without action", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ pubsub.subscribe("testAction", handler);++ const messageHandler = addEventListenerSpy.mock.calls[0][1];++ expect(() => {+ messageHandler({+ data: {+ token: "development-token",+ },+ });+ }).toThrow("Invalid payload, not wrapped");+ });++ test("should hide token from subsequent subscribers", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ pubsub.subscribe("testAction", handler);++ const messageHandler = addEventListenerSpy.mock.calls[0][1];++ const mockData = {+ action: { type: "testAction", payload: { value: "test" } },+ token: "development-token",+ };++ messageHandler({ data: mockData });++ // Token should be set to undefined after unwrapping+ expect(mockData.token).toBeUndefined();+ });++ test("should handle storybook environment", async () => {+ const originalIsStorybook = process.env.IS_STROYBOOK;+ process.env.IS_STROYBOOK = "true";++ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ // Create a fresh addEventListener spy for this test+ const localAddEventListenerSpy = vi.fn();+ global.window.addEventListener = localAddEventListenerSpy;++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ pubsub.subscribe("storybook", handler);++ // Get the message handler from this pubsub instance+ const messageHandler = localAddEventListenerSpy.mock.calls[0][1];++ messageHandler({ data: "storybook-data" });++ // Wait for requestAnimationFrame callback to execute+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(handler).toHaveBeenCalledWith("storybook-data");++ process.env.IS_STROYBOOK = originalIsStorybook;+ });+ });++ describe("action types", () => {+ test("should handle action with undefined payload", () => {+ global.window.self = asWindow({});+ global.window.top = asWindow(global.window);+ global.window.top.__webstudio__$__api_token = "test-token";++ const pubsub = createPubsub<TestPublishMap>();++ // Set token again after initialization+ global.window.top.__webstudio__$__api_token = "test-token";++ pubsub.publish({ type: "noPayloadAction", payload: undefined });++ expect(parentPostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ action: { type: "noPayloadAction", payload: undefined },+ }),+ "*"+ );+ });++ test("should handle action with number payload", () => {+ global.window.self = asWindow({});+ global.window.top = asWindow(global.window);+ global.window.top.__webstudio__$__api_token = "test-token";++ const pubsub = createPubsub<TestPublishMap>();++ // Set token again after initialization+ global.window.top.__webstudio__$__api_token = "test-token";++ pubsub.publish({ type: "numberAction", payload: 42 });++ expect(parentPostMessageSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ action: { type: "numberAction", payload: 42 },+ }),+ "*"+ );+ });+ });++ describe("event listener registration", () => {+ test("should register message event listener on initialization", () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ createPubsub<TestPublishMap>();++ expect(addEventListenerSpy).toHaveBeenCalledWith(+ "message",+ expect.any(Function),+ false+ );+ });+ });++ describe("command-specific subscriptions", () => {+ test("should subscribe to specific command and call handler", async () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const localAddEventListenerSpy = vi.fn();+ global.window.addEventListener = localAddEventListenerSpy;++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ pubsub.subscribe("command:testCommand", handler);++ const messageHandler = localAddEventListenerSpy.mock.calls[0][1];++ const mockEvent = {+ data: {+ action: {+ type: "command",+ payload: { source: "builder", name: "testCommand" },+ },+ token: "development-token",+ },+ };++ messageHandler(mockEvent);++ // Wait for requestAnimationFrame callback+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(handler).toHaveBeenCalledWith(undefined);+ });++ test("should only call handler for matching command", async () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const localAddEventListenerSpy = vi.fn();+ global.window.addEventListener = localAddEventListenerSpy;++ const pubsub = createPubsub<TestPublishMap>();++ const handler1 = vi.fn();+ const handler2 = vi.fn();++ pubsub.subscribe("command:testCommand", handler1);+ pubsub.subscribe("command:anotherCommand", handler2);++ const messageHandler = localAddEventListenerSpy.mock.calls[0][1];++ // Send testCommand+ const mockEvent = {+ data: {+ action: {+ type: "command",+ payload: { source: "builder", name: "testCommand" },+ },+ token: "development-token",+ },+ };++ messageHandler(mockEvent);++ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(handler1).toHaveBeenCalledTimes(1);+ expect(handler2).not.toHaveBeenCalled();+ });++ test("should call both general command handler and specific command handler", async () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const localAddEventListenerSpy = vi.fn();+ global.window.addEventListener = localAddEventListenerSpy;++ const pubsub = createPubsub<TestPublishMap>();++ const generalHandler = vi.fn();+ const specificHandler = vi.fn();++ pubsub.subscribe("command", generalHandler);+ pubsub.subscribe("command:testCommand", specificHandler);++ const messageHandler = localAddEventListenerSpy.mock.calls[0][1];++ const mockEvent = {+ data: {+ action: {+ type: "command",+ payload: { source: "builder", name: "testCommand" },+ },+ token: "development-token",+ },+ };++ messageHandler(mockEvent);++ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(generalHandler).toHaveBeenCalledWith({+ source: "builder",+ name: "testCommand",+ });+ expect(specificHandler).toHaveBeenCalledWith(undefined);+ });++ test("should unsubscribe from specific command", async () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const localAddEventListenerSpy = vi.fn();+ global.window.addEventListener = localAddEventListenerSpy;++ const pubsub = createPubsub<TestPublishMap>();++ const handler = vi.fn();+ const unsubscribe = pubsub.subscribe("command:testCommand", handler);++ unsubscribe();++ const messageHandler = localAddEventListenerSpy.mock.calls[0][1];++ const mockEvent = {+ data: {+ action: {+ type: "command",+ payload: { source: "builder", name: "testCommand" },+ },+ token: "development-token",+ },+ };++ messageHandler(mockEvent);++ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(handler).not.toHaveBeenCalled();+ });++ test("should handle multiple subscribers to the same specific command", async () => {+ global.window.self = asWindow(global.window);+ global.window.top = asWindow(global.window);++ const localAddEventListenerSpy = vi.fn();+ global.window.addEventListener = localAddEventListenerSpy;++ const pubsub = createPubsub<TestPublishMap>();++ const handler1 = vi.fn();+ const handler2 = vi.fn();++ pubsub.subscribe("command:testCommand", handler1);+ pubsub.subscribe("command:testCommand", handler2);++ const messageHandler = localAddEventListenerSpy.mock.calls[0][1];++ const mockEvent = {+ data: {+ action: {+ type: "command",+ payload: { source: "builder", name: "testCommand" },+ },+ token: "development-token",+ },+ };++ messageHandler(mockEvent);++ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(handler1).toHaveBeenCalledWith(undefined);+ expect(handler2).toHaveBeenCalledWith(undefined);+ });+ });+});diff --git a/apps/builder/app/shared/pubsub/create.ts b/apps/builder/app/shared/pubsub/create.tsindex acfcc974ed..7955491c5c 100644--- a/apps/builder/app/shared/pubsub/create.ts+++ b/apps/builder/app/shared/pubsub/create.ts@@ -102,7 +102,20 @@ export const createPubsub = <PublishMap>() => {const action = unwrapAction(event.data);const type = action.type;// Execute all updates within a single batch to improve performance- batchUpdate(() => emitter.emit(type, action.payload));+ batchUpdate(() => {+ emitter.emit(type, action.payload);++ // Also emit command-specific events for type-safe subscriptions+ if (+ type === "command" &&+ action.payload &&+ typeof action.payload === "object" &&+ "name" in action.payload+ ) {+ const commandName = (action.payload as { name: string }).name;+ emitter.emit(`command:${commandName}` as keyof PublishMap, undefined);+ }+ });};window.addEventListener("message", handleMessage, false);diff --git a/apps/builder/app/shared/pubsub/index.ts b/apps/builder/app/shared/pubsub/index.tsindex 6c3541e806..c7288e65a6 100644--- a/apps/builder/app/shared/pubsub/index.ts+++ b/apps/builder/app/shared/pubsub/index.ts@@ -1,7 +1,49 @@import { atom } from "nanostores";import { createPubsub } from "./create";-export interface PubsubMap {+/**+ * Module augmentation pattern for type-safe command subscriptions.+ *+ * This pattern allows each module to declare their own commands without+ * creating a central list that knows about every command in the application.+ *+ * Usage:+ *+ * 1. Declare your command in the module where it's used:+ *+ * declare module "~/shared/pubsub" {+ * interface CommandRegistry {+ * myCommand: undefined;+ * commandWithPayload: { data: string };+ * }+ * }+ *+ * 2. Subscribe to the command with full type safety:+ *+ * subscribe("command:myCommand", () => {+ * // handler receives no payload (undefined)+ * });+ *+ * subscribe("command:commandWithPayload", (payload) => {+ * // payload is typed as { data: string }+ * });+ *+ * 3. TypeScript will prevent subscribing to non-existent commands:+ *+ * subscribe("command:typo", ...) // Type error!+ */++// eslint-disable-next-line @typescript-eslint/no-empty-object-type+export interface CommandRegistry {+ // Base is empty - modules augment this+}++// Create a mapped type for command-specific subscriptions+type CommandSubscriptions = {+ [K in keyof CommandRegistry as `command:${K & string}`]: CommandRegistry[K];+};++export interface PubsubMap extends CommandSubscriptions {command: {source: string;name: string;diff --git a/apps/builder/package.json b/apps/builder/package.jsonindex 0d1f822e56..909b279948 100644--- a/apps/builder/package.json+++ b/apps/builder/package.json@@ -132,6 +132,7 @@"@types/dom-navigation": "^1.0.5","@types/react": "^18.2.70","@types/react-dom": "^18.2.25",+ "@vitest/coverage-v8": "3.1.2","@webstudio-is/tsconfig": "workspace:*","fast-glob": "^3.3.2","html-tags": "^4.0.0",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b517d392b7..b892ecd58a 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -443,6 +443,9 @@ importers:'@types/react-dom':specifier: ^18.2.25version: 18.2.25+ '@vitest/coverage-v8':+ specifier: 3.1.2+ version: 3.1.2(@vitest/[email protected])([email protected])'@webstudio-is/tsconfig':specifier: workspace:*version: link:../../packages/tsconfig@@ -2225,6 +2228,10 @@ packages:resolution: {integrity: sha512-lFMjJTrFL3j7L9yBxwYfCq2k6qqwHyzuUl/XBnif78PWTJYyL/dfowQHWE3sp6U6ZzqWiiIZnpTMO96zhkjwtg==}engines: {node: '>=6.0.0'}+ '@ampproject/[email protected]':+ resolution: {integrity: sha512-30iZtAPgz+LTIYoeivqYo853f02jBYSd5uGnGpkFV0M3xOt9aN73erkgYAmZU43x4VfqcnLxW9Kpg3R5LC4YYw==}+ engines: {node: '>=6.0.0'}+'@atlaskit/[email protected]':resolution: {integrity: sha512-E52y8/0BTTf4ai6BJyFYgdVHFgQ1AES33KvAVQpZ41jMkoukLIq6UoCudOXku7xs3qoPygQdpC+vitVUuEFJXw==}@@ -2372,11 +2379,6 @@ packages:engines: {node: '>=6.0.0'}hasBin: true- '@babel/[email protected]':- resolution: {integrity: sha512-DWMCZH9WA4Maitz2q21SRKHo9QXZxkDsbNZoVD62gusNtNBBqDg9i7uOhASfTfIGNzW+O+r7+jAlM8dwphcJKQ==}- engines: {node: '>=6.0.0'}- hasBin: true-'@babel/[email protected]':resolution: {integrity: sha512-iaepho73/2Pz7w2eMS0Q5f83+0RKI7i4xmiYeBmDzfRVbQtTOG7Ts0S4HzJVsTMGI9keU8rNfuZr8DKfSt7Yyg==}engines: {node: '>=6.0.0'}@@ -2466,6 +2468,10 @@ packages:resolution: {integrity: sha512-H45s8fVLYjbhFH62dIJ3WtmJ6RSPt/3DRO0ZcT2SUiYiQyz3BLVb9ADEnLl91m74aQPS3AzzeajZHYOalWe3bg==}engines: {node: '>=6.9.0'}+ '@bcoe/[email protected]':+ resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==}+ engines: {node: '>=18'}+'@bomb.sh/[email protected]':resolution: {integrity: sha512-CwxKrfgcorUPP6KfYD59aRdBYWBTsfsxT+GmoLVnKo5Tmyoqbpo0UNcjngRMyU+6tiPbd18RuIYxhgAn44wU/Q==}@@ -3726,6 +3732,10 @@ packages:resolution: {integrity: sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==}engines: {node: '>=12'}+ '@istanbuljs/[email protected]':+ resolution: {integrity: sha512-ZXRY4jNvVgSVQ8DL3LTcakaAtXwTVUxE81hslsyD2AtoXW/wVob10HkOJ1X/pAlcI7D+2YoZKg5do8G/w6RYgA==}+ engines: {node: '>=8'}+'@joshwooding/[email protected]':resolution: {integrity: sha512-qYDdL7fPwLRI+bJNurVcis+tNgJmvWjH4YTBGXTA8xMuxFrnAz6E5o35iyzyKbq5J5Lr8mJGfrR5GXl+WGwhgQ==}peerDependencies:@@ -3747,9 +3757,6 @@ packages:resolution: {integrity: sha512-R8gLRTZeyp03ymzP/6Lil/28tGeGEzhx1q2k703KGWRAI1VdvPIXdG70VJc2pAMw3NA6JKL5hhFu1sJX0Mnn/A==}engines: {node: '>=6.0.0'}- '@jridgewell/[email protected]':- resolution: {integrity: sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==}-'@jridgewell/[email protected]':resolution: {integrity: sha512-gv3ZRaISU3fjPAgNsriBRqGWQL6quFx04YMPW/zD8XMLsU32mhCCbfbO6KZFLjvYpCZ8zyDEgqsgf+PwPaM7GQ==}@@ -5562,6 +5569,15 @@ packages:webdriverio:optional: true+ '@vitest/[email protected]':+ resolution: {integrity: sha512-XDdaDOeaTMAMYW7N63AqoK32sYUWbXnTkC6tEbVcu3RlU1bB9of32T+PGf8KZvxqLNqeXhafDFqCkwpf2+dyaQ==}+ peerDependencies:+ '@vitest/browser': 3.1.2+ vitest: 3.1.2+ peerDependenciesMeta:+ '@vitest/browser':+ optional: true+'@vitest/[email protected]':resolution: {integrity: sha512-O8hJgr+zREopCAqWl3uCVaOdqJwZ9qaDwUP7vy3Xigad0phZe9APxKhPcDNqYYi0rX5oMvwJMSCAXY2afqeTSA==}@@ -6741,6 +6757,10 @@ packages:engines: {node: '>=16 || 14 >=14.17'}hasBin: true+ resolution: {integrity: sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==}+ hasBin: true+resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}deprecated: Glob versions prior to v9 are no longer supported@@ -6839,6 +6859,9 @@ packages:resolution: {integrity: sha512-oWv4T4yJ52iKrufjnyZPkrN0CH3QnrUqdB6In1g5Fe1mia8GmF36gnfNySxoZtxD5+NmYw1EElVXiBk93UeskA==}engines: {node: '>=12'}+ resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==}+resolution: {integrity: sha512-lNovG8CMCCmcVB1Q7xggMSf7tqPCijZXaH4gL6iE8BFghdQCbaY5Met9i1x2Ex8m/cZHDUtXK9H6/znKamRP8Q==}@@ -7095,10 +7118,29 @@ packages:resolution: {integrity: sha512-PIeMbHqMt4DnUP3MA/Flc0HElYjMXArsw1qwJZcm9sqR8mq3l8NYizFMty0pWwE/tzIGH3EKK5+jes5mAr85yw==}+ resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==}+ engines: {node: '>=8'}++ resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==}+ engines: {node: '>=10'}++ resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==}+ engines: {node: '>=8'}+resolution: {integrity: sha512-MXbxovZ/Pm42f6cDIDkl3xpwv1AGwObKwfmjs2nQePiy85tP3fatofl3FC1aBsOtP/6fq5SbtgHwWcMsLP+bDw==}engines: {node: '>=14'}+ resolution: {integrity: sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==}+resolution: {integrity: sha512-JVAfqNPTvNq3sB/VHQJAFxN/sPgKnsKrCwyRt15zwNCdrMMJDdcEOdubuy+DuJYYdm0ox1J4uzEuYKkN+9yhVg==}@@ -7256,6 +7298,13 @@ packages:resolution: {integrity: sha512-sNPKHvyjVf7gyjwS4xGTaW/mCnF8wnjtifKBEhxfZ7E/S8tQ0rssrwGNn6q8JH/ohItJfSQp9mBtQYuTlH5QnA==}+ resolution: {integrity: sha512-L0WhttDl+2BOsybvEOLK7fW3UA0OQ0IQ2d6Zl2x/a6vVRs3bAY0ECOSHHeL5jD+SbOpOCUEi0y1DgHEn9Qn1AQ==}++ resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==}+ engines: {node: '>=10'}+resolution: {integrity: sha512-0aF7ZmVon1igznGI4VS30yugpduQW3y3GkcgGJOp7d8x8QrizhigUxjI/m2UojsXXto+jLAH3KSz+xOJTiORjg==}@@ -7598,6 +7647,10 @@ packages:resolution: {integrity: sha512-jYofLM5Dam9279rdkWzqHozUo4ybjdZmCsDHePy5V/PbBcVMiSZR97gmAy45aqi8CK1lG2ECd356FU86avfwUQ==}engines: {node: '>=16 || 14 >=14.17'}+ resolution: {integrity: sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==}+ engines: {node: '>=16 || 14 >=14.17'}+resolution: {integrity: sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==}engines: {node: '>= 8'}@@ -7833,6 +7886,9 @@ packages:resolution: {integrity: sha512-hEt02O4hUct5wtwg4H4KcWgDdm+l1bOaEy/hWzd8xtXB9BqxTWBBhb+2ImAtH4Cv4rPjV76xN3Zumqk3k3AhhQ==}engines: {node: '>=16.17'}+ resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==}+resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==}@@ -7887,6 +7943,10 @@ packages:resolution: {integrity: sha512-MkhCqzzBEpPvxxQ71Md0b1Kk51W01lrYvlMzSUaIzNsODdd7mqhiimSZlr+VegAz5Z6Vzt9Xg2ttE//XBhH3EQ==}engines: {node: '>=16 || 14 >=14.17'}+ resolution: {integrity: sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==}+ engines: {node: '>=16 || 14 >=14.18'}+resolution: {integrity: sha512-7lf7qcQidTku0Gu3YDPc8DJ1q7OOucfa/BSsIwjuh56VU7katFvuM8hULfkwB3Fns/rsVF7PwPKVw1sl5KQS9w==}@@ -8520,10 +8580,6 @@ packages:resolution: {integrity: sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==}- resolution: {integrity: sha512-MY2/qGx4enyjprQnFaZsHib3Yadh3IXyV2C321GY0pjGfVBu4un0uDJkwgdxqO+Rdx8JMT8IfJIRwbYVz3Ob3Q==}- engines: {node: '>=14'}-resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}engines: {node: '>=14'}@@ -8601,9 +8657,6 @@ packages:resolution: {integrity: sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==}engines: {node: '>= 0.8'}- resolution: {integrity: sha512-Bc3YwwCB+OzldMxOXJIIvC6cPRWr/LxOp48CdQTOkPyk/t4JWWJbrilwBd7RJzKV8QW7tJkcgAmeuLLJugl5/w==}-resolution: {integrity: sha512-UGvjygr6F6tpH7o2qyqR6QYpwraIjKSdtzyBdyytFOHmPZY917kwdwLG0RbOjWOnKmnm3PeHjaoLLMie7kPLQw==}@@ -8727,6 +8780,10 @@ packages:resolution: {integrity: sha512-jdIBIN6LTIe2jqzay/2vtYLlBHa3JF42ot3h1dW8Q0PaAG4v8rm0cvpVePtau5C6OKXGGcgO9q2AMNSWxiLqKw==}engines: {node: '>=10'}+ resolution: {integrity: sha512-pFYqmTw68LXVjeWJMST4+borgQP2AyMNbg1BpZh9LbyhUeNkeaPF9gzfPGUAnSMV3qPYdWUwDIjjCLiSDOl7vg==}+ engines: {node: '>=18'}+resolution: {integrity: sha512-/mrRod8xqpA+IHSLyGCQ2s8SPHiCDEeQJSep1jqLYeEUClOFG2Qsh+4FU6G9VeqpZnGW/Su8LQGc4YKni5rYSQ==}@@ -9510,6 +9567,11 @@ snapshots:'@jridgewell/gen-mapping': 0.3.5'@jridgewell/trace-mapping': 0.3.25+ '@ampproject/[email protected]':+ dependencies:+ '@jridgewell/gen-mapping': 0.3.5+ '@jridgewell/trace-mapping': 0.3.25+'@atlaskit/[email protected]':dependencies:'@atlaskit/pragmatic-drag-and-drop': 1.7.4@@ -9561,12 +9623,12 @@ snapshots:'@babel/helper-compilation-targets': 7.25.9'@babel/helper-module-transforms': 7.26.0(@babel/[email protected])'@babel/helpers': 7.26.0- '@babel/parser': 7.26.2+ '@babel/parser': 7.27.0'@babel/template': 7.25.9'@babel/traverse': 7.25.9- '@babel/types': 7.26.0+ '@babel/types': 7.27.0convert-source-map: 2.0.0- debug: 4.3.7+ debug: 4.4.0gensync: 1.0.0-beta.2json5: 2.2.3semver: 6.3.1@@ -9595,8 +9657,8 @@ snapshots:'@babel/[email protected]':dependencies:- '@babel/parser': 7.26.2- '@babel/types': 7.26.0+ '@babel/parser': 7.27.0+ '@babel/types': 7.27.0'@jridgewell/gen-mapping': 0.3.5'@jridgewell/trace-mapping': 0.3.25jsesc: 3.0.2@@ -9656,7 +9718,7 @@ snapshots:'@babel/[email protected]':dependencies:'@babel/traverse': 7.25.9- '@babel/types': 7.26.0+ '@babel/types': 7.27.0transitivePeerDependencies:- supports-color@@ -9719,7 +9781,7 @@ snapshots:'@babel/[email protected]':dependencies:'@babel/template': 7.25.9- '@babel/types': 7.26.0+ '@babel/types': 7.27.0'@babel/[email protected]':dependencies:@@ -9728,11 +9790,7 @@ snapshots:'@babel/[email protected]':dependencies:- '@babel/types': 7.25.7-- '@babel/[email protected]':- dependencies:- '@babel/types': 7.26.0+ '@babel/types': 7.27.0'@babel/[email protected]':dependencies:@@ -9802,8 +9860,8 @@ snapshots:'@babel/[email protected]':dependencies:'@babel/code-frame': 7.26.2- '@babel/parser': 7.26.2- '@babel/types': 7.26.0+ '@babel/parser': 7.27.0+ '@babel/types': 7.27.0'@babel/[email protected]':dependencies:@@ -9815,10 +9873,10 @@ snapshots:dependencies:'@babel/code-frame': 7.26.2'@babel/generator': 7.26.2- '@babel/parser': 7.26.2+ '@babel/parser': 7.27.0'@babel/template': 7.25.9- '@babel/types': 7.26.0- debug: 4.3.7+ '@babel/types': 7.27.0+ debug: 4.4.0globals: 11.12.0transitivePeerDependencies:- supports-color@@ -9851,6 +9909,8 @@ snapshots:'@babel/helper-string-parser': 7.25.9'@babel/helper-validator-identifier': 7.25.9+ '@bcoe/[email protected]': {}+'@bomb.sh/[email protected]': {}'@brillout/[email protected]': {}@@ -10725,6 +10785,8 @@ snapshots:wrap-ansi: 8.1.0wrap-ansi-cjs: [email protected]+ '@istanbuljs/[email protected]': {}+'@joshwooding/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected]))':dependencies:glob: 10.3.3@@ -10744,8 +10806,6 @@ snapshots:'@jridgewell/[email protected]': {}- '@jridgewell/[email protected]': {}-'@jridgewell/[email protected]': {}'@jridgewell/[email protected]':@@ -10756,7 +10816,7 @@ snapshots:'@jridgewell/[email protected]':dependencies:'@jridgewell/resolve-uri': 3.1.0- '@jridgewell/sourcemap-codec': 1.4.15+ '@jridgewell/sourcemap-codec': 1.5.0'@jspm/[email protected]': {}@@ -12656,16 +12716,16 @@ snapshots:'@types/[email protected]':dependencies:- '@babel/types': 7.25.7+ '@babel/types': 7.27.0'@types/[email protected]':dependencies:- '@babel/parser': 7.25.7- '@babel/types': 7.25.7+ '@babel/parser': 7.27.0+ '@babel/types': 7.27.0'@types/[email protected]':dependencies:- '@babel/types': 7.25.7+ '@babel/types': 7.27.0'@types/[email protected]':dependencies:@@ -12968,6 +13028,26 @@ snapshots:- utf-8-validate- vite+ dependencies:+ '@ampproject/remapping': 2.3.0+ '@bcoe/v8-coverage': 1.0.2+ debug: 4.4.0+ istanbul-lib-coverage: 3.2.2+ istanbul-lib-report: 3.0.1+ istanbul-lib-source-maps: 5.0.6+ istanbul-reports: 3.2.0+ magic-string: 0.30.17+ magicast: 0.3.5+ std-env: 3.9.0+ test-exclude: 7.0.1+ tinyrainbow: 2.0.0+ vitest: 3.1.2(@types/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected])([email protected])([email protected](@types/[email protected])([email protected]))([email protected])+ optionalDependencies:+ '@vitest/browser': 3.1.2([email protected](@types/[email protected])([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected]))([email protected])+ transitivePeerDependencies:+ - supports-color+'@vitest/[email protected]':dependencies:'@vitest/spy': 3.1.2@@ -13264,7 +13344,7 @@ snapshots:dependencies:- semver: 7.6.3+ semver: 7.7.1dependencies:@@ -14227,7 +14307,7 @@ snapshots:dependencies:cross-spawn: 7.0.6- signal-exit: 4.0.2+ signal-exit: 4.1.0dependencies:@@ -14336,6 +14416,15 @@ snapshots:minipass: 7.0.4path-scurry: 1.10.1+ dependencies:+ foreground-child: 3.1.1+ jackspeak: 3.4.3+ minimatch: 9.0.4+ minipass: 7.1.2+ package-json-from-dist: 1.0.1+ path-scurry: 1.11.1+dependencies:fs.realpath: 1.0.0@@ -14459,6 +14548,8 @@ snapshots:whatwg-encoding: 2.0.0optional: true+ [email protected]: {}+@@ -14700,12 +14791,39 @@ snapshots:+ [email protected]: {}++ dependencies:+ istanbul-lib-coverage: 3.2.2+ make-dir: 4.0.0+ supports-color: 7.2.0++ dependencies:+ '@jridgewell/trace-mapping': 0.3.25+ debug: 4.4.0+ istanbul-lib-coverage: 3.2.2+ transitivePeerDependencies:+ - supports-color++ dependencies:+ html-escaper: 2.0.2+ istanbul-lib-report: 3.0.1+dependencies:'@isaacs/cliui': 8.0.2optionalDependencies:'@pkgjs/parseargs': 0.11.0+ dependencies:+ '@isaacs/cliui': 8.0.2+ optionalDependencies:+ '@pkgjs/parseargs': 0.11.0+@@ -14814,7 +14932,7 @@ snapshots:mlly: 1.7.4node-forge: 1.3.1pathe: 1.1.2- std-env: 3.8.0+ std-env: 3.9.0ufo: 1.5.4untun: 0.1.3uqr: 0.1.2@@ -14875,6 +14993,16 @@ snapshots:dependencies:'@jridgewell/sourcemap-codec': 1.5.0+ dependencies:+ '@babel/parser': 7.27.0+ '@babel/types': 7.27.0+ source-map-js: 1.2.1++ dependencies:+ semver: 7.7.1+@@ -15513,6 +15641,8 @@ snapshots:+ [email protected]: {}+dependencies:minipass: 3.3.6@@ -15659,7 +15789,7 @@ snapshots:dependencies:execa: 6.1.0parse-package-name: 1.0.0- semver: 7.6.3+ semver: 7.7.1validate-npm-package-name: 4.0.0@@ -15764,6 +15894,8 @@ snapshots:is-network-error: 1.1.0retry: 0.13.1+ [email protected]: {}+@@ -15814,6 +15946,11 @@ snapshots:lru-cache: 10.0.0minipass: 7.0.4+ dependencies:+ lru-cache: 10.4.3+ minipass: 7.1.2+@@ -16264,7 +16401,7 @@ snapshots:[email protected](@remix-run/[email protected]([email protected]))([email protected](@remix-run/[email protected]([email protected]([email protected]))([email protected])([email protected]))(@remix-run/[email protected]([email protected]))):dependencies:'@remix-run/server-runtime': 2.16.5([email protected])- debug: 4.3.7+ debug: 4.4.0remix-auth: 3.7.0(@remix-run/[email protected]([email protected]([email protected]))([email protected])([email protected]))(@remix-run/[email protected]([email protected]))uuid: 9.0.1transitivePeerDependencies:@@ -16489,8 +16626,6 @@ snapshots:- [email protected]: {}-@@ -16555,8 +16690,6 @@ snapshots:- [email protected]: {}-@@ -16689,6 +16822,12 @@ snapshots:mkdirp: 1.0.4yallist: 4.0.0+ dependencies:+ '@istanbuljs/schema': 0.1.3+ glob: 10.5.0+ minimatch: 9.0.4+dependencies:readable-stream: 2.3.8