Skip to content

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

TypeScript

fix(richtext): select a Markdown plugin node whole with a click (#7067)

Cindy Zhang090588faa24c
diff --git a/packages/richtext/src/MarkdownExtensionsPlugin.tsx b/packages/richtext/src/MarkdownExtensionsPlugin.tsx
index 4369c36909..7a78014159 100644
--- a/packages/richtext/src/MarkdownExtensionsPlugin.tsx
+++ b/packages/richtext/src/MarkdownExtensionsPlugin.tsx
@@ -22,16 +22,23 @@
import {useEffect, useMemo, type ReactNode} from 'react';
import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';
+import {useLexicalNodeSelection} from '@lexical/react/useLexicalNodeSelection';
import type {Transformer} from '@lexical/markdown';
-import {$dfs} from '@lexical/utils';
+import {
+ $dfs,
+ addClassNamesToElement,
+ removeClassNamesFromElement,
+} from '@lexical/utils';
import {
$getSelection,
$isRangeSelection,
+ CLICK_COMMAND,
COMMAND_PRIORITY_LOW,
FORMAT_TEXT_COMMAND,
HISTORY_MERGE_TAG,
TEXT_TYPE_TO_FORMAT,
type LexicalEditor,
+ type NodeKey,
type RangeSelection,
type TextFormatType,
} from 'lexical';
@@ -102,12 +109,54 @@ const NODE_FORMATS: ReadonlySet<TextFormatType> = new Set(
function ExtensionNodeView({
facts,
format,
+ nodeKey,
plugins,
}: {
facts: RichTextExtensionNodeFacts;
format: number;
+ nodeKey: NodeKey;
plugins: ReadonlyArray<MarkdownPluginEntry>;
}): ReactNode {
+ const [editor] = useLexicalComposerContext();
+ const [isSelected, setSelected, clearSelection] =
+ useLexicalNodeSelection(nodeKey);
+ // A click on the node selects it whole, as a click on a rule does, so a
+ // pointer user can format or delete it like a keyboard user.
+ useEffect(
+ () =>
+ editor.registerCommand(
+ CLICK_COMMAND,
+ event => {
+ const element = editor.getElementByKey(nodeKey);
+ if (
+ !editor.isEditable() ||
+ element == null ||
+ !(event.target instanceof Node) ||
+ !element.contains(event.target)
+ ) {
+ return false;
+ }
+ clearSelection();
+ setSelected(true);
+ return true;
+ },
+ COMMAND_PRIORITY_LOW,
+ ),
+ [clearSelection, editor, nodeKey, setSelected],
+ );
+ // A selected node shows the focus ring a selected rule shows.
+ useEffect(() => {
+ const element = editor.getElementByKey(nodeKey);
+ const className: unknown = editor._config.theme.markdownExtensionSelected;
+ if (element == null || typeof className !== 'string' || className === '') {
+ return;
+ }
+ if (isSelected) {
+ addClassNamesToElement(element, className);
+ } else {
+ removeClassNamesFromElement(element, className);
+ }
+ }, [editor, isSelected, nodeKey]);
const node = useMemo(
() => deriveExtensionNode(facts, plugins),
[facts, plugins],
@@ -177,9 +226,17 @@ export function MarkdownExtensionsPlugin({
);
useEffect(() => {
- const unset = setRichTextExtensionNodeDecorator(editor, (facts, format) => (
- <ExtensionNodeView facts={facts} format={format} plugins={plugins} />
- ));
+ const unset = setRichTextExtensionNodeDecorator(
+ editor,
+ (facts, format, nodeKey) => (
+ <ExtensionNodeView
+ facts={facts}
+ format={format}
+ nodeKey={nodeKey}
+ plugins={plugins}
+ />
+ ),
+ );
redrawExtensionNodes(editor);
return () => {
unset();
diff --git a/packages/richtext/src/RichTextEditorToolbar.tsx b/packages/richtext/src/RichTextEditorToolbar.tsx
index de65e89b63..e60ace48b3 100644
--- a/packages/richtext/src/RichTextEditorToolbar.tsx
+++ b/packages/richtext/src/RichTextEditorToolbar.tsx
@@ -88,6 +88,7 @@ import {
IS_APPLE,
isExactShortcutMatch,
$getSelection,
+ $isNodeSelection,
$isRangeSelection,
$setSelection,
$createParagraphNode,
@@ -509,11 +510,13 @@ export function RichTextEditorToolbar({
const $syncToolbar = useCallback(() => {
const selection = $getSelection();
- if (!$isRangeSelection(selection)) {
+ if (!$isRangeSelection(selection) && !$isNodeSelection(selection)) {
return;
}
const formats = new Set<string>();
- // A selection of Markdown plugin nodes alone shows their formats.
+ // A selection of Markdown plugin nodes alone — a range around them, or
+ // a node selection from a click — shows their formats. Any other node
+ // selection, such as a rule, has none.
const nodesOnly = $selectedExtensionNodesOnly(selection);
for (const fmt of [
'bold',
@@ -525,12 +528,15 @@ export function RichTextEditorToolbar({
if (
nodesOnly != null
? nodesOnly.every(node => node.hasFormat(fmt))
- : selection.hasFormat(fmt)
+ : $isRangeSelection(selection) && selection.hasFormat(fmt)
) {
formats.add(fmt);
}
}
setActiveFormats(formats);
+ if (!$isRangeSelection(selection)) {
+ return;
+ }
// Link active state — a link is "active" when the caret/selection anchor
// sits inside a LinkNode (or its immediate parent is one):
diff --git a/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts
index eb0712f245..b40e2b202c 100644
--- a/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts
+++ b/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts
@@ -248,6 +248,77 @@ test('the toolbar shows the format of a plugin node selected alone', async ({
expect(errors).toEqual([]);
});
+/** How many nodes the editor's selection holds as a node selection; 0 else. */
+function editorNodeSelectionSize(page: Page): Promise<number> {
+ return surface(page, 'editor')
+ .locator('[contenteditable="true"]')
+ .evaluate(root => {
+ const editor = (
+ root as HTMLElement & {
+ __lexicalEditor?: {
+ getEditorState(): {_selection: {_nodes?: Set<string>} | null};
+ };
+ }
+ ).__lexicalEditor;
+ return editor?.getEditorState()._selection?._nodes?.size ?? 0;
+ });
+}
+
+test('a click selects a plugin node whole, with the focus ring, to format or delete it', async ({
+ page,
+}) => {
+ const errors = await openStory(page);
+ const mention = surface(page, 'editor')
+ .locator('[contenteditable="true"] [data-markdown-extension]')
+ .first();
+ await expect(mention).toHaveCSS('outline-style', 'none');
+ await mention.click();
+ await expect.poll(() => editorNodeSelectionSize(page)).toBe(1);
+ await expectEditorSelection(page, '@{ada}');
+ await expect(mention).not.toHaveCSS('outline-style', 'none');
+ await page.keyboard.press('ControlOrMeta+b');
+ expect(await markdownOutput(page)).toContain('Ping **@{ada}** about');
+ // A click in the text takes the selection, and the ring, off the node.
+ await caretAt(page, 2);
+ await expect.poll(() => editorNodeSelectionSize(page)).toBe(0);
+ await expect(mention).toHaveCSS('outline-style', 'none');
+ await mention.click();
+ await expect.poll(() => editorNodeSelectionSize(page)).toBe(1);
+ await page.keyboard.press('Backspace');
+ expect(await markdownOutput(page)).toContain('Ping about');
+ expect(errors).toEqual([]);
+});
+
+test('the toolbar shows the format of a plugin node selected with a click', async ({
+ page,
+}) => {
+ const errors = await openStory(page);
+ const bold = surface(page, 'editor').getByRole('button', {name: 'Bold'});
+ const mention = surface(page, 'editor')
+ .locator('[contenteditable="true"] [data-markdown-extension]')
+ .first();
+ // Bold text, with the caret in it.
+ await surface(page, 'editor')
+ .locator('[contenteditable="true"]')
+ .getByText('Ping', {exact: false})
+ .first()
+ .click();
+ await page.keyboard.press('ControlOrMeta+b');
+ await page.keyboard.type('Z');
+ await expect(bold).toHaveAttribute('aria-pressed', 'true');
+ // A click on the plain node shows the node's own format.
+ await mention.click();
+ await expect.poll(() => editorNodeSelectionSize(page)).toBe(1);
+ await expect(bold).toHaveAttribute('aria-pressed', 'false');
+ // Bold then makes the node bold, and shows it.
+ await bold.click();
+ await expect(
+ surface(page, 'editor').locator('strong [data-mention="ada"]'),
+ ).toHaveCount(1);
+ await expect(bold).toHaveAttribute('aria-pressed', 'true');
+ expect(errors).toEqual([]);
+});
+
test('a copied plugin node pastes whole, drawn where the plugin is given and as source where it is not', async ({
page,
}) => {
diff --git a/packages/richtext/src/editorTheme.ts b/packages/richtext/src/editorTheme.ts
index 619ebb5974..9b84ac00a9 100644
--- a/packages/richtext/src/editorTheme.ts
+++ b/packages/richtext/src/editorTheme.ts
@@ -345,8 +345,8 @@ const editorTheme = stylex.create({
':last-child': spacingVars['--spacing-0'],
},
},
- // A selected rule (click, or arrow onto it) shows the focus ring, so
- // keyboard users can see what Backspace will delete.
+ // A selected rule (click, or arrow onto it) or Markdown plugin node (click)
+ // shows the focus ring, so users can see what Backspace will delete.
hrSelected: {
outlineWidth: focusVars['--focus-outline-width'],
outlineStyle: focusVars['--focus-outline-style'],
@@ -454,6 +454,8 @@ export function sharedEditorTheme(): EditorThemeClasses {
code: `${block(editorTheme.code)} ${CODE_SYNTAX_CLASS}`,
hr: stylex.props(editorTheme.hr).className,
hrSelected: stylex.props(editorTheme.hrSelected).className,
+ // MarkdownExtensionsPlugin puts it on a selected plugin node.
+ markdownExtensionSelected: stylex.props(editorTheme.hrSelected).className,
table: block(editorTheme.table),
// Lexical stamps rows and cells `dir="auto"` too, which would set a cell
// of English text left-to-right inside a right-to-left document.
diff --git a/packages/richtext/src/markdownExtensionNode.ts b/packages/richtext/src/markdownExtensionNode.ts
index 535b85cd70..922da75089 100644
--- a/packages/richtext/src/markdownExtensionNode.ts
+++ b/packages/richtext/src/markdownExtensionNode.ts
@@ -18,6 +18,7 @@
*/
import {
+ $isNodeSelection,
$isTextNode,
DecoratorNode,
TEXT_TYPE_TO_FORMAT,
@@ -28,6 +29,7 @@ import {
type LexicalEditor,
type LexicalNode,
type NodeKey,
+ type NodeSelection,
type RangeSelection,
type TextNode,
type SerializedLexicalNode,
@@ -71,12 +73,14 @@ export function factsFrom(
/**
* Draws a plugin node's content in one editor, inside the text formats the
- * node sits in. The client surfaces register one (MarkdownExtensionsPlugin);
- * without one, a node shows its source.
+ * node sits in; `nodeKey` lets it select the node. The client surfaces
+ * register one (MarkdownExtensionsPlugin); without one, a node shows its
+ * source.
*/
export type RichTextExtensionNodeDecorator = (
facts: RichTextExtensionNodeFacts,
format: number,
+ nodeKey: NodeKey,
) => unknown;
const decorators = new WeakMap<LexicalEditor, RichTextExtensionNodeDecorator>();
@@ -252,7 +256,7 @@ export class RichTextExtensionNode extends DecoratorNode<unknown> {
decorate(editor: LexicalEditor): unknown {
return (
- decorators.get(editor)?.(this.__facts, this.__format) ??
+ decorators.get(editor)?.(this.__facts, this.__format, this.__key) ??
this.__facts.source
);
}
@@ -301,12 +305,21 @@ export function $firstSelectedText(selection: RangeSelection): TextNode | null {
}
/**
- * The inline plugin nodes a range selects when it selects no text, only
- * nodes; null otherwise. A format shown or toggled then belongs to them.
+ * The inline plugin nodes a selection holds when it holds nothing else: a
+ * range that selects no text, only nodes, or a node selection of plugin
+ * nodes alone. Null otherwise. A format shown or toggled then belongs to
+ * them.
*/
export function $selectedExtensionNodesOnly(
- selection: RangeSelection,
+ selection: RangeSelection | NodeSelection,
): RichTextExtensionNode[] | null {
+ if ($isNodeSelection(selection)) {
+ const selected = selection.getNodes();
+ return selected.length > 0 &&
+ selected.every(node => $isRichTextExtensionNode(node) && node.isInline())
+ ? (selected as RichTextExtensionNode[])
+ : null;
+ }
const nodes = selection
.getNodes()
.filter(
diff --git a/packages/richtext/src/markdownExtensionSelection.test.ts b/packages/richtext/src/markdownExtensionSelection.test.ts
index d89b89dde9..5be1e0f854 100644
--- a/packages/richtext/src/markdownExtensionSelection.test.ts
+++ b/packages/richtext/src/markdownExtensionSelection.test.ts
@@ -3,6 +3,7 @@
import {describe, expect, it} from 'vitest';
import {createHeadlessEditor} from '@lexical/headless';
import {
+ $createNodeSelection,
$createParagraphNode,
$createRangeSelection,
$createTextNode,
@@ -62,4 +63,40 @@ describe('$selectedExtensionNodesOnly', () => {
);
expect(results).toEqual([1, 1, null, null]);
});
+
+ it('returns the plugin nodes a node selection holds when it holds nothing else', () => {
+ const editor = createHeadlessEditor({
+ nodes: [...DEFAULT_NODES],
+ onError(error) {
+ throw error;
+ },
+ });
+ const results: Array<unknown> = [];
+ editor.update(
+ () => {
+ const node = $createRichTextExtensionNode({
+ plugin: 'mentions',
+ apiVersion: 1,
+ name: 'mention',
+ display: 'inline',
+ data: {label: 'ada'},
+ source: '@{ada}',
+ });
+ const text = $createTextNode('Ping ');
+ const paragraph = $createParagraphNode().append(text, node);
+ $getRoot().clear().append(paragraph);
+ const select = (...keys: string[]) => {
+ const selection = $createNodeSelection();
+ keys.forEach(key => selection.add(key));
+ $setSelection(selection);
+ return $selectedExtensionNodesOnly(selection);
+ };
+ results.push(select(node.getKey())?.length);
+ results.push(select(node.getKey(), text.getKey()));
+ results.push(select(paragraph.getKey()));
+ },
+ {discrete: true},
+ );
+ expect(results).toEqual([1, null, null]);
+ });
});