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.

refactor: use content model to detect rich text (#5109)

Bogdan Chadkin3b8c58b435c0
diff --git a/apps/builder/app/builder/features/navigator/navigator-tree.tsx b/apps/builder/app/builder/features/navigator/navigator-tree.tsx
index 23918326f0..982a408869 100644
--- a/apps/builder/app/builder/features/navigator/navigator-tree.tsx
+++ b/apps/builder/app/builder/features/navigator/navigator-tree.tsx
@@ -67,7 +67,10 @@ import {
selectInstance,
} from "~/shared/awareness";
import { findClosestContainer, isTreeMatching } from "~/shared/matcher";
-import { isTreeSatisfyingContentModel } from "~/shared/content-model";
+import {
+ isRichTextContent,
+ isTreeSatisfyingContentModel,
+} from "~/shared/content-model";
type TreeItemAncestor =
| undefined
@@ -511,17 +514,18 @@ const canDrag = (instance: Instance, instanceSelector: InstanceSelector) => {
return false;
}
- const meta = $registeredComponentMetas.get().get(instance.component);
- if (meta === undefined) {
- return true;
- }
- const detachable = meta.type !== "rich-text-child";
- if (detachable === false) {
+ const isContent = isRichTextContent({
+ instanceSelector,
+ instances: $instances.get(),
+ props: $props.get(),
+ metas: $registeredComponentMetas.get(),
+ });
+ if (isContent) {
toast.error(
"This instance can not be moved outside of its parent component."
);
}
- return detachable;
+ return !isContent;
};
const canDrop = (
diff --git a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts
index 07afc73ef7..6c2a93e096 100644
--- a/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts
+++ b/apps/builder/app/builder/features/workspace/canvas-tools/outline/block-utils.ts
@@ -191,12 +191,13 @@ export const insertTemplateAt = (
const selectors: InstanceSelector[] = [];
- findAllEditableInstanceSelector(
- selectedInstanceSelector,
- data.instances,
- $registeredComponentMetas.get(),
- selectors
- );
+ findAllEditableInstanceSelector({
+ instanceSelector: selectedInstanceSelector,
+ instances: data.instances,
+ props: data.props,
+ metas: $registeredComponentMetas.get(),
+ results: selectors,
+ });
const editableInstanceSelector = selectors[0];
diff --git a/apps/builder/app/builder/shared/commands.ts b/apps/builder/app/builder/shared/commands.ts
index a8be91e85b..bc32942d65 100644
--- a/apps/builder/app/builder/shared/commands.ts
+++ b/apps/builder/app/builder/shared/commands.ts
@@ -36,15 +36,15 @@ import {
import { $selectedInstancePath, selectInstance } from "~/shared/awareness";
import { openCommandPanel } from "../features/command-panel";
import { builderApi } from "~/shared/builder-api";
-import {
- findClosestNonTextualContainer,
- isInstanceDetachable,
- isTreeMatching,
-} from "~/shared/matcher";
+import { isInstanceDetachable, isTreeMatching } from "~/shared/matcher";
import { getSetting, setSetting } from "./client-settings";
import { findAvailableVariables } from "~/shared/data-variables";
import { atom } from "nanostores";
-import { isTreeSatisfyingContentModel } from "~/shared/content-model";
+import {
+ findClosestNonTextualContainer,
+ isRichTextContent,
+ isTreeSatisfyingContentModel,
+} from "~/shared/content-model";
export const $styleSourceInputElement = atom<HTMLInputElement | undefined>();
@@ -155,8 +155,13 @@ export const wrapIn = (component: string) => {
const metas = $registeredComponentMetas.get();
try {
updateWebstudioData((data) => {
- const meta = metas.get(selectedInstance.component);
- if (meta?.type === "rich-text-child") {
+ 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");
}
@@ -206,12 +211,13 @@ export const unwrap = () => {
const [selectedItem, parentItem] = instancePath;
try {
updateWebstudioData((data) => {
- const nonTextualIndex = findClosestNonTextualContainer({
+ const instanceSelector = findClosestNonTextualContainer({
metas: $registeredComponentMetas.get(),
+ props: data.props,
instances: data.instances,
instanceSelector: selectedItem.instanceSelector,
});
- if (nonTextualIndex !== 0) {
+ if (selectedItem.instanceSelector.join() !== instanceSelector.join()) {
toast.error(`Cannot unwrap textual instance`);
throw Error("Abort transaction");
}
diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx
index 605b692f09..88b373126a 100644
--- a/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx
+++ b/apps/builder/app/canvas/features/text-editor/text-editor.stories.tsx
@@ -5,7 +5,7 @@ import type { StoryFn, Meta } from "@storybook/react";
import { action } from "@storybook/addon-actions";
import { Box, Button, Flex } from "@webstudio-is/design-system";
import { theme } from "@webstudio-is/design-system";
-import type { Instance, Instances } from "@webstudio-is/sdk";
+import type { Instance, Instances, Props } from "@webstudio-is/sdk";
import { $, renderData } from "@webstudio-is/template";
import {
$instances,
@@ -58,6 +58,8 @@ const instances: Instances = new Map([
]),
]);
+const props: Props = new Map();
+
export const Basic: StoryFn<typeof TextEditor> = ({ onChange }) => {
const state = useStore($textToolbar);
@@ -129,6 +131,7 @@ export const Basic: StoryFn<typeof TextEditor> = ({ onChange }) => {
<TextEditor
rootInstanceSelector={["1"]}
instances={instances}
+ props={props}
contentEditable={<ContentEditable />}
onChange={onChange}
onSelectInstance={(instanceId) =>
@@ -176,6 +179,7 @@ export const CursorPositioning: StoryFn<typeof TextEditor> = ({ onChange }) => {
<TextEditor
rootInstanceSelector={["1"]}
instances={instances}
+ props={props}
contentEditable={<ContentEditable />}
onChange={onChange}
onSelectInstance={(instanceId) =>
@@ -240,20 +244,8 @@ export const CursorPositioningUpDown: StoryFn<typeof TextEditor> = () => {
$registeredComponentMetas.set(
new Map([
- [
- "Box",
- {
- type: "container",
- icon: "icon",
- },
- ],
- [
- "Bold",
- {
- type: "rich-text-child",
- icon: "icon",
- },
- ],
+ ["Box", { type: "container", icon: "icon" }],
+ ["Bold", { type: "container", icon: "icon" }],
])
);
@@ -311,6 +303,7 @@ export const CursorPositioningUpDown: StoryFn<typeof TextEditor> = () => {
}
rootInstanceSelector={["boxAId", "bodyId"]}
instances={instances}
+ props={props}
contentEditable={<ContentEditable />}
onChange={(data) => {
setState((prev) => {
@@ -336,6 +329,7 @@ export const CursorPositioningUpDown: StoryFn<typeof TextEditor> = () => {
editable={textEditingInstanceSelector?.selector[0] === "boxBId"}
rootInstanceSelector={["boxBId", "bodyId"]}
instances={instances}
+ props={props}
contentEditable={<ContentEditable />}
onChange={(data) => {
setState((prev) => {
diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
index 55cffda660..ac8101ee32 100644
--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx
+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
@@ -51,7 +51,7 @@ import { LinkPlugin } from "@lexical/react/LexicalLinkPlugin";
import { nanoid } from "nanoid";
import { createRegularStyleSheet } from "@webstudio-is/css-engine";
-import type { Instance, Instances } from "@webstudio-is/sdk";
+import type { Instance, Instances, Props } from "@webstudio-is/sdk";
import {
collapsedAttribute,
idAttribute,
@@ -1440,6 +1440,7 @@ const onError = (error: Error) => {
type TextEditorProps = {
rootInstanceSelector: InstanceSelector;
instances: Instances;
+ props: Props;
contentEditable: JSX.Element;
editable?: boolean;
onChange: (instancesList: Instance[]) => void;
@@ -1520,6 +1521,7 @@ const AnyKeyDownPlugin = ({
export const TextEditor = ({
rootInstanceSelector: rootInstanceSelectorUnstable,
instances,
+ props,
contentEditable,
editable,
onChange,
@@ -1623,12 +1625,13 @@ export const TextEditor = ({
}
const editableInstanceSelectors: InstanceSelector[] = [];
- findAllEditableInstanceSelector(
- [rootInstanceId],
+ findAllEditableInstanceSelector({
+ instanceSelector: [rootInstanceId],
instances,
+ props,
metas,
- editableInstanceSelectors
- );
+ results: editableInstanceSelectors,
+ });
const currentIndex = editableInstanceSelectors.findIndex(
(instanceSelector) => {
diff --git a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
index e6d0d8e76e..cabd0ab5a6 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -45,6 +45,7 @@ import {
$registeredComponentMetas,
$selectedInstanceRenderState,
findBlockSelector,
+ $props,
} from "~/shared/nano-states";
import { $textEditingInstanceSelector } from "~/shared/nano-states";
import {
@@ -410,6 +411,7 @@ export const WebstudioComponentCanvas = forwardRef<
>(({ instance, instanceSelector, components, ...restProps }, ref) => {
const instanceId = instance.id;
const instances = useStore($instances);
+ const allProps = useStore($props);
const metas = useStore($registeredComponentMetas);
const textEditingInstanceSelector = useStore($textEditingInstanceSelector);
@@ -551,6 +553,7 @@ export const WebstudioComponentCanvas = forwardRef<
<TextEditor
rootInstanceSelector={instanceSelector}
instances={instances}
+ props={allProps}
contentEditable={
<ContentEditable
placeholder={getEditableComponentPlaceholder(
diff --git a/apps/builder/app/canvas/instance-selection.ts b/apps/builder/app/canvas/instance-selection.ts
index b44cab9453..c8145f9247 100644
--- a/apps/builder/app/canvas/instance-selection.ts
+++ b/apps/builder/app/canvas/instance-selection.ts
@@ -1,16 +1,17 @@
import { getInstanceSelectorFromElement } from "~/shared/dom-utils";
-import { findClosestEditableInstanceSelector } from "~/shared/instance-utils";
import {
$hoveredInstanceOutline,
$hoveredInstanceSelector,
$instances,
$isContentMode,
+ $props,
$registeredComponentMetas,
} from "~/shared/nano-states";
import { $textEditingInstanceSelector } from "~/shared/nano-states";
import { emitCommand } from "./shared/commands";
import { shallowEqual } from "shallow-equal";
import { $awareness, selectInstance } from "~/shared/awareness";
+import { findClosestRichText } from "~/shared/content-model";
const isElementBeingEdited = (element: Element) => {
if (element.closest("[contenteditable=true]")) {
@@ -67,11 +68,12 @@ const handleEdit = (event: MouseEvent) => {
const instances = $instances.get();
- let editableInstanceSelector = findClosestEditableInstanceSelector(
+ let editableInstanceSelector = findClosestRichText({
instanceSelector,
instances,
- $registeredComponentMetas.get()
- );
+ props: $props.get(),
+ metas: $registeredComponentMetas.get(),
+ });
// Do not allow edit bindable text instances with expression children in Content Mode
if (editableInstanceSelector !== undefined && $isContentMode.get()) {
diff --git a/apps/builder/app/canvas/shared/commands.ts b/apps/builder/app/canvas/shared/commands.ts
index 214c028636..f83b495457 100644
--- a/apps/builder/app/canvas/shared/commands.ts
+++ b/apps/builder/app/canvas/shared/commands.ts
@@ -2,12 +2,10 @@ import { FORMAT_TEXT_COMMAND } from "lexical";
import { TOGGLE_LINK_COMMAND } from "@lexical/link";
import { createCommandsEmitter } from "~/shared/commands-emitter";
import { getElementByInstanceSelector } from "~/shared/dom-utils";
-import {
- findClosestEditableInstanceSelector,
- findAllEditableInstanceSelector,
-} from "~/shared/instance-utils";
+import { findAllEditableInstanceSelector } from "~/shared/instance-utils";
import {
$instances,
+ $props,
$registeredComponentMetas,
$selectedInstanceSelector,
$textEditingInstanceSelector,
@@ -22,6 +20,7 @@ import {
import { selectInstance } from "~/shared/awareness";
import { isDescendantOrSelf, type InstanceSelector } from "~/shared/tree-utils";
import { deleteSelectedInstance } from "~/builder/shared/commands";
+import { findClosestRichText } from "~/shared/content-model";
export const { emitCommand, subscribeCommands } = createCommandsEmitter({
source: "canvas",
@@ -59,21 +58,23 @@ export const { emitCommand, subscribeCommands } = createCommandsEmitter({
return;
}
- let editableInstanceSelector = findClosestEditableInstanceSelector(
- selectedInstanceSelector,
- $instances.get(),
- $registeredComponentMetas.get()
- );
+ let editableInstanceSelector = findClosestRichText({
+ instanceSelector: selectedInstanceSelector,
+ instances: $instances.get(),
+ props: $props.get(),
+ metas: $registeredComponentMetas.get(),
+ });
if (editableInstanceSelector === undefined) {
const selectors: InstanceSelector[] = [];
- findAllEditableInstanceSelector(
- selectedInstanceSelector,
- $instances.get(),
- $registeredComponentMetas.get(),
- selectors
- );
+ findAllEditableInstanceSelector({
+ instanceSelector: selectedInstanceSelector,
+ instances: $instances.get(),
+ props: $props.get(),
+ metas: $registeredComponentMetas.get(),
+ results: selectors,
+ });
if (selectors.length === 0) {
$textEditingInstanceSelector.set(undefined);
diff --git a/apps/builder/app/canvas/shared/styles.ts b/apps/builder/app/canvas/shared/styles.ts
index 7661a2060b..b668fdf869 100644
--- a/apps/builder/app/canvas/shared/styles.ts
+++ b/apps/builder/app/canvas/shared/styles.ts
@@ -206,12 +206,13 @@ const subscribeContentEditModeHelperStyles = () => {
const editableInstanceSelectors: InstanceSelector[] = [];
const instances = $instances.get();
- findAllEditableInstanceSelector(
- [rootInstanceId],
+ findAllEditableInstanceSelector({
+ instanceSelector: [rootInstanceId],
instances,
- $registeredComponentMetas.get(),
- editableInstanceSelectors
- );
+ props: $props.get(),
+ metas: $registeredComponentMetas.get(),
+ results: editableInstanceSelectors,
+ });
// Group IDs into chunks of 20 since :is() allows for more efficient grouping
const chunkSize = 20;
diff --git a/apps/builder/app/canvas/shared/use-drag-drop.ts b/apps/builder/app/canvas/shared/use-drag-drop.ts
index 61d21adf5a..97913d0d8d 100644
--- a/apps/builder/app/canvas/shared/use-drag-drop.ts
+++ b/apps/builder/app/canvas/shared/use-drag-drop.ts
@@ -28,14 +28,16 @@ import {
import {
type InstanceSelector,
areInstanceSelectorsEqual,
- getAncestorInstanceSelector,
} from "~/shared/tree-utils";
import {
findClosestContainer,
findClosestInstanceMatchingFragment,
isTreeMatching,
} from "~/shared/matcher";
-import { isTreeSatisfyingContentModel } from "~/shared/content-model";
+import {
+ findClosestRichText,
+ isTreeSatisfyingContentModel,
+} from "~/shared/content-model";
declare module "~/shared/pubsub" {
export interface PubsubMap {
@@ -135,26 +137,6 @@ const sharedDropOptions = {
},
};
-const findClosestDraggable = (instanceSelector: InstanceSelector) => {
- // cannot drag root
- if (instanceSelector.length === 1) {
- return;
- }
- const instances = $instances.get();
- const metas = $registeredComponentMetas.get();
- for (const instanceId of instanceSelector) {
- const instance = instances.get(instanceId);
- if (instance === undefined) {
- return;
- }
- const meta = metas.get(instance.component);
- if (meta?.type === "rich-text-child") {
- continue;
- }
- return getAncestorInstanceSelector(instanceSelector, instanceId);
- }
-};
-
export const useDragAndDrop = () => {
const state = useRef({ ...initialState });
@@ -247,7 +229,14 @@ export const useDragAndDrop = () => {
return false;
}
// When trying to drag an instance inside editor, drag the editor instead
- return findClosestDraggable(instanceSelector) ?? false;
+ return (
+ findClosestRichText({
+ instanceSelector,
+ instances: $instances.get(),
+ props: $props.get(),
+ metas: $registeredComponentMetas.get(),
+ }) ?? instanceSelector
+ );
},
onStart({ data: dragInstanceSelector }) {
diff --git a/apps/builder/app/shared/content-model.test.tsx b/apps/builder/app/shared/content-model.test.tsx
index 6609400ef1..9283b66fe8 100644
--- a/apps/builder/app/shared/content-model.test.tsx
+++ b/apps/builder/app/shared/content-model.test.tsx
@@ -1,8 +1,13 @@
import { describe, expect, test } from "vitest";
import { coreMetas } from "@webstudio-is/sdk";
import * as baseComponentMetas from "@webstudio-is/sdk-components-react/metas";
-import { $, renderData, ws } from "@webstudio-is/template";
-import { isTreeSatisfyingContentModel } from "./content-model";
+import { $, expression, renderData, ws } from "@webstudio-is/template";
+import {
+ findClosestNonTextualContainer,
+ findClosestRichText,
+ isRichTextTree,
+ isTreeSatisfyingContentModel,
+} from "./content-model";
const defaultMetas = new Map(
Object.entries({ ...coreMetas, ...baseComponentMetas })
@@ -608,3 +613,316 @@ describe("component content model", () => {
).toBeTruthy();
});
});
+
+describe("rich text tree", () => {
+ test("check empty instance is rich text", () => {
+ expect(
+ isRichTextTree({
+ ...renderData(<$.Bold ws:id="instanceId"></$.Bold>),
+ metas: defaultMetas,
+ instanceId: "instanceId",
+ })
+ ).toBeTruthy();
+ expect(
+ isRichTextTree({
+ ...renderData(<$.HeadSlot ws:id="instanceId"></$.HeadSlot>),
+ metas: defaultMetas,
+ instanceId: "instanceId",
+ })
+ ).toBeFalsy();
+ });
+
+ test("any instance with text can be edited", () => {
+ expect(
+ isRichTextTree({
+ ...renderData(<$.HeadSlot ws:id="instanceId">my text</$.HeadSlot>),
+ metas: defaultMetas,
+ instanceId: "instanceId",
+ })
+ ).toBeTruthy();
+ expect(
+ isRichTextTree({
+ ...renderData(
+ <$.HeadSlot ws:id="instanceId">{expression``}</$.HeadSlot>
+ ),
+ metas: defaultMetas,
+ instanceId: "instanceId",
+ })
+ ).toBeTruthy();
+ });
+
+ test("rich text content tags can be edited", () => {
+ expect(
+ isRichTextTree({
+ ...renderData(
+ <$.Bold ws:id="instanceId">
+ <$.Italic></$.Italic>
+ </$.Bold>
+ ),
+ metas: defaultMetas,
+ instanceId: "instanceId",
+ })
+ ).toBeTruthy();
+ });
+
+ test("rich text instances with rich text content can be edited", () => {
+ expect(
+ isRichTextTree({
+ ...renderData(
+ <$.Paragraph ws:id="instanceId">
+ <$.Bold>bold</$.Bold>
+ </$.Paragraph>
+ ),
+ metas: defaultMetas,
+ instanceId: "instanceId",
+ })
+ ).toBeTruthy();
+ expect(
+ isRichTextTree({
+ ...renderData(
+ <$.HeadSlot ws:id="instanceId">
+ <$.Bold>bold</$.Bold>
+ </$.HeadSlot>
+ ),
+ metas: defaultMetas,
+ instanceId: "instanceId",
+ })
+ ).toBeFalsy();
+ });
+
+ test("div with paragraph cannot be rich text", () => {
+ expect(
+ isRichTextTree({
+ ...renderData(
+ <$.Box ws:id="instanceId">
+ <$.Paragraph></$.Paragraph>
+ </$.Box>
+ ),
+ metas: defaultMetas,
+ instanceId: "instanceId",
+ })
+ ).toBeFalsy();
+ });
+
+ test("finds closest rich text with rich text content", () => {
+ expect(
+ findClosestRichText({
+ ...renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="p" ws:id="paragraphId">
+ <ws.element ws:tag="b" ws:id="boldId"></ws.element>
+ </ws.element>
+ </ws.element>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["boldId", "paragraphId", "bodyId"],
+ })
+ ).toEqual(["paragraphId", "bodyId"]);
+ });
+
+ test("finds closest rich text with rich text content", () => {
+ expect(
+ findClosestRichText({
+ ...renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="p" ws:id="paragraphId">
+ text
+ </ws.element>
+ </ws.element>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["paragraphId", "bodyId"],
+ })
+ ).toEqual(["paragraphId", "bodyId"]);
+ });
+
+ test("treat body as rich text when has text inside", () => {
+ expect(
+ findClosestRichText({
+ ...renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ text
+ <ws.element ws:tag="p" ws:id="paragraphId">
+ <ws.element ws:tag="b" ws:id="boldId"></ws.element>
+ </ws.element>
+ </ws.element>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["boldId", "paragraphId", "bodyId"],
+ })
+ ).toEqual(["bodyId"]);
+ });
+
+ test("ignore <a> with <div> inside", () => {
+ const data = renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="a" ws:id="linkId">
+ <ws.element ws:tag="div" ws:id="divId"></ws.element>
+ </ws.element>
+ </ws.element>
+ );
+ expect(
+ findClosestRichText({
+ ...data,
+ metas: defaultMetas,
+ instanceSelector: ["divId", "linkId", "bodyId"],
+ })
+ ).toEqual(["divId", "linkId", "bodyId"]);
+ expect(
+ findClosestRichText({
+ ...data,
+ metas: defaultMetas,
+ instanceSelector: ["linkId", "bodyId"],
+ })
+ ).toEqual(undefined);
+ });
+
+ test("finds link rich text", () => {
+ expect(
+ findClosestRichText({
+ ...renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="div" ws:id="divId">
+ <ws.element ws:tag="a" ws:id="linkId">
+ my link
+ </ws.element>
+ </ws.element>
+ </ws.element>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["linkId", "divId", "bodyId"],
+ })
+ ).toEqual(["linkId", "divId", "bodyId"]);
+ });
+
+ test("finds span rich text", () => {
+ expect(
+ findClosestRichText({
+ ...renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="div" ws:id="divId">
+ <ws.element ws:tag="span" ws:id="spanId">
+ my span
+ </ws.element>
+ </ws.element>
+ </ws.element>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["spanId", "divId", "bodyId"],
+ })
+ ).toEqual(["spanId", "divId", "bodyId"]);
+ });
+
+ test("finds rich text with mixed children", () => {
+ expect(
+ findClosestRichText({
+ ...renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="div" ws:id="divId">
+ <ws.element ws:tag="span" ws:id="spanId">
+ my link
+ </ws.element>
+ <ws.element ws:tag="b" ws:id="boldId">
+ my link
+ </ws.element>
+ </ws.element>
+ </ws.element>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["spanId", "divId", "bodyId"],
+ })
+ ).toEqual(["divId", "bodyId"]);
+ });
+});
+
+describe("closest non textual container", () => {
+ test("skips non-container instances", () => {
+ expect(
+ findClosestNonTextualContainer({
+ ...renderData(
+ <$.Body ws:id="bodyId">
+ <$.Box ws:id="boxId">
+ <$.Image ws:id="imageId" />
+ </$.Box>
+ </$.Body>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["imageId", "boxId", "bodyId"],
+ })
+ ).toEqual(["boxId", "bodyId"]);
+ });
+
+ test("skips containers with text", () => {
+ expect(
+ findClosestNonTextualContainer({
+ ...renderData(
+ <$.Body ws:id="bodyId">
+ <$.Box ws:id="boxId">
+ <$.Box ws:id="box-with-text">text</$.Box>
+ </$.Box>
+ </$.Body>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["box-with-text", "boxId", "bodyId"],
+ })
+ ).toEqual(["boxId", "bodyId"]);
+ });
+
+ test("skips containers with expression", () => {
+ expect(
+ findClosestNonTextualContainer({
+ ...renderData(
+ <$.Body ws:id="bodyId">
+ <$.Box ws:id="boxId">
+ <$.Box ws:id="box-with-expr">{expression`1 + 1`}</$.Box>
+ </$.Box>
+ </$.Body>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["box-with-expr", "boxId", "bodyId"],
+ })
+ ).toEqual(["boxId", "bodyId"]);
+ });
+
+ test("skips containers with rich text children", () => {
+ expect(
+ findClosestNonTextualContainer({
+ ...renderData(
+ <$.Body ws:id="bodyId">
+ <$.Box ws:id="boxId">
+ <$.Box ws:id="box-with-bold">
+ <$.Bold ws:id="boldId"></$.Bold>
+ </$.Box>
+ </$.Box>
+ </$.Body>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["box-with-bold", "boxId", "bodyId"],
+ })
+ ).toEqual(["boxId", "bodyId"]);
+ });
+
+ test("allow root with text", () => {
+ expect(
+ findClosestNonTextualContainer({
+ ...renderData(<$.Body ws:id="body">text</$.Body>),
+ metas: defaultMetas,
+ instanceSelector: ["body"],
+ })
+ ).toEqual(["body"]);
+ });
+
+ test("matches empty div", () => {
+ expect(
+ findClosestNonTextualContainer({
+ ...renderData(
+ <ws.element ws:tag="body" ws:id="bodyId">
+ <ws.element ws:tag="div" ws:id="divId"></ws.element>
+ </ws.element>
+ ),
+ metas: defaultMetas,
+ instanceSelector: ["divId", "bodyId"],
+ })
+ ).toEqual(["divId", "bodyId"]);
+ });
+});
diff --git a/apps/builder/app/shared/content-model.ts b/apps/builder/app/shared/content-model.ts
index ab286b95b9..848330b245 100644
--- a/apps/builder/app/shared/content-model.ts
+++ b/apps/builder/app/shared/content-model.ts
@@ -11,6 +11,9 @@ import {
type WsComponentMeta,
} from "@webstudio-is/sdk";
import type { InstanceSelector } from "./tree-utils";
+import { setIsSubsetOf } from "./shim";
+
+type Metas = Map<Instance["component"], WsComponentMeta>;
const tagByInstanceIdCache = new WeakMap<Props, Map<Instance["id"], string>>();
@@ -34,7 +37,7 @@ const getTag = ({
props,
}: {
instance: Instance;
- metas: Map<Instance["component"], WsComponentMeta>;
+ metas: Metas;
props: Props;
}) => {
const meta = metas.get(instance.component);
@@ -155,7 +158,7 @@ const computeAllowedCategories = ({
}: {
instances: Instances;
props: Props;
- metas: Map<Instance["component"], WsComponentMeta>;
+ metas: Metas;
instanceSelector: InstanceSelector;
}) => {
let instance: undefined | Instance;
@@ -183,7 +186,7 @@ const isComponentSatisfyingContentModel = ({
component,
allowedCategories,
}: {
- metas: Map<Instance["component"], WsComponentMeta>;
+ metas: Metas;
component: string;
allowedCategories: undefined | string[];
}) => {
@@ -207,7 +210,7 @@ const getComponentChildrenCategories = ({
component,
allowedCategories,
}: {
- metas: Map<Instance["component"], WsComponentMeta>;
+ metas: Metas;
component: string;
allowedCategories: undefined | string[];
}) => {
@@ -229,7 +232,7 @@ const computeAllowedComponentCategories = ({
instanceSelector,
}: {
instances: Instances;
- metas: Map<Instance["component"], WsComponentMeta>;
+ metas: Metas;
instanceSelector: InstanceSelector;
}) => {
let instance: undefined | Instance;
@@ -296,7 +299,7 @@ export const isTreeSatisfyingContentModel = ({
}: {
instances: Instances;
props: Props;
- metas: Map<Instance["component"], WsComponentMeta>;
+ metas: Metas;
instanceSelector: InstanceSelector;
onError?: (message: string) => void;
_allowedCategories?: string[];
@@ -380,3 +383,196 @@ export const isTreeSatisfyingContentModel = ({
}
return isSatisfying;
};
+
+const richTextContentTags = new Set<undefined | string>([
+ "sup",
+ "sub",
+ "b",
+ "strong",
+ "i",
+ "em",
+ "a",
+ "span",
+]);
+
+const richTextContainerTags = new Set<undefined | string>(["a", "span"]);
+
+const findContentTags = ({
+ instances,
+ props,
+ metas,
+ instance,
+ _tags: tags = new Set(),
+}: {
+ instances: Instances;
+ props: Props;
+ metas: Metas;
+ instance: Instance;
+ _tags?: Set<undefined | string>;
+}) => {
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ const childInstance = instances.get(child.value);
+ // consider collection item as well
+ if (childInstance === undefined) {
+ tags.add(undefined);
+ continue;
+ }
+ const tag = getTag({ instance: childInstance, metas, props });
+ tags.add(tag);
+ findContentTags({
+ instances,
+ props,
+ metas,
+ instance: childInstance,
+ _tags: tags,
+ });
+ }
+ }
+ return tags;
+};
+
+export const isRichTextTree = ({
+ instanceId,
+ instances,
+ props,
+ metas,
+}: {
+ instanceId: Instance["id"];
+ instances: Instances;
+ props: Props;
+ metas: Metas;
+}): boolean => {
+ const instance = instances.get(instanceId);
+ // collection item is not rich text
+ if (instance === undefined) {
+ return false;
+ }
+ const componentContentModel =
+ metas.get(instance.component)?.contentModel ?? defaultComponentContentModel;
+ const isRichText = componentContentModel.children.includes("rich-text");
+ // only empty instance with rich text content can be edited
+ if (instance.children.length === 0) {
+ return isRichText;
+ }
+ for (const child of instance.children) {
+ if (child.type === "text" || child.type === "expression") {
+ return true;
+ }
+ }
+ const contentTags = findContentTags({
+ instances,
+ props,
+ metas,
+ instance,
+ });
+ return (
+ isRichText &&
+ // rich text must contain only supported elements in editor
+ setIsSubsetOf(contentTags, richTextContentTags) &&
+ // rich text cannot contain only span and only link
+ // those links and spans are containers in such cases
+ !setIsSubsetOf(contentTags, richTextContainerTags)
+ );
+};
+
+export const findClosestRichText = ({
+ instances,
+ props,
+ metas,
+ instanceSelector,
+}: {
+ instances: Instances;
+ props: Props;
+ metas: Metas;
+ instanceSelector: InstanceSelector;
+}): undefined | InstanceSelector => {
+ let foundRichText: undefined | InstanceSelector = undefined;
+ for (let index = 0; index < instanceSelector.length; index += 1) {
+ const instanceId = instanceSelector[index];
+ if (!isRichTextTree({ instanceId, instances, props, metas })) {
+ break;
+ }
+ foundRichText = instanceSelector.slice(index);
+ }
+ return foundRichText;
+};
+
+export const isRichTextContent = ({
+ instances,
+ props,
+ metas,
+ instanceSelector,
+}: {
+ instances: Instances;
+ props: Props;
+ metas: Metas;
+ instanceSelector: InstanceSelector;
+}) => {
+ const richTextSelector = findClosestRichText({
+ instanceSelector,
+ instances,
+ props,
+ metas,
+ });
+ return (
+ richTextSelector && richTextSelector.join() !== instanceSelector.join()
+ );
+};
+
+export const findClosestNonTextualContainer = ({
+ instances,
+ props,
+ metas,
+ instanceSelector,
+}: {
+ instances: Instances;
+ props: Props;
+ metas: Metas;
+ instanceSelector: InstanceSelector;
+}) => {
+ // page root with text can be used as container
+ if (instanceSelector.length === 1) {
+ return instanceSelector;
+ }
+ for (let index = 0; index < instanceSelector.length; index += 1) {
+ const instanceId = instanceSelector[index];
+ const instance = instances.get(instanceId);
+ // collection item can be undefined
+ if (instance === undefined) {
+ continue;
+ }
+ const meta = metas.get(instance.component);
+ if (meta?.type !== "container") {
+ continue;
+ }
+ const tag = getTag({ instance, props, metas });
+ if (
+ instance.children.length === 0 &&
+ !meta?.placeholder &&
+ !richTextContentTags.has(tag)
+ ) {
+ return instanceSelector.slice(index);
+ }
+ // placeholder exists only inside of empty instances
+ let hasText = false;
+ for (const child of instance.children) {
+ if (child.type === "text" || child.type === "expression") {
+ hasText = true;
+ }
+ }
+ const contentTags = findContentTags({
+ instances,
+ props,
+ metas,
+ instance,
+ });
+ if (setIsSubsetOf(contentTags, richTextContentTags)) {
+ hasText = true;
+ }
+ if (!hasText) {
+ return instanceSelector.slice(index);
+ }
+ }
+ return instanceSelector;
+};
diff --git a/apps/builder/app/shared/instance-utils.test.tsx b/apps/builder/app/shared/instance-utils.test.tsx
index b4f1b0e6d2..71118bdc46 100644
--- a/apps/builder/app/shared/instance-utils.test.tsx
+++ b/apps/builder/app/shared/instance-utils.test.tsx
@@ -16,7 +16,6 @@ import type {
Asset,
Breakpoint,
Instance,
- Instances,
Prop,
StyleDecl,
StyleDeclKey,
@@ -28,7 +27,6 @@ import type {
import { coreMetas, portalComponent } from "@webstudio-is/sdk";
import type { StyleProperty, StyleValue } from "@webstudio-is/css-engine";
import {
- findClosestEditableInstanceSelector,
deleteInstanceMutable,
extractWebstudioFragment,
insertWebstudioFragmentCopy,
@@ -92,7 +90,7 @@ const createFakeComponentMetas = (
const configs = {
Item: { ...base, type: "container", ...itemMeta },
AnotherItem: { ...base, type: "container", ...anotherItemMeta },
- Bold: { ...base, type: "rich-text-child" },
+ Bold: { ...base, type: "container" },
Text: { ...base, type: "container" },
Form: { ...base, type: "container" },
Box: { ...base, type: "container" },
@@ -166,80 +164,6 @@ const createFontAsset = (id: string, family: string): Asset => {
};
};
-describe("find closest editable instance selector", () => {
- test("searches closest container", () => {
- const instances: Instances = toMap([
- createInstance("body", "Body", [{ type: "id", value: "box" }]),
- createInstance("box", "Box", [
- { type: "text", value: "some text" },
- { type: "id", value: "bold" },
- ]),
- createInstance("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 = toMap([
- createInstance("body", "Body", [{ type: "id", value: "box" }]),
- createInstance("box", "Box", [
- { type: "text", value: "some text" },
- { type: "id", value: "bold" },
- { type: "id", value: "child-box" },
- ]),
- createInstance("bold", "Bold", [{ type: "text", value: "some-bold" }]),
- createInstance("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 = toMap([
- createInstance("body", "Body", [{ type: "id", value: "body" }]),
- createInstance("box", "Box", []),
- ]);
- expect(
- findClosestEditableInstanceSelector(
- ["box", "body"],
- instances,
- createFakeComponentMetas({})
- )
- ).toEqual(["box", "body"]);
- });
-
- test("prevent editing Body instance", () => {
- const instances: Instances = toMap([createInstance("body", "Body", [])]);
- expect(
- findClosestEditableInstanceSelector(
- ["body"],
- instances,
- createFakeComponentMetas({})
- )
- ).toEqual(undefined);
- });
-});
-
describe("insert instance children", () => {
test("insert instance children into empty target", () => {
const instances = toMap([createInstance("body", "Body", [])]);
@@ -1466,17 +1390,17 @@ describe("find closest insertable", () => {
const { instances } = renderData(
<$.Body ws:id="bodyId">
<$.Paragraph ws:id="paragraphId">
- <$.Box ws:id="spanId" ws:tag="span"></$.Box>
+ <$.Image ws:id="imageId"></$.Image>
</$.Paragraph>
</$.Body>
);
$instances.set(instances);
- selectInstance(["boxId", "paragraphId", "bodyId"]);
+ selectInstance(["imageId", "paragraphId", "bodyId"]);
expect(
findClosestInsertable(renderTemplate(<$.Box ws:tag="span"></$.Box>))
).toEqual({
parentSelector: ["paragraphId", "bodyId"],
- position: 0,
+ position: 1,
});
});
diff --git a/apps/builder/app/shared/instance-utils.ts b/apps/builder/app/shared/instance-utils.ts
index 9fa93c56de..594f92b0fc 100644
--- a/apps/builder/app/shared/instance-utils.ts
+++ b/apps/builder/app/shared/instance-utils.ts
@@ -29,6 +29,7 @@ import {
collectionComponent,
Prop,
parseComponentName,
+ Props,
} from "@webstudio-is/sdk";
import {
$props,
@@ -49,7 +50,6 @@ import {
type DroppableTarget,
type InstanceSelector,
findLocalStyleSourcesWithinInstances,
- getAncestorInstanceSelector,
getReparentDropTargetMutable,
getInstanceOrCreateFragmentIfNecessary,
wrapEditableChildrenAroundDropTargetMutable,
@@ -66,15 +66,16 @@ import {
selectInstance,
type InstancePath,
} from "./awareness";
-import {
- findClosestNonTextualContainer,
- findClosestInstanceMatchingFragment,
-} from "./matcher";
+import { findClosestInstanceMatchingFragment } from "./matcher";
import {
findAvailableVariables,
restoreExpressionVariables,
unsetExpressionVariables,
} from "./data-variables";
+import {
+ findClosestNonTextualContainer,
+ isRichTextTree,
+} from "./content-model";
/**
* structuredClone can be invoked on draft and throw error
@@ -180,108 +181,43 @@ export const getInstanceLabel = (
);
};
-const isTextEditableInstance = (
- instance: Instance,
- instances: Instances,
- metas: Map<string, WsComponentMeta>
-) => {
- // when start editing empty body all text content
- // including style and scripts appear in editor
- // assume body is root and stop checking further
- if (instance.component === "Body") {
- return false;
- }
-
- const meta = metas.get(instance.component);
-
- if (meta === undefined) {
- return false;
- }
-
- if (meta.type !== "container") {
- return false;
- }
-
- if (meta.constraints !== undefined) {
- const hasTextContraint = (
- Array.isArray(meta.constraints) ? meta.constraints : [meta.constraints]
- ).some(
- (constraint) =>
- constraint.relation === "child" && constraint.text === false
- );
- if (hasTextContraint) {
- return false;
- }
- }
-
- // 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 true;
-};
-
-export const findAllEditableInstanceSelector = (
- currentPath: InstanceSelector,
- instances: Map<string, Instance>,
- metas: Map<string, WsComponentMeta>,
- results: InstanceSelector[]
-) => {
- const instanceId = currentPath[0];
+export const findAllEditableInstanceSelector = ({
+ instanceSelector,
+ instances,
+ props,
+ metas,
+ results,
+}: {
+ instanceSelector: InstanceSelector;
+ instances: Instances;
+ props: Props;
+ metas: Map<string, WsComponentMeta>;
+ results: InstanceSelector[];
+}) => {
+ const [instanceId] = instanceSelector;
if (instanceId === undefined) {
return;
}
- const instance = instances.get(instanceId);
- if (instance === undefined) {
- return;
- }
-
// Check if current instance is text editing instance
- if (isTextEditableInstance(instance, instances, metas)) {
- results.push(currentPath);
+ if (isRichTextTree({ instanceId, instances, props, metas })) {
+ results.push(instanceSelector);
return;
}
- // If not, traverse its children
- for (const child of instance.children) {
- if (child.type === "id") {
- findAllEditableInstanceSelector(
- [child.value, ...currentPath],
- instances,
- metas,
- results
- );
- }
- }
-
- return null;
-};
-
-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;
- }
-
- if (isTextEditableInstance(instance, instances, metas)) {
- return getAncestorInstanceSelector(instanceSelector, instanceId);
+ const instance = instances.get(instanceId);
+ if (instance) {
+ for (const child of instance.children) {
+ if (child.type === "id") {
+ findAllEditableInstanceSelector({
+ instanceSelector: [child.value, ...instanceSelector],
+ instances,
+ props,
+ metas,
+ results,
+ });
+ }
}
}
};
@@ -1300,11 +1236,14 @@ export const findClosestInsertable = (
const metas = $registeredComponentMetas.get();
const instances = $instances.get();
const props = $props.get();
- const closestContainerIndex = findClosestNonTextualContainer({
+ const containerSelector = findClosestNonTextualContainer({
metas,
+ props,
instances,
instanceSelector,
});
+ const closestContainerIndex =
+ instanceSelector.length - containerSelector.length;
if (closestContainerIndex === -1) {
return;
}
diff --git a/apps/builder/app/shared/matcher.test.tsx b/apps/builder/app/shared/matcher.test.tsx
index 575fdd3657..79b5070603 100644
--- a/apps/builder/app/shared/matcher.test.tsx
+++ b/apps/builder/app/shared/matcher.test.tsx
@@ -11,7 +11,6 @@ import * as baseMetas from "@webstudio-is/sdk-components-react/metas";
import * as radixMetas from "@webstudio-is/sdk-components-react-radix/metas";
import type { Matcher, WsComponentMeta } from "@webstudio-is/sdk";
import {
- findClosestNonTextualContainer,
findClosestInstanceMatchingFragment,
isTreeMatching,
findClosestContainer,
@@ -1007,81 +1006,3 @@ describe("find closest container", () => {
).toEqual(0);
});
});
-
-describe("find closest non textual container", () => {
- test("skips non-container instances", () => {
- expect(
- findClosestNonTextualContainer({
- ...renderData(
- <$.Body ws:id="body">
- <$.Box ws:id="box">
- <$.Image ws:id="image" />
- </$.Box>
- </$.Body>
- ),
- metas,
- instanceSelector: ["image", "box", "body"],
- })
- ).toEqual(1);
- });
-
- test("skips containers with text", () => {
- expect(
- findClosestNonTextualContainer({
- ...renderData(
- <$.Body ws:id="body">
- <$.Box ws:id="box">
- <$.Box ws:id="box-with-text">text</$.Box>
- </$.Box>
- </$.Body>
- ),
- metas,
- instanceSelector: ["box-with-text", "box", "body"],
- })
- ).toEqual(1);
- });
-
- test("skips containers with expression", () => {
- expect(
- findClosestNonTextualContainer({
- ...renderData(
- <$.Body ws:id="body">
- <$.Box ws:id="box">
- <$.Box ws:id="box-with-expr">{expression`1 + 1`}</$.Box>
- </$.Box>
- </$.Body>
- ),
- metas,
- instanceSelector: ["box-with-expr", "box", "body"],
- })
- ).toEqual(1);
- });
-
- test("skips containers with rich text children", () => {
- expect(
- findClosestNonTextualContainer({
- ...renderData(
- <$.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({
- ...renderData(<$.Body ws:id="body">text</$.Body>),
- metas,
- instanceSelector: ["body"],
- })
- ).toEqual(0);
- });
-});
diff --git a/apps/builder/app/shared/matcher.ts b/apps/builder/app/shared/matcher.ts
index c1935afdbb..c1a01ff5c3 100644
--- a/apps/builder/app/shared/matcher.ts
+++ b/apps/builder/app/shared/matcher.ts
@@ -406,52 +406,6 @@ export const findClosestContainer = ({
return -1;
};
-export const findClosestNonTextualContainer = ({
- metas,
- instances,
- instanceSelector,
-}: {
- metas: Map<string, WsComponentMeta>;
- instances: Instances;
- instanceSelector: InstanceSelector;
-}) => {
- // page root with text can be used as container
- if (instanceSelector.length === 1) {
- return 0;
- }
- for (let index = 0; index < instanceSelector.length; index += 1) {
- const instanceId = instanceSelector[index];
- const instance = instances.get(instanceId);
- // collection item can be undefined
- if (instance === undefined) {
- continue;
- }
- const meta = metas.get(instance.component);
- // placeholder exists only inside of empty instances
- let hasText =
- meta?.placeholder !== undefined && instance.children.length === 0;
- for (const child of instance.children) {
- 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;
- }
- if (meta?.type === "container") {
- return index;
- }
- }
- return -1;
-};
-
export const __testing__ = {
isInstanceMatching,
};
diff --git a/apps/builder/app/shared/shim.test.ts b/apps/builder/app/shared/shim.test.ts
index 7871269033..d43e9ce4e3 100644
--- a/apps/builder/app/shared/shim.test.ts
+++ b/apps/builder/app/shared/shim.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from "vitest";
-import { mapGroupBy, setDifference, setUnion } from "./shim";
+import { mapGroupBy, setDifference, setIsSubsetOf, setUnion } from "./shim";
test("Set.prototype.difference", () => {
// this set is bigger than other
@@ -18,6 +18,15 @@ test("Set.prototype.union", () => {
);
});
+test("Set.prototype.isSubsetOf", () => {
+ expect(setIsSubsetOf(new Set([1, 2, 3]), new Set([1, 2, 3]))).toBeTruthy();
+ expect(setIsSubsetOf(new Set([1, 2]), new Set([1, 2, 3]))).toBeTruthy();
+ expect(setIsSubsetOf(new Set(), new Set([1, 2, 3]))).toBeTruthy();
+ expect(setIsSubsetOf(new Set(), new Set())).toBeTruthy();
+ expect(setIsSubsetOf(new Set([1, 2, 3]), new Set([1, 2]))).toBeFalsy();
+ expect(setIsSubsetOf(new Set([1, 2, 3]), new Set())).toBeFalsy();
+});
+
test("Map.groupBy", () => {
expect(mapGroupBy([1, 2, 3, 4, 5], (item) => item % 2)).toEqual(
new Map([
diff --git a/apps/builder/app/shared/shim.ts b/apps/builder/app/shared/shim.ts
index c0617d0e09..4ddf0d66a5 100644
--- a/apps/builder/app/shared/shim.ts
+++ b/apps/builder/app/shared/shim.ts
@@ -24,6 +24,18 @@ export const setUnion = <Item>(current: Set<Item>, other: Set<Item>) => {
return result;
};
+export const setIsSubsetOf = <Item>(current: Set<Item>, other: Set<Item>) => {
+ if (current.size > other.size) {
+ return false;
+ }
+ for (const item of current) {
+ if (!other.has(item)) {
+ return false;
+ }
+ }
+ return true;
+};
+
export const mapGroupBy = <Item, Key>(
array: Item[] | Iterable<Item>,
getKey: (item: Item) => Key
diff --git a/apps/builder/app/shared/tree-utils.test.ts b/apps/builder/app/shared/tree-utils.test.ts
index b2ed7ad3fd..6def465e75 100644
--- a/apps/builder/app/shared/tree-utils.test.ts
+++ b/apps/builder/app/shared/tree-utils.test.ts
@@ -8,10 +8,8 @@ import type {
} from "@webstudio-is/sdk";
import { getStyleDeclKey } from "@webstudio-is/sdk";
import {
- type InstanceSelector,
cloneStyles,
findLocalStyleSourcesWithinInstances,
- getAncestorInstanceSelector,
isDescendantOrSelf,
} from "./tree-utils";
@@ -75,18 +73,6 @@ const createStyleDeclPair = (
] as const;
};
-test("get ancestor instance selector", () => {
- const instanceSelector: InstanceSelector = ["4", "3", "2", "1"];
- expect(getAncestorInstanceSelector(instanceSelector, "2")).toEqual([
- "2",
- "1",
- ]);
- expect(getAncestorInstanceSelector(instanceSelector, "-1")).toEqual(
- undefined
- );
- expect(getAncestorInstanceSelector(instanceSelector, "1")).toEqual(["1"]);
-});
-
test("clone styles with appled new style source ids", () => {
const styles: Styles = new Map([
createStyleDeclPair("styleSource1", "bp1"),
diff --git a/apps/builder/app/shared/tree-utils.ts b/apps/builder/app/shared/tree-utils.ts
index 0894436228..9a5fcf5017 100644
--- a/apps/builder/app/shared/tree-utils.ts
+++ b/apps/builder/app/shared/tree-utils.ts
@@ -12,6 +12,7 @@ import type {
WsComponentMeta,
} from "@webstudio-is/sdk";
import { collectionComponent } from "@webstudio-is/sdk";
+import { isRichTextTree } from "./content-model";
// slots can have multiple parents so instance should be addressed
// with full rendered path to avoid double selections with slots
@@ -19,19 +20,6 @@ import { collectionComponent } from "@webstudio-is/sdk";
// selector starts with target instance and ends with root
export type InstanceSelector = Instance["id"][];
-// provide a selector starting with ancestor id
-// useful to select parent instance or one of breadcrumbs instances
-export const getAncestorInstanceSelector = (
- instanceSelector: InstanceSelector,
- ancestorId: Instance["id"]
-): undefined | InstanceSelector => {
- const ancestorIndex = instanceSelector.indexOf(ancestorId);
- if (ancestorIndex === -1) {
- return undefined;
- }
- return instanceSelector.slice(ancestorIndex);
-};
-
export const areInstanceSelectorsEqual = (
left?: InstanceSelector,
right?: InstanceSelector
@@ -161,17 +149,14 @@ export const wrapEditableChildrenAroundDropTargetMutable = (
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 isParentRichText = isRichTextTree({
+ instances,
+ props,
+ metas,
+ instanceId: parentId,
+ });
+ if (!isParentRichText) {
+ return;
}
const position =
dropTarget.position === "end"
diff --git a/packages/sdk-components-react/src/bold.ws.ts b/packages/sdk-components-react/src/bold.ws.ts
index 4f84d4c3a4..d6b3843590 100644
--- a/packages/sdk-components-react/src/bold.ws.ts
+++ b/packages/sdk-components-react/src/bold.ws.ts
@@ -14,7 +14,7 @@ const presetStyle = {
} satisfies PresetStyle<typeof defaultTag>;
export const meta: WsComponentMeta = {
- type: "rich-text-child",
+ type: "container",
label: "Bold Text",
icon: BoldIcon,
states: defaultStates,
diff --git a/packages/sdk-components-react/src/italic.ws.ts b/packages/sdk-components-react/src/italic.ws.ts
index dcc8ba6791..258c59b53c 100644
--- a/packages/sdk-components-react/src/italic.ws.ts
+++ b/packages/sdk-components-react/src/italic.ws.ts
@@ -20,7 +20,7 @@ const presetStyle = {
} satisfies PresetStyle<typeof defaultTag>;
export const meta: WsComponentMeta = {
- type: "rich-text-child",
+ type: "container",
label: "Italic Text",
icon: TextItalicIcon,
states: defaultStates,
diff --git a/packages/sdk-components-react/src/rich-text-link.ws.ts b/packages/sdk-components-react/src/rich-text-link.ws.ts
index 9c0c512dda..a5328bae44 100644
--- a/packages/sdk-components-react/src/rich-text-link.ws.ts
+++ b/packages/sdk-components-react/src/rich-text-link.ws.ts
@@ -3,7 +3,7 @@ import { meta as linkMeta, propsMeta as linkPropsMeta } from "./link.ws";
export const meta: WsComponentMeta = {
...linkMeta,
- type: "rich-text-child",
+ type: "container",
};
export const propsMeta: WsComponentPropsMeta = linkPropsMeta;
diff --git a/packages/sdk-components-react/src/span.ws.ts b/packages/sdk-components-react/src/span.ws.ts
index 3b521f0b3d..5a53475e4f 100644
--- a/packages/sdk-components-react/src/span.ws.ts
+++ b/packages/sdk-components-react/src/span.ws.ts
@@ -14,7 +14,7 @@ const presetStyle = {
} satisfies PresetStyle<typeof defaultTag>;
export const meta: WsComponentMeta = {
- type: "rich-text-child",
+ type: "container",
label: "Text",
icon: PaintBrushIcon,
states: defaultStates,
diff --git a/packages/sdk-components-react/src/subscript.ws.ts b/packages/sdk-components-react/src/subscript.ws.ts
index db8896d4e4..56d132092a 100644
--- a/packages/sdk-components-react/src/subscript.ws.ts
+++ b/packages/sdk-components-react/src/subscript.ws.ts
@@ -14,7 +14,7 @@ const presetStyle = {
} satisfies PresetStyle<typeof defaultTag>;
export const meta: WsComponentMeta = {
- type: "rich-text-child",
+ type: "container",
label: "Subscript Text",
icon: SubscriptIcon,
states: defaultStates,
diff --git a/packages/sdk-components-react/src/superscript.ws.ts b/packages/sdk-components-react/src/superscript.ws.ts
index 25aff83a6c..57b3916b09 100644
--- a/packages/sdk-components-react/src/superscript.ws.ts
+++ b/packages/sdk-components-react/src/superscript.ws.ts
@@ -14,7 +14,7 @@ const presetStyle = {
} satisfies PresetStyle<typeof defaultTag>;
export const meta: WsComponentMeta = {
- type: "rich-text-child",
+ type: "container",
label: "Superscript Text",
icon: SuperscriptIcon,
states: defaultStates,
diff --git a/packages/sdk/src/schema/component-meta.ts b/packages/sdk/src/schema/component-meta.ts
index a9169f72e6..74a8506588 100644
--- a/packages/sdk/src/schema/component-meta.ts
+++ b/packages/sdk/src/schema/component-meta.ts
@@ -91,8 +91,7 @@ export const WsComponentMeta = z.object({
// 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-child - formatted text fragment, not listed in components list
- type: z.enum(["container", "control", "embed", "rich-text-child"]),
+ type: z.enum(["container", "control", "embed"]),
/**
* a property used as textual placeholder when no content specified while in builder
* also signals to not insert components inside unless dropped explicitly