An open source design system that's fully customizable and agent ready
TypeScript
fix(richtext): an image's Markdown comes back as written through an edit (#10356)
Cindy Zhangd75edc1306a4
diff --git a/.changeset/richtext-image-source-through-edits.md b/.changeset/richtext-image-source-through-edits.mdnew file mode 100644index 0000000000..6c28ed9bb7--- /dev/null+++ b/.changeset/richtext-image-source-through-edits.md@@ -0,0 +1,7 @@+---+'@astryxdesign/richtext': patch+---++[fix] RichText: an image in Markdown, inline (``) or by reference (`![alt][ref]`), comes back exactly as written after you edit the text around it; a shortcut reference image (`![alt]`) followed directly by a link is written in its collapsed form (`![alt][]`), so the link stays a link. Before, an edit in an image's paragraph could escape its brackets (`!\[\](…)`), so other Markdown readers saw text instead of an image. RichText has no image node: an image shows as its Markdown source, one token that Backspace deletes whole and autolinking leaves alone. A caret placed inside it moves to its edge, so typing adds text beside the image instead of replacing it. Copying it, or splitting or joining its paragraph, keeps the source.++@cixzhangdiff --git a/apps/storybook/stories/RichTextEditor.stories.tsx b/apps/storybook/stories/RichTextEditor.stories.tsxindex 788a87762d..8be5bbb65a 100644--- a/apps/storybook/stories/RichTextEditor.stories.tsx+++ b/apps/storybook/stories/RichTextEditor.stories.tsx@@ -308,6 +308,55 @@ export const ControlledPersistence = {},};+const IMAGE_SOURCE_MARKDOWN = [+ 'Chart:  and  above.',+ '',+ '',+ '',+ 'Type in this paragraph.',+ '',+].join('\n');++/**+ * RichText has no image node: an image shows as its Markdown source, one token+ * that is deleted whole, and getMarkdown() writes it back as written through+ * any edit around it (spec:AST-062 FR5). The readout updates as you type.+ */+export const ImageSourceThroughEdits = {+ render: () => {+ const ref = useRef<RichTextEditorRef>(null);+ const [seed] = useState(() =>+ markdownToEditorStateJSON(IMAGE_SOURCE_MARKDOWN),+ );+ const [markdown, setMarkdown] = useState(IMAGE_SOURCE_MARKDOWN);+ return (+ <div style={{display: 'grid', gap: 16, maxWidth: 640}}>+ <RichTextEditor+ ref={ref}+ label="Notes with images"+ defaultValue={seed}+ plugins={<RichTextEditorAutoLinkPlugin />}+ onChange={() => setMarkdown(ref.current?.getMarkdown() ?? '')}+ />+ <pre+ data-image-source-readout+ style={{+ background: 'var(--color-background-muted)',+ color: 'var(--color-text-primary)',+ padding: 12,+ borderRadius: 6,+ fontSize: 13,+ whiteSpace: 'pre-wrap',+ wordBreak: 'break-word',+ margin: 0,+ }}>+ {markdown}+ </pre>+ </div>+ );+ },+};+export const ImperativeRef = {render: () => {const ref = useRef<RichTextEditorRef>(null);diff --git a/packages/richtext/src/ImageSourceCaretPlugin.tsx b/packages/richtext/src/ImageSourceCaretPlugin.tsxnew file mode 100644index 0000000000..eb909f1d7b--- /dev/null+++ b/packages/richtext/src/ImageSourceCaretPlugin.tsx@@ -0,0 +1,159 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file ImageSourceCaretPlugin.tsx+ * @input Uses @lexical/react (composer context), lexical (selection, the+ * selection-change and text-insertion commands, the root element), and+ * $isImageSource from markdownCharacterReferences.ts.+ * @output Exports ImageSourceCaretPlugin.+ * @position Rendered by RichTextEditor, always on. Lexical replaces a whole+ * token with text typed inside it. So a caret inside an image's source+ * moves to an edge: past the image for an arrow key, to the nearer edge+ * for a click or any other move.+ */++import {useEffect} from 'react';+import {useLexicalComposerContext} from '@lexical/react/LexicalComposerContext';+import {mergeRegister} from '@lexical/utils';+import {+ $getNodeByKey,+ $getSelection,+ $isRangeSelection,+ COMMAND_PRIORITY_CRITICAL,+ CONTROLLED_TEXT_INSERTION_COMMAND,+ SELECTION_CHANGE_COMMAND,+ type LexicalEditor,+ type NodeKey,+ type TextNode,+} from 'lexical';+import {$isImageSource} from './markdownCharacterReferences';++interface CaretPoint {+ readonly key: NodeKey;+ readonly offset: number;+}++/** The collapsed caret, when it is in text. */+function $caretPoint(): CaretPoint | null {+ const selection = $getSelection();+ return $isRangeSelection(selection) &&+ selection.isCollapsed() &&+ selection.anchor.type === 'text'+ ? {key: selection.anchor.key, offset: selection.anchor.offset}+ : null;+}++/**+ * The edge of `token` a caret at `offset` inside it moves to. An arrow key+ * that moved the caret in from one edge, or from the text beside it, moves+ * it on to the other edge.+ */+function $edgeFor(+ token: TextNode,+ offset: number,+ arrowFrom: CaretPoint | null,+): number {+ const size = token.getTextContentSize();+ const nearer = offset < size / 2 ? 0 : size;+ if (arrowFrom == null) {+ return nearer;+ }+ if (arrowFrom.key === token.getKey()) {+ return arrowFrom.offset === 0+ ? size+ : arrowFrom.offset === size+ ? 0+ : nearer;+ }+ const before = token.getPreviousSibling();+ if (+ before != null &&+ before.getKey() === arrowFrom.key &&+ arrowFrom.offset === before.getTextContentSize()+ ) {+ return size;+ }+ const after = token.getNextSibling();+ if (+ after != null &&+ after.getKey() === arrowFrom.key &&+ arrowFrom.offset === 0+ ) {+ return 0;+ }+ return nearer;+}++/** Moves a collapsed caret inside an image's source to an edge of it. */+function $moveCaretOutOfImage(arrowFrom: CaretPoint | null): void {+ const caret = $caretPoint();+ if (caret == null) {+ return;+ }+ const node = $getNodeByKey<TextNode>(caret.key);+ if (+ node == null ||+ !$isImageSource(node) ||+ caret.offset === 0 ||+ caret.offset === node.getTextContentSize()+ ) {+ return;+ }+ const edge = $edgeFor(node, caret.offset, arrowFrom);+ const selection = $getSelection();+ if ($isRangeSelection(selection)) {+ selection.anchor.set(caret.key, edge, 'text');+ selection.focus.set(caret.key, edge, 'text');+ }+}++function registerImageSourceCaret(editor: LexicalEditor): () => void {+ // Where the caret was when an arrow key went down; the next selection+ // change reads it once. A press is a click, never an arrow key.+ let arrowFrom: CaretPoint | null = null;+ const onKeyDown = (event: KeyboardEvent) => {+ arrowFrom =+ event.key === 'ArrowLeft' || event.key === 'ArrowRight'+ ? editor.getEditorState().read($caretPoint)+ : null;+ };+ const onPointerDown = () => {+ arrowFrom = null;+ };+ return mergeRegister(+ editor.registerRootListener((root, previousRoot) => {+ previousRoot?.removeEventListener('keydown', onKeyDown, true);+ previousRoot?.removeEventListener('pointerdown', onPointerDown, true);+ root?.addEventListener('keydown', onKeyDown, true);+ root?.addEventListener('pointerdown', onPointerDown, true);+ }),+ editor.registerCommand(+ SELECTION_CHANGE_COMMAND,+ () => {+ $moveCaretOutOfImage(arrowFrom);+ arrowFrom = null;+ return false;+ },+ COMMAND_PRIORITY_CRITICAL,+ ),+ // A key typed before the browser reports a caret move reaches the editor+ // with the caret still inside the source.+ editor.registerCommand(+ CONTROLLED_TEXT_INSERTION_COMMAND,+ () => {+ $moveCaretOutOfImage(null);+ return false;+ },+ COMMAND_PRIORITY_CRITICAL,+ ),+ );+}++/** Keeps a collapsed caret out of the text holding an image's source. */+export function ImageSourceCaretPlugin(): null {+ const [editor] = useLexicalComposerContext();+ useEffect(() => registerImageSourceCaret(editor), [editor]);+ return null;+}diff --git a/packages/richtext/src/RichTextEditor.tsx b/packages/richtext/src/RichTextEditor.tsxindex 92c52460df..04e4744a32 100644--- a/packages/richtext/src/RichTextEditor.tsx+++ b/packages/richtext/src/RichTextEditor.tsx@@ -84,6 +84,7 @@ import type {RichTextMarkdownExtension} from './markdownExtensions';import type {CodeLanguage} from '@astryxdesign/core/CodeBlock';import {TaskCheckboxPlugin} from './TaskCheckboxPlugin';import {SelectAllScopePlugin} from './SelectAllScopePlugin';+import {ImageSourceCaretPlugin} from './ImageSourceCaretPlugin';import {type Transformer} from '@lexical/markdown';import {$generateHtmlFromNodes} from '@lexical/html';import {DEFAULT_NODES} from './editorNodes';@@ -732,6 +733,7 @@ export const RichTextEditor = function RichTextEditor({<TabIndentationPlugin /><TabFocusEscapePlugin /><SelectAllScopePlugin />+ <ImageSourceCaretPlugin />{hasMarkdownShortcuts && (<MarkdownShortcutPlugin transformers={markdownTransformers} />)}diff --git a/packages/richtext/src/markdownCharacterReferences.ts b/packages/richtext/src/markdownCharacterReferences.tsindex 256000bba5..4e35c1d0d0 100644--- a/packages/richtext/src/markdownCharacterReferences.ts+++ b/packages/richtext/src/markdownCharacterReferences.ts@@ -32,8 +32,11 @@ import {$isLinkNode} from '@lexical/link';import {$isTableCellNode} from '@lexical/table';import {$dfs, $findMatchingParent} from '@lexical/utils';import {+ $getState,$isElementNode,$isTextNode,+ $setState,+ createState,type ElementNode,type LexicalNode,} from 'lexical';@@ -486,6 +489,138 @@ export function protectRefusedLinks(markdown: string): ProtectedMarkdown {return {markdown: output + markdown.slice(copied), standIns};}+/**+ * Marks text that holds one image's Markdown source. Export writes it+ * unescaped, so it stays an image.+ */+const imageSourceState = createState('astryxMdImage', {+ parse: (value: unknown): boolean => value === true,+});++/** Whether `node` is text that holds an image's Markdown source. */+export function $isImageSource(node: LexicalNode): boolean {+ return $isTextNode(node) && $getState(node, imageSourceState);+}++/**+ * Returns `markdown` with every image outside code replaced by a private-use+ * stand-in, and the source each stand-in replaced. An image starts with a `!`+ * that is not escaped and the paired brackets of its text. An inline image+ * (``) ends with the destination and title that close it, read whole+ * by core's inline parser. A reference image (`![a][b]`, `![a][]`, `![a]`)+ * ends with its label; its definition can sit in another block, so it is kept+ * whether or not one exists. A link around an image keeps its own brackets,+ * so the image stays inside the link's text.+ */+export function protectImages(markdown: string): {+ readonly markdown: string;+ readonly images: ReadonlyMap<string, string>;+} {+ const images = new Map<string, string>();+ if (!markdown.includes('![')) {+ return {markdown, images};+ }+ const pair = pairedDelimiters(markdown, codeRanges(markdown));+ const found: Array<{readonly start: number; readonly end: number}> = [];+ for (+ let start = markdown.indexOf('![');+ start !== -1;+ start = markdown.indexOf('![', start + 1)+ ) {+ const open = start + 1;+ const textClose = pair[open];+ if (textClose === -1 || textClose < open) {+ continue;+ }+ // An image inside another image's text belongs to the outer one.+ if (found.length > 0 && start < found[found.length - 1].end) {+ continue;+ }+ let backslashes = 0;+ while (markdown[start - 1 - backslashes] === '\\') {+ backslashes++;+ }+ if (backslashes % 2 === 1) {+ continue;+ }+ const after = markdown[textClose + 1];+ if (after === '(') {+ const angleClose = angleDestinationEnd(markdown, textClose + 1);+ const close =+ typeof angleClose === 'number' ? angleClose : pair[textClose + 1];+ if (close === -1 || angleClose === 'refused') {+ continue;+ }+ const [only, ...rest] = parseInlineAst(markdown.slice(start, close + 1));+ if (rest.length > 0 || only?.type !== 'image') {+ continue;+ }+ found.push({start, end: close + 1});+ } else if (after === '[' && pair[textClose + 1] > textClose + 1) {+ found.push({start, end: pair[textClose + 1] + 1});+ } else {+ found.push({start, end: textClose + 1});+ }+ }+ if (found.length === 0) {+ return {markdown, images};+ }+ const available = absentCharacters(markdown);+ let output = '';+ let copied = 0;+ for (const {start, end} of found) {+ const next = available.next();+ if (next.done === true) {+ break;+ }+ images.set(next.value, markdown.slice(start, end));+ output += markdown.slice(copied, start) + next.value;+ copied = end;+ }+ return {markdown: output + markdown.slice(copied), images};+}++/**+ * Puts each image's source back where its stand-in sits under `node`, as+ * text marked as an image's source. The text is a token: a person deletes it+ * whole, and autolinking leaves its URL alone. ImageSourceCaretPlugin keeps+ * the caret out of it, so typing never replaces it.+ */+export function $restoreImages(+ node: ElementNode,+ images: ReadonlyMap<string, string>,+): void {+ if (images.size === 0) {+ return;+ }+ for (const text of node.getAllTextNodes()) {+ const content = text.getTextContent();+ const offsets: number[] = [];+ let offset = 0;+ for (const character of content) {+ if (images.has(character)) {+ offsets.push(offset, offset + character.length);+ }+ offset += character.length;+ }+ if (offsets.length === 0) {+ continue;+ }+ const pieces = text.splitText(+ ...offsets.filter(point => point > 0 && point < content.length),+ );+ for (const piece of pieces) {+ const source = images.get(piece.getTextContent());+ if (source == null) {+ continue;+ }+ piece.setTextContent(source);+ piece.setMode('token');+ $setState(piece, imageSourceState, true);+ }+ }+}+/*** Takes every link under `node` whose URL core Markdown refuses out of its* link, leaving its text in place, so no form of link text or destinationdiff --git a/packages/richtext/src/markdownCodeSpans.test.ts b/packages/richtext/src/markdownCodeSpans.test.tsindex 1991e90dfe..27f34dee9c 100644--- a/packages/richtext/src/markdownCodeSpans.test.ts+++ b/packages/richtext/src/markdownCodeSpans.test.ts@@ -246,7 +246,6 @@ describe("backticks in a link destination or title are the link's", () => {it.each(['[a](`x`)','[a](https://e.com/`x`)',- '','[a](b "`t`")','`c` then [a](`x`)',])('reads %j with the destination core reads', markdown => {diff --git a/packages/richtext/src/markdownImages.test.tsx b/packages/richtext/src/markdownImages.test.tsxnew file mode 100644index 0000000000..000f92a7a6--- /dev/null+++ b/packages/richtext/src/markdownImages.test.tsx@@ -0,0 +1,386 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';+import {render, waitFor} from '@testing-library/react';+import {createRef} from 'react';+import {createHeadlessEditor} from '@lexical/headless';+import {+ $createTextNode,+ $getRoot,+ $isElementNode,+ $isRangeSelection,+ $isTextNode,+ $parseSerializedNode,+ $getSelection,+ type TextNode,+ CONTROLLED_TEXT_INSERTION_COMMAND,+ SELECTION_CHANGE_COMMAND,+} from 'lexical';+import {$createLinkNode} from '@lexical/link';+import {DEFAULT_NODES} from './editorNodes';+import {RichTextEditor, type RichTextEditorRef} from './RichTextEditor';+import {RichTextEditorAutoLinkPlugin} from './RichTextEditorAutoLinkPlugin';+import {+ editorStateJSONToMarkdown,+ markdownToEditorStateJSON,+} from './markdownSerializers';++/**+ * Image Markdown is source RichText cannot show as a structure+ * (spec:AST-062 FR5). An edit beside it must not change it (FR2), and an edit+ * in its own paragraph must keep every character of it (FR5), so another+ * client still reads an image.+ */++function editAndExport(markdown: string, edit: () => void): string {+ const editor = createHeadlessEditor({+ namespace: 'astryx-markdown-images-test',+ nodes: [...DEFAULT_NODES],+ onError(error: Error) {+ throw error;+ },+ });+ editor.setEditorState(+ editor.parseEditorState(markdownToEditorStateJSON(markdown)),+ );+ editor.update(edit, {discrete: true});+ return editorStateJSONToMarkdown(+ JSON.stringify(editor.getEditorState().toJSON()),+ );+}++/** Types `text` at the end of the first block containing `needle`. */+function $appendToBlockContaining(needle: string, text: string): void {+ const block = $getRoot()+ .getChildren()+ .find(candidate => candidate.getTextContent().includes(needle));+ if (!$isElementNode(block)) {+ throw new Error(`no block contains ${needle}`);+ }+ block.append($createTextNode(text));+}++/** The text node holding the image source `image`. */+function $imageText(image: string): TextNode {+ const node = $getRoot()+ .getAllTextNodes()+ .find(candidate => candidate.getTextContent() === image);+ if (node == null) {+ throw new Error(`no text holds ${image}`);+ }+ return node;+}++const IMAGES = {+ named: '',+ emptyAlt: '',+ titled: '',+ quotedTitle: `")`,+ angleDestination: "",+};++describe('image Markdown through edits (spec:AST-062)', () => {+ for (const [name, image] of Object.entries(IMAGES)) {+ it(`keeps a ${name} image on its own line when the next paragraph changes (FR2)`, () => {+ const source = `${image}\n\nEdit me\n`;+ expect(+ editAndExport(source, () =>+ $appendToBlockContaining('Edit me', ' now'),+ ),+ ).toBe(`${image}\n\nEdit me now\n`);+ });++ it(`keeps a ${name} image inline when the paragraph beside it changes (FR2)`, () => {+ const source = `Before ${image} after\n\nEdit me\n`;+ expect(+ editAndExport(source, () =>+ $appendToBlockContaining('Edit me', ' now'),+ ),+ ).toBe(`Before ${image} after\n\nEdit me now\n`);+ });++ it(`keeps every character of a ${name} image when its own paragraph changes (FR5)`, () => {+ const source = `Before ${image} after\n`;+ expect(+ editAndExport(source, () => $appendToBlockContaining('after', ' now')),+ ).toBe(`Before ${image} after now\n`);+ });++ it(`keeps every character of a ${name} image on its own line when text is added after it (FR5)`, () => {+ const source = `${image}\n`;+ expect(+ editAndExport(source, () =>+ $appendToBlockContaining('chart', ' caption'),+ ),+ ).toBe(`${image} caption\n`);+ });+ }++ it.each([+ ['full', '![A chart][chart]'],+ ['collapsed', '![chart][]'],+ ['shortcut', '![chart]'],+ ])(+ 'keeps a %s reference image as written when its paragraph changes (FR5)',+ (_form, image) => {+ const source = `Before ${image} after\n\n[chart]: https://example.com/chart.png\n`;+ expect(+ editAndExport(source, () => $appendToBlockContaining('Before', ' now')),+ ).toBe(+ `Before ${image} after now\n\n[chart]: https://example.com/chart.png\n`,+ );+ },+ );++ it('keeps an image inside a link, and the link around it, through an edit (FR5)', () => {+ const badge =+ '[](https://example.com/ci)';+ expect(+ editAndExport(`${badge} status\n`, () =>+ $appendToBlockContaining('status', ' now'),+ ),+ ).toBe(`${badge} status now\n`);+ });++ it('leaves an escaped image marker and an image in code as they were (FR3)', () => {+ const source =+ '\\ and ``\n';+ expect(+ editAndExport(source, () => $appendToBlockContaining('code', ' now')),+ ).toBe(+ '\\ and `` now\n',+ );+ });++ it('shows an image as its source text, one token a person deletes whole (FR5)', () => {+ const state = JSON.parse(+ markdownToEditorStateJSON(`Before ${IMAGES.emptyAlt} after\n`),+ ) as {+ root: {+ children: Array<{children: Array<{text?: string; mode?: string}>}>;+ };+ };+ const texts = state.root.children[0].children;+ expect(texts.map(node => node.text)).toEqual([+ 'Before ',+ IMAGES.emptyAlt,+ ' after',+ ]);+ expect(texts[1].mode).toBe('token');+ });++ it('copies an image within the editor as the same source (FR5)', () => {+ const source = `Before ${IMAGES.titled} after\n\nTarget\n`;+ expect(+ editAndExport(source, () => {+ const copy = $parseSerializedNode(+ $imageText(IMAGES.titled).exportJSON(),+ );+ const target = $getRoot().getChildren()[1];+ if (!$isElementNode(target)) {+ throw new Error('no target paragraph');+ }+ target.append($createTextNode(' '), copy);+ }),+ ).toBe(`Before ${IMAGES.titled} after\n\nTarget ${IMAGES.titled}\n`);+ });++ it('deletes an image whole when a selection takes part of it, and keeps the text around it (FR5)', () => {+ const source = `Before ${IMAGES.named} after\n`;+ expect(+ editAndExport(source, () => {+ const image = $imageText(IMAGES.named);+ const after = image.getNextSibling();+ if (!$isTextNode(after)) {+ throw new Error('no text after the image');+ }+ const selection = image.select(5, 5);+ selection.focus.set(after.getKey(), 0, 'text');+ selection.removeText();+ }),+ ).toBe('Before after\n');+ });++ it('keeps an image whole when Enter splits its paragraph before or after it (FR5)', () => {+ const source = `Before ${IMAGES.emptyAlt} after\n`;+ const splitAt = (atStart: boolean) =>+ editAndExport(source, () => {+ const image = $imageText(IMAGES.emptyAlt);+ const neighbour = atStart+ ? image.getPreviousSibling()+ : image.getNextSibling();+ if (!$isTextNode(neighbour)) {+ throw new Error('no text beside the image');+ }+ if (atStart) {+ neighbour.selectEnd();+ } else {+ neighbour.selectStart();+ }+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) {+ throw new Error('no range selection');+ }+ selection.insertParagraph();+ });+ expect(splitAt(true)).toBe(`Before \n\n${IMAGES.emptyAlt} after\n`);+ expect(splitAt(false)).toBe(`Before ${IMAGES.emptyAlt}\n\n after\n`);+ });++ it('keeps an image whole when its paragraph joins the one before (FR5)', () => {+ const source = `Lead\n\n${IMAGES.emptyAlt} after\n`;+ expect(+ editAndExport(source, () => {+ const [lead, imageParagraph] = $getRoot().getChildren();+ if (!$isElementNode(lead) || !$isElementNode(imageParagraph)) {+ throw new Error('no paragraphs');+ }+ lead.append($createTextNode(' '), ...imageParagraph.getChildren());+ imageParagraph.remove();+ }),+ ).toBe(`Lead ${IMAGES.emptyAlt} after\n`);+ });++ it('moves a caret placed inside an image to its edge, so typing adds text beside it (FR5)', async () => {+ const markdown = `Before ${IMAGES.titled} after\n`;+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor+ label="Notes"+ ref={ref}+ defaultValue={markdownToEditorStateJSON(markdown)}+ plugins={<RichTextEditorAutoLinkPlugin />}+ />,+ );+ await waitFor(() => expect(ref.current?.getEditor()).toBeTruthy());+ const editor = ref.current!.getEditor()!;+ const typeAt = (offset: number, text: string) => {+ editor.update(+ () => {+ $imageText(IMAGES.titled).select(offset, offset);+ },+ {discrete: true},+ );+ editor.update(+ () => {+ editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) {+ throw new Error('no range selection');+ }+ selection.insertText(text);+ },+ {discrete: true},+ );+ };+ typeAt(IMAGES.titled.length - 3, '!');+ expect(ref.current?.getMarkdown()).toBe(`Before ${IMAGES.titled}! after\n`);+ typeAt(2, 'x');+ expect(ref.current?.getMarkdown()).toBe(+ `Before x${IMAGES.titled}! after\n`,+ );+ });++ it('moves a caret still inside an image when a key arrives, so the key lands beside it (FR5)', async () => {+ const markdown = `Before ${IMAGES.emptyAlt} after\n`;+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor+ label="Notes"+ ref={ref}+ defaultValue={markdownToEditorStateJSON(markdown)}+ />,+ );+ await waitFor(() => expect(ref.current?.getEditor()).toBeTruthy());+ const editor = ref.current!.getEditor()!;+ editor.update(+ () => {+ $imageText(IMAGES.emptyAlt).select(4, 4);+ },+ {discrete: true},+ );+ editor.update(+ () => {+ editor.dispatchCommand(CONTROLLED_TEXT_INSERTION_COMMAND, 'k');+ },+ {discrete: true},+ );+ expect(ref.current?.getMarkdown()).toBe(+ `Before k${IMAGES.emptyAlt} after\n`,+ );+ });++ it('escapes a ( typed right after a reference image, so it never becomes its destination (FR3)', () => {+ const source = 'See ![logo] here\n\n[logo]: https://example.com/logo.png\n';+ expect(+ editAndExport(source, () => {+ $imageText('![logo]').insertAfter($createTextNode('(beta)'));+ }),+ ).toBe(+ 'See ![logo]\\(beta) here\n\n[logo]: https://example.com/logo.png\n',+ );+ });++ it('writes a shortcut reference image before a link in its collapsed form, so the link stays a link (FR3)', () => {+ const source = 'See ![logo] here\n\n[logo]: https://example.com/logo.png\n';+ expect(+ editAndExport(source, () => {+ const link = $createLinkNode('https://example.com/site');+ link.append($createTextNode('site'));+ $imageText('![logo]').insertAfter(link);+ }),+ ).toBe(+ 'See ![logo][][site](https://example.com/site) here\n\n[logo]: https://example.com/logo.png\n',+ );+ });++ it('moves a click inside an image to the nearer edge every time, and an arrow key past it (FR5)', async () => {+ const markdown = `Before ${IMAGES.emptyAlt} after\n`;+ const ref = createRef<RichTextEditorRef>();+ render(+ <RichTextEditor+ label="Notes"+ ref={ref}+ defaultValue={markdownToEditorStateJSON(markdown)}+ />,+ );+ await waitFor(() => expect(ref.current?.getEditor()).toBeTruthy());+ const editor = ref.current!.getEditor()!;+ const placeAndType = (offset: number, text: string, arrow = false) => {+ if (arrow) {+ editor.update(+ () => {+ $imageText(IMAGES.emptyAlt).select(0, 0);+ },+ {discrete: true},+ );+ editor+ .getRootElement()+ ?.dispatchEvent(+ new KeyboardEvent('keydown', {key: 'ArrowRight', bubbles: true}),+ );+ }+ editor.update(+ () => {+ $imageText(IMAGES.emptyAlt).select(offset, offset);+ editor.dispatchCommand(SELECTION_CHANGE_COMMAND, undefined);+ const selection = $getSelection();+ if (!$isRangeSelection(selection)) {+ throw new Error('no range selection');+ }+ selection.insertText(text);+ },+ {discrete: true},+ );+ };+ placeAndType(2, 'A');+ placeAndType(3, 'B');+ expect(ref.current?.getMarkdown()).toBe(+ `Before AB${IMAGES.emptyAlt} after\n`,+ );+ placeAndType(1, 'Z', true);+ expect(ref.current?.getMarkdown()).toBe(+ `Before AB${IMAGES.emptyAlt}Z after\n`,+ );+ });+});diff --git a/packages/richtext/src/markdownSource.ts b/packages/richtext/src/markdownSource.tsindex 4b3997ac2b..23ce9009d7 100644--- a/packages/richtext/src/markdownSource.ts+++ b/packages/richtext/src/markdownSource.ts@@ -29,6 +29,7 @@import {$convertFromMarkdownString, type Transformer} from '@lexical/markdown';import {$isCodeNode} from '@lexical/code';+import {$isLinkNode} from '@lexical/link';import {$isListItemNode, $isListNode} from '@lexical/list';import {$createParagraphNode,@@ -48,11 +49,14 @@ import {import {isMarkedHardLineBreak} from './markdownHardLineBreak';import {normalizeListIndentation} from './markdownListIndentation';import {+ $isImageSource,$restoreCharacterReferences,$restoreCodeSpans,+ $restoreImages,protectBackslashEscapes,protectCharacterReferences,protectCodeSpans,+ protectImages,protectLinkDestinationParentheses,protectRefusedLinks,$unwrapRefusedLinks,@@ -396,10 +400,13 @@ export function importMarkdownKeepingSource(withoutCarriageReturns(importChunks[index]?.content ?? chunk.content),plugins,);- // Links core refuses go first, on the source as written, so one whose- // text holds code (`[`x`](javascript:y)`) shows whole as core shows- // it; code spans next, so a safe link's code still reads as code.- const refused = protectRefusedLinks(shielded.markdown);+ // Images go first: RichText has no image node, so each comes back as+ // its source, whole. Links core refuses go next, on the source as+ // written, so one whose text holds code (`[`x`](javascript:y)`)+ // shows whole as core shows it; code spans next, so a safe link's+ // code still reads as code.+ const images = protectImages(shielded.markdown);+ const refused = protectRefusedLinks(images.markdown);const code = protectCodeSpans(refused.markdown);const escaped = protectBackslashEscapes(code.markdown);const destinations = protectLinkDestinationParentheses(@@ -418,6 +425,7 @@ export function importMarkdownKeepingSource(]),);$restoreCodeSpans(holder, code.spans);+ $restoreImages(holder, images.images);$unwrapRefusedLinks(holder);$restoreExtensionSources(holder, shielded.standIns);$joinSoftLineBreaks(holder);@@ -749,6 +757,11 @@ function markedView(if (placeholder != null && $isRichTextExtensionNode(node)) {return extensionTextView(node, placeholder);}+ if (placeholder != null && $isTextNode(node)) {+ const view = Object.create(node) as typeof node;+ view.getTextContent = () => placeholder;+ return view;+ }if ($isTextNode(node)) {if (node.hasFormat('code') || $isCodeNode(node.getParent())) {return node;@@ -759,6 +772,21 @@ function markedView(let text = node.getTextContent().replace(INLINE_SYNTAX, match => token + match);+ // A `!` right before a link would make the link an image.+ if (text.endsWith('!') && $isLinkNode(node.getNextSibling())) {+ text = text.slice(0, -1) + token + '!';+ }+ // A `(` right after an image that ends in `]` would become its+ // destination.+ const before = node.getPreviousSibling();+ if (+ text.startsWith('(') &&+ before != null &&+ $isImageSource(before) &&+ before.getTextContent().endsWith(']')+ ) {+ text = token + text;+ }const previous = node.getPreviousSibling();if (previous == null || $isLineBreakNode(previous)) {const ordered = ORDERED_LIST_START.exec(text);@@ -798,6 +826,22 @@ function markedView(return node;}+// A reference image's label at the end of its source: `[b]` in `![a][b]`.+const IMAGE_LABEL_END = /\]\[(?:[^\\\]]|\\.)*\]$/;++/**+ * An image's source as an export writes it. A shortcut reference image+ * (`![a]`) right before a link writes in its collapsed form (`![a][]`), so+ * the link's text never reads as its label.+ */+function $imageSourceForExport(node: LexicalNode): string {+ const source = node.getTextContent();+ const isShortcut = source.endsWith(']') && !IMAGE_LABEL_END.test(source);+ return isShortcut && $isLinkNode(node.getNextSibling())+ ? `${source}[]`+ : source;+}+/*** A placeholder for each inline plugin node among `nodes`, absent from* `text`, and the source each placeholder stands for.@@ -813,13 +857,19 @@ function extensionPlaceholders(const sources = new Map<string, string>();const free = absentCharacters(text);for (const node of nodes) {- if ($isRichTextExtensionNode(node) && node.isInline()) {+ const source =+ $isRichTextExtensionNode(node) && node.isInline()+ ? node.getSource()+ : $isImageSource(node)+ ? $imageSourceForExport(node)+ : null;+ if (source != null) {const placeholder = free.next().value;if (placeholder == null) {break;}placeholders.set(node.getKey(), placeholder);- sources.set(placeholder, node.getSource());+ sources.set(placeholder, source);}}return {placeholders, sources};