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.

Migrate text editor to normalized instances (#1187)

Bogdan Chadkin999b2d317194
diff --git a/apps/builder/app/canvas/features/text-editor/interop.test.ts b/apps/builder/app/canvas/features/text-editor/interop.test.ts
new file mode 100644
index 0000000000..6e08d46296
--- /dev/null
+++ b/apps/builder/app/canvas/features/text-editor/interop.test.ts
@@ -0,0 +1,205 @@
+import { test, expect } from "@jest/globals";
+import { createHeadlessEditor } from "@lexical/headless";
+import { LinkNode } from "@lexical/link";
+import type { Instance, InstancesItem } from "@webstudio-is/project-build";
+import { $convertToLexical, $convertToUpdates, Refs } from "./interop";
+
+const createInstance = (
+ id: Instance["id"],
+ component: string,
+ children: InstancesItem["children"]
+) => {
+ return {
+ type: "instance",
+ id,
+ component,
+ children,
+ };
+};
+
+const createInstancePair = (
+ id: Instance["id"],
+ component: string,
+ children: InstancesItem["children"]
+): [Instance["id"], InstancesItem] => {
+ return [
+ id,
+ {
+ type: "instance",
+ id,
+ component,
+ children,
+ },
+ ];
+};
+
+const instances = new Map([
+ createInstancePair("1", "Body", [
+ { type: "id", value: "2" },
+ { type: "id", value: "3" },
+ ]),
+ createInstancePair("2", "Box", []),
+ createInstancePair("3", "Box", [
+ { type: "text", value: "Hello" },
+ { type: "text", value: "\n" },
+ { type: "id", value: "4" },
+ { type: "text", value: "\n" },
+ { type: "id", value: "6" },
+ { type: "text", value: "\n" },
+ { type: "id", value: "7" },
+ ]),
+ createInstancePair("4", "Bold", [{ type: "id", value: "5" }]),
+ createInstancePair("5", "Italic", [{ type: "text", value: "world" }]),
+ createInstancePair("6", "Span", [{ type: "text", value: "and" }]),
+ createInstancePair("7", "RichTextLink", [
+ { type: "text", value: "other realms" },
+ ]),
+]);
+
+const expectedRefs = new Map([
+ ["4:bold", "4"],
+ ["4:italic", "5"],
+ ["6:span", "6"],
+ ["8", "7"],
+]);
+
+test("convert instances to lexical", async () => {
+ const refs: Refs = new Map();
+ const editor = createHeadlessEditor({
+ nodes: [LinkNode],
+ });
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ $convertToLexical(instances, "3", refs);
+ },
+ { onUpdate: resolve }
+ );
+ });
+
+ expect(editor.getEditorState().toJSON()).toMatchInlineSnapshot(`
+ {
+ "root": {
+ "children": [
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "Hello",
+ "type": "text",
+ "version": 1,
+ },
+ {
+ "type": "linebreak",
+ "version": 1,
+ },
+ {
+ "detail": 0,
+ "format": 3,
+ "mode": "normal",
+ "style": "",
+ "text": "world",
+ "type": "text",
+ "version": 1,
+ },
+ {
+ "type": "linebreak",
+ "version": 1,
+ },
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "--style-node-trigger:;",
+ "text": "and",
+ "type": "text",
+ "version": 1,
+ },
+ {
+ "type": "linebreak",
+ "version": 1,
+ },
+ {
+ "children": [
+ {
+ "detail": 0,
+ "format": 0,
+ "mode": "normal",
+ "style": "",
+ "text": "other realms",
+ "type": "text",
+ "version": 1,
+ },
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "rel": null,
+ "target": null,
+ "type": "link",
+ "url": "",
+ "version": 1,
+ },
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "type": "paragraph",
+ "version": 1,
+ },
+ ],
+ "direction": null,
+ "format": "",
+ "indent": 0,
+ "type": "root",
+ "version": 1,
+ },
+ }
+ `);
+
+ expect(refs).toEqual(expectedRefs);
+});
+
+test("convert lexical to instances updates", async () => {
+ const refs: Refs = new Map();
+ const editor = createHeadlessEditor({
+ nodes: [LinkNode],
+ });
+ await new Promise<void>((resolve) => {
+ editor.update(
+ () => {
+ $convertToLexical(instances, "3", refs);
+ },
+ { onUpdate: resolve }
+ );
+ });
+ const treeRootInstance = instances.get("3");
+ if (treeRootInstance === undefined) {
+ throw Error("Tree root instance should be in test data");
+ }
+
+ const updates = editor.getEditorState().read(() => {
+ return $convertToUpdates(treeRootInstance, refs);
+ });
+
+ expect(updates).toEqual([
+ createInstance("3", "Box", [
+ { type: "text", value: "Hello" },
+ { type: "text", value: "\n" },
+ { type: "id", value: "4" },
+ { type: "text", value: "\n" },
+ { type: "id", value: "6" },
+ { type: "text", value: "\n" },
+ { type: "id", value: "7" },
+ ]),
+ createInstance("4", "Bold", [{ type: "id", value: "5" }]),
+ createInstance("5", "Italic", [{ type: "text", value: "world" }]),
+ createInstance("6", "Span", [{ type: "text", value: "and" }]),
+ createInstance("7", "RichTextLink", [
+ { type: "text", value: "other realms" },
+ ]),
+ ]);
+});
diff --git a/apps/builder/app/canvas/features/text-editor/interop.ts b/apps/builder/app/canvas/features/text-editor/interop.ts
index a2aeb6a034..3a75171cf3 100644
--- a/apps/builder/app/canvas/features/text-editor/interop.ts
+++ b/apps/builder/app/canvas/features/text-editor/interop.ts
@@ -11,7 +11,12 @@ import {
$isLineBreakNode,
} from "lexical";
import { $createLinkNode, $isLinkNode } from "@lexical/link";
-import type { Instance, Text } from "@webstudio-is/project-build";
+import type {
+ Instance,
+ Instances,
+ InstancesItem,
+ InstancesList,
+} from "@webstudio-is/project-build";
import { utils } from "@webstudio-is/project";
import { $isSpanNode, $setNodeSpan } from "./toolbar-connector";
@@ -27,28 +32,33 @@ const lexicalFormats = [
const $writeUpdates = (
node: ElementNode,
- updates: Instance["children"],
+ instanceChildren: InstancesItem["children"],
+ instancesList: InstancesList,
refs: Refs
) => {
const children = node.getChildren();
for (const child of children) {
if ($isParagraphNode(child)) {
- $writeUpdates(child, updates, refs);
+ $writeUpdates(child, instanceChildren, instancesList, refs);
}
if ($isLineBreakNode(child)) {
- updates.push({ type: "text", value: "\n" });
+ instanceChildren.push({ type: "text", value: "\n" });
}
if ($isLinkNode(child)) {
const key = child.getKey();
const id = refs.get(key) ?? utils.tree.createInstanceId();
refs.set(key, id);
- const childrenUpdates: Instance["children"] = [];
- $writeUpdates(child, childrenUpdates, refs);
- updates.push({
+ instanceChildren.push({
+ type: "id",
+ value: id,
+ });
+ const childChildren: InstancesItem["children"] = [];
+ $writeUpdates(child, childChildren, instancesList, refs);
+ instancesList.push({
type: "instance",
id,
component: "RichTextLink",
- children: childrenUpdates,
+ children: childChildren,
});
}
if ($isTextNode(child)) {
@@ -56,20 +66,21 @@ const $writeUpdates = (
// considering lexical represents both as single node
// and add ref suffix to distinct styling on one node key
const text = child.getTextContent();
- let parentUpdates = updates;
+ let parentUpdates = instanceChildren;
if ($isSpanNode(child)) {
// prematurely generate span id to select it right after applying
const key = `${child.getKey()}:span`;
const id = refs.get(key) ?? utils.tree.createInstanceId();
refs.set(key, id);
- const update: Instance["children"][number] = {
+ const childInstance: InstancesItem = {
type: "instance",
id,
component: "Span",
children: [],
};
- parentUpdates.push(update);
- parentUpdates = update.children;
+ instancesList.push(childInstance);
+ parentUpdates.push({ type: "id", value: id });
+ parentUpdates = childInstance.children;
}
// convert all lexical formats
for (const [format, component] of lexicalFormats) {
@@ -77,14 +88,15 @@ const $writeUpdates = (
const key = `${child.getKey()}:${format}`;
const id = refs.get(key) ?? utils.tree.createInstanceId();
refs.set(key, id);
- const update: Instance["children"][number] = {
+ const childInstance: InstancesItem = {
type: "instance",
id,
component,
children: [],
};
- parentUpdates.push(update);
- parentUpdates = update.children;
+ instancesList.push(childInstance);
+ parentUpdates.push({ type: "id", value: id });
+ parentUpdates = childInstance.children;
}
}
parentUpdates.push({ type: "text", value: text });
@@ -92,18 +104,26 @@ const $writeUpdates = (
}
};
-export const $convertToUpdates = (refs: Refs) => {
- const updates: Instance["children"] = [];
+export const $convertToUpdates = (
+ treeRootInstance: InstancesItem,
+ refs: Refs
+) => {
+ const treeRootInstanceChildren: InstancesItem["children"] = [];
+ const instancesList: InstancesItem[] = [
+ {
+ ...treeRootInstance,
+ children: treeRootInstanceChildren,
+ },
+ ];
const root = $getRoot();
- $writeUpdates(root, updates, refs);
- return updates;
+ $writeUpdates(root, treeRootInstanceChildren, instancesList, refs);
+ return instancesList;
};
-type InstanceChild = Text | Instance;
-
const $writeLexical = (
parent: ElementNode | TextNode,
- children: InstanceChild[],
+ children: InstancesItem["children"],
+ instances: Instances,
refs: Refs
) => {
for (const child of children) {
@@ -123,14 +143,19 @@ const $writeLexical = (
continue;
}
+ const instance = instances.get(child.value);
+ if (instance === undefined) {
+ continue;
+ }
+
// convert instances
- if (child.component === "RichTextLink" && $isElementNode(parent)) {
+ if (instance.component === "RichTextLink" && $isElementNode(parent)) {
const linkNode = $createLinkNode("");
- refs.set(linkNode.getKey(), child.id);
+ refs.set(linkNode.getKey(), instance.id);
parent.append(linkNode);
- $writeLexical(linkNode, child.children, refs);
+ $writeLexical(linkNode, instance.children, instances, refs);
}
- if (child.component === "Span") {
+ if (instance.component === "Span") {
let textNode;
if ($isTextNode(parent)) {
textNode = parent;
@@ -139,12 +164,12 @@ const $writeLexical = (
parent.append(textNode);
}
$setNodeSpan(textNode);
- refs.set(`${textNode.getKey()}:span`, child.id);
- $writeLexical(textNode, child.children, refs);
+ refs.set(`${textNode.getKey()}:span`, instance.id);
+ $writeLexical(textNode, instance.children, instances, refs);
}
// convert all lexical formats
for (const [format, component] of lexicalFormats) {
- if (child.component === component) {
+ if (instance.component === component) {
let textNode;
if ($isTextNode(parent)) {
textNode = parent;
@@ -153,16 +178,23 @@ const $writeLexical = (
parent.append(textNode);
}
textNode.toggleFormat(format);
- refs.set(`${textNode.getKey()}:${format}`, child.id);
- $writeLexical(textNode, child.children, refs);
+ refs.set(`${textNode.getKey()}:${format}`, instance.id);
+ $writeLexical(textNode, instance.children, instances, refs);
}
}
}
};
-export const $convertToLexical = (instance: Instance, refs: Refs) => {
+export const $convertToLexical = (
+ instances: Instances,
+ rootInstanceId: Instance["id"],
+ refs: Refs
+) => {
const root = $getRoot();
const p = $createParagraphNode();
root.append(p);
- $writeLexical(p, instance.children, refs);
+ const rootInstance = instances.get(rootInstanceId);
+ if (rootInstance) {
+ $writeLexical(p, rootInstance.children, instances, refs);
+ }
};
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 b4365b248f..642c06b848 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
@@ -4,10 +4,14 @@ import type { ComponentStory, ComponentMeta } from "@storybook/react";
import { action } from "@storybook/addon-actions";
import { Box } from "@webstudio-is/design-system";
import { useSubscribe, publish } from "~/shared/pubsub";
-import { utils } from "@webstudio-is/project";
import type { TextToolbarState } from "~/builder/shared/nano-states";
import { TextEditor } from "./text-editor";
import { theme } from "@webstudio-is/design-system";
+import type {
+ Instance,
+ Instances,
+ InstancesItem,
+} from "@webstudio-is/project-build";
export default {
component: TextEditor,
@@ -23,6 +27,37 @@ type Format =
| "span"
| "clear";
+const createInstancePair = (
+ id: Instance["id"],
+ component: string,
+ children: InstancesItem["children"]
+): [Instance["id"], InstancesItem] => {
+ return [
+ id,
+ {
+ type: "instance",
+ id,
+ component,
+ children,
+ },
+ ];
+};
+
+const instances: Instances = new Map([
+ createInstancePair("1", "TextBlock", [
+ { type: "text", value: "Paragraph you can edit " },
+ { type: "id", value: "2" },
+ { type: "id", value: "3" },
+ { type: "id", value: "5" },
+ ]),
+ createInstancePair("2", "Bold", [{ type: "text", value: "very bold text " }]),
+ createInstancePair("3", "Bold", [{ type: "id", value: "4" }]),
+ createInstancePair("4", "Italic", [
+ { type: "text", value: "with small italic" },
+ ]),
+ createInstancePair("5", "Bold", [{ type: "text", value: " subtext" }]),
+]);
+
export const Basic: ComponentStory<typeof TextEditor> = ({ onChange }) => {
const [state, setState] = useState<null | TextToolbarState>(null);
useSubscribe("showTextToolbar", (event) => {
@@ -41,7 +76,10 @@ export const Basic: ComponentStory<typeof TextEditor> = ({ onChange }) => {
<button
disabled={state == null}
style={{ fontWeight: state?.isBold ? "bold" : "normal" }}
- onClick={() => setFormat("bold")}
+ onClick={(event) => {
+ event.preventDefault();
+ setFormat("bold");
+ }}
>
Bold
</button>
@@ -97,29 +135,8 @@ export const Basic: ComponentStory<typeof TextEditor> = ({ onChange }) => {
}}
>
<TextEditor
- instance={utils.tree.createInstance({
- component: "TextBlock",
- children: [
- { type: "text", value: "Paragraph you can edit " },
- utils.tree.createInstance({
- component: "Bold",
- children: [{ type: "text", value: "very bold text " }],
- }),
- utils.tree.createInstance({
- component: "Bold",
- children: [
- utils.tree.createInstance({
- component: "Italic",
- children: [{ type: "text", value: "with small italic" }],
- }),
- ],
- }),
- utils.tree.createInstance({
- component: "Bold",
- children: [{ type: "text", value: " subtext" }],
- }),
- ],
- })}
+ rootInstanceId={"1"}
+ instances={instances}
contentEditable={<ContentEditable />}
onChange={onChange}
onSelectInstance={(instanceId) =>
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 58c27bb2c6..6c066588e5 100644
--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx
+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx
@@ -19,7 +19,11 @@ import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";
import { LinkPlugin } from "@lexical/react/LexicalLinkPlugin";
import { nanoid } from "nanoid";
import { createCssEngine } from "@webstudio-is/css-engine";
-import type { Instance } from "@webstudio-is/project-build";
+import type {
+ Instance,
+ Instances,
+ InstancesList,
+} from "@webstudio-is/project-build";
import { idAttribute } from "@webstudio-is/react-sdk";
import { ToolbarConnectorPlugin } from "./toolbar-connector";
import { type Refs, $convertToLexical, $convertToUpdates } from "./interop";
@@ -113,14 +117,16 @@ const onError = (error: Error) => {
};
type TextEditorProps = {
- instance: Instance;
+ rootInstanceId: Instance["id"];
+ instances: Instances;
contentEditable: JSX.Element;
- onChange: (updates: Instance["children"]) => void;
+ onChange: (instancesList: InstancesList) => void;
onSelectInstance: (instanceId: string) => void;
};
export const TextEditor = ({
- instance,
+ rootInstanceId,
+ instances,
contentEditable,
onChange,
onSelectInstance,
@@ -160,7 +166,7 @@ export const TextEditor = ({
// text editor is unmounted when change properties in side panel
// so assume new nodes don't need to preserve instance id
// and store only initial references
- $convertToLexical(instance, refs);
+ $convertToLexical(instances, rootInstanceId, refs);
},
nodes: [LinkNode],
onError,
@@ -190,7 +196,10 @@ export const TextEditor = ({
ignoreSelectionChange={true}
onChange={(editorState) => {
editorState.read(() => {
- onChange($convertToUpdates(refs));
+ const treeRootInstance = instances.get(rootInstanceId);
+ if (treeRootInstance) {
+ onChange($convertToUpdates(treeRootInstance, refs));
+ }
});
}}
/>
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 4242ac6536..3ed24148ed 100644
--- a/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
+++ b/apps/builder/app/canvas/features/webstudio-component/webstudio-component.tsx
@@ -12,16 +12,14 @@ import {
import type { GetComponent } from "@webstudio-is/react-sdk";
import {
instancesStore,
- patchInstancesMutable,
- rootInstanceContainer,
selectedInstanceIdStore,
useInstanceProps,
useInstanceStyles,
useTextEditingInstanceId,
} from "~/shared/nano-states";
-import { createInstancesIndex } from "~/shared/tree-utils";
import { useCssRules } from "~/canvas/shared/styles";
import { SelectedInstanceConnector } from "./selected-instance-connector";
+import { findTreeInstances } from "~/shared/tree-utils";
const TextEditor = lazy(() => import("../text-editor"));
@@ -63,6 +61,7 @@ export const WebstudioComponentDev = ({
const instanceElementRef = useRef<HTMLElement>();
const instanceStyles = useInstanceStyles(instanceId);
useCssRules({ instanceId: instance.id, instanceStyles });
+ const instances = useStore(instancesStore);
const [editingInstanceId, setTextEditingInstanceId] =
useTextEditingInstanceId();
@@ -148,7 +147,8 @@ export const WebstudioComponentDev = ({
return (
<Suspense fallback={instanceElement}>
<TextEditor
- instance={instance}
+ rootInstanceId={instance.id}
+ instances={instances}
contentEditable={
<ContentEditable
{...props}
@@ -156,15 +156,17 @@ export const WebstudioComponentDev = ({
Component={Component}
/>
}
- onChange={(updates) => {
- const rootInstance = rootInstanceContainer.get();
+ onChange={(instancesList) => {
store.createTransaction([instancesStore], (instances) => {
- const { instancesById } = createInstancesIndex(rootInstance);
- const instance = instancesById.get(instanceId);
- if (instance) {
- instance.children = updates;
+ const deletedTreeIds = findTreeInstances(instances, instance.id);
+ for (const updatedInstance of instancesList) {
+ instances.set(updatedInstance.id, updatedInstance);
+ // exclude reused instances
+ deletedTreeIds.delete(updatedInstance.id);
+ }
+ for (const instanceId of deletedTreeIds) {
+ instances.delete(instanceId);
}
- patchInstancesMutable(rootInstance, instances);
});
}}
onSelectInstance={(instanceId) => {
diff --git a/apps/builder/jest.config.js b/apps/builder/jest.config.js
index 13aaab2931..80f6b1d293 100644
--- a/apps/builder/jest.config.js
+++ b/apps/builder/jest.config.js
@@ -7,5 +7,14 @@ const baseConfig = require("@webstudio-is/jest-config");
module.exports = {
...baseConfig,
testMatch: ["<rootDir>/app/**/*.test.ts"],
- moduleNameMapper: { "^~/(.*)$": "<rootDir>/app/$1" },
+ moduleNameMapper: {
+ "^~/(.*)$": "<rootDir>/app/$1",
+ "^lexical$": "lexical/Lexical.dev.js",
+ "^@lexical/headless$": "@lexical/headless/LexicalHeadless.dev.js",
+ "^@lexical/utils$": "@lexical/utils/LexicalUtils.dev.js",
+ "^@lexical/selection$": "@lexical/selection/LexicalSelection.dev.js",
+ "^@lexical/link$": "@lexical/link/LexicalLink.dev.js",
+ "^@lexical/react/LexicalComposerContext$":
+ "@lexical/react/LexicalComposerContext.dev.js",
+ },
};
diff --git a/apps/builder/package.json b/apps/builder/package.json
index 4eb44ecdf3..f7733d1e60 100644
--- a/apps/builder/package.json
+++ b/apps/builder/package.json
@@ -22,6 +22,7 @@
"@fontsource/inter": "^4.5.15",
"@fontsource/manrope": "^4.5.13",
"@fontsource/roboto-mono": "^4.5.10",
+ "@lexical/headless": "^0.6.0",
"@lexical/link": "^0.6.0",
"@lexical/react": "^0.6.0",
"@lexical/selection": "^0.6.0",
diff --git a/packages/asset-uploader/package.json b/packages/asset-uploader/package.json
index e8873a7614..b9a555c851 100644
--- a/packages/asset-uploader/package.json
+++ b/packages/asset-uploader/package.json
@@ -37,7 +37,10 @@
"zod": "^3.19.1"
},
"exports": {
- ".": "./lib/index.js",
+ ".": {
+ "import": "./lib/index.js",
+ "require": "./lib/cjs/index.cjs"
+ },
"./server": "./server.js"
},
"types": "src/index.ts",
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index d440946ec5..925e8b9bdb 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -65,6 +65,9 @@ importers:
'@fontsource/roboto-mono':
specifier: ^4.5.10
version: 4.5.10
+ '@lexical/headless':
+ specifier: ^0.6.0
+ version: 0.6.0([email protected])
'@lexical/link':
specifier: ^0.6.0
version: 0.6.0([email protected])
@@ -5715,6 +5718,14 @@ packages:
lexical: 0.6.0
dev: false
+ resolution: {integrity: sha512-d8JH0voJ9R771Rk+pRrzyDpHEvyDY0HYnGz6k8AHib1Dqq0u8UVfQzmDi3rwGrFmAZaxBNYnOh9DHdc9AAtYow==}
+ peerDependencies:
+ lexical: 0.6.0
+ dependencies:
+ lexical: 0.6.0
+ dev: false
+
resolution: {integrity: sha512-I8b3/t4ab7swvclcN1JJbeD8IAEc6baEkl3XSmXAQfFUaiGvP0+FqhTOQM66o7EeJhcgAlw96HRnZoEVFhsgew==}
peerDependencies: