Skip to content

Commit

Permalink
fix pasting of markdown containing links
Browse files Browse the repository at this point in the history
  • Loading branch information
susanwere committed Feb 23, 2024
1 parent ca6eeb0 commit fd65fcc
Showing 1 changed file with 7 additions and 7 deletions.
14 changes: 7 additions & 7 deletions src/paste-markdown-html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ function onPaste(event: ClipboardEvent) {
// Generate DOM tree from HTML string
const parser = new DOMParser()
const doc = parser.parseFromString(textHTMLClean, 'text/html')
const walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_ELEMENT, node =>
const whatToShow = navigator.userAgent.indexOf('Firefox') > -1 ? NodeFilter.SHOW_ALL : NodeFilter.SHOW_ELEMENT
const walker = doc.createTreeWalker(doc.body, whatToShow, node =>
node.parentNode && isLink(node.parentNode) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT
)

Expand All @@ -62,14 +63,11 @@ function convertToMarkdown(plaintext: string, walker: TreeWalker): string {
// Walk through the DOM tree
while (currentNode && index < NODE_LIMIT) {
index++
const currentNodeText =
navigator.userAgent.indexOf('Firefox') > -1 ? (currentNode as Text) : (currentNode.firstChild as Text)
const text = isLink(currentNode)
? (currentNode.textContent || '').replace(/[\t\n\r ]+/g, ' ')
: (currentNode.firstChild as Text)?.wholeText || ''

// update value of markdownIgnoreBeforeIndex with current index if the current node is not a link
if (!isLink(currentNode)) {
markdownIgnoreBeforeIndex += text.replace(/[\t\n\r ]+/g, ' ').trimStart().length
}
: currentNodeText?.wholeText || ''

// No need to transform whitespace
if (isEmptyString(text)) {
Expand All @@ -88,6 +86,8 @@ function convertToMarkdown(plaintext: string, walker: TreeWalker): string {
markdown =
markdown.slice(0, markdownFoundIndex) + markdownLink + markdown.slice(markdownFoundIndex + text.length)
markdownIgnoreBeforeIndex = markdownFoundIndex + markdownLink.length
} else {
markdownIgnoreBeforeIndex = markdownFoundIndex + text.length
}
}

Expand Down

0 comments on commit fd65fcc

Please sign in to comment.