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
feat: Support new link selection in the text editor (#4509)
Ivan Starkov9cf443a3c57a
diff --git a/apps/builder/app/canvas/features/text-editor/interop.test.ts b/apps/builder/app/canvas/features/text-editor/interop.test.tsindex 787a5bcb4d..d1f87c3773 100644--- a/apps/builder/app/canvas/features/text-editor/interop.test.ts+++ b/apps/builder/app/canvas/features/text-editor/interop.test.ts@@ -184,7 +184,7 @@ test("convert lexical to instances updates", async () => {}const updates = editor.getEditorState().read(() => {- return $convertToUpdates(treeRootInstance, refs);+ return $convertToUpdates(treeRootInstance, refs, new Map());});expect(updates).toEqual([diff --git a/apps/builder/app/canvas/features/text-editor/interop.ts b/apps/builder/app/canvas/features/text-editor/interop.tsindex 39cd4cc841..1127cecb32 100644--- a/apps/builder/app/canvas/features/text-editor/interop.ts+++ b/apps/builder/app/canvas/features/text-editor/interop.ts@@ -29,26 +29,39 @@ const $writeUpdates = (node: ElementNode,instanceChildren: Instance["children"],instancesList: Instance[],- refs: Refs+ refs: Refs,+ newLinkKeyToInstanceId: Refs) => {const children = node.getChildren();for (const child of children) {if ($isParagraphNode(child)) {- $writeUpdates(child, instanceChildren, instancesList, refs);+ $writeUpdates(+ child,+ instanceChildren,+ instancesList,+ refs,+ newLinkKeyToInstanceId+ );}if ($isLineBreakNode(child)) {instanceChildren.push({ type: "text", value: "\n" });}if ($isLinkNode(child)) {const key = child.getKey();- const id = refs.get(key) ?? nanoid();+ const id = refs.get(key) ?? newLinkKeyToInstanceId.get(key) ?? nanoid();refs.set(key, id);instanceChildren.push({type: "id",value: id,});const childChildren: Instance["children"] = [];- $writeUpdates(child, childChildren, instancesList, refs);+ $writeUpdates(+ child,+ childChildren,+ instancesList,+ refs,+ newLinkKeyToInstanceId+ );instancesList.push({type: "instance",id,@@ -99,7 +112,11 @@ const $writeUpdates = (}};-export const $convertToUpdates = (treeRootInstance: Instance, refs: Refs) => {+export const $convertToUpdates = (+ treeRootInstance: Instance,+ refs: Refs,+ newLinkKeyToInstanceId: Refs+) => {const treeRootInstanceChildren: Instance["children"] = [];const instancesList: Instance[] = [{@@ -108,7 +125,13 @@ export const $convertToUpdates = (treeRootInstance: Instance, refs: Refs) => {},];const root = $getRoot();- $writeUpdates(root, treeRootInstanceChildren, instancesList, refs);+ $writeUpdates(+ root,+ treeRootInstanceChildren,+ instancesList,+ refs,+ newLinkKeyToInstanceId+ );return instancesList;};diff --git a/apps/builder/app/canvas/features/text-editor/text-editor.tsx b/apps/builder/app/canvas/features/text-editor/text-editor.tsxindex 95290093fd..7ce5460455 100644--- a/apps/builder/app/canvas/features/text-editor/text-editor.tsx+++ b/apps/builder/app/canvas/features/text-editor/text-editor.tsx@@ -35,6 +35,7 @@ import {$createTextNode,KEY_DOWN_COMMAND,COMMAND_PRIORITY_NORMAL,+ type NodeKey,} from "lexical";import { LinkNode } from "@lexical/link";import { LexicalComposer } from "@lexical/react/LexicalComposer";@@ -43,6 +44,7 @@ import { RichTextPlugin } from "@lexical/react/LexicalRichTextPlugin";import { LexicalErrorBoundary } from "@lexical/react/LexicalErrorBoundary";import { HistoryPlugin } from "@lexical/react/LexicalHistoryPlugin";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";@@ -71,7 +73,11 @@ import {} from "~/shared/dom-utils";import deepEqual from "fast-deep-equal";import { setDataCollapsed } from "~/canvas/collapsed";-import { $selectedPage, selectInstance } from "~/shared/awareness";+import {+ $selectedPage,+ addTemporaryInstance,+ selectInstance,+} from "~/shared/awareness";import { shallowEqual } from "shallow-equal";const BindInstanceToNodePlugin = ({@@ -176,7 +182,21 @@ const OnChangeOnBlurPlugin = ({return null;};-const LinkSelectionPlugin = () => {+const getNodeKeyFromDOMNode = (+ dom: Node,+ editor: LexicalEditor+): NodeKey | undefined => {+ const prop = `__lexicalKey_${editor._key}`;+ return (dom as Node & Record<typeof prop, NodeKey | undefined>)[prop];+};++const LinkSelectionPlugin = ({+ rootInstanceSelector,+ registerNewLink,+}: {+ rootInstanceSelector: InstanceSelector;+ registerNewLink: (key: NodeKey, instanceId: string) => void;+}) => {const [editor] = useLexicalComposerContext();const [preservedSelection] = useState($selectedInstanceSelector.get());@@ -189,14 +209,43 @@ const LinkSelectionPlugin = () => {({ editorState }) => {editorState.read(() => {const selection = $getSelection();- // console.log(selection);if (!$isRangeSelection(selection)) {return false;}const key = selection.anchor.getNode().getKey();const elt = editor.getElementByKey(key);- const link = elt?.closest(`a[${selectorIdAttribute}]`);+ let link = elt?.closest(`a[${selectorIdAttribute}]`);+ const newLink = elt?.closest(`a`);++ while (newLink != null && link == null) {+ // new link detected++ // https://github.com/facebook/lexical/blob/b7fa4cf673869dac0c2e0c1fe667e71e72ff6adb/packages/lexical/src/LexicalUtils.ts#L465+ const key = getNodeKeyFromDOMNode(newLink, editor);+ if (key === undefined) {+ console.error("Key not found for node", newLink);+ break;+ }++ // Register new link+ const instanceId = nanoid();++ newLink.setAttribute(idAttribute, instanceId);+ // We set id + root selector here, for simplicity+ // This solves hover behavior during mouseMove for editable child outline+ // @todo: A normal selector must be used, but it would require significantly more code to detect the tree structure.+ newLink.setAttribute(+ selectorIdAttribute,+ [instanceId, ...rootInstanceSelector].join(",")+ );++ registerNewLink(key, instanceId);++ link = newLink;++ break;+ }if (link == null) {if (@@ -232,7 +281,7 @@ const LinkSelectionPlugin = () => {return () => {removeUpdateListener();};- }, [editor, preservedSelection]);+ }, [editor, preservedSelection, registerNewLink, rootInstanceSelector]);return null;};@@ -950,6 +999,7 @@ export const TextEditor = ({const [paragraphClassName] = useState(() => `a${nanoid()}`);const [italicClassName] = useState(() => `a${nanoid()}`);const lastSavedStateJsonRef = useRef<SerializedEditorState | null>(null);+ const [newLinkKeyToInstanceId] = useState(() => new Map());const handleChange = useEffectEvent((editorState: EditorState) => {editorState.read(() => {@@ -961,7 +1011,10 @@ export const TextEditor = ({return;}- onChange($convertToUpdates(treeRootInstance, refs));+ onChange(+ $convertToUpdates(treeRootInstance, refs, newLinkKeyToInstanceId)+ );+ newLinkKeyToInstanceId.clear();lastSavedStateJsonRef.current = jsonState;}@@ -1113,6 +1166,19 @@ export const TextEditor = ({$hoveredInstanceSelector.set(undefined);}, []);+ const registerNewLink = useCallback(+ (key: NodeKey, instanceId: string) => {+ newLinkKeyToInstanceId.set(key, instanceId);+ addTemporaryInstance({+ id: instanceId,+ component: "RichTextLink",+ type: "instance",+ children: [],+ });+ },+ [newLinkKeyToInstanceId]+ );+return (<LexicalComposer initialConfig={initialConfig}><RemoveParagaphsPlugin />@@ -1142,7 +1208,10 @@ export const TextEditor = ({<SwitchBlockPlugin onNext={handleNext} /><OnChangeOnBlurPlugin onChange={handleChange} /><InitCursorPlugin />- <LinkSelectionPlugin />+ <LinkSelectionPlugin+ rootInstanceSelector={rootInstanceSelector}+ registerNewLink={registerNewLink}+ /><AnyKeyDownPlugin onKeyDown={handleAnyKeydown} /><InitialJSONStatePluginonInitialState={(json) => {diff --git a/apps/builder/app/shared/awareness.ts b/apps/builder/app/shared/awareness.tsindex 96e377a196..4eaacd80b7 100644--- a/apps/builder/app/shared/awareness.ts+++ b/apps/builder/app/shared/awareness.ts@@ -31,6 +31,12 @@ export const $selectedPage = computed(});+export const $temporaryInstances = atom<Instances>(new Map());+export const addTemporaryInstance = (instance: Instance) => {+ $temporaryInstances.get().set(instance.id, instance);+ $temporaryInstances.set($temporaryInstances.get());+};+export const $virtualInstances = computed($selectedPage, (selectedPage) => {const virtualInstances: Instances = new Map();if (selectedPage) {@@ -45,15 +51,16 @@ export const $virtualInstances = computed($selectedPage, (selectedPage) => {});export const $selectedInstance = computed(- [$instances, $virtualInstances, $awareness],- (instances, virtualInstances, awareness) => {+ [$instances, $virtualInstances, $temporaryInstances, $awareness],+ (instances, virtualInstances, tempInstances, awareness) => {if (awareness?.instanceSelector === undefined) {return;}const [selectedInstanceId] = awareness.instanceSelector;return (instances.get(selectedInstanceId) ??- virtualInstances.get(selectedInstanceId)+ virtualInstances.get(selectedInstanceId) ??+ tempInstances.get(selectedInstanceId));});diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex 0715c6ed3e..19065c8ed9 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -48,7 +48,7 @@ import {$modifierKeys,} from "~/shared/nano-states";import { $ephemeralStyles } from "~/canvas/stores";-import { $awareness } from "../awareness";+import { $awareness, $temporaryInstances } from "../awareness";import {ImmerhinSyncObject,NanostoresSyncObject,@@ -88,6 +88,8 @@ export const createObjectPool = () => {$selectedInstanceSelector),new NanostoresSyncObject("awareness", $awareness),+ new NanostoresSyncObject("temporaryInstances", $temporaryInstances),+new NanostoresSyncObject("project", $project),new NanostoresSyncObject("dataSourceVariables", $dataSourceVariables),new NanostoresSyncObject("resourceValues", $resourceValues),