Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions packages/lexical-markdown/src/MarkdownExport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {isEmptyParagraph, transformersByType} from './utils';
export function createMarkdownExport(
transformers: Array<Transformer>,
shouldPreserveNewLines: boolean = false,
shouldPreserveWhitespaces: boolean = false,
): (node?: ElementNode) => string {
const byType = transformersByType(transformers);
const elementTransformers = [...byType.multilineElement, ...byType.element];
Expand Down Expand Up @@ -60,6 +61,7 @@ export function createMarkdownExport(
elementTransformers,
textFormatTransformers,
byType.textMatch,
shouldPreserveWhitespaces,
);

if (result != null) {
Expand All @@ -85,6 +87,7 @@ function exportTopLevelElements(
elementTransformers: Array<ElementTransformer | MultilineElementTransformer>,
textTransformersIndex: Array<TextFormatTransformer>,
textMatchTransformers: Array<TextMatchTransformer>,
shouldPreserveWhitespaces: boolean = false,
): string | null {
for (const transformer of elementTransformers) {
if (!transformer.export) {
Expand All @@ -100,7 +103,14 @@ function exportTopLevelElements(
}

if ($isElementNode(node)) {
return exportChildren(node, textTransformersIndex, textMatchTransformers);
return exportChildren(
node,
textTransformersIndex,
textMatchTransformers,
undefined,
undefined,
shouldPreserveWhitespaces,
);
} else if ($isDecoratorNode(node)) {
return node.getTextContent();
} else {
Expand All @@ -114,6 +124,7 @@ function exportChildren(
textMatchTransformers: Array<TextMatchTransformer>,
unclosedTags?: Array<{format: TextFormatType; tag: string}>,
unclosableTags?: Array<{format: TextFormatType; tag: string}>,
shouldPreserveWhitespaces: boolean = false,
): string {
const output = [];
const children = node.getChildren();
Expand Down Expand Up @@ -145,6 +156,7 @@ function exportChildren(
// is invalid markdown, as the closing ** is inside the link.
//
[...unclosableTags, ...unclosedTags],
shouldPreserveWhitespaces,
),
(textNode, textContent) =>
exportTextFormat(
Expand All @@ -153,6 +165,7 @@ function exportChildren(
textTransformersIndex,
unclosedTags,
unclosableTags,
shouldPreserveWhitespaces,
),
);

Expand All @@ -172,6 +185,7 @@ function exportChildren(
textTransformersIndex,
unclosedTags,
unclosableTags,
shouldPreserveWhitespaces,
),
);
} else if ($isElementNode(child)) {
Expand All @@ -183,6 +197,7 @@ function exportChildren(
textMatchTransformers,
unclosedTags,
unclosableTags,
shouldPreserveWhitespaces,
),
);
} else if ($isDecoratorNode(child)) {
Expand All @@ -200,14 +215,15 @@ function exportTextFormat(
// unclosed tags include the markdown tags that haven't been closed yet, and their associated formats
unclosedTags: Array<{format: TextFormatType; tag: string}>,
unclosableTags?: Array<{format: TextFormatType; tag: string}>,
shouldPreserveWhitespaces: boolean = false,
): string {
// This function handles the case of a string looking like this: " foo "
// Where it would be invalid markdown to generate: "** foo **"
// If the node has no format, we use the original text.
// Otherwise, we escape leading and trailing whitespaces to their corresponding code points,
// ensuring the returned string maintains its original formatting, e.g., "**&#32;&#32;&#32;foo&#32;&#32;&#32;**".
let output =
node.getFormat() === 0
node.getFormat() === 0 || shouldPreserveWhitespaces
? textContent
: escapeLeadingAndTrailingWhitespaces(textContent);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1047,6 +1047,78 @@ describe('Markdown', () => {
});
});

describe('whitespace preservation in export', () => {
it('exports leading/trailing whitespaces as HTML code points by default', () => {
const editor = createHeadlessEditor({
nodes: [
HeadingNode,
ListNode,
ListItemNode,
QuoteNode,
CodeNode,
LinkNode,
],
});

const html =
'<p><b><strong style="white-space: pre-wrap;"> Hello </strong></b></p>';

editor.update(
() => {
const parser = new DOMParser();
const dom = parser.parseFromString(html, 'text/html');
const nodes = $generateNodesFromDOM(editor, dom);
$getRoot().select();
$insertNodes(nodes);
},
{discrete: true},
);

const exported = editor
.getEditorState()
.read(() =>
$convertToMarkdownString([...TRANSFORMERS], undefined, false, false),
);

expect(exported).toBe('**&#32;&#32;&#32;Hello&#32;&#32;&#32;**');
});

it('preserves leading/trailing whitespaces when shouldPreserveWhitespaces=true', () => {
const editor = createHeadlessEditor({
nodes: [
HeadingNode,
ListNode,
ListItemNode,
QuoteNode,
CodeNode,
LinkNode,
],
});

const html =
'<p><b><strong style="white-space: pre-wrap;"> Hello </strong></b></p>';

editor.update(
() => {
const parser = new DOMParser();
const dom = parser.parseFromString(html, 'text/html');
const nodes = $generateNodesFromDOM(editor, dom);
$getRoot().select();
$insertNodes(nodes);
},
{discrete: true},
);

const exported = editor
.getEditorState()
.read(() =>
$convertToMarkdownString([...TRANSFORMERS], undefined, false, true),
);

expect(exported).toBe('** Hello **');
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking closer at what this is supposed to do now that there are tests I don't think this is useful, because this is not something most markdown parsers will accept.

For example here's what github does with it:

** Hello **

The commonmark reference implementation also doesn't parse it as formatting

});
});

describe('normalizeMarkdown - shouldMergeAdjacentLines = true', () => {
it('should combine lines separated by a single \n unless they are in a codeblock', () => {
const markdown = `
Expand Down
2 changes: 2 additions & 0 deletions packages/lexical-markdown/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,12 @@ function $convertToMarkdownString(
transformers: Array<Transformer> = TRANSFORMERS,
node?: ElementNode,
shouldPreserveNewLines: boolean = false,
shouldPreserveWhitespaces: boolean = false,
): string {
const exportMarkdown = createMarkdownExport(
transformers,
shouldPreserveNewLines,
shouldPreserveWhitespaces,
);
return exportMarkdown(node);
}
Expand Down
Loading