An open source design system that's fully customizable and agent ready
TypeScript
feat(richtext): draw Markdown plugin nodes in the editor and the view as core Markdown does (#7041)
Cindy Zhang3c6f7df5f283
diff --git a/apps/storybook/stories/RichTextEditor.markdownPlugins.tsx b/apps/storybook/stories/RichTextEditor.markdownPlugins.tsxnew file mode 100644index 0000000000..82a409abe9--- /dev/null+++ b/apps/storybook/stories/RichTextEditor.markdownPlugins.tsx@@ -0,0 +1,202 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file RichTextEditor.markdownPlugins.tsx+ * @input Uses core Markdown and its plugin protocol, and the RichText+ * surfaces, serializers, and plugin adapter.+ * @output Exports MarkdownPluginsSandbox: one document with an inline and a+ * block Markdown plugin node, shown in core Markdown, RichTextView, and+ * RichTextEditor, plus two editors to paste into — one given the plugins,+ * one not.+ * @position Lab sandbox for spec:AST-064; its Chrome spec checks that a plugin+ * node renders the same on every surface and edits as one unit.+ */++import {useMemo, useRef, useState} from 'react';+import {Markdown} from '@astryxdesign/core/Markdown';+import {+ createMarkdownPlugin,+ type MarkdownExtensionNode,+} from '@astryxdesign/core/Markdown/plugins';+import {+ createRichTextExtension,+ markdownToEditorStateJSON,+ RichTextEditor,+ RichTextEditorToolbar,+ RichTextView,+ type RichTextEditorRef,+} from '@astryxdesign/richtext';++type MentionNode = MarkdownExtensionNode<+ 'sandbox-mentions',+ 'mention',+ {readonly handle: string},+ 'inline'+>;+type NoteNode = MarkdownExtensionNode<+ 'sandbox-notes',+ 'note',+ {readonly body: string},+ 'block'+>;++const mentions = createMarkdownPlugin<'sandbox-mentions', MentionNode>({+ name: 'sandbox-mentions',+ apiVersion: 1,+ parseKey: 'v1',+ syntax: {+ inline: [+ {+ startsWith: ['@{'],+ maxSpan: 64,+ tokenize({source, offset, end}) {+ const close = source.indexOf('}', offset + 2);+ if (close < 0 || close >= end) {+ return {status: 'no-match'};+ }+ return {+ status: 'match',+ end: close + 1,+ node: {+ type: 'extension',+ plugin: 'sandbox-mentions',+ name: 'mention',+ display: 'inline',+ data: {handle: source.slice(offset + 2, close)},+ },+ };+ },+ },+ ],+ },+ renderers: {+ mention: {+ render: ({node}) => (+ <a href={`#people/${node.data.handle}`} data-mention={node.data.handle}>+ @{node.data.handle}+ </a>+ ),+ toText: node => `@${node.data.handle}`,+ },+ },+});++const notes = createMarkdownPlugin<'sandbox-notes', NoteNode>({+ name: 'sandbox-notes',+ apiVersion: 1,+ parseKey: 'v1',+ syntax: {+ block: [+ {+ startsWith: [':::note'],+ maxSpan: 400,+ tokenize({source, offset, end}) {+ const close = source.indexOf('\n:::', offset);+ if (close < 0 || close + 4 > end) {+ return {status: 'no-match'};+ }+ return {+ status: 'match',+ end: close + 4,+ node: {+ type: 'extension',+ plugin: 'sandbox-notes',+ name: 'note',+ display: 'block',+ data: {body: source.slice(offset + 8, close)},+ },+ };+ },+ },+ ],+ },+ renderers: {+ note: {+ render: ({node}) => (+ // A note, not a landmark: the story shows the same note on three+ // surfaces, and landmarks must be unique on a page.+ <div role="note" aria-label="Note" data-note="">+ {node.data.body}+ </div>+ ),+ toText: node => node.data.body,+ },+ },+});++const PLUGINS = [mentions, notes];+const EXTENSIONS = PLUGINS.map(createRichTextExtension);++export const MARKDOWN_PLUGINS_SOURCE = [+ 'Ping @{ada} about the review.',+ '',+ ':::note',+ 'Ship on Thursday',+ ':::',+ '',+ 'Then @{grace} signs off, *with thanks to @{linus}*.',+ '',+].join('\n');++const column = {display: 'grid', gap: 8, alignContent: 'start'} as const;++export function MarkdownPluginsSandbox() {+ const value = useMemo(+ () =>+ markdownToEditorStateJSON(MARKDOWN_PLUGINS_SOURCE, {+ extensions: EXTENSIONS,+ }),+ [],+ );+ const editor = useRef<RichTextEditorRef>(null);+ const withPlugins = useRef<RichTextEditorRef>(null);+ const [output, setOutput] = useState('');+ return (+ <div+ style={{+ display: 'grid',+ gap: 24,+ gridTemplateColumns: 'repeat(3, minmax(0, 1fr))',+ }}>+ <section data-plugin-surface="markdown" style={column}>+ <div>Markdown</div>+ <Markdown plugins={PLUGINS}>{MARKDOWN_PLUGINS_SOURCE}</Markdown>+ </section>+ <section data-plugin-surface="view" style={column}>+ <div>RichTextView</div>+ <RichTextView value={value} markdownExtensions={EXTENSIONS} />+ </section>+ <section data-plugin-surface="editor" style={column}>+ <RichTextEditor+ label="Editor"+ ref={editor}+ defaultValue={value}+ markdownExtensions={EXTENSIONS}+ toolbar={<RichTextEditorToolbar />}+ />+ <button+ type="button"+ onClick={() =>+ setOutput(+ [editor, withPlugins]+ .map(ref => ref.current?.getMarkdown() ?? '')+ .join('\n---\n'),+ )+ }>+ Show Markdown+ </button>+ <pre data-markdown-output="">{output}</pre>+ </section>+ <section data-plugin-surface="paste-with" style={column}>+ <RichTextEditor+ label="Paste target with the plugins"+ ref={withPlugins}+ markdownExtensions={EXTENSIONS}+ />+ </section>+ <section data-plugin-surface="paste-without" style={column}>+ <RichTextEditor label="Paste target without the plugins" />+ </section>+ </div>+ );+}diff --git a/apps/storybook/stories/RichTextEditor.markdownPluginsImportExport.tsx b/apps/storybook/stories/RichTextEditor.markdownPluginsImportExport.tsxindex 67fe255797..82505f4e16 100644--- a/apps/storybook/stories/RichTextEditor.markdownPluginsImportExport.tsx+++ b/apps/storybook/stories/RichTextEditor.markdownPluginsImportExport.tsx@@ -6,8 +6,8 @@* editor, and plugin adapter.* @output Exports MarkdownPluginsImportExport: Markdown with plugin syntax in,* the plugin nodes RichText recognized, and the Markdown it exports beside- * the input, byte for byte; an editor to change the text around the nodes;- * and a refused plugin's error.+ * the input, byte for byte; an editor, given the same extensions, to change+ * the text around the nodes; and a refused plugin's error.* @position Lab story for spec:AST-064's import and export. How plugin nodes* look in the editor and the view is the "Markdown plugins" story.*/@@ -302,14 +302,15 @@ export function MarkdownPluginsImportExport() {</section><section {...stylex.props(styles.stack)}><Text type="label">- Edit the text around the nodes, then export. Here a node shows its- source; the "Markdown plugins" story shows it rendered.+ Edit the text around the nodes, then export. The editor is given the+ same extensions, so each node renders as Markdown renders it.</Text><RichTextEditorkey={json}label="Editor"ref={editor}defaultValue={json}+ markdownExtensions={EXTENSIONS}/><div><Buttondiff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsxindex cbedc35590..c705e4e1cd 100644--- a/apps/storybook/stories/RichTextEditor.stories.tsx+++ b/apps/storybook/stories/RichTextEditor.stories.tsx@@ -20,6 +20,7 @@ import {type MarkdownParitySandboxProps,} from './RichTextEditor.markdownParity';import {MarkdownPluginsImportExport as MarkdownPluginsImportExportStory} from './RichTextEditor.markdownPluginsImportExport';+import {MarkdownPluginsSandbox} from './RichTextEditor.markdownPlugins';const meta: Meta<typeof RichTextEditor> = {title: 'Lab/RichTextEditor',@@ -378,6 +379,17 @@ Supports **bold**, _italic_, and lists:* 4. Round-trip it back to Markdown with `editorStateJSONToMarkdown`* so you can eyeball that Markdown -> JSON -> Markdown is stable.*/+/**+ * One document with an inline and a block Markdown plugin node in core+ * Markdown, RichTextView, and RichTextEditor (spec:AST-064): each node renders+ * the same everywhere and edits as one unit. Copy a node into the editor+ * given the plugins, or into the one that is not, which shows its source.+ */+export const MarkdownPlugins = {+ name: 'Markdown plugins',+ render: () => <MarkdownPluginsSandbox />,+};+/*** Markdown with plugin syntax in, and out again (spec:AST-064). A mention* plugin and a note-block plugin, adopted with createRichTextExtension, arediff --git a/packages/richtext/src/MarkdownExtensionsPlugin.test.tsx b/packages/richtext/src/MarkdownExtensionsPlugin.test.tsxnew file mode 100644index 0000000000..856766ffd2--- /dev/null+++ b/packages/richtext/src/MarkdownExtensionsPlugin.test.tsx@@ -0,0 +1,279 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, expect, it, vi} from 'vitest';+import {createRef} from 'react';+import {render, waitFor} from '@testing-library/react';+import {Markdown} from '@astryxdesign/core/Markdown';+import {+ createMarkdownPlugin,+ type MarkdownExtensionNode,+} from '@astryxdesign/core/Markdown/plugins';+import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';+import {RichTextView} from './RichTextView';+import {+ createRichTextExtension,+ markdownToEditorStateJSON,+ RichTextExtensionError,+} from './markdown';++type MentionNode = MarkdownExtensionNode<+ 'demo-mentions',+ 'mention',+ {readonly label: string},+ 'inline'+>;+type NoteNode = MarkdownExtensionNode<+ 'demo-notes',+ 'note',+ {readonly body: string},+ 'block'+>;++const mentions = createMarkdownPlugin<'demo-mentions', MentionNode>({+ name: 'demo-mentions',+ apiVersion: 1,+ parseKey: 'v1',+ syntax: {+ inline: [+ {+ startsWith: ['@{'],+ maxSpan: 80,+ tokenize({source, offset, end}) {+ const close = source.indexOf('}', offset + 2);+ if (close < 0 || close >= end) {+ return {status: 'no-match'};+ }+ return {+ status: 'match',+ end: close + 1,+ node: {+ type: 'extension',+ plugin: 'demo-mentions',+ name: 'mention',+ display: 'inline',+ data: {label: source.slice(offset + 2, close)},+ },+ };+ },+ },+ ],+ },+ renderers: {+ mention: {+ render: ({node}) => {+ if (node.data.label === 'broken') {+ throw new Error('broken mention');+ }+ return <mark data-mention={node.data.label}>@{node.data.label}</mark>;+ },+ toText: node => `@${node.data.label}`,+ },+ },+});++const notes = createMarkdownPlugin<'demo-notes', NoteNode>({+ name: 'demo-notes',+ apiVersion: 1,+ parseKey: 'v1',+ syntax: {+ block: [+ {+ startsWith: [':::note'],+ maxSpan: 500,+ tokenize({source, offset, end}) {+ const close = source.indexOf('\n:::', offset);+ if (close < 0 || close + 4 > end) {+ return {status: 'no-match'};+ }+ return {+ status: 'match',+ end: close + 4,+ node: {+ type: 'extension',+ plugin: 'demo-notes',+ name: 'note',+ display: 'block',+ data: {body: source.slice(offset + 8, close)},+ },+ };+ },+ },+ ],+ },+ renderers: {+ note: {+ render: ({node}) => <aside data-note="">{node.data.body}</aside>,+ toText: node => node.data.body,+ },+ },+});++const EXTENSIONS = [+ createRichTextExtension(mentions),+ createRichTextExtension(notes),+];++const SOURCE = 'Hi @{ada} and @{broken}.\n\n:::note\nRemember this\n:::\n';++/** The HTML each plugin node renders inside its RichText element. */+function richTextNodes(root: Element): Array<string> {+ return [...root.querySelectorAll('[data-lexical-decorator="true"]')].map(+ element => element.innerHTML,+ );+}++describe('Markdown plugin nodes in RichText (spec:AST-064 FR8, FR11)', () => {+ it('renders each node exactly as core Markdown does, fallback included, in the view and the editor', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const core = render(+ <Markdown plugins={[mentions, notes]}>{SOURCE}</Markdown>,+ );+ const expected = [+ core.container.querySelector('[data-mention="ada"]')?.outerHTML,+ '@{broken}',+ core.container.querySelector('[data-note]')?.outerHTML,+ ];+ expect(core.container.textContent).toContain('@{broken}');+ core.unmount();+ const value = markdownToEditorStateJSON(SOURCE, {extensions: EXTENSIONS});+ for (const surface of [+ <RichTextView+ key="view"+ value={value}+ markdownExtensions={EXTENSIONS}+ />,+ <RichTextEditor+ key="editor"+ label="Notes"+ defaultValue={value}+ markdownExtensions={EXTENSIONS}+ />,+ ]) {+ const {container, unmount} = render(surface);+ await waitFor(() => expect(richTextNodes(container)).toEqual(expected));+ // A block node is spaced as a paragraph; an inline one sits in text.+ const block = container.querySelector(+ '[data-lexical-decorator="true"] > aside',+ )?.parentElement;+ expect(block?.tagName).toBe('DIV');+ expect(block?.className).not.toBe('');+ unmount();+ }+ } finally {+ warn.mockRestore();+ error.mockRestore();+ }+ });++ it('draws a node inside the marks around it, as core Markdown does', async () => {+ const source = 'See *thanks to @{ada}* and **ask @{ada}**.\n';+ const core = render(<Markdown plugins={[mentions]}>{source}</Markdown>);+ expect(+ core.container.querySelector('em [data-mention="ada"]'),+ ).not.toBeNull();+ expect(+ core.container.querySelector('strong [data-mention="ada"]'),+ ).not.toBeNull();+ core.unmount();+ const {container} = render(+ <RichTextView+ value={markdownToEditorStateJSON(source, {extensions: EXTENSIONS})}+ markdownExtensions={EXTENSIONS}+ />,+ );+ await waitFor(() =>+ expect(richTextNodes(container)).toEqual([+ '<em><mark data-mention="ada">@ada</mark></em>',+ '<strong><mark data-mention="ada">@ada</mark></strong>',+ ]),+ );+ });++ it('shows the source of a node whose plugin the surface was not given', async () => {+ const value = markdownToEditorStateJSON(SOURCE, {extensions: EXTENSIONS});+ const {container} = render(+ <RichTextView+ value={value}+ markdownExtensions={[createRichTextExtension(notes)]}+ />,+ );+ await waitFor(() =>+ expect(richTextNodes(container)).toEqual([+ '@{ada}',+ '@{broken}',+ expect.stringContaining('data-note'),+ ]),+ );+ });++ it('derives each node again from its source and never draws stored data', async () => {+ const stored = JSON.parse(+ markdownToEditorStateJSON('Hi @{ada}.\n', {extensions: EXTENSIONS}),+ ) as {root: {children: Array<{children: Array<Record<string, unknown>>}>}};+ const node = stored.root.children[0]?.children.find(+ child => child.type === 'astryx-markdown-extension',+ );+ if (node == null) {+ throw new Error('No extension node');+ }+ node.data = {label: 'stale'};+ const tampered = JSON.stringify(stored);+ const {container, unmount} = render(+ <RichTextView value={tampered} markdownExtensions={EXTENSIONS} />,+ );+ await waitFor(() =>+ expect(richTextNodes(container)).toEqual([+ '<mark data-mention="ada">@ada</mark>',+ ]),+ );+ unmount();+ // A node stored under another protocol version shows its source.+ node.data = {label: 'ada'};+ node.apiVersion = 2;+ const other = render(+ <RichTextView+ value={JSON.stringify(stored)}+ markdownExtensions={EXTENSIONS}+ />,+ );+ await waitFor(() =>+ expect(richTextNodes(other.container)).toEqual(['@{ada}']),+ );+ });++ it('keeps every node source in getMarkdown()', async () => {+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor+ label="Notes"+ ref={ref}+ defaultValue={markdownToEditorStateJSON(SOURCE, {+ extensions: EXTENSIONS,+ })}+ markdownExtensions={EXTENSIONS}+ />,+ );+ await waitFor(() => expect(ref.current?.getMarkdown()).toBe(SOURCE));+ });++ it('refuses a configuration that adopts one plugin twice', () => {+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ expect(() =>+ render(+ <RichTextView+ value={markdownToEditorStateJSON('x')}+ markdownExtensions={[+ createRichTextExtension(mentions),+ createRichTextExtension(mentions),+ ]}+ />,+ ),+ ).toThrow(RichTextExtensionError);+ } finally {+ error.mockRestore();+ }+ });+});diff --git a/packages/richtext/src/MarkdownExtensionsPlugin.tsx b/packages/richtext/src/MarkdownExtensionsPlugin.tsxnew file mode 100644index 0000000000..7abd719cba--- /dev/null+++ b/packages/richtext/src/MarkdownExtensionsPlugin.tsx@@ -0,0 +1,211 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file MarkdownExtensionsPlugin.tsx+ * @input Uses @lexical/react (composer context), @lexical/utils ($dfs),+ * lexical, core's client-only MarkdownPluginNodeRenderer and server-safe+ * parser, and the RichText adapter and extension node.+ * @output Exports MarkdownExtensionsPlugin, which draws every Markdown plugin+ * node in an editor with its plugin's renderer, and deriveExtensionNode.+ * @position Rendered by RichTextEditor and RichTextView when they are given+ * `markdownExtensions` (spec:AST-064 FR2). It checks the configuration+ * first (FR6), so a conflicting one throws a RichTextExtensionError while+ * the surface renders. Each node is derived again from its source with the+ * adopted plugins and drawn by core's MarkdownPluginNodeRenderer, so it+ * renders, falls back, and reports failures exactly as Markdown does (FR8,+ * FR9); stored data is never drawn on its own, and a node its plugin no+ * longer recognizes — or whose plugin is not adopted — shows its source+ * (FR11). Without this plugin a node shows its source.+ */++import {useEffect, useMemo, type ReactNode} from 'react';+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';+import type {Transformer} from '@lexical/markdown';+import {$dfs} from '@lexical/utils';+import {+ $getSelection,+ $isRangeSelection,+ $isTextNode,+ COMMAND_PRIORITY_LOW,+ FORMAT_TEXT_COMMAND,+ HISTORY_MERGE_TAG,+ TEXT_TYPE_TO_FORMAT,+ type LexicalEditor,+ type TextFormatType,+} from 'lexical';+import {MarkdownPluginNodeRenderer} from '@astryxdesign/core/Markdown/plugin-renderer';+import {+ parseInlineAst,+ parseMarkdownAst,+} from '@astryxdesign/core/Markdown/parser';+import type {+ MarkdownExtensionNode,+ MarkdownPluginEntry,+} from '@astryxdesign/core/Markdown/plugins';+import {pluginsOf, type RichTextMarkdownExtension} from './markdownExtensions';+import {+ $isRichTextExtensionNode,+ setRichTextExtensionNodeDecorator,+ type RichTextExtensionNode,+ type RichTextExtensionNodeFacts,+} from './markdownExtensionNode';++/**+ * The node core derives from a stored node's source with `plugins`, or null+ * when no adopted plugin of the same protocol version reads that exact source+ * as that node.+ */+export function deriveExtensionNode(+ facts: RichTextExtensionNodeFacts,+ plugins: ReadonlyArray<MarkdownPluginEntry>,+): MarkdownExtensionNode | null {+ const plugin = plugins.find(entry => entry.name === facts.plugin);+ if (plugin == null || plugin.apiVersion !== facts.apiVersion) {+ return null;+ }+ const nodes: ReadonlyArray<{readonly type: string}> =+ facts.display === 'inline'+ ? parseInlineAst(facts.source, {plugins: [plugin]})+ : parseMarkdownAst(facts.source, {plugins: [plugin]}).children;+ const [node] = nodes;+ if (nodes.length !== 1 || node?.type !== 'extension') {+ return null;+ }+ const extension = node as MarkdownExtensionNode;+ return extension.plugin === facts.plugin &&+ extension.name === facts.name &&+ extension.display === facts.display &&+ extension.source === facts.source+ ? extension+ : null;+}++/**+ * The formats a plugin node can sit inside, outermost first, as RichText draws+ * them around text (textSemantics.ts): a deletion, then emphasis, then strong.+ */+const MARKS: ReadonlyArray<readonly [TextFormatType, 'del' | 'em' | 'strong']> =+ [+ ['strikethrough', 'del'],+ ['italic', 'em'],+ ['bold', 'strong'],+ ];++/** The formats a toggle can put a plugin node inside. */+const NODE_FORMATS: ReadonlySet<TextFormatType> = new Set(+ MARKS.map(([format]) => format),+);++function ExtensionNodeView({+ facts,+ format,+ plugins,+}: {+ facts: RichTextExtensionNodeFacts;+ format: number;+ plugins: ReadonlyArray<MarkdownPluginEntry>;+}): ReactNode {+ const node = useMemo(+ () => deriveExtensionNode(facts, plugins),+ [facts, plugins],+ );+ let content: ReactNode =+ node == null ? (+ facts.source+ ) : (+ <MarkdownPluginNodeRenderer plugins={plugins} node={node} />+ );+ // Inside emphasis, strong, or strikethrough, the node is drawn inside the+ // same elements, as core Markdown draws it inside the text's.+ for (const [type, Tag] of [...MARKS].reverse()) {+ if ((format & TEXT_TYPE_TO_FORMAT[type]) !== 0) {+ content = <Tag>{content}</Tag>;+ }+ }+ return content;+}++/**+ * Marks every plugin node so Lexical draws it again with the decorator the+ * editor has now. Not an edit, so it adds nothing to undo history.+ */+function redrawExtensionNodes(editor: LexicalEditor): void {+ editor.update(+ () => {+ for (const {node} of $dfs()) {+ if ($isRichTextExtensionNode(node)) {+ node.markDirty();+ }+ }+ },+ {tag: HISTORY_MERGE_TAG},+ );+}++export interface MarkdownExtensionsPluginProps {+ extensions: ReadonlyArray<RichTextMarkdownExtension>;+ /** The surface's Markdown transformers, checked against the extensions. */+ transformers: ReadonlyArray<Transformer>;+}++export function MarkdownExtensionsPlugin({+ extensions,+ transformers,+}: MarkdownExtensionsPluginProps): null {+ const [editor] = useLexicalComposerContext();+ const plugins = useMemo(+ () => pluginsOf(extensions, transformers),+ [extensions, transformers],+ );++ useEffect(() => {+ const unset = setRichTextExtensionNodeDecorator(editor, (facts, format) => (+ <ExtensionNodeView facts={facts} format={format} plugins={plugins} />+ ));+ redrawExtensionNodes(editor);+ return () => {+ unset();+ redrawExtensionNodes(editor);+ };+ }, [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.+ useEffect(+ () =>+ editor.registerCommand(+ FORMAT_TEXT_COMMAND,+ format => {+ const selection = $getSelection();+ if (!$isRangeSelection(selection) || !NODE_FORMATS.has(format)) {+ return false;+ }+ const nodes = selection+ .getNodes()+ .filter(+ (node): node is RichTextExtensionNode =>+ $isRichTextExtensionNode(node) && node.isInline(),+ );+ if (nodes.length === 0) {+ return false;+ }+ selection.formatText(format);+ const text = selection.getNodes().find($isTextNode);+ const isOn =+ text != null+ ? text.hasFormat(format)+ : !nodes.every(node => node.hasFormat(format));+ for (const node of nodes) {+ node.setFormatFlag(format, isOn);+ }+ return true;+ },+ COMMAND_PRIORITY_LOW,+ ),+ [editor],+ );++ return null;+}diff --git a/packages/richtext/src/RichTextEditor.doc.mjs b/packages/richtext/src/RichTextEditor.doc.mjsindex 9b4d6a2bc9..1c5d69804a 100644--- a/packages/richtext/src/RichTextEditor.doc.mjs+++ b/packages/richtext/src/RichTextEditor.doc.mjs@@ -112,6 +112,12 @@ export const docs = {'Enable Markdown shortcut typing (e.g. "# " for a heading). Uses the transformers prop (defaults to thematic breaks, the standard @lexical/markdown transformers, hard line breaks, and GFM tables).',default: 'true',},+ {+ name: 'markdownExtensions',+ type: 'ReadonlyArray<RichTextMarkdownExtension>',+ description:+ 'Markdown plugins whose nodes the editor draws, each adopted with createRichTextExtension. A plugin node renders exactly as core Markdown renders it and edits as one unit; a node whose plugin is not given here shows its source. Pass the extensions the content was converted with, and create them in a client module. RichTextView takes the same prop.',+ },{name: 'transformers',type: 'ReadonlyArray<Transformer>',@@ -212,7 +218,7 @@ export const docs = {{guidance: true,description:- "To recognize a Markdown plugin made with createMarkdownPlugin, adopt it with createRichTextExtension(plugin) and pass the result in the extensions option of markdownToEditorStateJSON. Core's parser finds the plugin's syntax, and each node keeps its exact source, which is what it exports; base Markdown inside plugin source stays part of the node. A plugin that declares a transform is refused with a RichTextExtensionError, and so is a configuration that adopts one plugin twice. Without the extension, plugin syntax stays text. createRichTextExtension and the serializers are also exported from @astryxdesign/richtext/markdown for server code.",+ "To recognize a Markdown plugin made with createMarkdownPlugin, adopt it with createRichTextExtension(plugin) and pass the result in the extensions option of markdownToEditorStateJSON. Core's parser finds the plugin's syntax, and each node keeps its exact source, which is what it exports; base Markdown inside plugin source stays part of the node. A plugin that declares a transform is refused with a RichTextExtensionError, and so is a configuration that adopts one plugin twice. Without the extension, plugin syntax stays text. createRichTextExtension and the serializers are also exported from @astryxdesign/richtext/markdown for server code. Pass the same extensions to the markdownExtensions prop of RichTextEditor and RichTextView to draw the nodes: each renders as core Markdown renders it, edits as one unit (the caret steps over it; Backspace, cut, copy, and paste take it whole), and exports its exact source.",},{guidance: true,diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex ec85a67aae..08dc00ed02 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -77,6 +77,8 @@ import {TextSemanticsExtension} from './textSemantics';import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';import {CodeSyntaxPlugin} from './CodeSyntaxPlugin';+import {MarkdownExtensionsPlugin} from './MarkdownExtensionsPlugin';+import type {RichTextMarkdownExtension} from './markdownExtensions';import {TaskCheckboxPlugin} from './TaskCheckboxPlugin';import {type Transformer} from '@lexical/markdown';export type {Transformer} from '@lexical/markdown';@@ -429,6 +431,15 @@ export interface RichTextEditorProps extends Omit<* the serialization APIs added in later phases.*/transformers?: ReadonlyArray<Transformer>;+ /**+ * Markdown plugins whose nodes this surface draws, each adopted with+ * `createRichTextExtension` (spec:AST-064). A plugin node renders exactly as+ * core `Markdown` renders it, and one whose plugin is not given here shows+ * its source. Pass the extensions the content was converted with. Create+ * them in a client module: they hold the plugins' functions, so they are not+ * serializable props.+ */+ markdownExtensions?: ReadonlyArray<RichTextMarkdownExtension>;/** Whether to automatically focus the editor on mount. @default false */hasAutoFocus?: boolean;/**@@ -506,6 +517,7 @@ export const RichTextEditor = forwardRef<plugins,hasMarkdownShortcuts = true,transformers = DEFAULT_TRANSFORMERS,+ markdownExtensions,hasAutoFocus = false,tabEscapeHint = DEFAULT_TAB_ESCAPE_HINT,maxLength,@@ -696,6 +708,12 @@ export const RichTextEditor = forwardRef<<TableColumnFloorPlugin /><CodeBlockHeaderPlugin /><CodeSyntaxPlugin />+ {markdownExtensions != null && markdownExtensions.length > 0 ? (+ <MarkdownExtensionsPlugin+ extensions={markdownExtensions}+ transformers={markdownTransformers}+ />+ ) : null}<TabIndentationPlugin /><TabFocusEscapePlugin />{hasMarkdownShortcuts && (diff --git a/packages/richtext/src/RichTextView.tsx b/packages/richtext/src/RichTextView.tsxindex 953adea722..a78d995061 100644--- a/packages/richtext/src/RichTextView.tsx+++ b/packages/richtext/src/RichTextView.tsx@@ -34,6 +34,8 @@ import {TableScrollRegionPlugin} from './TableScrollRegionPlugin';import {TableColumnFloorPlugin} from './TableColumnFloorPlugin';import {CodeBlockHeaderPlugin} from './CodeBlockHeaderPlugin';import {CodeSyntaxPlugin} from './CodeSyntaxPlugin';+import {MarkdownExtensionsPlugin} from './MarkdownExtensionsPlugin';+import type {RichTextMarkdownExtension} from './markdownExtensions';import {TaskCheckboxPlugin} from './TaskCheckboxPlugin';import type {AnyLexicalExtension,@@ -82,6 +84,9 @@ const VIEW_CONTENT_EDITABLE_PROPS = {role: null as unknown as undefined,} as const;+/** The view imports and exports no Markdown, so it uses no transformers. */+const NO_TRANSFORMERS: ReadonlyArray<never> = [];+export interface RichTextViewProps extends BaseProps {/*** Serialized editor state to render (a JSON string produced by@@ -93,6 +98,15 @@ export interface RichTextViewProps extends BaseProps {* the nodes used to author `value` so custom node types deserialize.*/nodes?: ReadonlyArray<Klass<LexicalNode>>;+ /**+ * Markdown plugins whose nodes this surface draws, each adopted with+ * `createRichTextExtension` (spec:AST-064). A plugin node renders exactly as+ * core `Markdown` renders it, and one whose plugin is not given here shows+ * its source. Pass the extensions the content was converted with. Create+ * them in a client module: they hold the plugins' functions, so they are not+ * serializable props.+ */+ markdownExtensions?: ReadonlyArray<RichTextMarkdownExtension>;/*** Additional read-only plugins to render inside the composer (e.g. hover* cards, decorators).@@ -175,6 +189,7 @@ function SyncValuePlugin({value}: {value: string}): null {export function RichTextView({value,nodes,+ markdownExtensions,plugins,namespace = 'astryx-view',onParseError,@@ -298,6 +313,12 @@ export function RichTextView({in tab order. */}<CodeBlockHeaderPlugin /><CodeSyntaxPlugin />+ {markdownExtensions != null && markdownExtensions.length > 0 ? (+ <MarkdownExtensionsPlugin+ extensions={markdownExtensions}+ transformers={NO_TRANSFORMERS}+ />+ ) : null}<TaskCheckboxPlugin isReadOnly />{plugins}</LexicalExtensionComposer>diff --git a/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts b/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.tsnew file mode 100644index 0000000000..a22c5c7d03--- /dev/null+++ b/packages/richtext/src/__tests__/MarkdownPlugins.a11y.chromium.spec.ts@@ -0,0 +1,255 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MarkdownPlugins.a11y.chromium.spec.ts+ * @input The built Storybook's Lab/RichTextEditor "Markdown plugins" story.+ * @output Real-browser proof for spec:AST-064 FR7 and FR8: a plugin node+ * renders the same DOM and accessibility in core Markdown, RichTextView, and+ * RichTextEditor, and the editor moves over, selects, deletes, restores,+ * copies, and pastes it as one unit.+ *+ * Run after building Storybook:+ * pnpm storybook:build+ * pnpm exec playwright test packages/richtext --project chromium+ */++import AxeBuilder from '@axe-core/playwright';+import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const STORYBOOK_DIR = process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR;+const STORY = 'lab-richtexteditor--markdown-plugins';++let storybook: StaticServer;++test.beforeAll(async () => {+ storybook = await serveStorybook(STORYBOOK_DIR);+});++test.afterAll(async () => {+ await storybook?.close();+});++async function openStory(page: Page): Promise<string[]> {+ const errors: string[] = [];+ page.on('pageerror', error => errors.push(String(error)));+ page.on('console', message => {+ if (message.type() === 'error' && !message.text().includes('404')) {+ errors.push(message.text());+ }+ });+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write'], {+ origin: storybook.origin,+ });+ await page.setViewportSize({width: 1440, height: 900});+ await page.goto(+ `${storybook.origin}/iframe.html?id=${STORY}&viewMode=story&globals=astryxTheme:neutral;colorMode:light;direction:ltr`,+ {waitUntil: 'load'},+ );+ await expect(+ page.locator('[data-plugin-surface="editor"] [data-mention="ada"]'),+ ).toBeVisible();+ return errors;+}++const surface = (page: Page, name: string) =>+ page.locator(`[data-plugin-surface="${name}"]`);++async function markdownOutput(page: Page): Promise<string> {+ await page.getByRole('button', {name: 'Show Markdown'}).click();+ return (await page.locator('[data-markdown-output]').textContent()) ?? '';+}++test('a plugin node renders the same DOM and accessibility in Markdown, the view, and the editor', async ({+ page,+}) => {+ const errors = await openStory(page);+ const html = async (name: string, selector: string) =>+ surface(page, name)+ .locator(selector)+ .first()+ .evaluate(element => element.outerHTML);+ for (const selector of [+ '[data-mention="ada"]',+ '[data-mention="grace"]',+ '[data-note]',+ ]) {+ const expected = await html('markdown', selector);+ expect(await html('view', selector), selector).toBe(expected);+ expect(await html('editor', selector), selector).toBe(expected);+ }+ for (const name of ['markdown', 'view', 'editor']) {+ // A node inside emphasis is drawn inside an emphasis element.+ await expect(+ surface(page, name).locator('em [data-mention="linus"]'),+ ).toHaveCount(1);+ await expect(+ surface(page, name).getByRole('link', {name: '@ada'}),+ ).toHaveAttribute('href', '#people/ada');+ await expect(+ surface(page, name).getByRole('note', {name: 'Note'}),+ ).toHaveText('Ship on Thursday');+ }+ // The node adds no tab stop of its own beyond the plugin's link.+ const decorators = surface(page, 'editor').locator(+ '[data-lexical-decorator="true"]',+ );+ for (const tabIndex of await decorators.evaluateAll(elements =>+ elements.map(element => element.getAttribute('tabindex')),+ )) {+ expect(tabIndex).toBeNull();+ }+ expect(errors).toEqual([]);+});++/**+ * Puts the caret `steps` arrow presses from the start of the editor's first+ * line, extending the selection when `extend` is set.+ */+async function caretAt(+ page: Page,+ steps: number,+ extend = false,+): Promise<void> {+ await surface(page, 'editor')+ .locator('[contenteditable="true"]')+ .getByText('Ping', {exact: false})+ .first()+ .click();+ await page.keyboard.press('Home');+ for (let index = 0; index < steps; index++) {+ await page.keyboard.press(extend ? 'Shift+ArrowRight' : 'ArrowRight');+ }+}++/**+ * Waits until the editor's own selection holds `text`. The editor formats and+ * copies its selection, which follows the browser's a moment after each key.+ */+async function expectEditorSelection(page: Page, text: string): Promise<void> {+ await expect+ .poll(() =>+ surface(page, 'editor')+ .locator('[contenteditable="true"]')+ .evaluate(root => {+ const editor = (+ root as HTMLElement & {+ __lexicalEditor?: {+ getEditorState(): {+ read<T>(fn: () => T): T;+ _selection: {getTextContent(): string} | null;+ };+ };+ }+ ).__lexicalEditor;+ const state = editor?.getEditorState();+ return state?.read(() => state._selection?.getTextContent());+ }),+ )+ .toBe(text);+}++test('the editor moves over, deletes, and restores a plugin node as one unit', async ({+ page,+}) => {+ const errors = await openStory(page);+ const mention = surface(page, 'editor').locator('[data-mention="ada"]');+ // "Ping " is five steps; one more crosses the whole node.+ await caretAt(page, 6);+ await page.keyboard.type('X');+ expect(await markdownOutput(page)).toContain('Ping @{ada}X about');+ await caretAt(page, 7);+ // Backspace removes the X, then the whole node in one press.+ await page.keyboard.press('Backspace');+ await expect(mention).toHaveCount(1);+ await page.keyboard.press('Backspace');+ await expect(mention).toHaveCount(0);+ expect(await markdownOutput(page)).toContain('Ping about');+ await surface(page, 'editor').locator('[contenteditable="true"]').focus();+ await page.keyboard.press('ControlOrMeta+z');+ await expect(mention).toHaveCount(1);+ expect(await markdownOutput(page)).toContain('Ping @{ada} about');+ expect(errors).toEqual([]);+});++test('italic toggled on a range takes the plugin node in it along', async ({+ page,+}) => {+ const errors = await openStory(page);+ const mention = surface(page, 'editor').locator('[data-mention="ada"]');+ const italic = surface(page, 'editor').getByRole('button', {name: 'Italic'});+ // Select "Ping " and the node, then make them italic.+ await caretAt(page, 6, true);+ await expectEditorSelection(page, 'Ping @{ada}');+ await italic.click();+ await expect(+ surface(page, 'editor').locator('em [data-mention="ada"]'),+ ).toHaveCount(1);+ expect(await markdownOutput(page)).toContain('*Ping @{ada}* about');+ // And back.+ await caretAt(page, 6, true);+ await expectEditorSelection(page, 'Ping @{ada}');+ await italic.click();+ await expect(+ surface(page, 'editor').locator('em [data-mention="ada"]'),+ ).toHaveCount(0);+ await expect(mention).toHaveCount(1);+ 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,+}) => {+ const errors = await openStory(page);+ // Select "Ping " and the node, then copy them.+ await caretAt(page, 6, true);+ await expectEditorSelection(page, 'Ping @{ada}');+ await page.keyboard.press('ControlOrMeta+c');+ for (const [name, drawn] of [+ ['paste-with', true],+ ['paste-without', false],+ ] as const) {+ await surface(page, name).locator('[contenteditable="true"]').click();+ await page.keyboard.press('ControlOrMeta+v');+ if (drawn) {+ await expect(+ surface(page, name).locator('[data-mention="ada"]'),+ ).toHaveCount(1);+ } else {+ await expect(+ surface(page, name).locator('[data-lexical-decorator="true"]'),+ ).toHaveText('@{ada}');+ }+ }+ expect(await markdownOutput(page)).toContain('---\nPing @{ada}');+ expect(errors).toEqual([]);+});++// The repository's Storybook audit runs axe with these exemptions; the same+// note on three surfaces must not make three identical landmarks.+const AXE_DISABLED_RULES = [+ 'html-has-lang',+ 'document-title',+ 'landmark-one-main',+ 'page-has-heading-one',+ 'region',+];++test('the story has no axe violations, landmarks included', async ({page}) => {+ const errors = await openStory(page);+ const results = await new AxeBuilder({page})+ .disableRules(AXE_DISABLED_RULES)+ .analyze();+ expect(+ results.violations.map(violation => [+ violation.id,+ violation.nodes.map(node => node.target.join(' ')),+ ]),+ ).toEqual([]);+ expect(errors).toEqual([]);+});diff --git a/packages/richtext/src/editorTheme.ts b/packages/richtext/src/editorTheme.tsindex f2719143f3..619ebb5974 100644--- a/packages/richtext/src/editorTheme.ts+++ b/packages/richtext/src/editorTheme.ts@@ -411,6 +411,9 @@ export function sharedEditorTheme(): EditorThemeClasses {stylex.props(style).className ?? '';return {paragraph: block(editorTheme.paragraph),+ // A Markdown plugin's block node is spaced and measured as a paragraph,+ // as core Markdown spaces its block (RichTextExtensionNode reads it).+ markdownExtensionBlock: block(editorTheme.paragraph),heading: {h1: block(editorTheme.h1),h2: block(editorTheme.h2),diff --git a/packages/richtext/src/markdownExtensionNode.ts b/packages/richtext/src/markdownExtensionNode.tsindex 6d24c6423b..598dd9cd03 100644--- a/packages/richtext/src/markdownExtensionNode.ts+++ b/packages/richtext/src/markdownExtensionNode.ts@@ -13,13 +13,18 @@* FR10). Stored state keeps that source, the plugin's name and protocol* version, the data the plugin derived for rendering (FR11), and the text* formats the node sits inside, so a node inside emphasis, strong, or- * strikethrough stays inside it. Imports no React.+ * strikethrough stays inside it. Imports no React: the client surfaces+ * register how an editor draws plugin nodes.*/import {DecoratorNode,TEXT_TYPE_TO_FORMAT,+ type DOMConversionMap,+ type DOMConversionOutput,+ type DOMExportOutput,type EditorConfig,+ type LexicalEditor,type LexicalNode,type NodeKey,type SerializedLexicalNode,@@ -61,6 +66,71 @@ 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.+ */+export type RichTextExtensionNodeDecorator = (+ facts: RichTextExtensionNodeFacts,+ format: number,+) => unknown;++const decorators = new WeakMap<LexicalEditor, RichTextExtensionNodeDecorator>();++/** Sets how `editor` draws plugin nodes; returns a function that unsets it. */+export function setRichTextExtensionNodeDecorator(+ editor: LexicalEditor,+ decorator: RichTextExtensionNodeDecorator,+): () => void {+ decorators.set(editor, decorator);+ return () => {+ if (decorators.get(editor) === decorator) {+ decorators.delete(editor);+ }+ };+}++/**+ * The attribute that carries a node's facts and formats in its element, so+ * copying it as HTML — the browser's own copy, or the editor's HTML export —+ * and pasting it into any RichText editor brings back the same node with the+ * same source and marks.+ */+const FACTS_ATTRIBUTE = 'data-markdown-extension';++function factsAttribute(node: RichTextExtensionNode): string {+ return JSON.stringify({...node.__facts, format: node.__format});+}++function convertExtensionElement(element: HTMLElement): DOMConversionOutput {+ let node: RichTextExtensionNode | null = null;+ try {+ const parsed: unknown = JSON.parse(+ element.getAttribute(FACTS_ATTRIBUTE) ?? '',+ );+ if (parsed != null && typeof parsed === 'object') {+ const value = parsed as Record<string, unknown>;+ node = $createRichTextExtensionNode(+ factsFrom(value),+ typeof value.format === 'number' ? value.format : 0,+ );+ }+ } catch {+ node = null;+ }+ return {+ node,+ // The element's content is the node's rendering, not more document.+ forChild: () => null,+ };+}++const importExtensionElement = (element: HTMLElement) =>+ element.hasAttribute(FACTS_ATTRIBUTE)+ ? {conversion: convertExtensionElement, priority: 4 as const}+ : null;+export class RichTextExtensionNode extends DecoratorNode<unknown> {__facts: RichTextExtensionNodeFacts;/**@@ -88,6 +158,10 @@ export class RichTextExtensionNode extends DecoratorNode<unknown> {).updateFromJSON(serialized);}+ static importDOM(): DOMConversionMap {+ return {span: importExtensionElement, div: importExtensionElement};+ }+constructor(facts: RichTextExtensionNodeFacts, format = 0, key?: NodeKey) {super(key);this.__facts = facts;@@ -132,13 +206,35 @@ export class RichTextExtensionNode extends DecoratorNode<unknown> {return writable;}- createDOM(_config: EditorConfig): HTMLElement {- return document.createElement(- this.__facts.display === 'block' ? 'div' : 'span',+ createDOM(config: EditorConfig): HTMLElement {+ const element = document.createElement(+ this.__facts.display === 'inline' ? 'span' : 'div',+ );+ element.setAttribute(FACTS_ATTRIBUTE, factsAttribute(this));+ if (this.__facts.display === 'block') {+ // A block node is spaced and measured as Markdown spaces its block.+ const className: unknown = config.theme.markdownExtensionBlock;+ if (typeof className === 'string' && className !== '') {+ element.className = className;+ }+ }+ return element;+ }++ exportDOM(): DOMExportOutput {+ const element = document.createElement(+ this.__facts.display === 'inline' ? 'span' : 'div',);+ element.setAttribute(FACTS_ATTRIBUTE, factsAttribute(this));+ element.textContent = this.__facts.source;+ return {element};}- updateDOM(): false {+ updateDOM(prevNode: RichTextExtensionNode, dom: HTMLElement): false {+ // A mark toggled on the node changes what its element carries.+ if (prevNode.__format !== this.__format) {+ dom.setAttribute(FACTS_ATTRIBUTE, factsAttribute(this));+ }return false;}@@ -151,9 +247,11 @@ export class RichTextExtensionNode extends DecoratorNode<unknown> {return this.getLatest().__facts.source;}- /** Until a surface draws plugin nodes, a node shows its source. */- decorate(): unknown {- return this.__facts.source;+ decorate(editor: LexicalEditor): unknown {+ return (+ decorators.get(editor)?.(this.__facts, this.__format) ??+ this.__facts.source+ );}}diff --git a/packages/richtext/src/markdownExtensions.test.ts b/packages/richtext/src/markdownExtensions.test.tsindex 36edc5234f..eedf261a9e 100644--- a/packages/richtext/src/markdownExtensions.test.ts+++ b/packages/richtext/src/markdownExtensions.test.ts@@ -5,7 +5,8 @@ import {dirname, join, resolve} from 'node:path';import {fileURLToPath} from 'node:url';import {describe, expect, it} from 'vitest';import {createHeadlessEditor} from '@lexical/headless';-import {$getRoot, $isTextNode} from 'lexical';+import {$generateHtmlFromNodes, $generateNodesFromDOM} from '@lexical/html';+import {$getRoot, $insertNodes, $isTextNode} from 'lexical';import {createMarkdownPlugin,type MarkdownExtensionNode,@@ -19,7 +20,10 @@ import {RichTextExtensionError,} from './markdown';import {DEFAULT_NODES} from './editorNodes';-import {RichTextExtensionNode} from './markdownExtensionNode';+import {+ $isRichTextExtensionNode,+ RichTextExtensionNode,+} from './markdownExtensionNode';import {$exportMarkdownKeepingSource,importMarkdownKeepingSource,@@ -618,6 +622,59 @@ describe('placement cost', () => {});});+describe('plugin nodes as HTML (spec:AST-064 FR7)', () => {+ it('come back as the same nodes, with the same source, from the HTML they copy as', () => {+ const editorWith = () =>+ createHeadlessEditor({+ nodes: [...DEFAULT_NODES],+ onError(error) {+ throw error;+ },+ });+ const source = editorWith();+ importMarkdownKeepingSource(+ source,+ 'Hi @{ada}.\n\n:::note\nBody **bold**\n:::\n',+ [...DEFAULT_TRANSFORMERS],+ PLUGINS,+ );+ const html = source+ .getEditorState()+ .read(() => $generateHtmlFromNodes(source, null));+ const target = editorWith();+ target.update(+ () => {+ const dom = new DOMParser().parseFromString(html, 'text/html');+ $getRoot().clear().select();+ $insertNodes($generateNodesFromDOM(target, dom));+ },+ {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()),+ );+ expect(facts(target)).toEqual(facts(source));+ expect(facts(source).map(({source: text}) => text)).toEqual([+ '@{ada}',+ ':::note\nBody **bold**\n:::',+ ]);+ });+});+describe('@astryxdesign/richtext/markdown (spec:AST-064 FR3, FR12)', () => {it('imports no React, DOM, or client module', () => {const here = dirname(fileURLToPath(import.meta.url));