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.

experimental: add wrap/unwrap commands (#4588)

Bogdan Chadkin9dd1d8979b20
diff --git a/apps/builder/app/builder/features/command-panel/command-panel.tsx b/apps/builder/app/builder/features/command-panel/command-panel.tsx
index de33f6af4d..374ae2ca30 100644
--- a/apps/builder/app/builder/features/command-panel/command-panel.tsx
+++ b/apps/builder/app/builder/features/command-panel/command-panel.tsx
@@ -317,16 +317,16 @@ type ShortcutOption = {
type: "shortcut";
name: string;
label: string;
- keys: string[];
+ keys?: string[];
};
const $shortcutOptions = computed([$commandMetas], (commandMetas) => {
const shortcutOptions: ShortcutOption[] = [];
for (const [name, meta] of commandMetas) {
- if (meta.defaultHotkeys && !meta.hidden) {
+ if (!meta.hidden) {
const label = humanizeString(name);
- const keys = meta.defaultHotkeys[0]
- .split("+")
+ const keys = meta.defaultHotkeys?.[0]
+ ?.split("+")
.map((key) => (key === "meta" ? "cmd" : key));
shortcutOptions.push({
tokens: ["shortcuts", "commands", label],
@@ -337,6 +337,9 @@ const $shortcutOptions = computed([$commandMetas], (commandMetas) => {
});
}
}
+ shortcutOptions.sort(
+ (left, right) => (left.keys ? 0 : 1) - (right.keys ? 0 : 1)
+ );
return shortcutOptions;
});
@@ -358,7 +361,7 @@ const ShortcutOptionsGroup = ({ options }: { options: ShortcutOption[] }) => {
}}
>
<Text variant="labelsTitleCase">{label}</Text>
- <Kbd value={keys} />
+ {keys && <Kbd value={keys} />}
</CommandItem>
))}
</CommandGroup>
diff --git a/apps/builder/app/builder/shared/commands.test.ts b/apps/builder/app/builder/shared/commands.test.ts
deleted file mode 100644
index 7b9d9d58c5..0000000000
--- a/apps/builder/app/builder/shared/commands.test.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { describe, expect, test } from "vitest";
-import type { Instance } from "@webstudio-is/sdk";
-import * as baseMetas from "@webstudio-is/sdk-components-react/metas";
-import {
- $instances,
- $pages,
- $registeredComponentMetas,
-} from "~/shared/nano-states";
-import { registerContainers } from "~/shared/sync";
-import { emitCommand } from "./commands";
-import { createDefaultPages } from "@webstudio-is/project-build";
-import { $awareness } from "~/shared/awareness";
-
-registerContainers();
-
-const createInstancePair = (
- id: Instance["id"],
- component: string,
- children: Instance["children"]
-): [Instance["id"], Instance] => {
- return [id, { type: "instance", id, component, children }];
-};
-
-const metas = new Map(Object.entries(baseMetas));
-
-$pages.set(createDefaultPages({ rootInstanceId: "", systemDataSourceId: "" }));
-
-describe("deleteInstance", () => {
- // body
- // parent
- // child1
- // child2
- // child3
- const threeChildInstances = new Map([
- createInstancePair("body", "Body", [{ type: "id", value: "parent" }]),
- createInstancePair("parent", "Box", [
- { type: "id", value: "child1" },
- { type: "id", value: "child2" },
- { type: "id", value: "child3" },
- ]),
- createInstancePair("child1", "Box", []),
- createInstancePair("child2", "Box", []),
- createInstancePair("child3", "Box", []),
- ]);
-
- test("delete selected instance and select next one", () => {
- $registeredComponentMetas.set(metas);
- $awareness.set({
- pageId: "",
- instanceSelector: ["child2", "parent", "body"],
- });
- $instances.set(threeChildInstances);
- emitCommand("deleteInstance");
- expect($awareness.get()?.instanceSelector).toEqual([
- "child3",
- "parent",
- "body",
- ]);
- });
-
- test("delete selected instance and select previous one", () => {
- $registeredComponentMetas.set(metas);
- $awareness.set({
- pageId: "",
- instanceSelector: ["child3", "parent", "body"],
- });
- $instances.set(threeChildInstances);
- emitCommand("deleteInstance");
- expect($awareness.get()?.instanceSelector).toEqual([
- "child2",
- "parent",
- "body",
- ]);
- });
-
- test("delete selected instance and select parent one", () => {
- $awareness.set({
- pageId: "",
- instanceSelector: ["child1", "parent", "body"],
- });
- $registeredComponentMetas.set(metas);
- // body
- // parent
- // child1
- $instances.set(
- new Map([
- createInstancePair("body", "Body", [{ type: "id", value: "parent" }]),
- createInstancePair("parent", "Box", [{ type: "id", value: "child1" }]),
- createInstancePair("child1", "Box", []),
- ])
- );
- emitCommand("deleteInstance");
- expect($awareness.get()?.instanceSelector).toEqual(["parent", "body"]);
- });
-});
diff --git a/apps/builder/app/builder/shared/commands.test.tsx b/apps/builder/app/builder/shared/commands.test.tsx
new file mode 100644
index 0000000000..9fd6d7f276
--- /dev/null
+++ b/apps/builder/app/builder/shared/commands.test.tsx
@@ -0,0 +1,208 @@
+import { describe, expect, test } from "vitest";
+import * as baseMetas from "@webstudio-is/sdk-components-react/metas";
+import { createDefaultPages } from "@webstudio-is/project-build";
+import {
+ $instances,
+ $pages,
+ $registeredComponentMetas,
+} from "~/shared/nano-states";
+import { registerContainers } from "~/shared/sync";
+import { $awareness, selectInstance } from "~/shared/awareness";
+import { deleteSelectedInstance, unwrap, wrapIn } from "./commands";
+import { renderJsx, $ } from "@webstudio-is/sdk/testing";
+
+registerContainers();
+
+const metas = new Map(Object.entries(baseMetas));
+$registeredComponentMetas.set(metas);
+$pages.set(createDefaultPages({ rootInstanceId: "", systemDataSourceId: "" }));
+$awareness.set({ pageId: "" });
+
+describe("deleteInstance", () => {
+ test("delete selected instance and select next one", () => {
+ $instances.set(
+ renderJsx(
+ <$.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(
+ renderJsx(
+ <$.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(
+ renderJsx(
+ <$.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("wrap in", () => {
+ test("wrap instance in link", () => {
+ $instances.set(
+ renderJsx(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box"></$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+ wrapIn("Link");
+ expect($instances.get()).toEqual(
+ renderJsx(
+ <$.Body ws:id="body">
+ <$.Link ws:id={expect.any(String)}>
+ <$.Box ws:id="box"></$.Box>
+ </$.Link>
+ </$.Body>
+ ).instances
+ );
+ });
+
+ test("wrap image in box", () => {
+ $instances.set(
+ renderJsx(
+ <$.Body ws:id="body">
+ <$.Image ws:id="image" />
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["image", "body"]);
+ wrapIn("Box");
+ expect($instances.get()).toEqual(
+ renderJsx(
+ <$.Body ws:id="body">
+ <$.Box ws:id={expect.any(String)}>
+ <$.Image ws:id="image" />
+ </$.Box>
+ </$.Body>
+ ).instances
+ );
+ });
+
+ test("avoid wrapping text with link in link", () => {
+ const { instances } = renderJsx(
+ <$.Body ws:id="body">
+ <$.Text ws:id="text">
+ <$.RichTextLink ws:id="richtextlink"></$.RichTextLink>
+ </$.Text>
+ </$.Body>
+ );
+ $instances.set(instances);
+ selectInstance(["text", "body"]);
+ wrapIn("Link");
+ // nothing is changed
+ expect($instances.get()).toEqual(instances);
+ });
+
+ test("avoid wrapping textual content", () => {
+ const { instances } = renderJsx(
+ <$.Body ws:id="body">
+ <$.Text ws:id="text">
+ <$.Bold ws:id="bold"></$.Bold>
+ </$.Text>
+ </$.Body>
+ );
+ $instances.set(instances);
+ selectInstance(["bold", "text", "body"]);
+ wrapIn("Box");
+ // nothing is changed
+ expect($instances.get()).toEqual(instances);
+ });
+});
+
+describe("unwrap", () => {
+ test("unwrap instance", () => {
+ $instances.set(
+ renderJsx(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box">
+ <$.Image ws:id="image" />
+ <$.Text ws:id="text">text</$.Text>
+ </$.Box>
+ </$.Body>
+ ).instances
+ );
+ selectInstance(["box", "body"]);
+ unwrap();
+ expect($instances.get()).toEqual(
+ renderJsx(
+ <$.Body ws:id="body">
+ <$.Image ws:id="image" />
+ <$.Text ws:id="text">text</$.Text>
+ </$.Body>
+ ).instances
+ );
+ });
+
+ test("avoid unwrapping textual instance", () => {
+ const { instances } = renderJsx(
+ <$.Body ws:id="body">
+ <$.Text ws:id="text1">text</$.Text>
+ <$.Text ws:id="text2">
+ <$.Bold ws:id="bold">bold</$.Bold>
+ </$.Text>
+ </$.Body>
+ );
+ $instances.set(instances);
+ selectInstance(["text1", "body"]);
+ unwrap();
+ selectInstance(["text2", "body"]);
+ unwrap();
+ expect($instances.get()).toEqual(instances);
+ });
+
+ test("avoid unwrapping constrained instances", () => {
+ const { instances } = renderJsx(
+ <$.Body ws:id="body">
+ <$.List ws:id="list">
+ <$.ListItem ws:id="listitem"></$.ListItem>
+ </$.List>
+ </$.Body>
+ );
+ $instances.set(instances);
+ selectInstance(["list", "body"]);
+ unwrap();
+ expect($instances.get()).toEqual(instances);
+ });
+});
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index 93b4556aa4..ccf605bb70 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -1,4 +1,6 @@
+import { nanoid } from "nanoid";
import { blockTemplateComponent } from "@webstudio-is/react-sdk";
+import type { Instance } from "@webstudio-is/sdk";
import { toast } from "@webstudio-is/design-system";
import { createCommandsEmitter, type Command } from "~/shared/commands-emitter";
import {
@@ -10,6 +12,7 @@ import {
toggleBuilderMode,
$isPreviewMode,
$isContentMode,
+ $registeredComponentMetas,
} from "~/shared/nano-states";
import {
$breakpointsMenuView,
@@ -31,10 +34,18 @@ import {
setActiveSidebarPanel,
toggleActiveSidebarPanel,
} from "./nano-states";
-import { selectInstance } from "~/shared/awareness";
+import {
+ $parentInstance,
+ $selectedInstance,
+ selectInstance,
+} from "~/shared/awareness";
import { openCommandPanel } from "../features/command-panel";
import { builderApi } from "~/shared/builder-api";
import { findBlockSelector } from "../features/workspace/canvas-tools/outline/block-instance-outline";
+import {
+ findClosestNonTextualContainer,
+ isTreeMatching,
+} from "~/shared/matcher";
const makeBreakpointCommand = <CommandName extends string>(
name: CommandName,
@@ -50,7 +61,7 @@ const makeBreakpointCommand = <CommandName extends string>(
},
});
-const deleteSelectedInstance = () => {
+export const deleteSelectedInstance = () => {
if ($isPreviewMode.get()) {
builderApi.toast.info("Deleting is not allowed in preview mode.");
return;
@@ -131,6 +142,107 @@ const deleteSelectedInstance = () => {
});
};
+export const wrapIn = (component: string) => {
+ const selectedInstance = $selectedInstance.get();
+ const parentInstanceId = $parentInstance.get()?.id;
+ // global root or body are selected
+ if (selectedInstance === undefined || parentInstanceId === undefined) {
+ return;
+ }
+ const selectedInstanceSelector = $selectedInstanceSelector.get();
+ if (selectedInstanceSelector === undefined) {
+ return;
+ }
+ const newInstanceId = nanoid();
+ const parentInstanceSelector = selectedInstanceSelector.slice(1);
+ const newInstanceSelector = [newInstanceId, ...parentInstanceSelector];
+ const metas = $registeredComponentMetas.get();
+ try {
+ updateWebstudioData((data) => {
+ const meta = metas.get(selectedInstance.component);
+ if (meta?.type === "rich-text-child") {
+ toast.error(`Cannot wrap textual content`);
+ throw Error("Abort transaction");
+ }
+ const newInstance: Instance = {
+ type: "instance",
+ id: newInstanceId,
+ component,
+ children: [{ type: "id", value: selectedInstance.id }],
+ };
+ const parentInstance = data.instances.get(parentInstanceId);
+ 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 matches = isTreeMatching({
+ metas,
+ instances: data.instances,
+ instanceSelector: newInstanceSelector,
+ });
+ if (matches === false) {
+ toast.error(`Cannot wrap in "${component}"`);
+ throw Error("Abort transaction");
+ }
+ });
+ selectInstance(newInstanceSelector);
+ } catch {
+ // do nothing
+ }
+};
+
+export const unwrap = () => {
+ const selectedInstanceId = $selectedInstance.get()?.id;
+ const parentInstanceId = $parentInstance.get()?.id;
+ // global root or body are selected
+ if (selectedInstanceId === undefined || parentInstanceId === undefined) {
+ return;
+ }
+ const selectedInstanceSelector = $selectedInstanceSelector.get();
+ if (selectedInstanceSelector === undefined) {
+ return;
+ }
+ const parentInstanceSelector = selectedInstanceSelector.slice(1);
+ try {
+ updateWebstudioData((data) => {
+ const nonTextualIndex = findClosestNonTextualContainer({
+ metas: $registeredComponentMetas.get(),
+ instances: data.instances,
+ instanceSelector: selectedInstanceSelector,
+ });
+ if (nonTextualIndex !== 0) {
+ toast.error(`Cannot unwrap textual instance`);
+ throw Error("Abort transaction");
+ }
+ const parentInstance = data.instances.get(parentInstanceId);
+ const selectedInstance = data.instances.get(selectedInstanceId);
+ data.instances.delete(selectedInstanceId);
+ if (parentInstance && selectedInstance) {
+ const index = parentInstance.children.findIndex(
+ (child) => child.type === "id" && child.value === selectedInstanceId
+ );
+ parentInstance.children.splice(index, 1, ...selectedInstance.children);
+ }
+ const matches = isTreeMatching({
+ metas: $registeredComponentMetas.get(),
+ instances: data.instances,
+ instanceSelector: parentInstanceSelector,
+ });
+ if (matches === false) {
+ toast.error(`Cannot unwrap instance`);
+ throw Error("Abort transaction");
+ }
+ });
+ selectInstance(parentInstanceSelector);
+ } catch {
+ // do nothing
+ }
+};
+
export const { emitCommand, subscribeCommands } = createCommandsEmitter({
source: "builder",
externalCommands: [
@@ -159,6 +271,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
},
{
name: "clickCanvas",
+ hidden: true,
handler: () => {
$breakpointsMenuView.set(undefined);
setActiveSidebarPanel("auto");
@@ -345,6 +458,18 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
$editingItemSelector.set(selectedInstanceSelector);
},
},
+ {
+ name: "wrapInBox",
+ handler: () => wrapIn("Box"),
+ },
+ {
+ name: "wrapInLink",
+ handler: () => wrapIn("Link"),
+ },
+ {
+ name: "unwrap",
+ handler: () => unwrap(),
+ },
// history
diff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.ts
index 4cf022b652..3b7b12ef66 100644
--- a/apps/builder/app/canvas/shared/commands.ts
+++ b/apps/builder/app/canvas/shared/commands.ts
@@ -79,6 +79,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
{
name: "formatBold",
+ hidden: true,
handler: () => {
const editor = getActiveEditor();
editor?.dispatchCommand(FORMAT_TEXT_COMMAND, "bold");
@@ -89,6 +90,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
},
{
name: "formatItalic",
+ hidden: true,
handler: () => {
const editor = getActiveEditor();
editor?.dispatchCommand(FORMAT_TEXT_COMMAND, "italic");
@@ -97,6 +99,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
},
{
name: "formatSuperscript",
+ hidden: true,
handler: () => {
const editor = getActiveEditor();
editor?.dispatchCommand(FORMAT_TEXT_COMMAND, "superscript");
@@ -109,6 +112,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
},
{
name: "formatSubscript",
+ hidden: true,
handler: () => {
const editor = getActiveEditor();
editor?.dispatchCommand(FORMAT_TEXT_COMMAND, "subscript");
@@ -121,6 +125,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
},
{
name: "formatLink",
+ hidden: true,
handler: () => {
const editor = getActiveEditor();
if (hasSelectionFormat("link")) {
@@ -133,6 +138,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
},
{
name: "formatSpan",
+ hidden: true,
handler: () => {
const editor = getActiveEditor();
editor?.dispatchCommand(TOGGLE_SPAN_COMMAND, undefined);
@@ -141,6 +147,7 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
},
{
name: "formatClear",
+ hidden: true,
handler: () => {
const editor = getActiveEditor();
editor?.dispatchCommand(CLEAR_FORMAT_COMMAND, undefined);
diff --git a/apps/builder/app/shared/awareness.ts b/apps/builder/app/shared/awareness.ts
index 4eaacd80b7..c5f0c3eda8 100644
--- a/apps/builder/app/shared/awareness.ts
+++ b/apps/builder/app/shared/awareness.ts
@@ -65,6 +65,19 @@ export const $selectedInstance = computed(
}
);
+export const $parentInstance = computed(
+ [$instances, $virtualInstances, $awareness],
+ (instances, virtualInstances, awareness) => {
+ if (awareness?.instanceSelector === undefined) {
+ return;
+ }
+ const [_, parentInstanceId] = awareness.instanceSelector;
+ return (
+ instances.get(parentInstanceId) ?? virtualInstances.get(parentInstanceId)
+ );
+ }
+);
+
export const getInstanceKey = <
InstanceSelector extends undefined | Instance["id"][],
>(
diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsx
index c88f94e444..b210d6007e 100644
--- a/apps/builder/app/shared/instance-utils.test.tsx
+++ b/apps/builder/app/shared/instance-utils.test.tsx
@@ -3069,7 +3069,7 @@ describe("find closest insertable", () => {
$instances.set(instances);
selectInstance(["boldId", "paragraphId", "bodyId"]);
expect(findClosestInsertable(newBoxFragment)).toEqual({
- parentSelector: ["paragraphId", "bodyId"],
+ parentSelector: ["bodyId"],
position: 1,
});
});
diff --git a/apps/builder/app/shared/matcher.test.tsx b/apps/builder/app/shared/matcher.test.tsx
index f9c0fe18a3..e4423f7c5a 100644
--- a/apps/builder/app/shared/matcher.test.tsx
+++ b/apps/builder/app/shared/matcher.test.tsx
@@ -990,6 +990,24 @@ describe("find closest non textual container", () => {
).toEqual(1);
});
+ test("skips containers with rich text children", () => {
+ expect(
+ findClosestNonTextualContainer({
+ ...renderJsx(
+ <$.Body ws:id="body">
+ <$.Box ws:id="box">
+ <$.Box ws:id="box-with-bold">
+ <$.Bold ws:id="bold"></$.Bold>
+ </$.Box>
+ </$.Box>
+ </$.Body>
+ ),
+ metas,
+ instanceSelector: ["box-with-bold", "box", "body"],
+ })
+ ).toEqual(1);
+ });
+
test("allow root with text", () => {
expect(
findClosestNonTextualContainer({
diff --git a/apps/builder/app/shared/matcher.ts b/apps/builder/app/shared/matcher.ts
index 7eac050557..73ae06102f 100644
--- a/apps/builder/app/shared/matcher.ts
+++ b/apps/builder/app/shared/matcher.ts
@@ -339,6 +339,13 @@ export const findClosestNonTextualContainer = ({
if (child.type === "text" || child.type === "expression") {
hasText = true;
}
+ if (child.type === "id") {
+ const childInstance = instances.get(child.value);
+ const meta = metas.get(childInstance?.component ?? "");
+ if (meta?.type === "rich-text-child") {
+ hasText = true;
+ }
+ }
}
if (hasText) {
continue;