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
Reimplement text editor (#412)
Bogdan Chadkin0c3993dce5fd
diff --git a/apps/designer/app/canvas/features/text-editor/index.ts b/apps/designer/app/canvas/features/text-editor/index.tsnew file mode 100644index 0000000000..f01ea7c6e6--- /dev/null+++ b/apps/designer/app/canvas/features/text-editor/index.ts@@ -0,0 +1,3 @@+export { TextEditor } from "./text-editor";+// React.lazy requires default export+export { TextEditor as default } from "./text-editor";diff --git a/apps/designer/app/canvas/features/text-editor/interop.ts b/apps/designer/app/canvas/features/text-editor/interop.tsnew file mode 100644index 0000000000..52a9467cac--- /dev/null+++ b/apps/designer/app/canvas/features/text-editor/interop.ts@@ -0,0 +1,100 @@+import {+ type ElementNode,+ $getRoot,+ $createTextNode,+ $createParagraphNode,+ TextNode,+ LineBreakNode,+ ParagraphNode,+} from "lexical";+import { $createLinkNode, LinkNode } from "@lexical/link";+import type { ChildrenUpdates, Instance } from "@webstudio-is/react-sdk";+import { createInstanceId } from "~/shared/tree-utils";++// Map<nodeKey, Instance>+export type Refs = Map<string, Instance>;++const $writeUpdates = (+ node: ElementNode,+ updates: ChildrenUpdates,+ refs: Refs+) => {+ const children = node.getChildren();+ for (const child of children) {+ if (child instanceof ParagraphNode) {+ if (updates.length !== 0) {+ updates.push("\n");+ }+ $writeUpdates(child, updates, refs);+ }+ if (child instanceof LineBreakNode) {+ if (updates.length !== 0) {+ // @todo should we visually distinct line breaks and paragraphs?+ updates.push("\n");+ }+ }+ if (child instanceof LinkNode) {+ // @todo support link children styling+ const text = child.getTextContent();+ const id = refs.get(child.getKey())?.id ?? createInstanceId();+ updates.push({ id, component: "Link", text });+ }+ if (child instanceof TextNode) {+ // @todo support nesting bold into italic and vice versa+ const text = child.getTextContent();+ if (child.hasFormat("bold")) {+ const id = refs.get(child.getKey())?.id ?? createInstanceId();+ updates.push({ id, component: "Bold", text });+ } else if (child.hasFormat("italic")) {+ const id = refs.get(child.getKey())?.id ?? createInstanceId();+ updates.push({ id, component: "Italic", text });+ } else {+ updates.push(text);+ }+ }+ }+};++export const $convertToUpdates = (refs: Refs) => {+ const updates: ChildrenUpdates = [];+ const root = $getRoot();+ $writeUpdates(root, updates, refs);+ return updates;+};++export const $convertToLexical = (instance: Instance, refs: Refs) => {+ const root = $getRoot();+ let p = $createParagraphNode();+ root.append(p);+ for (const child of instance.children) {+ if (child === "\n") {+ p = $createParagraphNode();+ root.append(p);+ } else if (typeof child === "string") {+ const textNode = $createTextNode(child);+ p.append(textNode);+ } else {+ // inline components should always have a single child string+ const text =+ typeof child.children[0] === "string" ? child.children[0] : "";+ if (child.component === "Bold") {+ const textNode = $createTextNode(text);+ textNode.setFormat("bold");+ refs.set(textNode.getKey(), child);+ p.append(textNode);+ }+ if (child.component === "Italic") {+ const textNode = $createTextNode(text);+ textNode.setFormat("italic");+ refs.set(textNode.getKey(), child);+ p.append(textNode);+ }+ if (child.component === "Link") {+ const textNode = $createTextNode(text);+ const linkNode = $createLinkNode(text).append(textNode);+ refs.set(linkNode.getKey(), child);+ p.append(linkNode);+ }+ }+ }+};diff --git a/apps/designer/app/canvas/features/text-editor/text-editor.stories.tsx b/apps/designer/app/canvas/features/text-editor/text-editor.stories.tsxnew file mode 100644index 0000000000..28144ab987--- /dev/null+++ b/apps/designer/app/canvas/features/text-editor/text-editor.stories.tsx@@ -0,0 +1,82 @@+import { useState } from "react";+import { ContentEditable } from "@lexical/react/LexicalContentEditable";+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 { createInstance } from "~/shared/tree-utils";+import { TextEditor } from "./text-editor";++export default {+ component: TextEditor,+ title: "Text Editor 2",+} as ComponentMeta<typeof TextEditor>;++export const Basic: ComponentStory<typeof TextEditor> = ({ onChange }) => {+ const [isEnabled, setIsEnabled] = useState(false);+ const [isBold, setIsBold] = useState(false);+ const [isItalic, setIsItalic] = useState(false);+ const [isLink, setIsLink] = useState(false);+ useSubscribe("showTextToolbar", (event) => {+ setIsEnabled(true);+ setIsBold(event.isBold);+ setIsItalic(event.isItalic);+ setIsLink(event.isLink);+ });+ useSubscribe("hideTextToolbar", () => {+ setIsEnabled(false);+ });++ return (+ <div>+ <button+ disabled={isEnabled === false}+ style={{ fontWeight: isBold ? "bold" : "normal" }}+ onClick={() => publish({ type: "formatTextToolbar", payload: "bold" })}+ >+ Bold+ </button>+ <button+ disabled={isEnabled === false}+ style={{ fontWeight: isItalic ? "bold" : "normal" }}+ onClick={() =>+ publish({ type: "formatTextToolbar", payload: "italic" })+ }+ >+ Italic+ </button>+ <button+ disabled={isEnabled === false}+ style={{ fontWeight: isLink ? "bold" : "normal" }}+ onClick={() => publish({ type: "formatTextToolbar", payload: "link" })}+ >+ Link+ </button>+ <Box+ css={{+ "& > div": {+ padding: "0 8px",+ border: "1px solid #999",+ color: "black",+ },+ }}+ >+ <TextEditor+ instance={createInstance({+ component: "TextBlock",+ children: [+ "Pragraph you can edit ",+ createInstance({ component: "Bold", children: ["bold"] }),+ ],+ })}+ contentEditable={<ContentEditable />}+ onChange={onChange}+ />+ </Box>+ </div>+ );+};++Basic.args = {+ onChange: action("onChange"),+};diff --git a/apps/designer/app/canvas/features/text-editor/text-editor.tsx b/apps/designer/app/canvas/features/text-editor/text-editor.tsxnew file mode 100644index 0000000000..338fa7f5be--- /dev/null+++ b/apps/designer/app/canvas/features/text-editor/text-editor.tsx@@ -0,0 +1,106 @@+import { useEffect, useState } from "react";+import type { LexicalEditor } from "lexical";+import { LinkNode } from "@lexical/link";+import { LexicalComposer } from "@lexical/react/LexicalComposer";+import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";+import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";+import LexicalErrorBoundary from "@lexical/react/LexicalErrorBoundary";+import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";+import { OnChangePlugin } from "@lexical/react/LexicalOnChangePlugin";+import { LinkPlugin } from "@lexical/react/LexicalLinkPlugin";+import type { ChildrenUpdates, Instance } from "@webstudio-is/react-sdk";+import { toCss, css } from "@webstudio-is/react-sdk";+import { useBreakpoints } from "~/shared/nano-states";+import { ToolbarConnectorPlugin } from "./toolbar-connector";+import { type Refs, $convertToLexical, $convertToUpdates } from "./interop";++const NodeConnector = ({+ editor,+ nodeKey,+ instance,+}: {+ editor: LexicalEditor;+ nodeKey: string;+ instance: Instance;+}) => {+ const [breakpoints] = useBreakpoints();+ useEffect(() => {+ const element = editor.getElementByKey(nodeKey);+ if (element) {+ const className = css(toCss(instance.cssRules, breakpoints))().toString();+ // assume only styles are important while editing text+ element.className = className;+ }+ }, [editor, nodeKey, instance, breakpoints]);+ return null;+};++const NodesConnectorPlugin = ({ refs }: { refs: Refs }) => {+ const [editor] = useLexicalComposerContext();+ return (+ <>+ {Array.from(refs).map(([nodeKey, instance]) => (+ <NodeConnector+ key={nodeKey}+ editor={editor}+ nodeKey={nodeKey}+ instance={instance}+ />+ ))}+ </>+ );+};++const onError = (error: Error) => {+ throw error;+};++type TextEditorProps = {+ instance: Instance;+ contentEditable: JSX.Element;+ onChange: (updates: ChildrenUpdates) => void;+};++export const TextEditor = ({+ instance,+ contentEditable,+ onChange,+}: TextEditorProps) => {+ // store references separately because lexical nodes+ // cannot store custom data+ // Map<nodeKey, Instance>+ const [refs] = useState<Refs>(() => new Map());+ const initialConfig = {+ namespace: "WsTextEditor",+ editorState: () => {+ // 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);+ },+ nodes: [LinkNode],+ onError,+ };++ return (+ <LexicalComposer initialConfig={initialConfig}>+ <ToolbarConnectorPlugin />+ <NodesConnectorPlugin refs={refs} />+ <RichTextPlugin+ ErrorBoundary={LexicalErrorBoundary}+ contentEditable={contentEditable}+ placeholder=""+ />+ <LinkPlugin />+ <HistoryPlugin />+ <OnChangePlugin+ ignoreSelectionChange={true}+ onChange={(editorState) => {+ editorState.read(() => {+ onChange($convertToUpdates(refs));+ });+ }}+ />+ </LexicalComposer>+ );+};diff --git a/apps/designer/app/canvas/features/text-editor/toolbar-connector.tsx b/apps/designer/app/canvas/features/text-editor/toolbar-connector.tsxnew file mode 100644index 0000000000..41c4cf6cf5--- /dev/null+++ b/apps/designer/app/canvas/features/text-editor/toolbar-connector.tsx@@ -0,0 +1,113 @@+import { useCallback, useEffect } from "react";+import {+ type RangeSelection,+ $getSelection,+ $isRangeSelection,+ FORMAT_TEXT_COMMAND,+ SELECTION_CHANGE_COMMAND,+ COMMAND_PRIORITY_LOW,+} from "lexical";+import { $isLinkNode, TOGGLE_LINK_COMMAND } from "@lexical/link";+import { $isAtNodeEnd } from "@lexical/selection";+import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";+import { useSubscribe, publish } from "~/shared/pubsub";++const getSelectedNode = (selection: RangeSelection) => {+ const anchor = selection.anchor;+ const focus = selection.focus;+ const anchorNode = anchor.getNode();+ const focusNode = focus.getNode();+ if (anchorNode === focusNode) {+ return anchorNode;+ }+ const isBackward = selection.isBackward();+ if (isBackward) {+ return $isAtNodeEnd(focus) ? anchorNode : focusNode;+ } else {+ return $isAtNodeEnd(anchor) ? focusNode : anchorNode;+ }+};++const isSelectedLink = (selection: RangeSelection) => {+ const node = getSelectedNode(selection);+ const parent = node.getParent();+ return $isLinkNode(parent) || $isLinkNode(node);+};++export const ToolbarConnectorPlugin = () => {+ const [editor] = useLexicalComposerContext();++ // control toolbar state on data or selection updates+ const updateToolbar = useCallback(() => {+ const selection = $getSelection();+ const nativeSelection = window.getSelection();+ if (+ $isRangeSelection(selection) &&+ selection.getTextContent().length !== 0 &&+ nativeSelection != null+ ) {+ const domRange = nativeSelection.getRangeAt(0);+ const selectionRect = domRange.getBoundingClientRect();+ const isBold = selection.hasFormat("bold");+ const isItalic = selection.hasFormat("italic");+ const isLink = isSelectedLink(selection);+ publish({+ type: "showTextToolbar",+ payload: { selectionRect, isBold, isItalic, isLink },+ });+ } else {+ publish({ type: "hideTextToolbar" });+ }+ }, []);++ useEffect(() => {+ // hide toolbar when editor is unmounted+ return () => {+ publish({ type: "hideTextToolbar" });+ };+ }, []);++ useEffect(() => {+ return editor.registerCommand(+ SELECTION_CHANGE_COMMAND,+ () => {+ updateToolbar();+ return false;+ },+ COMMAND_PRIORITY_LOW+ );+ }, [editor, updateToolbar]);++ useEffect(() => {+ return editor.registerUpdateListener(({ editorState }) => {+ editorState.read(() => {+ updateToolbar();+ });+ });+ }, [editor, updateToolbar]);++ // dispatch commands sent from toolbar+ useSubscribe("formatTextToolbar", (type) => {+ if (type === "bold") {+ editor.dispatchCommand(FORMAT_TEXT_COMMAND, "bold");+ }+ if (type === "italic") {+ editor.dispatchCommand(FORMAT_TEXT_COMMAND, "italic");+ }+ if (type === "link") {+ const editorState = editor.getEditorState();+ let isLink = false;+ editorState.read(() => {+ const selection = $getSelection();+ isLink = $isRangeSelection(selection) && isSelectedLink(selection);+ });+ if (isLink) {+ editor.dispatchCommand(TOGGLE_LINK_COMMAND, null);+ } else {+ editor.dispatchCommand(TOGGLE_LINK_COMMAND, "https://");+ }+ }+ });++ return null;+};diff --git a/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx b/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsxindex 3cece599d3..d79d96c4a7 100644--- a/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx+++ b/apps/designer/app/canvas/features/wrapper-component/wrapper-component.tsx@@ -1,4 +1,6 @@-import { useCallback, MouseEvent, FormEvent, useMemo } from "react";+import { MouseEvent, FormEvent } from "react";+import { Suspense, lazy, useCallback, useMemo } from "react";+import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext";import {type Instance,type CSS,@@ -10,10 +12,33 @@ import {} from "@webstudio-is/react-sdk";import { useBreakpoints, useTextEditingInstanceId } from "~/shared/nano-states";import { useCss } from "./use-css";-import { Editor } from "./text-editor";import noop from "lodash.noop";import { useSelectedElement } from "~/canvas/shared/nano-states";+const TextEditor = lazy(() => import("../text-editor"));++const ContentEditable = ({+ Component,+ elementRef,+ ...props+}: {+ // eslint-disable-next-line+ Component: any;+ elementRef: (element: null | HTMLElement) => void;+}) => {+ const [editor] = useLexicalComposerContext();++ const ref = useCallback(+ (rootElement: null | HTMLElement) => {+ editor.setRootElement(rootElement);+ elementRef(rootElement);+ },+ [editor, elementRef]+ );++ return <Component ref={ref} {...props} contentEditable={true} />;+};+type WrapperComponentDevProps = {instance: Instance;css: CSS;@@ -59,7 +84,6 @@ export const WrapperComponentDev = ({id: instance.id,"data-component": instance.component,"data-id": instance.id,- ref: refCallback,onClick: (event: MouseEvent) => {if (instance.component === "Link") {event.preventDefault();@@ -80,23 +104,21 @@ export const WrapperComponentDev = ({}return (- <Editor- instance={instance}- fallback={instanceElement}- renderInstance={({ ref, ...renderProps }) => (- <Component- {...props}- {...renderProps}- ref={(element: HTMLElement | null) => {- props.ref(element);- ref(element);- }}- />- )}- onChange={(updates) => {- onChangeChildren({ instanceId: instance.id, updates });- }}- />+ <Suspense fallback={instanceElement}>+ <TextEditor+ instance={instance}+ contentEditable={+ <ContentEditable+ {...props}+ elementRef={refCallback}+ Component={Component}+ />+ }+ onChange={(updates) => {+ onChangeChildren({ instanceId: instance.id, updates });+ }}+ />+ </Suspense>);};diff --git a/apps/designer/app/shared/tree-utils/create-instance.ts b/apps/designer/app/shared/tree-utils/create-instance.tsindex 00a88e0053..7f02eaff37 100644--- a/apps/designer/app/shared/tree-utils/create-instance.ts+++ b/apps/designer/app/shared/tree-utils/create-instance.ts@@ -5,6 +5,10 @@ import {components,} from "@webstudio-is/react-sdk";+export const createInstanceId = () => {+ return ObjectId().toString();+};+export const createInstance = ({component,id,@@ -19,7 +23,7 @@ export const createInstance = ({const componentMeta = components[component];return {component,- id: id === undefined ? ObjectId().toString() : id,+ id: id === undefined ? createInstanceId() : id,cssRules: cssRules ?? [],children: children === undefined ? componentMeta.children ?? [] : children,};