From dedae8d80cedbdd46203197ced80c3157403101b Mon Sep 17 00:00:00 2001 From: Ian Candy Date: Wed, 10 Aug 2022 20:51:23 -0400 Subject: [PATCH] Only paste links when pasted text is only url 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 --- src/paste-markdown-link.ts | 3 ++- test/test.js | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/paste-markdown-link.ts b/src/paste-markdown-link.ts index 1c9674d..34111ee 100644 --- a/src/paste-markdown-link.ts +++ b/src/paste-markdown-link.ts @@ -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) } diff --git a/test/test.js b/test/test.js index b88f5e0..f5c74f8 100644 --- a/test/test.js +++ b/test/test.js @@ -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' @@ -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