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
Allow inserting into editable containers (#1735)
Bogdan Chadkindcae1b5a9db7
diff --git a/apps/builder/app/canvas/canvas-shortcuts.ts b/apps/builder/app/canvas/canvas-shortcuts.tsindex 20a1814709..40531104a5 100644--- a/apps/builder/app/canvas/canvas-shortcuts.ts+++ b/apps/builder/app/canvas/canvas-shortcuts.ts@@ -2,8 +2,7 @@ import { useHotkeys } from "react-hotkeys-hook";import { shortcuts, instanceTreeShortcuts, options } from "~/shared/shortcuts";import { publish, useSubscribe } from "~/shared/pubsub";import { isPreviewModeStore } from "~/shared/nano-states";-import { enterEditingMode } from "~/shared/nano-states";-import { escapeSelection } from "~/shared/instance-utils";+import { enterEditingMode, escapeSelection } from "~/shared/instance-utils";declare module "~/shared/pubsub" {export interface PubsubMap {diff --git a/apps/builder/app/canvas/instance-selection.ts b/apps/builder/app/canvas/instance-selection.tsindex 9237e96022..0e7ea7e9d6 100644--- a/apps/builder/app/canvas/instance-selection.ts+++ b/apps/builder/app/canvas/instance-selection.ts@@ -1,4 +1,5 @@import { getInstanceSelectorFromElement } from "~/shared/dom-utils";+import { findClosestEditableInstanceSelector } from "~/shared/instance-utils";import {instancesStore,registeredComponentMetasStore,@@ -7,10 +8,6 @@ import {} from "~/shared/nano-states";import { textEditingInstanceSelectorStore } from "~/shared/nano-states";import { publish } from "~/shared/pubsub";-import {- type InstanceSelector,- getAncestorInstanceSelector,-} from "~/shared/tree-utils";declare module "~/shared/pubsub" {export interface PubsubMap {@@ -18,23 +15,6 @@ declare module "~/shared/pubsub" {}}-const findClosestRichTextInstanceSelector = (- instanceSelector: InstanceSelector-) => {- const instances = instancesStore.get();- const metas = registeredComponentMetasStore.get();- for (const instanceId of instanceSelector) {- const instance = instances.get(instanceId);- if (- instance !== undefined &&- metas.get(instance.component)?.type === "rich-text"- ) {- return getAncestorInstanceSelector(instanceSelector, instanceId);- }- }- return;-};-export const subscribeInstanceSelection = () => {let mouseDownElement: undefined | Element = undefined;@@ -77,13 +57,16 @@ export const subscribeInstanceSelection = () => {// the second click in a double click.if (event.detail === 2) {- const richTextInstanceSelector =- findClosestRichTextInstanceSelector(instanceSelector);+ const editableInstanceSelector = findClosestEditableInstanceSelector(+ instanceSelector,+ instancesStore.get(),+ registeredComponentMetasStore.get()+ );// enable text editor when double click on its instance or one of its descendants- if (richTextInstanceSelector) {- selectedInstanceSelectorStore.set(richTextInstanceSelector);- textEditingInstanceSelectorStore.set(richTextInstanceSelector);+ if (editableInstanceSelector) {+ selectedInstanceSelectorStore.set(editableInstanceSelector);+ textEditingInstanceSelectorStore.set(editableInstanceSelector);selectedStyleSourceSelectorStore.set(undefined);}}diff --git a/apps/builder/app/canvas/shared/use-drag-drop.ts b/apps/builder/app/canvas/shared/use-drag-drop.tsindex 2704a8cbf4..be243b1bc0 100644--- a/apps/builder/app/canvas/shared/use-drag-drop.ts+++ b/apps/builder/app/canvas/shared/use-drag-drop.ts@@ -13,10 +13,10 @@ import {instancesStore,registeredComponentMetasStore,} from "~/shared/nano-states";-import { textEditingInstanceSelectorStore } from "~/shared/nano-states";import { publish, useSubscribe } from "~/shared/pubsub";import {findClosestDroppableComponentIndex,+ findClosestEditableInstanceSelector,insertNewComponentInstance,reparentInstance,} from "~/shared/instance-utils";@@ -27,7 +27,6 @@ import {} from "~/shared/dom-utils";import {type InstanceSelector,- getAncestorInstanceSelector,areInstanceSelectorsEqual,} from "~/shared/tree-utils";@@ -57,23 +56,6 @@ export type DragEndPayload = {export type DragMovePayload = { canvasCoordinates: Point };-const findClosestRichTextInstanceSelector = (- instanceSelector: InstanceSelector-) => {- const instances = instancesStore.get();- const metas = registeredComponentMetasStore.get();- for (const instanceId of instanceSelector) {- const instance = instances.get(instanceId);- if (- instance !== undefined &&- metas.get(instance.component)?.type === "rich-text"- ) {- return getAncestorInstanceSelector(instanceSelector, instanceId);- }- }- return;-};-const findClosestDroppableInstanceSelector = (instanceSelector: InstanceSelector,dragPayload: DragStartPayload@@ -221,18 +203,16 @@ export const useDragAndDrop = () => {return false;}// cannot drag while editing text- if (- areInstanceSelectorsEqual(- instanceSelector,- textEditingInstanceSelectorStore.get()- )- ) {+ if (element.closest("[contenteditable=true]")) {return false;}// When trying to drag an instance inside editor, drag the editor insteadreturn (- findClosestRichTextInstanceSelector(instanceSelector) ??- instanceSelector+ findClosestEditableInstanceSelector(+ instanceSelector,+ instancesStore.get(),+ registeredComponentMetasStore.get()+ ) ?? instanceSelector);},diff --git a/apps/builder/app/shared/copy-paste/plugin-instance.ts b/apps/builder/app/shared/copy-paste/plugin-instance.tsindex 77548ca970..24f1ee5e52 100644--- a/apps/builder/app/shared/copy-paste/plugin-instance.ts+++ b/apps/builder/app/shared/copy-paste/plugin-instance.ts@@ -283,6 +283,8 @@ export const onPaste = (clipboardData: string) => {const copiedInstanceIds = insertInstancesCopyMutable(instances,+ props,+ registeredComponentMetasStore.get(),data.instances,dropTarget);diff --git a/apps/builder/app/shared/copy-paste/plugin-markdown.ts b/apps/builder/app/shared/copy-paste/plugin-markdown.tsindex 208f8c99c7..5dcc90d8ea 100644--- a/apps/builder/app/shared/copy-paste/plugin-markdown.ts+++ b/apps/builder/app/shared/copy-paste/plugin-markdown.ts@@ -228,6 +228,8 @@ export const onPaste = (clipboardData: string) => {store.createTransaction([instancesStore, propsStore], (instances, props) => {insertInstancesMutable(instances,+ props,+ registeredComponentMetasStore.get(),data.instances,data.children,dropTargetdiff --git a/apps/builder/app/shared/instance-utils.test.ts b/apps/builder/app/shared/instance-utils.test.tsindex ccb855bd80..0b997a48c2 100644--- a/apps/builder/app/shared/instance-utils.test.ts+++ b/apps/builder/app/shared/instance-utils.test.ts@@ -1,37 +1,112 @@-import { describe, it, expect } from "@jest/globals";+import { describe, test, expect } from "@jest/globals";import type { WsComponentMeta } from "@webstudio-is/react-sdk";import * as defaultMetas from "@webstudio-is/sdk-components-react/metas";-import type { Instance } from "@webstudio-is/project-build";+import type { Instance, Instances } from "@webstudio-is/project-build";import {findClosestDroppableComponentIndex,findClosestDroppableTarget,+ findClosestEditableInstanceSelector,} from "./instance-utils";const defaultMetasMap = new Map(Object.entries(defaultMetas));-describe("find closest droppable component index", () => {- const createFakeComponentMetas = (- itemMeta: Partial<WsComponentMeta>,- anotherItemMeta?: Partial<WsComponentMeta>- ): Map<string, WsComponentMeta> => {- const base = {- label: "",- Icon: () => null,- };- const configs = {- Item: { ...base, type: "container", ...itemMeta },- AnotherItem: { ...base, type: "container", ...anotherItemMeta },- Bold: { ...base, type: "rich-text-child" },- TextBlock: { ...base, type: "rich-text" },- Form: { ...base, type: "container" },- Box: { ...base, type: "container" },- Div: { ...base, type: "container" },- Body: { ...base, type: "container" },- } as const;- return new Map(Object.entries(configs)) as Map<string, WsComponentMeta>;+const createFakeComponentMetas = (+ itemMeta: Partial<WsComponentMeta>,+ anotherItemMeta?: Partial<WsComponentMeta>+): Map<string, WsComponentMeta> => {+ const base = {+ label: "",+ Icon: () => null,};+ const configs = {+ Item: { ...base, type: "container", ...itemMeta },+ AnotherItem: { ...base, type: "container", ...anotherItemMeta },+ Bold: { ...base, type: "rich-text-child" },+ TextBlock: { ...base, type: "container" },+ Form: { ...base, type: "container" },+ Box: { ...base, type: "container" },+ Div: { ...base, type: "container" },+ Body: { ...base, type: "container" },+ } as const;+ return new Map(Object.entries(configs)) as Map<string, WsComponentMeta>;+};++const createInstancePair = (+ id: Instance["id"],+ component: string,+ children: Instance["children"]+): [Instance["id"], Instance] => {+ return [id, { type: "instance", id, component, children }];+};- it("finds container", () => {+describe("find closest editable instance selector", () => {+ test("searches closest container", () => {+ const instances: Instances = new Map([+ createInstancePair("body", "Body", [{ type: "id", value: "box" }]),+ createInstancePair("box", "Box", [+ { type: "text", value: "some text" },+ { type: "id", value: "bold" },+ ]),+ createInstancePair("bold", "Bold", [+ { type: "text", value: "some-bold" },+ ]),+ ]);+ expect(+ findClosestEditableInstanceSelector(+ ["bold", "box", "body"],+ instances,+ createFakeComponentMetas({})+ )+ ).toEqual(["box", "body"]);+ expect(+ findClosestEditableInstanceSelector(+ ["box", "body"],+ instances,+ createFakeComponentMetas({})+ )+ ).toEqual(["box", "body"]);+ });++ test("skips when container has anything except rich-text-child or text", () => {+ const instances: Instances = new Map([+ createInstancePair("body", "Body", [{ type: "id", value: "box" }]),+ createInstancePair("box", "Box", [+ { type: "text", value: "some text" },+ { type: "id", value: "bold" },+ { type: "id", value: "child-box" },+ ]),+ createInstancePair("bold", "Bold", [+ { type: "text", value: "some-bold" },+ ]),+ createInstancePair("child-box", "Box", [+ { type: "text", value: "child-box" },+ ]),+ ]);+ expect(+ findClosestEditableInstanceSelector(+ ["bold", "box", "body"],+ instances,+ createFakeComponentMetas({})+ )+ ).toEqual(undefined);+ });++ test("considers empty container as editable", () => {+ const instances: Instances = new Map([+ createInstancePair("body", "Body", []),+ ]);+ expect(+ findClosestEditableInstanceSelector(+ ["body"],+ instances,+ createFakeComponentMetas({})+ )+ ).toEqual(["body"]);+ });+});++describe("find closest droppable component index", () => {+ test("finds container", () => {expect(findClosestDroppableComponentIndex(createFakeComponentMetas({}),@@ -41,17 +116,17 @@ describe("find closest droppable component index", () => {).toEqual(0);});- it("skips non containers", () => {+ test("skips non containers", () => {expect(findClosestDroppableComponentIndex(createFakeComponentMetas({}),- ["Bold", "TextBlock", "Box", "Body"],+ ["Bold", "Italic", "TextBlock", "Box", "Body"],["Item"])).toEqual(2);});- it("can be dropped into itself", () => {+ test("can be dropped into itself", () => {expect(findClosestDroppableComponentIndex(createFakeComponentMetas({}),@@ -61,7 +136,7 @@ describe("find closest droppable component index", () => {).toEqual(0);});- it("can be forbidden to drop into itself", () => {+ test("can be forbidden to drop into itself", () => {expect(findClosestDroppableComponentIndex(createFakeComponentMetas({@@ -73,7 +148,7 @@ describe("find closest droppable component index", () => {).toEqual(2);});- it("requires some ancestor", () => {+ test("requires some ancestor", () => {expect(findClosestDroppableComponentIndex(createFakeComponentMetas({@@ -94,7 +169,7 @@ describe("find closest droppable component index", () => {).toEqual(0);});- it("considers both required and invalid ancestors", () => {+ test("considers both required and invalid ancestors", () => {expect(findClosestDroppableComponentIndex(createFakeComponentMetas({@@ -117,7 +192,7 @@ describe("find closest droppable component index", () => {).toEqual(-1);});- it("considers multiple children", () => {+ test("considers multiple children", () => {expect(findClosestDroppableComponentIndex(createFakeComponentMetas(@@ -158,7 +233,7 @@ describe("find closest droppable target", () => {return [id, { type: "instance", id, component, children }];};- it("puts in the end if closest instance is container", () => {+ test("puts in the end if closest instance is container", () => {const instances = new Map([createInstancePair("body", "Body", [{ type: "id", value: "box" }]),createInstancePair("box", "Box", [{ type: "id", value: "paragraph" }]),@@ -187,7 +262,7 @@ describe("find closest droppable target", () => {).toEqual(undefined);});- it("puts in the end of root instance", () => {+ test("puts in the end of root instance", () => {const instances = new Map([createInstancePair("body", "Body", [{ type: "id", value: "box" }]),createInstancePair("box", "Box", [{ type: "id", value: "paragraph" }]),@@ -200,10 +275,9 @@ describe("find closest droppable target", () => {});});- it("finds closest container and puts after its child within selection", () => {+ test("finds closest container and puts after its child within selection", () => {const instances = new Map([- createInstancePair("body", "Body", [{ type: "id", value: "box" }]),- createInstancePair("box", "Box", [{ type: "id", value: "paragraph" }]),+ createInstancePair("body", "Body", [{ type: "id", value: "paragraph" }]),createInstancePair("paragraph", "Paragraph", [{ type: "id", value: "bold" },]),@@ -213,26 +287,26 @@ describe("find closest droppable target", () => {findClosestDroppableTarget(defaultMetasMap,instances,- ["bold", "paragraph", "box", "body"],+ ["bold", "paragraph", "body"],["Box"])).toEqual({- parentSelector: ["box", "body"],+ parentSelector: ["paragraph", "body"],position: 1,});});- it("puts multiple children", () => {+ test("puts multiple children", () => {const instances = new Map([createInstancePair("body", "Body", [{ type: "id", value: "box" }]),- createInstancePair("box", "Box", [{ type: "id", value: "paragraph" }]),- createInstancePair("paragraph", "Paragraph", []),+ createInstancePair("box", "Box", [{ type: "id", value: "bold" }]),+ createInstancePair("bold", "Bold", []),]);expect(findClosestDroppableTarget(defaultMetasMap,instances,- ["paragraph", "box", "body"],+ ["bold", "box", "body"],["Box", "Form"])).toEqual({diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.tsindex d701907149..92a7641499 100644--- a/apps/builder/app/shared/instance-utils.ts+++ b/apps/builder/app/shared/instance-utils.ts@@ -34,6 +34,41 @@ import {} from "./tree-utils";import { removeByMutable } from "./array-utils";import { isBaseBreakpoint } from "./breakpoints";+import { getElementByInstanceSelector } from "./dom-utils";++export const findClosestEditableInstanceSelector = (+ instanceSelector: InstanceSelector,+ instances: Instances,+ metas: Map<string, WsComponentMeta>+) => {+ for (const instanceId of instanceSelector) {+ const instance = instances.get(instanceId);+ if (instance === undefined) {+ return;+ }+ const meta = metas.get(instance.component);+ if (meta === undefined) {+ return;+ }+ if (meta.type !== "container") {+ continue;+ }+ // only container with rich-text-child children and text can be edited+ for (const child of instance.children) {+ if (child.type === "id") {+ const childInstance = instances.get(child.value);+ if (childInstance === undefined) {+ return;+ }+ const childMeta = metas.get(childInstance.component);+ if (childMeta?.type !== "rich-text-child") {+ return;+ }+ }+ }+ return getAncestorInstanceSelector(instanceSelector, instanceId);+ }+};export const findClosestDroppableComponentIndex = (metas: Map<string, WsComponentMeta>,@@ -156,6 +191,8 @@ export const insertTemplate = ((instances, props, styleSourceSelections, styleSources, styles) => {insertInstancesMutable(instances,+ props,+ registeredComponentMetasStore.get(),insertedInstances,children,dropTarget@@ -204,8 +241,14 @@ export const reparentInstance = (targetInstanceSelector: InstanceSelector,dropTarget: DroppableTarget) => {- store.createTransaction([instancesStore], (instances) => {- reparentInstanceMutable(instances, targetInstanceSelector, dropTarget);+ store.createTransaction([instancesStore, propsStore], (instances, props) => {+ reparentInstanceMutable(+ instances,+ props,+ registeredComponentMetasStore.get(),+ targetInstanceSelector,+ dropTarget+ );});selectedInstanceSelectorStore.set(targetInstanceSelector);selectedStyleSourceSelectorStore.set(undefined);@@ -302,6 +345,32 @@ export const deleteSelectedInstance = () => {deleteInstance(selectedInstanceSelector);};+export const enterEditingMode = (event?: KeyboardEvent) => {+ const selectedInstanceSelector = selectedInstanceSelectorStore.get();+ if (selectedInstanceSelector === undefined) {+ return;+ }+ const editableInstanceSelector = findClosestEditableInstanceSelector(+ selectedInstanceSelector,+ instancesStore.get(),+ registeredComponentMetasStore.get()+ );+ if (editableInstanceSelector === undefined) {+ return;+ }+ const element = getElementByInstanceSelector(editableInstanceSelector);+ if (element === undefined) {+ return;+ }+ // When an event is triggered from the Builder,+ // the canvas element may be unfocused, so it's important to focus the element on the canvas.+ element.focus();+ // Prevents inserting a newline when entering text-editing mode+ event?.preventDefault();+ selectedInstanceSelectorStore.set(editableInstanceSelector);+ textEditingInstanceSelectorStore.set(editableInstanceSelector);+};+export const escapeSelection = () => {const selectedInstanceSelector = selectedInstanceSelectorStore.get();const textEditingInstanceSelector = textEditingInstanceSelectorStore.get();diff --git a/apps/builder/app/shared/nano-states/instances.ts b/apps/builder/app/shared/nano-states/instances.tsindex dca0efb506..9059afe53d 100644--- a/apps/builder/app/shared/nano-states/instances.ts+++ b/apps/builder/app/shared/nano-states/instances.ts@@ -1,9 +1,7 @@import { atom, computed } from "nanostores";import type { Instance, Instances } from "@webstudio-is/project-build";import type { InstanceSelector } from "../tree-utils";-import { getElementByInstanceSelector } from "../dom-utils";import { useSyncInitializeOnce } from "../hook-utils";-import { registeredComponentMetasStore } from "./components-meta";export const isResizingCanvasStore = atom(false);@@ -15,37 +13,6 @@ export const textEditingInstanceSelectorStore = atom<undefined | InstanceSelector>();-export const enterEditingMode = (event?: KeyboardEvent) => {- const selectedInstanceSelector = selectedInstanceSelectorStore.get();- const selectedInstance = selectedInstanceStore.get();- if (- selectedInstance === undefined ||- selectedInstanceSelector === undefined- ) {- return;- }-- const metas = registeredComponentMetasStore.get();- const meta = metas.get(selectedInstance.component);- if (meta?.type !== "rich-text") {- return;- }-- const element = getElementByInstanceSelector(selectedInstanceSelector);-- if (element === undefined) {- return;- }-- // When an event is triggered from the Builder,- // the canvas element may be unfocused, so it's important to focus the element on the canvas.- element.focus();-- // Prevents inserting a newline when entering text-editing mode- event?.preventDefault();- textEditingInstanceSelectorStore.set(selectedInstanceSelector);-};-export const instancesStore = atom<Instances>(new Map());export const useSetInstances = (instances: [Instance["id"], Instance][]) => {useSyncInitializeOnce(() => {diff --git a/apps/builder/app/shared/tree-utils.test.ts b/apps/builder/app/shared/tree-utils.test.tsindex 53d8aa64b1..9252d0bc6c 100644--- a/apps/builder/app/shared/tree-utils.test.ts+++ b/apps/builder/app/shared/tree-utils.test.ts@@ -1,4 +1,4 @@-import { test, expect } from "@jest/globals";+import { test, expect, describe } from "@jest/globals";import type {Breakpoint,Instance,@@ -10,6 +10,7 @@ import type {StyleSourceSelection,} from "@webstudio-is/project-build";import { getStyleDeclKey } from "@webstudio-is/project-build";+import * as baseMetas from "@webstudio-is/sdk-components-react/metas";import {type InstanceSelector,cloneStyles,@@ -25,6 +26,8 @@ import {mergeNewBreakpointsMutable,} from "./tree-utils";+const baseMetasMap = new Map(Object.entries(baseMetas));+const expectString = expect.any(String) as unknown as string;const createBreakpoint = (@@ -157,6 +160,8 @@ test("insert instances tree into target", () => {insertInstancesMutable(instances,+ new Map(),+ baseMetasMap,[createInstance("inserted1", "Box", [{ type: "id", value: "inserted2" }]),createInstance("inserted2", "Box", []),@@ -186,6 +191,8 @@ test("insert instances tree into target", () => {insertInstancesMutable(instances,+ new Map(),+ baseMetasMap,[createInstance("inserted3", "Box", [{ type: "id", value: "inserted4" }]),createInstance("inserted4", "Box", []),@@ -219,6 +226,145 @@ test("insert instances tree into target", () => {]);});+describe("insert instances into container with text or rich text children", () => {+ test("insert in the end after text", () => {+ const getInstances = () =>+ new Map([+ createInstancePair("root", "Body", [{ type: "id", value: "box" }]),+ createInstancePair("box", "Box", [{ type: "text", value: "text" }]),+ ]);++ const instances1 = getInstances();+ insertInstancesMutable(+ instances1,+ new Map(),+ baseMetasMap,+ [createInstance("inserted", "Box", [])],+ [{ type: "id", value: "inserted" }],+ {+ parentSelector: ["box", "root"],+ position: 0,+ }+ );+ expect(Array.from(instances1.entries())).toEqual([+ createInstancePair("root", "Body", [{ type: "id", value: "box" }]),+ createInstancePair("box", "Box", [+ { type: "id", value: "inserted" },+ { type: "id", value: expectString },+ ]),+ createInstancePair(expectString, "TextBlock", [+ { type: "text", value: "text" },+ ]),+ createInstancePair("inserted", "Box", []),+ ]);++ const instances2 = getInstances();+ insertInstancesMutable(+ instances2,+ new Map(),+ baseMetasMap,+ [createInstance("inserted", "Box", [])],+ [{ type: "id", value: "inserted" }],+ {+ parentSelector: ["box", "root"],+ position: "end",+ }+ );+ expect(Array.from(instances2.entries())).toEqual([+ createInstancePair("root", "Body", [{ type: "id", value: "box" }]),+ createInstancePair("box", "Box", [+ { type: "id", value: expectString },+ { type: "id", value: "inserted" },+ ]),+ createInstancePair(expectString, "TextBlock", [+ { type: "text", value: "text" },+ ]),+ createInstancePair("inserted", "Box", []),+ ]);+ });++ test("insert container between rich text children", () => {+ const getInstances = () =>+ new Map([+ createInstancePair("root", "Body", [{ type: "id", value: "box" }]),+ createInstancePair("box", "Box", [+ { type: "id", value: "bold" },+ { type: "text", value: "text" },+ { type: "id", value: "italic" },+ ]),+ createInstancePair("bold", "Bold", [{ type: "text", value: "bold" }]),+ createInstancePair("italic", "Italic", [+ { type: "text", value: "italic" },+ ]),+ ]);++ // insert before text+ const instances1 = getInstances();+ insertInstancesMutable(+ instances1,+ new Map(),+ baseMetasMap,+ [createInstance("inserted", "Box", [])],+ [{ type: "id", value: "inserted" }],+ {+ parentSelector: ["box", "root"],+ position: 1,+ }+ );+ expect(Array.from(instances1.entries())).toEqual([+ createInstancePair("root", "Body", [{ type: "id", value: "box" }]),+ createInstancePair("box", "Box", [+ { type: "id", value: expectString },+ { type: "id", value: "inserted" },+ { type: "id", value: expectString },+ ]),+ createInstancePair("bold", "Bold", [{ type: "text", value: "bold" }]),+ createInstancePair("italic", "Italic", [+ { type: "text", value: "italic" },+ ]),+ createInstancePair(expectString, "TextBlock", [+ { type: "id", value: "bold" },+ ]),+ createInstancePair(expectString, "TextBlock", [+ { type: "text", value: "text" },+ { type: "id", value: "italic" },+ ]),+ createInstancePair("inserted", "Box", []),+ ]);++ // insert after text+ const instances2 = getInstances();+ insertInstancesMutable(+ instances2,+ new Map(),+ baseMetasMap,+ [createInstance("inserted", "Box", [])],+ [{ type: "id", value: "inserted" }],+ {+ parentSelector: ["box", "root"],+ position: 2,+ }+ );+ expect(Array.from(instances2.entries())).toEqual([+ createInstancePair("root", "Body", [{ type: "id", value: "box" }]),+ createInstancePair("box", "Box", [+ { type: "id", value: expectString },+ { type: "id", value: "inserted" },+ ]),+ createInstancePair("bold", "Bold", [{ type: "text", value: "bold" }]),+ createInstancePair("italic", "Italic", [+ { type: "text", value: "italic" },+ ]),+ createInstancePair(expectString, "TextBlock", [+ { type: "id", value: "bold" },+ { type: "text", value: "text" },+ { type: "id", value: "italic" },+ ]),+ createInstancePair("inserted", "Box", []),+ ]);+ });+});+test("reparent instance into target", () => {const instances: Instances = new Map([createInstancePair("root", "Body", [@@ -238,10 +384,16 @@ test("reparent instance into target", () => {createInstancePair("box13", "Box", []),]);- reparentInstanceMutable(instances, ["target", "root"], {- parentSelector: ["box1", "root"],- position: 1,- });+ reparentInstanceMutable(+ instances,+ new Map(),+ baseMetasMap,+ ["target", "root"],+ {+ parentSelector: ["box1", "root"],+ position: 1,+ }+ );expect(instances).toEqual(new Map([createInstancePair("root", "Body", [@@ -262,10 +414,16 @@ test("reparent instance into target", () => {]));- reparentInstanceMutable(instances, ["target", "box1", "root"], {- parentSelector: ["box1", "root"],- position: 3,- });+ reparentInstanceMutable(+ instances,+ new Map(),+ baseMetasMap,+ ["target", "box1", "root"],+ {+ parentSelector: ["box1", "root"],+ position: 3,+ }+ );expect(instances).toEqual(new Map([createInstancePair("root", "Body", [@@ -286,10 +444,16 @@ test("reparent instance into target", () => {]));- reparentInstanceMutable(instances, ["target", "box1", "root"], {- parentSelector: ["root"],- position: "end",- });+ reparentInstanceMutable(+ instances,+ new Map(),+ baseMetasMap,+ ["target", "box1", "root"],+ {+ parentSelector: ["root"],+ position: "end",+ }+ );expect(instances).toEqual(new Map([createInstancePair("root", "Body", [@@ -332,10 +496,16 @@ test("reparent instance into slot", () => {]);// reuse existing fragment when drop into slot- reparentInstanceMutable(instances, ["box2", "root"], {- parentSelector: ["slot1", "root"],- position: "end",- });+ reparentInstanceMutable(+ instances,+ new Map(),+ baseMetasMap,+ ["box2", "root"],+ {+ parentSelector: ["slot1", "root"],+ position: "end",+ }+ );expect(instances).toEqual(new Map([createInstancePair("root", "Body", [@@ -361,10 +531,16 @@ test("reparent instance into slot", () => {);// create new fragment when drop into empty slot- reparentInstanceMutable(instances, ["box2", "fragment11", "slot1", "root"], {- parentSelector: ["slot3", "root"],- position: "end",- });+ reparentInstanceMutable(+ instances,+ new Map(),+ baseMetasMap,+ ["box2", "fragment11", "slot1", "root"],+ {+ parentSelector: ["slot3", "root"],+ position: "end",+ }+ );expect(instances).toEqual(new Map([createInstancePair("root", "Body", [@@ -393,10 +569,16 @@ test("reparent instance into slot", () => {);// prevent reparenting into own children to avoid infinite loop- reparentInstanceMutable(instances, ["slot1", "root"], {- parentSelector: ["fragment11", "slot1", "root"],- position: "end",- });+ reparentInstanceMutable(+ instances,+ new Map(),+ baseMetasMap,+ ["slot1", "root"],+ {+ parentSelector: ["fragment11", "slot1", "root"],+ position: "end",+ }+ );expect(instances).toEqual(new Map([createInstancePair("root", "Body", [@@ -444,6 +626,8 @@ test("insert tree of instances copy and provide map from ids map", () => {];const copiedInstanceIds = insertInstancesCopyMutable(instances,+ new Map(),+ baseMetasMap,copiedInstances,{parentSelector: ["3", "1"],@@ -493,6 +677,8 @@ test("insert slot or do nothing when slot is cyclic", () => {// insert slot own descendantlet copiedInstanceIds = insertInstancesCopyMutable(instances,+ new Map(),+ baseMetasMap,copiedInstances,{parentSelector: ["child", "fragment", "slot", "root"],@@ -514,10 +700,16 @@ test("insert slot or do nothing when slot is cyclic", () => {]);// do not insert slot into itself- copiedInstanceIds = insertInstancesCopyMutable(instances, copiedInstances, {- parentSelector: ["slot", "root"],- position: "end",- });+ copiedInstanceIds = insertInstancesCopyMutable(+ instances,+ new Map(),+ baseMetasMap,+ copiedInstances,+ {+ parentSelector: ["slot", "root"],+ position: "end",+ }+ );expect(copiedInstanceIds).toEqual(new Map());expect(Array.from(instances.entries())).toEqual([createInstancePair("root", "Body", [@@ -533,10 +725,16 @@ test("insert slot or do nothing when slot is cyclic", () => {]);// insert slot into sibling- copiedInstanceIds = insertInstancesCopyMutable(instances, copiedInstances, {- parentSelector: ["sibling", "root"],- position: "end",- });+ copiedInstanceIds = insertInstancesCopyMutable(+ instances,+ new Map(),+ baseMetasMap,+ copiedInstances,+ {+ parentSelector: ["sibling", "root"],+ position: "end",+ }+ );expect(copiedInstanceIds).toEqual(new Map([["slot", expectString]]));expect(Array.from(instances.entries())).toEqual([createInstancePair("root", "Body", [@@ -562,10 +760,16 @@ test("insert slot or do nothing when slot is cyclic", () => {]),createInstance("slot2box", "Box", []),];- copiedInstanceIds = insertInstancesCopyMutable(instances, copiedInstances, {- parentSelector: ["root"],- position: "end",- });+ copiedInstanceIds = insertInstancesCopyMutable(+ instances,+ new Map(),+ baseMetasMap,+ copiedInstances,+ {+ parentSelector: ["root"],+ position: "end",+ }+ );expect(copiedInstanceIds).toEqual(new Map([["slot2", expectString]]));expect(Array.from(instances.entries())).toEqual([createInstancePair("root", "Body", [diff --git a/apps/builder/app/shared/tree-utils.ts b/apps/builder/app/shared/tree-utils.tsindex cc03597fe5..9617384465 100644--- a/apps/builder/app/shared/tree-utils.ts+++ b/apps/builder/app/shared/tree-utils.ts@@ -19,6 +19,7 @@ import {StyleSourcesList,} from "@webstudio-is/project-build";import { equalMedia } from "@webstudio-is/css-engine";+import type { WsComponentMeta } from "@webstudio-is/react-sdk";// slots can have multiple parents so instance should be addressed// with full rendered path to avoid double selections with slots@@ -56,9 +57,10 @@ export type DroppableTarget = {const getInstanceOrCreateFragmentIfNecessary = (instances: Instances,- instanceId: Instance["id"]+ dropTarget: DroppableTarget) => {- const instance = instances.get(instanceId);+ const [parentId] = dropTarget.parentSelector;+ const instance = instances.get(parentId);if (instance === undefined) {return;}@@ -76,14 +78,128 @@ const getInstanceOrCreateFragmentIfNecessary = (};instances.set(id, fragment);instance.children.push({ type: "id", value: id });- return fragment;+ return {+ parentSelector: [fragment.id, ...dropTarget.parentSelector],+ position: dropTarget.position,+ };}// first slot child is always fragmentif (instance.children[0].type === "id") {- return instances.get(instance.children[0].value);+ const fragmentId = instance.children[0].value;+ return {+ parentSelector: [fragmentId, ...dropTarget.parentSelector],+ position: dropTarget.position,+ };}}- return instance;+ return;+};++/**+ * Navigator tree and canvas dnd do not have text representation+ * and position does not consider it and include only instances.+ * This function adjust the position to consider text children+ */+const adjustChildrenPosition = (+ children: Instance["children"],+ position: number+) => {+ let newPosition = 0;+ let idPosition = 0;+ for (let index = 0; index < children.length; index += 1) {+ newPosition = index;+ if (idPosition === position) {+ return newPosition;+ }+ const child = children[index];+ if (child.type === "id") {+ idPosition += 1;+ }+ }+ // the index after last item+ return newPosition + 1;+};++/**+ * Wrap children before and after drop target with spans+ * to preserve lexical specific components while allowing+ * to insert into editable components+ */+const wrapEditableChildrenAroundDropTargetMutable = (+ instances: Instances,+ props: Props,+ metas: Map<string, WsComponentMeta>,+ dropTarget: DroppableTarget+) => {+ const [parentId] = dropTarget.parentSelector;+ const parentInstance = instances.get(parentId);+ if (parentInstance === undefined) {+ return;+ }+ // wrap only containers with text and rich text childre+ for (const child of parentInstance.children) {+ if (child.type === "id") {+ const childInstance = instances.get(child.value);+ if (childInstance === undefined) {+ return;+ }+ const childMeta = metas.get(childInstance.component);+ if (childMeta?.type !== "rich-text-child") {+ return;+ }+ }+ }+ const position =+ dropTarget.position === "end"+ ? parentInstance.children.length+ : adjustChildrenPosition(parentInstance.children, dropTarget.position);++ const newChildren: Instance["children"] = [];+ let newPosition = 0;+ // create left span when not at the beginning+ if (position !== 0) {+ const leftSpan: Instance = {+ id: nanoid(),+ type: "instance",+ component: "TextBlock",+ children: parentInstance.children.slice(0, position),+ };+ newChildren.push({ type: "id", value: leftSpan.id });+ instances.set(leftSpan.id, leftSpan);+ const tagProp: Prop = {+ id: nanoid(),+ instanceId: leftSpan.id,+ type: "string",+ name: "tag",+ value: "span",+ };+ props.set(tagProp.id, tagProp);+ newPosition = 1;+ }+ // create right span when not in the end+ if (position < parentInstance.children.length) {+ const rightSpan: Instance = {+ id: nanoid(),+ type: "instance",+ component: "TextBlock",+ children: parentInstance.children.slice(position),+ };+ newChildren.push({ type: "id", value: rightSpan.id });+ instances.set(rightSpan.id, rightSpan);+ const tagProp: Prop = {+ id: nanoid(),+ instanceId: rightSpan.id,+ type: "string",+ name: "tag",+ value: "span",+ };+ props.set(tagProp.id, tagProp);+ }+ parentInstance.children = newChildren;+ return {+ parentSelector: dropTarget.parentSelector,+ position: newPosition,+ };};const getSlotFragmentSelector = (@@ -104,6 +220,8 @@ const getSlotFragmentSelector = (export const reparentInstanceMutable = (instances: Instances,+ props: Props,+ metas: Map<string, WsComponentMeta>,instanceSelector: InstanceSelector,dropTarget: DroppableTarget) => {@@ -112,10 +230,17 @@ export const reparentInstanceMutable = (parentInstanceId === undefined? undefined: instances.get(parentInstanceId);- const nextParent = getInstanceOrCreateFragmentIfNecessary(- instances,- dropTarget.parentSelector[0]- );+ dropTarget =+ getInstanceOrCreateFragmentIfNecessary(instances, dropTarget) ?? dropTarget;+ dropTarget =+ wrapEditableChildrenAroundDropTargetMutable(+ instances,+ props,+ metas,+ dropTarget+ ) ?? dropTarget;+ const [parentId] = dropTarget.parentSelector;+ const nextParent = instances.get(parentId);const instance = instances.get(instanceId);// delect is target is one of own descendants@@ -212,14 +337,23 @@ export const findLocalStyleSourcesWithinInstances = (export const insertInstancesMutable = (instances: Instances,+ props: Props,+ metas: Map<string, WsComponentMeta>,insertedInstances: Instance[],children: Instance["children"],dropTarget: DroppableTarget) => {- const parentInstance = getInstanceOrCreateFragmentIfNecessary(- instances,- dropTarget.parentSelector[0]- );+ dropTarget =+ getInstanceOrCreateFragmentIfNecessary(instances, dropTarget) ?? dropTarget;+ dropTarget =+ wrapEditableChildrenAroundDropTargetMutable(+ instances,+ props,+ metas,+ dropTarget+ ) ?? dropTarget;+ const [parentId] = dropTarget.parentSelector;+ const parentInstance = instances.get(parentId);if (parentInstance === undefined) {return;}@@ -245,6 +379,8 @@ export const insertInstancesMutable = (export const insertInstancesCopyMutable = (instances: Instances,+ props: Props,+ metas: Map<string, WsComponentMeta>,copiedInstances: Instance[],dropTarget: DroppableTarget) => {@@ -308,6 +444,8 @@ export const insertInstancesCopyMutable = (insertInstancesMutable(instances,+ props,+ metas,copiedInstancesWithNewIds,// consider the first instance as child[diff --git a/packages/react-sdk/src/components/component-meta.ts b/packages/react-sdk/src/components/component-meta.tsindex 244d655de6..c1ef5aadae 100644--- a/packages/react-sdk/src/components/component-meta.ts+++ b/packages/react-sdk/src/components/component-meta.ts@@ -45,18 +45,11 @@ export const defaultStates: ComponentState[] = [const WsComponentMeta = z.object({category: z.enum(componentCategories).optional(),- // container - can accept other components with dnd+ // container - can accept other components with dnd or be edited as text// control - usually form controls like inputs, without children// embed - images, videos or other embeddable components, without children- // rich-text - editable text component// rich-text-child - formatted text fragment, not listed in components list- type: z.enum([- "container",- "control",- "embed",- "rich-text",- "rich-text-child",- ]),+ type: z.enum(["container", "control", "embed", "rich-text-child"]),requiredAncestors: z.optional(z.array(z.string())),invalidAncestors: z.optional(z.array(z.string())),stylable: z.optional(z.boolean()),diff --git a/packages/sdk-components-react/src/blockquote.ws.tsx b/packages/sdk-components-react/src/blockquote.ws.tsxindex 902e3feb79..23978967a2 100644--- a/packages/sdk-components-react/src/blockquote.ws.tsx+++ b/packages/sdk-components-react/src/blockquote.ws.tsx@@ -61,7 +61,7 @@ const presetStyle = {export const meta: WsComponentMeta = {category: "text",- type: "rich-text",+ type: "container",label: "Blockquote",icon: BlockquoteIcon,states: defaultStates,diff --git a/packages/sdk-components-react/src/code-text.ws.tsx b/packages/sdk-components-react/src/code-text.ws.tsxindex 29b9b5a3b0..337ee1ad2f 100644--- a/packages/sdk-components-react/src/code-text.ws.tsx+++ b/packages/sdk-components-react/src/code-text.ws.tsx@@ -37,7 +37,7 @@ const presetStyle = {export const meta: WsComponentMeta = {category: "general",- type: "rich-text",+ type: "container",label: "Code Text",icon: CodeTextIcon,states: defaultStates,diff --git a/packages/sdk-components-react/src/heading.ws.tsx b/packages/sdk-components-react/src/heading.ws.tsxindex 89e024c598..2c4b116aa3 100644--- a/packages/sdk-components-react/src/heading.ws.tsx+++ b/packages/sdk-components-react/src/heading.ws.tsx@@ -23,7 +23,7 @@ const presetStyle = {export const meta: WsComponentMeta = {category: "text",- type: "rich-text",+ type: "container",label: "Heading",icon: HeadingIcon,states: defaultStates,diff --git a/packages/sdk-components-react/src/label.ws.tsx b/packages/sdk-components-react/src/label.ws.tsxindex cc8cfb1e7f..32de54ac8c 100644--- a/packages/sdk-components-react/src/label.ws.tsx+++ b/packages/sdk-components-react/src/label.ws.tsx@@ -18,7 +18,7 @@ const presetStyle = {export const meta: WsComponentMeta = {category: "forms",- type: "rich-text",+ type: "container",label: "Input Label",icon: TextBlockIcon,states: defaultStates,diff --git a/packages/sdk-components-react/src/link.ws.tsx b/packages/sdk-components-react/src/link.ws.tsxindex 4f2fdea347..41b58542ef 100644--- a/packages/sdk-components-react/src/link.ws.tsx+++ b/packages/sdk-components-react/src/link.ws.tsx@@ -25,8 +25,8 @@ const presetStyle = {export const meta: WsComponentMeta = {category: "general",- type: "rich-text",- label: "Link Text",+ type: "container",+ label: "Link",icon: LinkIcon,presetStyle,order: 1,diff --git a/packages/sdk-components-react/src/list-item.ws.tsx b/packages/sdk-components-react/src/list-item.ws.tsxindex d975ad96e4..844fed6459 100644--- a/packages/sdk-components-react/src/list-item.ws.tsx+++ b/packages/sdk-components-react/src/list-item.ws.tsx@@ -15,7 +15,7 @@ const presetStyle = {export const meta: WsComponentMeta = {category: "general",- type: "rich-text",+ type: "container",requiredAncestors: ["List"],label: "List Item",icon: ListItemIcon,diff --git a/packages/sdk-components-react/src/paragraph.ws.tsx b/packages/sdk-components-react/src/paragraph.ws.tsxindex 50932dd252..e0e22fbdd4 100644--- a/packages/sdk-components-react/src/paragraph.ws.tsx+++ b/packages/sdk-components-react/src/paragraph.ws.tsx@@ -15,7 +15,7 @@ const presetStyle = {export const meta: WsComponentMeta = {category: "text",- type: "rich-text",+ type: "container",label: "Paragraph",icon: TextAlignLeftIcon,states: defaultStates,diff --git a/packages/sdk-components-react/src/text-block.ws.tsx b/packages/sdk-components-react/src/text-block.ws.tsxindex a8801288a1..47ae315a1f 100644--- a/packages/sdk-components-react/src/text-block.ws.tsx+++ b/packages/sdk-components-react/src/text-block.ws.tsx@@ -21,7 +21,7 @@ const presetStyle = {export const meta: WsComponentMeta = {category: "text",- type: "rich-text",+ type: "container",label: "Text Block",icon: TextBlockIcon,states: defaultStates,