Skip to content

Commit

Permalink
fix: Prevent extra blank lines on list items (#685)
Browse files Browse the repository at this point in the history
Co-authored-by: Ricardo Amaral <ricardo@doist.com>
  • Loading branch information
gnapse and rfgamaral committed Mar 6, 2024
1 parent 06730db commit b538ebe
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
20 changes: 20 additions & 0 deletions src/serializers/markdown/markdown.test.ts
Expand Up @@ -106,6 +106,17 @@ const HTML_INPUT_UNORDERED_LISTS = `<ul>
<li>And here&#39;s the third list item.</li>
</ul>`

const HTML_NESTED_UNORDERED_LIST = `<ul>
<li>
<p>Parent list element</p>
<ul>
<li><p>Sub-item 1</p></li>
<li><p>Sub-item 2</p></li>
</ul>
</li>
<li>And back to the first list</li>
</ul>`

const HTML_INPUT_TASK_LISTS = `<ul data-type="taskList">
<li data-type="taskItem" data-checked="false">First item</li>
<li data-type="taskItem" data-checked="true">Second item</li>
Expand Down Expand Up @@ -471,6 +482,15 @@ Strikethrough uses two tildes: ~~scratch this~~`,
)
})

test('nested unordered lists Markdown output is correct', () => {
expect(markdownSerializer.serialize(HTML_NESTED_UNORDERED_LIST)).toBe(
`- Parent list element
- Sub-item 1
- Sub-item 2
- And back to the first list`,
)
})

test('task lists syntax is ignored (unsupported by default)', () => {
expect(markdownSerializer.serialize(HTML_INPUT_TASK_LISTS)).toBe(
`- First item
Expand Down
13 changes: 10 additions & 3 deletions src/serializers/markdown/plugins/paragraph.ts
Expand Up @@ -3,7 +3,8 @@ import type Turndown from 'turndown'

/**
* A Turndown plugin which adds a custom rule for paragraphs. This custom rule is required to avoid
* adding unnecessary blank lines between paragraphs to plain-text documents.
* adding unnecessary blank lines between paragraphs to plain-text documents, and to list items in
* rich-text documents.
*
* @param nodeType The node object that matches this rule.
* @param isPlainText Specifies if the schema represents a plain-text document.
Expand All @@ -12,8 +13,14 @@ function paragraph(nodeType: NodeType, isPlainText: boolean): Turndown.Plugin {
return (turndown: Turndown) => {
turndown.addRule(nodeType.name, {
filter: 'p',
replacement(content) {
return isPlainText ? `\n${content}\n` : `\n\n${content}\n\n`
replacement(content, node) {
const useSingleLineSpacing =
isPlainText ||
// Paragraphs within list items should be wrapped with a single line feed to
// maintain proper list formatting in rich-text documents.
(!isPlainText && node.parentNode?.nodeName === 'LI')

return useSingleLineSpacing ? `\n${content}\n` : `\n\n${content}\n\n`
},
})
}
Expand Down

0 comments on commit b538ebe

Please sign in to comment.