An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): show a plugin node's format in the toolbar when it is selected alone (#7063)
Cindy Zhang52e4193ac107
diff --git a/packages/richtext/src/MarkdownExtensionsPlugin.tsx b/packages/richtext/src/MarkdownExtensionsPlugin.tsxindex 457ec3eb7e..4369c36909 100644--- a/packages/richtext/src/MarkdownExtensionsPlugin.tsx+++ b/packages/richtext/src/MarkdownExtensionsPlugin.tsx@@ -27,7 +27,6 @@ import {$dfs} from '@lexical/utils';import {$getSelection,$isRangeSelection,- $isTextNode,COMMAND_PRIORITY_LOW,FORMAT_TEXT_COMMAND,HISTORY_MERGE_TAG,@@ -35,7 +34,6 @@ import {type LexicalEditor,type RangeSelection,type TextFormatType,- type TextNode,} from 'lexical';import {MarkdownPluginNodeRenderer} from '@astryxdesign/core/Markdown/plugin-renderer';import {@@ -48,6 +46,7 @@ import type {} from '@astryxdesign/core/Markdown/plugins';import {pluginsOf, type RichTextMarkdownExtension} from './markdownExtensions';import {+ $firstSelectedText,$isRichTextExtensionNode,setRichTextExtensionNodeDecorator,type RichTextExtensionNode,@@ -155,33 +154,10 @@ function $nextTextFormat(selection: RangeSelection,format: TextFormatType,): boolean | null {- const texts = selection.getNodes().filter($isTextNode);- const isBackward = selection.isBackward();- const start = isBackward ? selection.focus : selection.anchor;- const end = isBackward ? selection.anchor : selection.focus;- let first: TextNode | undefined = texts[0];- let startOffset = start.type === 'element' ? 0 : start.offset;- // A range that starts at the end of a text node starts in the next one.- if (- first != null &&- start.type === 'text' &&- startOffset === first.getTextContentSize()- ) {- first = texts[1];- startOffset = 0;- }- const last = texts[texts.length - 1];- if (first == null || last == null) {- return null;- }- const endOffset =- end.type === 'text' ? end.offset : last.getTextContentSize();- if (first.is(last) && startOffset === endOffset) {- return null;- }- return (- (first.getFormatFlags(format, null) & TEXT_TYPE_TO_FORMAT[format]) !== 0- );+ const first = $firstSelectedText(selection);+ return first == null+ ? null+ : (first.getFormatFlags(format, null) & TEXT_TYPE_TO_FORMAT[format]) !== 0;}export interface MarkdownExtensionsPluginProps {diff --git a/packages/richtext/src/RichTextEditorToolbar.tsx b/packages/richtext/src/RichTextEditorToolbar.tsxindex dc43dfd4e1..de65e89b63 100644--- a/packages/richtext/src/RichTextEditorToolbar.tsx+++ b/packages/richtext/src/RichTextEditorToolbar.tsx@@ -95,6 +95,7 @@ import {type RangeSelection,} from 'lexical';import {sanitizeUrl} from './linkUtils';+import {$selectedExtensionNodesOnly} from './markdownExtensionNode';/** Block types exposed by the toolbar's format selector. */type BlockType =@@ -512,6 +513,8 @@ export function RichTextEditorToolbar({return;}const formats = new Set<string>();+ // A selection of Markdown plugin nodes alone shows their formats.+ const nodesOnly = $selectedExtensionNodesOnly(selection);for (const fmt of ['bold','italic',@@ -519,7 +522,11 @@ export function RichTextEditorToolbar({'strikethrough','code',] as const) {- if (selection.hasFormat(fmt)) {+ if (+ nodesOnly != null+ ? nodesOnly.every(node => node.hasFormat(fmt))+ : selection.hasFormat(fmt)+ ) {formats.add(fmt);}}diff --git a/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.tsindex f50805572c..eb0712f245 100644--- a/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts+++ b/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts@@ -226,6 +226,28 @@ test('bold toggled with only a plugin node selected toggles that node', async ({expect(errors).toEqual([]);});+test('the toolbar shows the format of a plugin node selected alone', async ({+ page,+}) => {+ const errors = await openStory(page);+ const bold = surface(page, 'editor').getByRole('button', {name: 'Bold'});+ // From just after the node, one step back selects the node alone.+ await caretAt(page, 6);+ await page.keyboard.press('Shift+ArrowLeft');+ await expectEditorSelection(page, '@{ada}');+ await expect(bold).toHaveAttribute('aria-pressed', 'false');+ await bold.click();+ await expect(bold).toHaveAttribute('aria-pressed', 'true');+ // The text around the node is not bold, and the node still is.+ await caretAt(page, 2);+ await expect(bold).toHaveAttribute('aria-pressed', 'false');+ await caretAt(page, 6);+ await page.keyboard.press('Shift+ArrowLeft');+ await expectEditorSelection(page, '@{ada}');+ 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/markdownExtensionNode.ts b/packages/richtext/src/markdownExtensionNode.tsindex 598dd9cd03..535b85cd70 100644--- a/packages/richtext/src/markdownExtensionNode.ts+++ b/packages/richtext/src/markdownExtensionNode.ts@@ -18,6 +18,7 @@*/import {+ $isTextNode,DecoratorNode,TEXT_TYPE_TO_FORMAT,type DOMConversionMap,@@ -27,6 +28,8 @@ import {type LexicalEditor,type LexicalNode,type NodeKey,+ type RangeSelection,+ type TextNode,type SerializedLexicalNode,type Spread,type TextFormatType,@@ -267,3 +270,50 @@ export function $isRichTextExtensionNode(): node is RichTextExtensionNode {return node instanceof RichTextExtensionNode;}++/**+ * The first text node a range selects characters of, as Lexical's formatText+ * reads it: a range that starts at the end of a text node starts in the next.+ * Null when the range selects no text, only nodes.+ */+export function $firstSelectedText(selection: RangeSelection): TextNode | null {+ const texts = selection.getNodes().filter($isTextNode);+ const isBackward = selection.isBackward();+ const start = isBackward ? selection.focus : selection.anchor;+ const end = isBackward ? selection.anchor : selection.focus;+ let first: TextNode | undefined = texts[0];+ let startOffset = start.type === 'element' ? 0 : start.offset;+ if (+ first != null &&+ start.type === 'text' &&+ startOffset === first.getTextContentSize()+ ) {+ first = texts[1];+ startOffset = 0;+ }+ const last = texts[texts.length - 1];+ if (first == null || last == null) {+ return null;+ }+ const endOffset =+ end.type === 'text' ? end.offset : last.getTextContentSize();+ return first.is(last) && startOffset === endOffset ? null : first;+}++/**+ * 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.+ */+export function $selectedExtensionNodesOnly(+ selection: RangeSelection,+): RichTextExtensionNode[] | null {+ const nodes = selection+ .getNodes()+ .filter(+ (node): node is RichTextExtensionNode =>+ $isRichTextExtensionNode(node) && node.isInline(),+ );+ return nodes.length > 0 && $firstSelectedText(selection) == null+ ? nodes+ : null;+}diff --git a/packages/richtext/src/markdownExtensionSelection.test.ts b/packages/richtext/src/markdownExtensionSelection.test.tsnew file mode 100644index 0000000000..d89b89dde9--- /dev/null+++ b/packages/richtext/src/markdownExtensionSelection.test.ts@@ -0,0 +1,65 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it} from 'vitest';+import {createHeadlessEditor} from '@lexical/headless';+import {+ $createParagraphNode,+ $createRangeSelection,+ $createTextNode,+ $getRoot,+ $setSelection,+} from 'lexical';+import {DEFAULT_NODES} from './editorNodes';+import {+ $createRichTextExtensionNode,+ $selectedExtensionNodesOnly,+} from './markdownExtensionNode';++describe('$selectedExtensionNodesOnly', () => {+ it('returns the plugin nodes a range selects when it selects no text', () => {+ const editor = createHeadlessEditor({+ nodes: [...DEFAULT_NODES],+ onError(error) {+ throw error;+ },+ });+ const results: Array<unknown> = [];+ editor.update(+ () => {+ const before = $createTextNode('Ping ');+ const node = $createRichTextExtensionNode({+ plugin: 'mentions',+ apiVersion: 1,+ name: 'mention',+ display: 'inline',+ data: {label: 'ada'},+ source: '@{ada}',+ });+ const after = $createTextNode(' about');+ $getRoot()+ .clear()+ .append($createParagraphNode().append(before, node, after));+ const select = (+ anchor: [typeof before, number],+ focus: [typeof before, number],+ ) => {+ const selection = $createRangeSelection();+ selection.anchor.set(anchor[0].getKey(), anchor[1], 'text');+ selection.focus.set(focus[0].getKey(), focus[1], 'text');+ $setSelection(selection);+ return $selectedExtensionNodesOnly(selection);+ };+ // From the end of the text before to the start of the text after.+ results.push(select([before, 5], [after, 0])?.length);+ // The same, backward.+ results.push(select([after, 0], [before, 5])?.length);+ // With a character of text.+ results.push(select([before, 4], [after, 0]));+ // A caret.+ results.push(select([before, 5], [before, 5]));+ },+ {discrete: true},+ );+ expect(results).toEqual([1, 1, null, null]);+ });+});