Skip to content

Commit

Permalink
Only paste links when pasted text is only url
Browse files Browse the repository at this point in the history
When the text being pasted contained a URL, we were attempting to convert the target text into a markdown link. However, this was causing some undeseried behavior, because the pasted text was being treated like an exact URL. This updates the RegExp test to look for an exact string of a URL so that we don't match on longer strings.

Borrowed from SO: https://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url
  • Loading branch information
ipc103 committed Aug 11, 2022
1 parent a329717 commit dedae8d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/paste-markdown-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ function linkify(selectedText: string, text: string): string {
return `[${selectedText}](${text})`
}

const URL_REGEX = /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\/?\s*?$/i
function isURL(url: string): boolean {
return /^https?:\/\//i.test(url)
return URL_REGEX.test(url)
}
17 changes: 17 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ describe('paste-markdown', function () {
assert.equal(textarea.value, 'The examples can be found [here](https://github.com).')
})

it('creates a markdown link when the pasted url includes a trailing slash', function () {
// eslint-disable-next-line i18n-text/no-en
textarea.value = 'The examples can be found here.'
textarea.setSelectionRange(26, 30)
paste(textarea, {'text/plain': 'https://www.github.com/'})
assert.equal(textarea.value, 'The examples can be found [here](https://www.github.com/).')
})

it("doesn't paste a markdown URL when pasting over a selected URL", function () {
// eslint-disable-next-line i18n-text/no-en
textarea.value = 'The examples can be found here: https://docs.github.com'
Expand All @@ -66,6 +74,15 @@ describe('paste-markdown', function () {
assert.equal(textarea.value, '@')
})

it("doesn't paste markdown URL when additional text is being copied", function () {
textarea.value = 'github'
textarea.setSelectionRange(0, 6)
paste(textarea, {'text/plain': 'https://github.com plus some other content'})
// Synthetic paste events don't manipulate the DOM. The same textarea value
// means that the event handler didn't fire and normal paste happened.
assert.equal(textarea.value, 'github')
})

it('turns html tables into markdown', function () {
const data = {
'text/html': tableHtml
Expand Down

0 comments on commit dedae8d

Please sign in to comment.