Skip to content

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.

feat: Wrap an instance into any component that can do it (#5508)

Oleg Isonen876b02aaec3a
diff --git a/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx b/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx
index 778f11fd1c..c90972ba30 100644
--- a/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/breakpoints-group.tsx
@@ -13,7 +13,7 @@ import {
$selectedBreakpoint,
$selectedBreakpointId,
} from "~/shared/nano-states";
-import { closeCommandPanel } from "../command-state";
+import { closeCommandPanel, $isCommandPanelOpen } from "../command-state";
import type { BaseOption } from "../shared/types";
import { setCanvasWidth } from "~/builder/shared/calc-canvas-width";
@@ -24,8 +24,11 @@ export type BreakpointOption = BaseOption & {
};
export const $breakpointOptions = computed(
- [$breakpoints, $selectedBreakpoint],
- (breakpoints, selectedBreakpoint) => {
+ [$isCommandPanelOpen, $breakpoints, $selectedBreakpoint],
+ (isOpen, breakpoints, selectedBreakpoint) => {
+ if (!isOpen) {
+ return [];
+ }
const sortedBreakpoints = Array.from(breakpoints.values()).sort(
compareMedia
);
diff --git a/apps/builder/app/builder/features/command-panel/groups/commands-group.tsx b/apps/builder/app/builder/features/command-panel/groups/commands-group.tsx
index 2d1dfd8534..df00bf0fce 100644
--- a/apps/builder/app/builder/features/command-panel/groups/commands-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/commands-group.tsx
@@ -17,28 +17,38 @@ export type CommandOption = BaseOption & {
name: string;
label: string;
keys?: string[];
+ keepCommandPanelOpen?: boolean;
};
-export const $commandOptions = computed([$commandMetas], (commandMetas) => {
- const commandOptions: CommandOption[] = [];
- for (const [name, meta] of commandMetas) {
- if (!meta.hidden) {
- const label = meta.label ?? humanizeString(name);
- const keys = meta.defaultHotkeys?.[0]?.split("+");
- commandOptions.push({
- terms: ["shortcuts", "commands", label],
- type: "command",
- name,
- label,
- keys,
- });
+import { $isCommandPanelOpen } from "../command-state";
+
+export const $commandOptions = computed(
+ [$isCommandPanelOpen, $commandMetas],
+ (isOpen, commandMetas) => {
+ if (!isOpen) {
+ return [];
+ }
+ const commandOptions: CommandOption[] = [];
+ for (const [name, meta] of commandMetas) {
+ if (!meta.hidden) {
+ const label = meta.label ?? humanizeString(name);
+ const keys = meta.defaultHotkeys?.[0]?.split("+");
+ commandOptions.push({
+ terms: ["shortcuts", "commands", label],
+ type: "command",
+ name,
+ label,
+ keys,
+ keepCommandPanelOpen: meta.keepCommandPanelOpen,
+ });
+ }
}
+ commandOptions.sort(
+ (left, right) => (left.keys ? 0 : 1) - (right.keys ? 0 : 1)
+ );
+ return commandOptions;
}
- commandOptions.sort(
- (left, right) => (left.keys ? 0 : 1) - (right.keys ? 0 : 1)
- );
- return commandOptions;
-});
+);
export const CommandsGroup = ({ options }: { options: CommandOption[] }) => {
return (
@@ -47,13 +57,15 @@ export const CommandsGroup = ({ options }: { options: CommandOption[] }) => {
heading={<CommandGroupHeading>Commands</CommandGroupHeading>}
actions={["execute"]}
>
- {options.map(({ name, label, keys }) => (
+ {options.map(({ name, label, keys, keepCommandPanelOpen }) => (
<CommandItem
key={name}
// preserve selected state when rerender
value={name}
onSelect={() => {
- closeCommandPanel();
+ if (!keepCommandPanelOpen) {
+ closeCommandPanel();
+ }
emitCommand(name as never);
}}
>
diff --git a/apps/builder/app/builder/features/command-panel/groups/components-group.tsx b/apps/builder/app/builder/features/command-panel/groups/components-group.tsx
index e410059553..1b48eab97b 100644
--- a/apps/builder/app/builder/features/command-panel/groups/components-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/components-group.tsx
@@ -8,11 +8,7 @@ import {
} from "@webstudio-is/design-system";
import { computed } from "nanostores";
import type { TemplateMeta } from "@webstudio-is/template";
-import {
- componentCategories,
- collectionComponent,
- elementComponent,
-} from "@webstudio-is/sdk";
+import { collectionComponent, elementComponent } from "@webstudio-is/sdk";
import {
$registeredComponentMetas,
$registeredTemplates,
@@ -28,8 +24,12 @@ import {
getInstanceLabel,
InstanceIcon,
} from "~/builder/shared/instance-label";
-import { closeCommandPanel } from "../command-state";
+import { closeCommandPanel, $isCommandPanelOpen } from "../command-state";
import type { BaseOption } from "../shared/types";
+import {
+ shouldFilterCategory,
+ getComponentScore,
+} from "../shared/component-utils";
export type ComponentOption = BaseOption & {
type: "component";
@@ -41,48 +41,77 @@ export type ComponentOption = BaseOption & {
firstInstance: { component: string };
};
-const getComponentScore = (meta: ComponentOption) => {
- const categoryScore = componentCategories.indexOf(meta.category ?? "hidden");
- const componentScore = meta.order ?? Number.MAX_SAFE_INTEGER;
- // shift category
- return categoryScore * 1000 + componentScore;
-};
-
export const $componentOptions = computed(
- [$registeredComponentMetas, $registeredTemplates, $selectedPage],
- (metas, templates, selectedPage) => {
+ [
+ $isCommandPanelOpen,
+ $registeredComponentMetas,
+ $registeredTemplates,
+ $selectedPage,
+ ],
+ (isOpen, metas, templates, selectedPage) => {
const componentOptions: ComponentOption[] = [];
- for (const [name, meta] of metas) {
- const category = meta.category ?? "hidden";
- if (category === "hidden" || category === "internal") {
- continue;
- }
+ if (!isOpen) {
+ return componentOptions;
+ }
+ const addComponentOption = ({
+ name,
+ category,
+ label,
+ icon,
+ order,
+ firstInstance,
+ }: {
+ name: string;
+ category: TemplateMeta["category"];
+ label: string;
+ icon?: string;
+ order?: number;
+ firstInstance: { component: string };
+ }) => {
// show only xml category and collection component in xml documents
if (selectedPage?.meta.documentType === "xml") {
if (category !== "xml" && name !== collectionComponent) {
- continue;
+ return;
}
} else {
// show everything except xml category in html documents
if (category === "xml") {
- continue;
+ return;
}
}
- const label = getInstanceLabel({ component: name });
+
componentOptions.push({
terms: ["components", label, category],
type: "component",
component: name,
label,
category,
+ icon,
+ order,
+ firstInstance,
+ });
+ };
+
+ for (const [name, meta] of metas) {
+ if (shouldFilterCategory(meta.category)) {
+ continue;
+ }
+ const category = meta.category ?? "hidden";
+ const label = meta.label ?? getInstanceLabel({ component: name });
+
+ addComponentOption({
+ name,
+ category,
+ label,
icon: meta.icon,
order: meta.order,
firstInstance: { component: name },
});
}
+
for (const [name, meta] of templates) {
- if (meta.category === "hidden" || meta.category === "internal") {
+ if (shouldFilterCategory(meta.category)) {
continue;
}
@@ -91,17 +120,17 @@ export const $componentOptions = computed(
meta.label ??
componentMeta?.label ??
getInstanceLabel({ component: name });
- componentOptions.push({
- terms: ["components", label, meta.category],
- type: "component",
- component: name,
- label,
+
+ addComponentOption({
+ name,
category: meta.category,
+ label,
icon: meta.icon ?? componentMeta?.icon,
order: meta.order,
firstInstance: meta.template.instances[0],
});
}
+
componentOptions.sort(
(leftOption, rightOption) =>
getComponentScore(leftOption) - getComponentScore(rightOption)
diff --git a/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
index de47531817..7bb076d574 100644
--- a/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/css-variables-group.tsx
@@ -23,6 +23,7 @@ import { deleteProperty } from "~/builder/features/style-panel/shared/use-style-
import { InstanceList, showInstance } from "../shared/instance-list";
import {
$commandContent,
+ $isCommandPanelOpen,
closeCommandPanel,
focusCommandPanel,
} from "../command-state";
@@ -38,9 +39,12 @@ export type CssVariableOption = BaseOption & {
};
export const $cssVariableOptions = computed(
- [$cssVariableDefinitionsByVariable, $unusedCssVariables],
- (definitionsByVariable, unusedVariables) => {
+ [$isCommandPanelOpen, $cssVariableDefinitionsByVariable, $unusedCssVariables],
+ (isOpen, definitionsByVariable, unusedVariables) => {
const cssVariableOptions: CssVariableOption[] = [];
+ if (!isOpen) {
+ return cssVariableOptions;
+ }
// Create options for each defined CSS variable on each instance
for (const [property, instanceIds] of definitionsByVariable) {
diff --git a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
index fb75e8fe67..e3707a432f 100644
--- a/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/data-variables-group.tsx
@@ -12,6 +12,7 @@ import {
import { $dataSources } from "~/shared/nano-states";
import {
$commandContent,
+ $isCommandPanelOpen,
closeCommandPanel,
focusCommandPanel,
} from "../command-state";
@@ -36,9 +37,12 @@ export type DataVariableOption = BaseOption & {
};
export const $dataVariableOptions = computed(
- [$dataSources, $usedVariablesInInstances],
- (dataSources, usedInInstances) => {
+ [$isCommandPanelOpen, $dataSources, $usedVariablesInInstances],
+ (isOpen, dataSources, usedInInstances) => {
const dataVariableOptions: DataVariableOption[] = [];
+ if (!isOpen) {
+ return dataVariableOptions;
+ }
for (const dataSource of dataSources.values()) {
if (
diff --git a/apps/builder/app/builder/features/command-panel/groups/pages-group.tsx b/apps/builder/app/builder/features/command-panel/groups/pages-group.tsx
index 66d6477893..b3e120c6a6 100644
--- a/apps/builder/app/builder/features/command-panel/groups/pages-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/pages-group.tsx
@@ -10,7 +10,7 @@ import type { Page } from "@webstudio-is/sdk";
import { $pages, $editingPageId } from "~/shared/nano-states";
import { $selectedPage, selectPage } from "~/shared/awareness";
import { setActiveSidebarPanel } from "~/builder/shared/nano-states";
-import { closeCommandPanel } from "../command-state";
+import { closeCommandPanel, $isCommandPanelOpen } from "../command-state";
import type { BaseOption } from "../shared/types";
export type PageOption = BaseOption & {
@@ -19,8 +19,11 @@ export type PageOption = BaseOption & {
};
export const $pageOptions = computed(
- [$pages, $selectedPage],
- (pages, selectedPage) => {
+ [$isCommandPanelOpen, $pages, $selectedPage],
+ (isOpen, pages, selectedPage) => {
+ if (!isOpen) {
+ return [];
+ }
const pageOptions: PageOption[] = [];
if (pages) {
for (const page of [pages.homePage, ...pages.pages]) {
diff --git a/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx
index 58d9858770..ddc578c9a0 100644
--- a/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/tags-group.tsx
@@ -18,7 +18,7 @@ import { insertWebstudioFragmentAt } from "~/shared/instance-utils";
import { $selectedInstancePath } from "~/shared/awareness";
import { InstanceIcon } from "~/builder/shared/instance-label";
import { isTreeSatisfyingContentModel } from "~/shared/content-model";
-import { closeCommandPanel } from "../command-state";
+import { closeCommandPanel, $isCommandPanelOpen } from "../command-state";
import type { BaseOption } from "../shared/types";
export type TagOption = BaseOption & {
@@ -27,9 +27,18 @@ export type TagOption = BaseOption & {
};
export const $tagOptions = computed(
- [$selectedInstancePath, $instances, $props, $registeredComponentMetas],
- (instancePath, instances, props, metas) => {
+ [
+ $isCommandPanelOpen,
+ $selectedInstancePath,
+ $instances,
+ $props,
+ $registeredComponentMetas,
+ ],
+ (isOpen, instancePath, instances, props, metas) => {
const tagOptions: TagOption[] = [];
+ if (!isOpen) {
+ return tagOptions;
+ }
if (instancePath === undefined) {
return tagOptions;
}
diff --git a/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx b/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx
index 5223c771c2..09ccabeee7 100644
--- a/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx
+++ b/apps/builder/app/builder/features/command-panel/groups/tokens-group.tsx
@@ -21,6 +21,7 @@ import {
import { InstanceList, showInstance } from "../shared/instance-list";
import {
$commandContent,
+ $isCommandPanelOpen,
closeCommandPanel,
focusCommandPanel,
} from "../command-state";
@@ -34,9 +35,12 @@ export type TokenOption = BaseOption & {
};
export const $tokenOptions = computed(
- [$styleSources, $styleSourceUsages],
- (styleSources, styleSourceUsages) => {
+ [$isCommandPanelOpen, $styleSources, $styleSourceUsages],
+ (isOpen, styleSources, styleSourceUsages) => {
const tokenOptions: TokenOption[] = [];
+ if (!isOpen) {
+ return tokenOptions;
+ }
for (const styleSource of styleSources.values()) {
if (styleSource.type !== "token") {
continue;
diff --git a/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx b/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx
new file mode 100644
index 0000000000..6d6001986e
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/wrap-group.test.tsx
@@ -0,0 +1,410 @@
+import { describe, expect, test, beforeEach } from "vitest";
+import { coreMetas, elementComponent } from "@webstudio-is/sdk";
+import * as baseMetas from "@webstudio-is/sdk-components-react/metas";
+import * as animationMetas from "@webstudio-is/sdk-components-animation/metas";
+import { createDefaultPages } from "@webstudio-is/project-build";
+import { $, renderData } from "@webstudio-is/template";
+import {
+ $instances,
+ $pages,
+ $props,
+ $registeredComponentMetas,
+} from "~/shared/nano-states";
+import { registerContainers } from "~/shared/sync";
+import { $awareness, selectInstance } from "~/shared/awareness";
+import { __testing__ } from "./wrap-group";
+
+const { canWrapInstance } = __testing__;
+
+registerContainers();
+
+const metas = new Map(
+ Object.entries({ ...coreMetas, ...baseMetas, ...animationMetas })
+);
+
+beforeEach(() => {
+ $registeredComponentMetas.set(metas);
+ $pages.set(createDefaultPages({ rootInstanceId: "" }));
+ $awareness.set({ pageId: "" });
+});
+
+describe("canWrapInstance for components", () => {
+ test("should allow wrapping text in a Link", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Text ws:id="text">Hello</$.Text>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["text", "body"]);
+
+ const result = canWrapInstance(
+ "text",
+ ["text", "body"],
+ "body",
+ "Link",
+ undefined,
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should allow wrapping text in a Heading", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Text ws:id="text">Hello</$.Text>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["text", "body"]);
+
+ const result = canWrapInstance(
+ "text",
+ ["text", "body"],
+ "body",
+ "Heading",
+ undefined,
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should allow wrapping box in a Form", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ "Form",
+ undefined,
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should reject invalid wrapping (text in CodeText)", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ // CodeText only accepts text content, not boxes
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ "CodeText",
+ undefined,
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(false);
+ });
+});
+
+describe("canWrapInstance for HTML elements", () => {
+ test("should allow wrapping text in a span", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Text ws:id="text">Hello</$.Text>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["text", "body"]);
+
+ const result = canWrapInstance(
+ "text",
+ ["text", "body"],
+ "body",
+ elementComponent,
+ "span",
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should allow wrapping box in a div", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ elementComponent,
+ "div",
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should allow wrapping box in span (content model allows it)", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ // Note: The content model currently allows this even though
+ // it's not valid phrasing content in strict HTML
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ elementComponent,
+ "span",
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should allow wrapping list item in ul", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.ListItem ws:id="li">Item</$.ListItem>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["li", "body"]);
+
+ const result = canWrapInstance(
+ "li",
+ ["li", "body"],
+ "body",
+ elementComponent,
+ "ul",
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should reject wrapping box in ul (ul requires li children)", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ // ul can only contain li elements
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ elementComponent,
+ "ul",
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(false);
+ });
+});
+
+describe("canWrapInstance edge cases", () => {
+ test("should handle wrapping with Slot", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ "Slot",
+ undefined,
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should allow wrapping with Collection", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ "ws:collection",
+ undefined,
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should allow wrapping with AnimateChildren", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ "@webstudio-is/sdk-components-animation:AnimateChildren",
+ undefined,
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should allow wrapping with AnimateText", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ "@webstudio-is/sdk-components-animation:AnimateText",
+ undefined,
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should allow wrapping with StaggerAnimation", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ "@webstudio-is/sdk-components-animation:StaggerAnimation",
+ undefined,
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should allow wrapping with VideoAnimation", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+
+ const result = canWrapInstance(
+ "box",
+ ["box", "body"],
+ "body",
+ "@webstudio-is/sdk-components-animation:VideoAnimation",
+ undefined,
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+
+ test("should handle wrapping multiple elements", () => {
+ $instances.set(
+ renderData(
+ <$.Body ws:id="body">
+ <$.Box ws:id="parent">
+ <$.Box ws:id="child1"></$.Box>
+ <$.Box ws:id="child2"></$.Box>
+ </$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["child1", "parent", "body"]);
+
+ const result = canWrapInstance(
+ "child1",
+ ["child1", "parent", "body"],
+ "parent",
+ elementComponent,
+ "div",
+ $instances.get(),
+ $props.get(),
+ $registeredComponentMetas.get()
+ );
+ expect(result).toBe(true);
+ });
+});
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.tsx
new file mode 100644
index 0000000000..25562fabe7
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/groups/wrap-group.tsx
@@ -0,0 +1,310 @@
+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 type {
+ Instance,
+ Instances,
+ Props,
+ WsComponentMeta,
+} 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 { isTreeSatisfyingContentModel } from "~/shared/content-model";
+import {
+ $commandContent,
+ $isCommandPanelOpen,
+ closeCommandPanel,
+} from "../command-state";
+import { useState } from "react";
+import { BackButton } from "../shared/back-button";
+import { wrapIn } from "~/shared/instance-utils";
+
+type WrapOption = {
+ component: string;
+ tag?: string;
+ label: string;
+ category?: string;
+ order?: number;
+};
+
+// Component names we want to allow as wrappers
+// These will be looked up in the registered metas to get the full namespaced name
+const wrapperComponentNames = [
+ "Element",
+ "Slot",
+ "Collection",
+ "AnimateChildren",
+ "AnimateText",
+ "StaggerAnimation",
+ "VideoAnimation",
+ "Form",
+];
+
+// Check if an instance can be wrapped with a specific component or tag
+const canWrapInstance = (
+ selectedInstanceId: string,
+ selectedInstanceSelector: string[],
+ parentInstanceId: string,
+ component: string,
+ tag: string | undefined,
+ instances: Instances,
+ props: Props,
+ metas: Map<Instance["component"], WsComponentMeta>
+): boolean => {
+ const selectedInstance = instances.get(selectedInstanceId);
+ const parentInstance = instances.get(parentInstanceId);
+
+ if (!selectedInstance || !parentInstance) {
+ return false;
+ }
+
+ const wrapperInstance: Instance = {
+ type: "instance",
+ id: "wrapper_instance",
+ component,
+ children: [{ type: "id", value: selectedInstanceId }],
+ };
+
+ if (tag || component === elementComponent) {
+ wrapperInstance.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) {
+ wrapperInstance.tag = defaultTag;
+ }
+ }
+
+ const newInstances = new Map(instances);
+ newInstances.set(wrapperInstance.id, wrapperInstance);
+
+ // Update parent to point to wrapper
+ const newParentInstance = { ...parentInstance };
+ newParentInstance.children = parentInstance.children.map((child) => {
+ if (child.type === "id" && child.value === selectedInstanceId) {
+ return { type: "id", value: wrapperInstance.id };
+ }
+ return child;
+ });
+ newInstances.set(parentInstance.id, newParentInstance);
+
+ // Validate the wrapper in the parent
+ const wrapperValid = isTreeSatisfyingContentModel({
+ instances: newInstances,
+ props,
+ metas,
+ instanceSelector: [
+ wrapperInstance.id,
+ ...selectedInstanceSelector.slice(1),
+ ],
+ });
+
+ if (!wrapperValid) {
+ return false;
+ }
+
+ // Validate the selected instance inside the wrapper
+ const childValid = isTreeSatisfyingContentModel({
+ instances: newInstances,
+ props,
+ metas,
+ instanceSelector: [
+ selectedInstanceId,
+ wrapperInstance.id,
+ ...selectedInstanceSelector.slice(1),
+ ],
+ });
+
+ return childValid;
+};
+
+const $wrapOptions = computed(
+ [
+ $isCommandPanelOpen,
+ $selectedInstancePath,
+ $instances,
+ $props,
+ $registeredComponentMetas,
+ ],
+ (isOpen, instancePath, instances, props, metas) => {
+ const wrapOptions: WrapOption[] = [];
+ if (!isOpen) {
+ return wrapOptions;
+ }
+ if (instancePath === undefined || instancePath.length === 1) {
+ return wrapOptions;
+ }
+ const [selectedItem, parentItem] = instancePath;
+
+ // Build list of allowed wrappers from registered metas
+ const allowedComponents: string[] = [];
+ for (const [componentName, meta] of metas) {
+ // Check if this component is in our wrapper list by:
+ // 1. Exact component name match
+ // 2. Label match
+ // 3. Ends with wrapper name after namespace (e.g., "namespace:WrapperName")
+ const matchesName = wrapperComponentNames.includes(componentName);
+ const matchesLabel =
+ meta.label && wrapperComponentNames.includes(meta.label);
+ const matchesNamespacedName = wrapperComponentNames.some((wrapperName) =>
+ componentName.endsWith(`:${wrapperName}`)
+ );
+
+ if (matchesName || matchesLabel || matchesNamespacedName) {
+ allowedComponents.push(componentName);
+ }
+ }
+
+ // Test each allowed component
+ for (const component of allowedComponents) {
+ if (
+ canWrapInstance(
+ selectedItem.instance.id,
+ selectedItem.instanceSelector,
+ parentItem.instance.id,
+ component,
+ undefined,
+ instances,
+ props,
+ metas
+ )
+ ) {
+ const meta = metas.get(component);
+ const label = getInstanceLabel({ component });
+ wrapOptions.push({
+ component,
+ label,
+ category: meta?.category,
+ order: meta?.order,
+ });
+ }
+ }
+
+ // Test all valid HTML tags
+ for (const tag of tags) {
+ if (
+ canWrapInstance(
+ selectedItem.instance.id,
+ selectedItem.instanceSelector,
+ parentItem.instance.id,
+ elementComponent,
+ tag,
+ instances,
+ props,
+ metas
+ )
+ ) {
+ const label = getInstanceLabel({ component: elementComponent, tag });
+ wrapOptions.push({
+ component: elementComponent,
+ tag,
+ label,
+ });
+ }
+ }
+
+ return wrapOptions;
+ }
+);
+
+const WrapComponentsList = () => {
+ const [search, setSearch] = useState("");
+ const wrapOptions = $wrapOptions.get();
+
+ let matches = wrapOptions;
+ if (search.trim().length > 0) {
+ for (const word of search.trim().split(/\s+/)) {
+ matches = matchSorter(matches, word, {
+ keys: ["label"],
+ });
+ }
+ }
+
+ return (
+ <>
+ <CommandInput
+ action="wrap"
+ placeholder="Search components to wrap with..."
+ 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 are allowed to wrap this instance
+ </Text>
+ </Flex>
+ ) : (
+ <CommandGroup name="wrap-components" actions={["wrap"]}>
+ {matches.map(({ component, tag, label }) => {
+ const key = tag ? `${component}:${tag}` : component;
+ return (
+ <CommandItem
+ key={key}
+ value={key}
+ onSelect={() => {
+ wrapIn(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 showWrapComponentsList = () => {
+ $commandContent.set(<WrapComponentsList />);
+};
+
+export const __testing__ = {
+ canWrapInstance,
+};
diff --git a/apps/builder/app/builder/features/command-panel/index.ts b/apps/builder/app/builder/features/command-panel/index.ts
index feaf2671b8..b1f4a8befc 100644
--- a/apps/builder/app/builder/features/command-panel/index.ts
+++ b/apps/builder/app/builder/features/command-panel/index.ts
@@ -1,2 +1,2 @@
-export { openCommandPanel } from "./command-state";
+export { openCommandPanel, $commandSearch } from "./command-state";
export * from "./command-panel";
diff --git a/apps/builder/app/builder/features/command-panel/shared/back-button.tsx b/apps/builder/app/builder/features/command-panel/shared/back-button.tsx
new file mode 100644
index 0000000000..b9f992ec0f
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/shared/back-button.tsx
@@ -0,0 +1,16 @@
+import { Button, Kbd } from "@webstudio-is/design-system";
+import { $commandContent } from "../command-state";
+
+export const BackButton = () => {
+ return (
+ <Button
+ tabIndex={-1}
+ color="ghost"
+ onClick={() => {
+ $commandContent.set(undefined);
+ }}
+ >
+ <Kbd value={["backspace"]} /> Back
+ </Button>
+ );
+};
diff --git a/apps/builder/app/builder/features/command-panel/shared/component-utils.ts b/apps/builder/app/builder/features/command-panel/shared/component-utils.ts
new file mode 100644
index 0000000000..0ab8126a9d
--- /dev/null
+++ b/apps/builder/app/builder/features/command-panel/shared/component-utils.ts
@@ -0,0 +1,35 @@
+import { componentCategories } from "@webstudio-is/sdk";
+
+/**
+ * Normalizes a component's category, defaulting undefined to "hidden"
+ */
+export const normalizeCategory = (
+ category: string | undefined
+): (typeof componentCategories)[number] => {
+ return (category ?? "hidden") as (typeof componentCategories)[number];
+};
+
+/**
+ * Checks if a component should be filtered out based on its category
+ */
+export const shouldFilterCategory = (category: string | undefined): boolean => {
+ const normalized = normalizeCategory(category);
+ return normalized === "hidden" || normalized === "internal";
+};
+
+type ComponentMetaLike = {
+ category?: string;
+ order?: number;
+};
+
+/**
+ * Calculates a sort score for a component based on category and order.
+ * Used to sort components in the same way across the application.
+ */
+export const getComponentScore = (meta: ComponentMetaLike): number => {
+ const category = normalizeCategory(meta.category);
+ const categoryScore = componentCategories.indexOf(category);
+ const componentScore = meta.order ?? Number.MAX_SAFE_INTEGER;
+ // Shift category score to ensure category takes precedence over order
+ return categoryScore * 1000 + componentScore;
+};
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.tsx
index 213630df58..efd74f69e8 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
@@ -9,8 +9,6 @@ import {
Flex,
ScrollArea,
Text,
- Button,
- Kbd,
} from "@webstudio-is/design-system";
import type { Instance } from "@webstudio-is/sdk";
import { $instances, $pages } from "~/shared/nano-states";
@@ -19,6 +17,7 @@ import { $awareness, findAwarenessByInstanceId } from "~/shared/awareness";
import { buildInstancePath } from "~/shared/instance-utils";
import { $commandContent } from "../command-state";
import { $activeInspectorPanel } from "~/builder/shared/nano-states";
+import { BackButton } from "./back-button";
export type InstanceOption = {
label: string;
@@ -68,6 +67,7 @@ export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {
<>
<CommandInput
action="select"
+ placeholder="Search instances..."
value={search}
onValueChange={setSearch}
onKeyDown={(event) => {
@@ -111,9 +111,7 @@ export const InstanceList = ({ instanceIds, onSelect }: InstanceListProps) => {
</Flex>
<CommandGroupFooter>
<Flex grow>
- <Button tabIndex={-1} color="ghost" onClick={goBack}>
- <Kbd value={["backspace"]} /> Back
- </Button>
+ <BackButton />
</Flex>
</CommandGroupFooter>
</>
diff --git a/apps/builder/app/builder/shared/commands.test.tsx b/apps/builder/app/builder/shared/commands.test.tsx
index c1d132daa6..d36156748b 100644
--- a/apps/builder/app/builder/shared/commands.test.tsx
+++ b/apps/builder/app/builder/shared/commands.test.tsx
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
-import { coreMetas } from "@webstudio-is/sdk";
+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";
@@ -11,13 +11,7 @@ import {
} from "~/shared/nano-states";
import { registerContainers } from "~/shared/sync";
import { $awareness, selectInstance } from "~/shared/awareness";
-import {
- deleteSelectedInstance,
- replaceWith,
- unwrap,
- wrapIn,
-} from "./commands";
-import { elementComponent } from "@webstudio-is/sdk";
+import { deleteSelectedInstance, replaceWith, unwrap } from "./commands";
registerContainers();
@@ -85,95 +79,6 @@ describe("deleteInstance", () => {
});
});
-describe("wrap in", () => {
- test("wrap instance in link", () => {
- $instances.set(
- renderData(
- <ws.element ws:tag="body" ws:id="bodyId">
- <ws.element ws:tag="div" ws:id="divId"></ws.element>
- </ws.element>
- ).instances
- );
- selectInstance(["divId", "bodyId"]);
- wrapIn(elementComponent, "a");
- expect($instances.get()).toEqual(
- renderData(
- <ws.element ws:tag="body" ws:id="bodyId">
- <ws.element ws:tag="a" ws:id={expect.any(String)}>
- <ws.element ws:tag="div" ws:id="divId"></ws.element>
- </ws.element>
- </ws.element>
- ).instances
- );
- });
-
- test("wrap image in element", () => {
- $instances.set(
- renderData(
- <ws.element ws:tag="body" ws:id="bodyId">
- <ws.element ws:tag="img" ws:id="imageId"></ws.element>
- </ws.element>
- ).instances
- );
- selectInstance(["imageId", "bodyId"]);
- wrapIn(elementComponent);
- expect($instances.get()).toEqual(
- renderData(
- <ws.element ws:tag="body" ws:id="bodyId">
- <ws.element ws:tag="div" ws:id={expect.any(String)}>
- <ws.element ws:tag="img" ws:id="imageId"></ws.element>
- </ws.element>
- </ws.element>
- ).instances
- );
- });
-
- test("avoid wrapping text with link in link", () => {
- const { instances } = renderData(
- <ws.element ws:tag="body" ws:id="bodyId">
- <ws.element ws:tag="p" ws:id="textId">
- <ws.element ws:tag="a" ws:id="linkId"></ws.element>
- </ws.element>
- </ws.element>
- );
- $instances.set(instances);
- selectInstance(["textId", "bodyId"]);
- wrapIn(elementComponent, "a");
- // nothing is changed
- expect($instances.get()).toEqual(instances);
- });
-
- test("avoid wrapping textual content", () => {
- const { instances } = renderData(
- <ws.element ws:tag="body" ws:id="bodyId">
- <ws.element ws:tag="div" ws:id="textId">
- <ws.element ws:tag="bold" ws:id="boldId"></ws.element>
- </ws.element>
- </ws.element>
- );
- $instances.set(instances);
- selectInstance(["boldId", "textId", "bodyId"]);
- wrapIn(elementComponent);
- // nothing is changed
- expect($instances.get()).toEqual(instances);
- });
-
- test("avoid wrapping list item", () => {
- const { instances } = renderData(
- <ws.element ws:tag="body" ws:id="bodyId">
- <ws.element ws:tag="ul" ws:id="listId">
- <ws.element ws:tag="li" ws:id="listItemId"></ws.element>
- </ws.element>
- </ws.element>
- );
- $instances.set(instances);
- selectInstance(["listItemId", "listId", "bodyId"]);
- wrapIn(elementComponent);
- // nothing is changed
- expect($instances.get()).toEqual(instances);
- });
-});
-
describe("replace with", () => {
test("replace legacy tag with element", () => {
const { instances, props } = renderData(
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index 9ada4ed0b9..8ddccb66cb 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -1,10 +1,8 @@
-import { nanoid } from "nanoid";
import {
blockTemplateComponent,
elementComponent,
isComponentDetachable,
} from "@webstudio-is/sdk";
-import type { Instance } from "@webstudio-is/sdk";
import { toast } from "@webstudio-is/design-system";
import { createCommandsEmitter, type Command } from "~/shared/commands-emitter";
import {
@@ -41,13 +39,13 @@ import {
} from "./nano-states";
import { $selectedInstancePath, selectInstance } from "~/shared/awareness";
import { openCommandPanel } from "../features/command-panel";
+import { showWrapComponentsList } from "../features/command-panel/groups/wrap-group";
import { builderApi } from "~/shared/builder-api";
import { getSetting, setSetting } from "./client-settings";
import { findAvailableVariables } from "~/shared/data-variables";
import { atom } from "nanostores";
import {
findClosestNonTextualContainer,
- isRichTextContent,
isTreeSatisfyingContentModel,
} from "~/shared/content-model";
import { generateFragmentFromHtml } from "~/shared/html";
@@ -151,65 +149,6 @@ export const deleteSelectedInstance = () => {
});
};
-export const wrapIn = (component: string, tag?: string) => {
- const instancePath = $selectedInstancePath.get();
- // global root or body are selected
- if (instancePath === undefined || instancePath.length === 1) {
- return;
- }
- const [selectedItem, parentItem] = instancePath;
- const selectedInstance = selectedItem.instance;
- const newInstanceId = nanoid();
- const newInstanceSelector = [newInstanceId, ...parentItem.instanceSelector];
- const metas = $registeredComponentMetas.get();
- try {
- updateWebstudioData((data) => {
- const isContent = isRichTextContent({
- instanceSelector: selectedItem.instanceSelector,
- instances: data.instances,
- props: data.props,
- metas,
- });
- if (isContent) {
- toast.error(`Cannot wrap textual content`);
- throw Error("Abort transaction");
- }
- const newInstance: Instance = {
- type: "instance",
- id: newInstanceId,
- component,
- children: [{ type: "id", value: selectedInstance.id }],
- };
- if (tag || component === elementComponent) {
- newInstance.tag = tag ?? "div";
- }
- const parentInstance = data.instances.get(parentItem.instance.id);
- data.instances.set(newInstanceId, newInstance);
- if (parentInstance) {
- for (const child of parentInstance.children) {
- if (child.type === "id" && child.value === selectedInstance.id) {
- child.value = newInstanceId;
- }
- }
- }
- const isSatisfying = isTreeSatisfyingContentModel({
- instances: data.instances,
- props: data.props,
- metas,
- instanceSelector: newInstanceSelector,
- });
- if (isSatisfying === false) {
- const label = getInstanceLabel({ component, tag });
- toast.error(`Cannot wrap in ${label}`);
- throw Error("Abort transaction");
- }
- });
- selectInstance(newInstanceSelector);
- } catch {
- // do nothing
- }
-};
-
export const replaceWith = (component: string, tag?: string) => {
const instancePath = $selectedInstancePath.get();
// global root or body are selected
@@ -601,16 +540,13 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
},
},
{
- name: "wrapInElement",
- label: "Wrap in an Element",
- description: "Wrap in new element",
- handler: () => wrapIn(elementComponent),
- },
- {
- name: "wrapInLink",
- label: "Wrap in a Link",
- description: "Wrap in link element",
- handler: () => wrapIn(elementComponent, "a"),
+ name: "wrap",
+ label: "Wrap",
+ description: "Wrap",
+ keepCommandPanelOpen: true,
+ handler: () => {
+ showWrapComponentsList();
+ },
},
{
name: "unwrap",
diff --git a/apps/builder/app/shared/commands-emitter.ts b/apps/builder/app/shared/commands-emitter.ts
index 9b20960d28..ac1bcef21e 100644
--- a/apps/builder/app/shared/commands-emitter.ts
+++ b/apps/builder/app/shared/commands-emitter.ts
@@ -24,6 +24,10 @@ export type CommandMeta<CommandName extends string> = {
* hide the command in meta+k panel
*/
hidden?: boolean;
+ /**
+ * keep command panel open after executing the command
+ */
+ keepCommandPanelOpen?: boolean;
};
type CommandHandler = () => void;
diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsx
index 3713b4ffa4..a5b7eb3196 100644
--- a/apps/builder/app/shared/instance-utils.test.tsx
+++ b/apps/builder/app/shared/instance-utils.test.tsx
@@ -23,7 +23,11 @@ import type {
WebstudioFragment,
WsComponentMeta,
} from "@webstudio-is/sdk";
-import { coreMetas, portalComponent } from "@webstudio-is/sdk";
+import {
+ coreMetas,
+ portalComponent,
+ elementComponent,
+} from "@webstudio-is/sdk";
import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
import {
deleteInstanceMutable,
@@ -36,6 +40,7 @@ import {
insertWebstudioFragmentAt,
insertWebstudioElementAt,
buildInstancePath,
+ wrapIn,
} from "./instance-utils";
import {
$assets,
@@ -1011,6 +1016,95 @@ describe("delete instance", () => {
});
});
+describe("wrap in", () => {
+ test("wrap instance in link", () => {
+ $instances.set(
+ renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="div" ws:id="divId"></ws.element>
+ </ws.element>
+ ).instances
+ );
+ selectInstance(["divId", "bodyId"]);
+ wrapIn(elementComponent, "a");
+ expect($instances.get()).toEqual(
+ renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="a" ws:id={expect.any(String)}>
+ <ws.element ws:tag="div" ws:id="divId"></ws.element>
+ </ws.element>
+ </ws.element>
+ ).instances
+ );
+ });
+
+ test("wrap image in element", () => {
+ $instances.set(
+ renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="img" ws:id="imageId"></ws.element>
+ </ws.element>
+ ).instances
+ );
+ selectInstance(["imageId", "bodyId"]);
+ wrapIn(elementComponent);
+ expect($instances.get()).toEqual(
+ renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="div" ws:id={expect.any(String)}>
+ <ws.element ws:tag="img" ws:id="imageId"></ws.element>
+ </ws.element>
+ </ws.element>
+ ).instances
+ );
+ });
+
+ test("avoid wrapping text with link in link", () => {
+ const { instances } = renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="p" ws:id="textId">
+ <ws.element ws:tag="a" ws:id="linkId"></ws.element>
+ </ws.element>
+ </ws.element>
+ );
+ $instances.set(instances);
+ selectInstance(["textId", "bodyId"]);
+ wrapIn(elementComponent, "a");
+ // nothing is changed
+ expect($instances.get()).toEqual(instances);
+ });
+
+ test("avoid wrapping textual content", () => {
+ const { instances } = renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="div" ws:id="textId">
+ <ws.element ws:tag="bold" ws:id="boldId"></ws.element>
+ </ws.element>
+ </ws.element>
+ );
+ $instances.set(instances);
+ selectInstance(["boldId", "textId", "bodyId"]);
+ wrapIn(elementComponent);
+ // nothing is changed
+ expect($instances.get()).toEqual(instances);
+ });
+
+ test("avoid wrapping list item", () => {
+ const { instances } = renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="ul" ws:id="listId">
+ <ws.element ws:tag="li" ws:id="listItemId"></ws.element>
+ </ws.element>
+ </ws.element>
+ );
+ $instances.set(instances);
+ selectInstance(["listItemId", "listId", "bodyId"]);
+ wrapIn(elementComponent);
+ // nothing is changed
+ expect($instances.get()).toEqual(instances);
+ });
+});
+
describe("extract webstudio fragment", () => {
test("collect all styles and breakpoints bound to fragment instances", () => {
// body
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index b0dea5db60..3bc29312e1 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -79,6 +79,7 @@ import {
findClosestNonTextualContainer,
isRichTextTree,
isTreeSatisfyingContentModel,
+ isRichTextContent,
} from "./content-model";
import type { Project } from "@webstudio-is/project";
import { getInstanceLabel } from "~/builder/shared/instance-label";
@@ -609,6 +610,69 @@ export const deleteInstanceMutable = (
return true;
};
+export const wrapIn = (component: string, tag?: string) => {
+ const instancePath = $selectedInstancePath.get();
+ // global root or body are selected
+ if (instancePath === undefined || instancePath.length === 1) {
+ return;
+ }
+ const [selectedItem, parentItem] = instancePath;
+ const selectedInstance = selectedItem.instance;
+ const newInstanceId = nanoid();
+ const newInstanceSelector = [newInstanceId, ...parentItem.instanceSelector];
+ const metas = $registeredComponentMetas.get();
+
+ try {
+ updateWebstudioData((data) => {
+ const isContent = isRichTextContent({
+ instanceSelector: selectedItem.instanceSelector,
+ instances: data.instances,
+ props: data.props,
+ metas,
+ });
+ if (isContent) {
+ toast.error(`Cannot wrap textual content`);
+ throw Error("Abort transaction");
+ }
+ const newInstance: Instance = {
+ type: "instance",
+ id: newInstanceId,
+ component,
+ children: [{ type: "id", value: selectedInstance.id }],
+ };
+
+ if (tag || component === elementComponent) {
+ newInstance.tag = tag ?? "div";
+ }
+ const parentInstance = data.instances.get(parentItem.instance.id);
+ data.instances.set(newInstanceId, newInstance);
+ if (parentInstance) {
+ for (const child of parentInstance.children) {
+ if (child.type === "id" && child.value === selectedInstance.id) {
+ child.value = newInstanceId;
+ }
+ }
+ }
+
+ const isSatisfying = isTreeSatisfyingContentModel({
+ instances: data.instances,
+ props: data.props,
+ metas,
+ instanceSelector: newInstanceSelector,
+ });
+
+ if (isSatisfying === false) {
+ const label = getInstanceLabel({ component, tag });
+ toast.error(`Cannot wrap in ${label}`);
+ throw Error("Abort transaction");
+ }
+ });
+ selectInstance(newInstanceSelector);
+ } catch {
+ // do nothing
+ }
+};
+
const traverseStyleValue = (
value: StyleValue,
callback: (value: StyleValue) => void
diff --git a/packages/design-system/src/components/command.tsx b/packages/design-system/src/components/command.tsx
index 594690213a..45560b3bf1 100644
--- a/packages/design-system/src/components/command.tsx
+++ b/packages/design-system/src/components/command.tsx
@@ -169,18 +169,23 @@ const CommandInputField = styled(CommandPrimitive.Input, {
export const CommandInput = (
props: ComponentPropsWithoutRef<typeof CommandPrimitive.Input> & {
action?: string;
+ placeholder?: string;
}
) => {
const inputRef = useRef<HTMLInputElement>(null);
const contextAction = useSelectedAction();
- const { action = contextAction, ...inputProps } = props;
+ const {
+ action = contextAction,
+ placeholder = "Type a command or search...",
+ ...inputProps
+ } = props;
return (
<CommandInputContainer>
<CommandInputIcon />
<CommandInputField
ref={inputRef}
autoFocus={true}
- placeholder="Type a command or search..."
+ placeholder={placeholder}
{...inputProps}
onValueChange={(value) => {
// reset scroll whenever search is changed
diff --git a/packages/sdk-components-react/src/blockquote.tsx b/packages/sdk-components-react/src/blockquote.tsx
index 1b4465eda7..c27a2fd707 100644
--- a/packages/sdk-components-react/src/blockquote.tsx
+++ b/packages/sdk-components-react/src/blockquote.tsx
@@ -1,3 +1,7 @@
+/**
+ * @deprecated This component will be replaced by the Element component in the future.
+ * Use Element with tag="blockquote" instead.
+ */
import { forwardRef, type ElementRef, type ComponentProps } from "react";
export const defaultTag = "blockquote";
diff --git a/packages/sdk-components-react/src/code-text.tsx b/packages/sdk-components-react/src/code-text.tsx
index d2693c2e8c..b617859553 100644
--- a/packages/sdk-components-react/src/code-text.tsx
+++ b/packages/sdk-components-react/src/code-text.tsx
@@ -1,3 +1,7 @@
+/**
+ * @deprecated This component will be replaced by the Element component in the future.
+ * Use Element with tag="code" instead.
+ */
import {
type ElementRef,
type ComponentProps,
diff --git a/packages/sdk-components-react/src/heading.tsx b/packages/sdk-components-react/src/heading.tsx
index c5cdb8cf4e..365cd90e52 100644
--- a/packages/sdk-components-react/src/heading.tsx
+++ b/packages/sdk-components-react/src/heading.tsx
@@ -1,3 +1,7 @@
+/**
+ * @deprecated This component will be replaced by the Element component in the future.
+ * Use Element with tag="h1", "h2", etc. instead.
+ */
import {
forwardRef,
type ElementRef,
diff --git a/packages/sdk-components-react/src/link.tsx b/packages/sdk-components-react/src/link.tsx
index a33d6b77fe..6e328ceecc 100644
--- a/packages/sdk-components-react/src/link.tsx
+++ b/packages/sdk-components-react/src/link.tsx
@@ -1,3 +1,7 @@
+/**
+ * @deprecated This component will be replaced by the Element component in the future.
+ * Use Element with tag="a" instead.
+ */
import { forwardRef, type ComponentProps } from "react";
export const defaultTag = "a";
diff --git a/packages/sdk-components-react/src/list.tsx b/packages/sdk-components-react/src/list.tsx
index 02dca367cf..92fcab98e2 100644
--- a/packages/sdk-components-react/src/list.tsx
+++ b/packages/sdk-components-react/src/list.tsx
@@ -1,3 +1,7 @@
+/**
+ * @deprecated This component will be replaced by the Element component in the future.
+ * Use Element with tag="ul" or tag="ol" instead.
+ */
import {
forwardRef,
createElement,
diff --git a/packages/sdk-components-react/src/paragraph.tsx b/packages/sdk-components-react/src/paragraph.tsx
index f7370c6ffb..1aa33f2e15 100644
--- a/packages/sdk-components-react/src/paragraph.tsx
+++ b/packages/sdk-components-react/src/paragraph.tsx
@@ -1,3 +1,7 @@
+/**
+ * @deprecated This component will be replaced by the Element component in the future.
+ * Use Element with tag="p" instead.
+ */
import { forwardRef, type ElementRef, type ComponentProps } from "react";
export const defaultTag = "p";