Skip to content

Commit fd12c0f

Browse files
committed
fix: normalize whitespace in link labels
1 parent 983a716 commit fd12c0f

File tree

2 files changed

+15
-4
lines changed

2 files changed

+15
-4
lines changed

src/paste-markdown-html.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,9 @@ function convertToMarkdown(plaintext: string, walker: TreeWalker): string {
5555
// Walk through the DOM tree
5656
while (currentNode && index < NODE_LIMIT) {
5757
index++
58-
const text = isLink(currentNode) ? currentNode.textContent || '' : (currentNode.firstChild as Text)?.wholeText || ''
58+
const text = isLink(currentNode)
59+
? (currentNode.textContent || '').replace(/[\t\n\r ]+/g, ' ')
60+
: (currentNode.firstChild as Text)?.wholeText || ''
5961

6062
// No need to transform whitespace
6163
if (isEmptyString(text)) {
@@ -68,7 +70,7 @@ function convertToMarkdown(plaintext: string, walker: TreeWalker): string {
6870

6971
if (markdownFoundIndex >= 0) {
7072
if (isLink(currentNode)) {
71-
const markdownLink = linkify(currentNode)
73+
const markdownLink = linkify(currentNode, text)
7274
// Transform 'example link plus more text' into 'example [link](example link) plus more text'
7375
// Method: 'example [link](example link) plus more text' = 'example ' + '[link](example link)' + ' plus more text'
7476
markdown =
@@ -99,8 +101,7 @@ function hasHTML(transfer: DataTransfer): boolean {
99101
}
100102

101103
// Makes markdown link from a link element, avoiding special GitHub links
102-
function linkify(element: HTMLAnchorElement): string {
103-
const label = element.textContent || ''
104+
function linkify(element: HTMLAnchorElement, label: string): string {
104105
const url = element.href || ''
105106
let markdown = ''
106107

test/test.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,16 @@ describe('paste-markdown', function () {
160160
assert.equal(textarea.value, markdownSentence)
161161
})
162162

163+
it('deals with link labels that contains line breaks in html', function () {
164+
// eslint-disable-next-line github/unescaped-html-literal
165+
const sentence = '<a href="https://example.com/">foo\nbar</a>'
166+
const plaintextSentence = 'foo bar'
167+
const markdownSentence = '[foo bar](https://example.com/)'
168+
169+
paste(textarea, {'text/html': sentence, 'text/plain': plaintextSentence})
170+
assert.equal(textarea.value, markdownSentence)
171+
})
172+
163173
it("doesn't render any markdown for html link without corresponding plaintext", function () {
164174
// eslint-disable-next-line github/unescaped-html-literal
165175
const link = `<meta charset='utf-8'><a href="https://github.com/monalisa/playground/issues/1">

0 commit comments

Comments
 (0)