Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(RichTextEditorToolbar): Insert link with nothing selected inserts the link at the caret (#9668)

Cindy Zhang1c7150d7863e
diff --git a/.changeset/richtext-link-at-caret.md b/.changeset/richtext-link-at-caret.md
new file mode 100644
index 0000000000..540dc40eb4
--- /dev/null
+++ b/.changeset/richtext-link-at-caret.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/richtext': patch
+---
+
+[fix] RichTextEditorToolbar: Insert link with nothing selected did not insert a link at the caret. In an empty paragraph nothing was inserted, and with the caret inside text the whole text around it was linked, while the dialog closed as if it had worked. Now, with the caret outside a link, Insert link inserts the entered URL as link text at the caret; with a non-empty selection it links the selected text, and with the caret inside a link it updates that link, as before.
+
+@cixzhang
diff --git a/packages/richtext/src/RichTextEditor.test.tsx b/packages/richtext/src/RichTextEditor.test.tsx
index a7b512f40b..d1fe8e7a8e 100644
--- a/packages/richtext/src/RichTextEditor.test.tsx
+++ b/packages/richtext/src/RichTextEditor.test.tsx
@@ -13,6 +13,7 @@
* SYNC: When the editor components change, update these tests to match.
*/
+import {$createLinkNode} from '@lexical/link';
import {describe, it, expect, vi, beforeAll, afterAll} from 'vitest';
import {
render,
@@ -1760,6 +1761,178 @@ describe('RichTextEditorToolbar — links', () => {
});
});
+ describe('with a collapsed selection', () => {
+ /** The paragraph's children as `text` or `link:<href>:<text>`. */
+ function paragraphParts(editor: LexicalEditor): string[] {
+ const parts: string[] = [];
+ editor.getEditorState().read(() => {
+ const paragraph = $getRoot().getFirstChild();
+ if (!$isElementNode(paragraph)) {
+ return;
+ }
+ for (const child of paragraph.getChildren()) {
+ parts.push(
+ 'getURL' in child
+ ? `link:${(child as {getURL(): string}).getURL()}:${child.getTextContent()}`
+ : child.getTextContent(),
+ );
+ }
+ });
+ return parts;
+ }
+
+ async function renderWithPrompt() {
+ let editor!: LexicalEditor;
+ render(
+ <RichTextEditor
+ label="Notes"
+ toolbar={<RichTextEditorToolbar promptForUrl={() => 'example.com'} />}
+ plugins={<CaptureEditor onReady={e => (editor = e)} />}
+ />,
+ );
+ await waitFor(() => expect(editor).toBeDefined());
+ return editor;
+ }
+
+ it('inserts the URL as a link in an empty paragraph', async () => {
+ const editor = await renderWithPrompt();
+ editor.update(() => {
+ const root = $getRoot();
+ root.clear();
+ const paragraph = $createParagraphNode();
+ root.append(paragraph);
+ paragraph.select();
+ });
+
+ fireEvent.click(screen.getByRole('button', {name: 'Link'}));
+
+ await waitFor(() =>
+ expect(paragraphParts(editor)).toEqual([
+ 'link:https://example.com/:example.com',
+ ]),
+ );
+ });
+
+ it('inserts the link at a caret inside text, linking nothing else', async () => {
+ const editor = await renderWithPrompt();
+ editor.update(() => {
+ const root = $getRoot();
+ root.clear();
+ const paragraph = $createParagraphNode();
+ const textNode = $createTextNode('hello world');
+ paragraph.append(textNode);
+ root.append(paragraph);
+ textNode.select(6, 6);
+ });
+
+ fireEvent.click(screen.getByRole('button', {name: 'Link'}));
+
+ await waitFor(() =>
+ expect(paragraphParts(editor)).toEqual([
+ 'hello ',
+ 'link:https://example.com/:example.com',
+ 'world',
+ ]),
+ );
+ });
+
+ it('inserts the link at a caret from Cmd/Ctrl+K with promptForUrl', async () => {
+ const editor = await renderWithPrompt();
+ editor.update(() => {
+ const root = $getRoot();
+ root.clear();
+ const paragraph = $createParagraphNode();
+ const textNode = $createTextNode('hello world');
+ paragraph.append(textNode);
+ root.append(paragraph);
+ textNode.select(6, 6);
+ });
+ await waitFor(() =>
+ expect(paragraphParts(editor)).toEqual(['hello world']),
+ );
+
+ const textbox = screen.getByRole('textbox');
+ fireEvent.keyDown(textbox, {key: 'k', metaKey: true});
+ fireEvent.keyDown(textbox, {key: 'k', ctrlKey: true});
+
+ await waitFor(() =>
+ expect(paragraphParts(editor)).toContain(
+ 'link:https://example.com/:example.com',
+ ),
+ );
+ expect(paragraphParts(editor)[0]).toBe('hello ');
+ expect(paragraphParts(editor)).not.toContain(
+ 'link:https://example.com/:hello world',
+ );
+ });
+
+ it('updates the link around a caret instead of splitting it', async () => {
+ let editor!: LexicalEditor;
+ render(
+ <RichTextEditor
+ label="Notes"
+ toolbar={<RichTextEditorToolbar />}
+ plugins={<CaptureEditor onReady={e => (editor = e)} />}
+ />,
+ );
+ await waitFor(() => expect(editor).toBeDefined());
+ editor.update(() => {
+ const root = $getRoot();
+ root.clear();
+ const paragraph = $createParagraphNode();
+ const link = $createLinkNode('https://old.example/');
+ const linkText = $createTextNode('docs');
+ link.append(linkText);
+ paragraph.append($createTextNode('see '), link);
+ root.append(paragraph);
+ linkText.select(2, 2);
+ });
+ await waitFor(() =>
+ expect(paragraphParts(editor)).toEqual([
+ 'see ',
+ 'link:https://old.example/:docs',
+ ]),
+ );
+
+ fireEvent.click(screen.getByRole('button', {name: 'Link'}));
+ expect(
+ await screen.findByRole('dialog', {name: 'Edit link', ...h}),
+ ).toBeInTheDocument();
+ const url = screen.getByRole('textbox', {name: 'URL', ...h});
+ fireEvent.change(url, {target: {value: 'https://new.example/'}});
+ fireEvent.click(screen.getByRole('button', {name: 'Update link', ...h}));
+
+ await waitFor(() =>
+ expect(paragraphParts(editor)).toEqual([
+ 'see ',
+ 'link:https://new.example/:docs',
+ ]),
+ );
+ });
+
+ it('still links the selected text when the selection is not empty', async () => {
+ const editor = await renderWithPrompt();
+ editor.update(() => {
+ const root = $getRoot();
+ root.clear();
+ const paragraph = $createParagraphNode();
+ const textNode = $createTextNode('hello world');
+ paragraph.append(textNode);
+ root.append(paragraph);
+ textNode.select(0, 5);
+ });
+
+ fireEvent.click(screen.getByRole('button', {name: 'Link'}));
+
+ await waitFor(() =>
+ expect(paragraphParts(editor)).toEqual([
+ 'link:https://example.com/:hello',
+ ' world',
+ ]),
+ );
+ });
+ });
+
it('does not create a link when promptForUrl returns an unsafe scheme', async () => {
let editor!: LexicalEditor;
const promptForUrl = vi.fn(() => 'javascript:alert(1)');
diff --git a/packages/richtext/src/RichTextEditorToolbar.tsx b/packages/richtext/src/RichTextEditorToolbar.tsx
index bbae191f6b..c2987bfeaf 100644
--- a/packages/richtext/src/RichTextEditorToolbar.tsx
+++ b/packages/richtext/src/RichTextEditorToolbar.tsx
@@ -483,7 +483,9 @@ export interface RichTextEditorToolbarProps extends BaseProps<HTMLDivElement> {
/**
* Whether to show the insert/edit-link button. By default, pressing it opens
* an Astryx Dialog. The form can add, update, or remove a link without
- * losing the editor selection.
+ * losing the editor selection. With a collapsed selection, Insert link
+ * inserts the entered URL as link text at the caret; with a non-empty
+ * selection it links the selected text.
*
* Requires `LinkNode` to be registered (it is, by default) — no extra setup.
* The entered URL is sanitized (see `sanitizeUrl`) so only
@@ -694,27 +696,36 @@ export function RichTextEditorToolbar({
return false;
}
- restoreLinkSelection();
const linkAttributes = hasNewTabLinks
? {target: '_blank', rel: 'noopener noreferrer'}
: {};
- const handled = editor.dispatchCommand(TOGGLE_LINK_COMMAND, {
- url,
- ...linkAttributes,
- });
- if (!handled) {
- editor.update(() => {
- const selection = $getSelection();
- if ($isRangeSelection(selection) && selection.isCollapsed()) {
+ const savedSelection = savedSelectionRef.current;
+ // One update restores the selection, decides, and applies. Inside a
+ // command listener (Cmd/Ctrl+K) Lexical queues an update, so a flag set
+ // in one update cannot steer code that runs after it.
+ editor.update(() => {
+ if (savedSelection) {
+ $setSelection(savedSelection.clone());
+ }
+ const selection = $getSelection();
+ if ($isRangeSelection(selection) && selection.isCollapsed()) {
+ const node = selection.anchor.getNode();
+ const isInLink = $isLinkNode(node) || $isLinkNode(node.getParent());
+ // At a caret outside a link there is no text to link, so the URL
+ // becomes the link's text. The toggle command would link the whole
+ // text node around the caret instead.
+ if (!isInLink) {
const linkNode = $createLinkNode(url, linkAttributes);
linkNode.append($createTextNode(trimmed));
selection.insertNodes([linkNode]);
+ return;
}
- });
- }
+ }
+ editor.dispatchCommand(TOGGLE_LINK_COMMAND, {url, ...linkAttributes});
+ });
return true;
},
- [editor, hasNewTabLinks, restoreLinkSelection],
+ [editor, hasNewTabLinks],
);
const toggleLink = useCallback(() => {