An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): toggle a format on plugin nodes selected alone (#7047)
Cindy Zhanga97259bce83f
diff --git a/packages/richtext/src/MarkdownExtensionsPlugin.tsx b/packages/richtext/src/MarkdownExtensionsPlugin.tsxindex 7abd719cba..457ec3eb7e 100644--- a/packages/richtext/src/MarkdownExtensionsPlugin.tsx+++ b/packages/richtext/src/MarkdownExtensionsPlugin.tsx@@ -33,7 +33,9 @@ import {HISTORY_MERGE_TAG,TEXT_TYPE_TO_FORMAT,type LexicalEditor,+ type RangeSelection,type TextFormatType,+ type TextNode,} from 'lexical';import {MarkdownPluginNodeRenderer} from '@astryxdesign/core/Markdown/plugin-renderer';import {@@ -144,6 +146,44 @@ function redrawExtensionNodes(editor: LexicalEditor): void {);}+/**+ * Whether `format` will be on for the text a range selects once it is+ * toggled, as Lexical's formatText decides it from the first selected+ * character; null when the range selects no text, only nodes.+ */+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+ );+}+export interface MarkdownExtensionsPluginProps {extensions: ReadonlyArray<RichTextMarkdownExtension>;/** The surface's Markdown transformers, checked against the extensions. */@@ -171,15 +211,16 @@ export function MarkdownExtensionsPlugin({};}, [editor, plugins]);- // Bold, italic, or strikethrough toggled on a range takes the plugin nodes- // in it along, so they stay inside the marks the text around them gets.+ // Bold, italic, or strikethrough toggled on a selection takes the plugin+ // nodes in it along, so they stay inside the marks the text around them+ // gets — and a selection of nodes alone toggles them by themselves.useEffect(() =>editor.registerCommand(FORMAT_TEXT_COMMAND,format => {const selection = $getSelection();- if (!$isRangeSelection(selection) || !NODE_FORMATS.has(format)) {+ if (!NODE_FORMATS.has(format) || selection == null) {return false;}const nodes = selection@@ -191,12 +232,16 @@ export function MarkdownExtensionsPlugin({if (nodes.length === 0) {return false;}- selection.formatText(format);- const text = selection.getNodes().find($isTextNode);+ // The state Lexical gives the selected text, read before it does;+ // null when no text is selected, only nodes.+ const textState = $isRangeSelection(selection)+ ? $nextTextFormat(selection, format)+ : null;+ if ($isRangeSelection(selection)) {+ selection.formatText(format);+ }const isOn =- text != null- ? text.hasFormat(format)- : !nodes.every(node => node.hasFormat(format));+ textState ?? !nodes.every(node => node.hasFormat(format));for (const node of nodes) {node.setFormatFlag(format, isOn);}diff --git a/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.tsindex a22c5c7d03..f50805572c 100644--- a/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts+++ b/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts@@ -202,6 +202,30 @@ test('italic toggled on a range takes the plugin node in it along', async ({expect(errors).toEqual([]);});+test('bold toggled with only a plugin node selected toggles that node', async ({+ page,+}) => {+ const errors = await openStory(page);+ const bold = surface(page, 'editor').getByRole('button', {name: 'Bold'});+ const strongMention = surface(page, 'editor').locator(+ 'strong [data-mention="ada"]',+ );+ // 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 bold.click();+ await expect(strongMention).toHaveCount(1);+ expect(await markdownOutput(page)).toContain('Ping **@{ada}** about');+ await caretAt(page, 6);+ await page.keyboard.press('Shift+ArrowLeft');+ await expectEditorSelection(page, '@{ada}');+ await bold.click();+ await expect(strongMention).toHaveCount(0);+ expect(await markdownOutput(page)).toContain('Ping @{ada} about');+ 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/markdownExtensions.test.ts b/packages/richtext/src/markdownExtensions.test.tsindex eedf261a9e..1725c9769a 100644--- a/packages/richtext/src/markdownExtensions.test.ts+++ b/packages/richtext/src/markdownExtensions.test.ts@@ -569,6 +569,40 @@ describe('nodes inside marks (spec:AST-064 FR5, FR10)', () => {});});+describe('a mark on a node alone (spec:AST-064 FR10)', () => {+ it('exports when only the node changes, and reads back inside the mark', () => {+ const editor = createHeadlessEditor({+ nodes: [...DEFAULT_NODES],+ onError(error) {+ throw error;+ },+ });+ importMarkdownKeepingSource(+ editor,+ 'Ping @{ada} about it.\n',+ [...DEFAULT_TRANSFORMERS],+ PLUGINS,+ );+ editor.update(+ () => {+ const node = $getRoot().getAllTextNodes()[0]?.getNextSibling();+ if (!$isRichTextExtensionNode(node)) {+ throw new Error('No plugin node');+ }+ node.setFormatFlag('bold', true);+ },+ {discrete: true},+ );+ const exported = editor+ .getEditorState()+ .read(() => $exportMarkdownKeepingSource([...DEFAULT_TRANSFORMERS]));+ expect(exported).toBe('Ping **@{ada}** about it.\n');+ expect(+ formatsOf(markdownToEditorStateJSON(exported, {extensions: EXTENSIONS})),+ ).toEqual([['@{ada}', 1]]);+ });+});+describe('a block after a paragraph line (spec:AST-064 FR5)', () => {it('splits the paragraph around the block node, as core reads it', () => {const markdown = 'Intro line\n:::note\nBody\n:::\nAfter line\n';@@ -634,7 +668,7 @@ describe('plugin nodes as HTML (spec:AST-064 FR7)', () => {const source = editorWith();importMarkdownKeepingSource(source,- 'Hi @{ada}.\n\n:::note\nBody **bold**\n:::\n',+ 'Hi @{ada}, *see @{grace}*.\n\n:::note\nBody **bold**\n:::\n',[...DEFAULT_TRANSFORMERS],PLUGINS,);@@ -651,26 +685,30 @@ describe('plugin nodes as HTML (spec:AST-064 FR7)', () => {{discrete: true},);const facts = (editor: typeof source) =>- editor- .getEditorState()- .read(() =>- [...$getRoot().getChildren()]- .flatMap(node =>- $isRichTextExtensionNode(node)- ? [node]- : 'getChildren' in node &&- typeof node.getChildren === 'function'- ? (node.getChildren() as Array<unknown>).filter(- $isRichTextExtensionNode as (value: unknown) => boolean,- )- : [],- )- .map(node => (node as RichTextExtensionNode).getFacts()),- );+ editor.getEditorState().read(() =>+ [...$getRoot().getChildren()]+ .flatMap(node =>+ $isRichTextExtensionNode(node)+ ? [node]+ : 'getChildren' in node && typeof node.getChildren === 'function'+ ? (node.getChildren() as Array<unknown>).filter(+ $isRichTextExtensionNode as (value: unknown) => boolean,+ )+ : [],+ )+ .map(node => ({+ ...(node as RichTextExtensionNode).getFacts(),+ format: (node as RichTextExtensionNode).getFormat(),+ })),+ );expect(facts(target)).toEqual(facts(source));- expect(facts(source).map(({source: text}) => text)).toEqual([- '@{ada}',- ':::note\nBody **bold**\n:::',+ // The node inside emphasis keeps its italic format (2) through the HTML.+ expect(+ facts(source).map(({source: text, format}) => [text, format]),+ ).toEqual([+ ['@{ada}', 0],+ ['@{grace}', 2],+ [':::note\nBody **bold**\n:::', 0],]);});});diff --git a/packages/richtext/src/markdownSource.ts b/packages/richtext/src/markdownSource.tsindex f6d285556e..ab0b7aeb1a 100644--- a/packages/richtext/src/markdownSource.ts+++ b/packages/richtext/src/markdownSource.ts@@ -599,10 +599,23 @@ function $canonicalMarkdown() {return cached;}- const markdown = $convertToMarkdownString(+ // Inline plugin nodes read as text inside the marks around them, so a mark+ // put on or taken off a node alone changes the canonical form too.+ const {placeholders, sources} = extensionPlaceholders(+ descendants,+ descendants.map(node => node.getTextContent()).join(''),+ );+ let markdown = $convertToMarkdownString(withExtensionExport(transformers),- childrenOf(nodes),+ childrenOf(+ placeholders.size === 0+ ? nodes+ : nodes.map(node => markedView(node, null, placeholders)),+ ),);+ for (const [placeholder, source] of sources) {+ markdown = markdown.split(placeholder).join(source);+ }const entry = {descendants, transformers, markdown, hash: hashOf(markdown)};canonicalCache.set(nodes[0], entry);return entry;@@ -663,12 +676,14 @@ export function absentToken(text: string): string {/*** A view of `node` whose text marks every character that needs a backslash- * with `token`. Views delegate everything else to the node they wrap, so- * Lexical's exporter reads them like the real tree without changing it.+ * with `token` (none when `token` is null), and whose inline plugin nodes read+ * as text holding their placeholders. Views delegate everything else to the+ * node they wrap, so Lexical's exporter reads them like the real tree without+ * changing it.*/function markedView(node: LexicalNode,- token: string,+ token: string | null,placeholders: ReadonlyMap<NodeKey, string>,): LexicalNode {const placeholder = placeholders.get(node.getKey());@@ -679,6 +694,9 @@ function markedView(if (node.hasFormat('code') || $isCodeNode(node.getParent())) {return node;}+ if (token == null) {+ return Object.create(node) as typeof node;+ }let text = node.getTextContent().replace(INLINE_SYNTAX, match => token + match);@@ -716,6 +734,33 @@ function markedView(return node;}+/**+ * A placeholder for each inline plugin node among `nodes`, absent from+ * `text`, and the source each placeholder stands for.+ */+function extensionPlaceholders(+ nodes: ReadonlyArray<LexicalNode>,+ text: string,+): {+ readonly placeholders: ReadonlyMap<NodeKey, string>;+ readonly sources: ReadonlyMap<string, string>;+} {+ const placeholders = new Map<NodeKey, string>();+ const sources = new Map<string, string>();+ const free = absentCharacters(text);+ for (const node of nodes) {+ if ($isRichTextExtensionNode(node) && node.isInline()) {+ const placeholder = free.next().value;+ if (placeholder == null) {+ break;+ }+ placeholders.set(node.getKey(), placeholder);+ sources.set(placeholder, node.getSource());+ }+ }+ return {placeholders, sources};+}+/*** The canonical Markdown of a changed group, with literal text escaped so it* imports again as the structure the editor showed (spec:AST-062 FR3).@@ -732,19 +777,10 @@ function $regeneratedMarkdown(// Inline plugin nodes export as placeholders inside the text around them,// so the marks around a node wrap it; each placeholder becomes the node's// exact source afterwards.- const placeholders = new Map<NodeKey, string>();- const sources = new Map<string, string>();- const free = absentCharacters(text + token);- for (const node of descendantsOf(nodes)) {- if ($isRichTextExtensionNode(node) && node.isInline()) {- const placeholder = free.next().value;- if (placeholder == null) {- break;- }- placeholders.set(node.getKey(), placeholder);- sources.set(placeholder, node.getSource());- }- }+ const {placeholders, sources} = extensionPlaceholders(+ descendantsOf(nodes),+ text + token,+ );let marked = $convertToMarkdownString(withExtensionExport(transformers),childrenOf(nodes.map(node => markedView(node, token, placeholders))),