From 5a61c9bb145df2db410431f7e5801712d7612ee1 Mon Sep 17 00:00:00 2001 From: Signior-X Date: Tue, 15 Jun 2021 15:37:29 +0530 Subject: [PATCH] compose: Convert pasted url to named link. This commit changes the pastehandler to have a case when a url is tried to paste on composebox. It instead of directly pasting it, changes the content as we do using ctrl + shift + L, just the difference is here it uses, the copied text instead of url and cursor moves forward. Fixes #18692 --- static/js/copy_and_paste.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/static/js/copy_and_paste.js b/static/js/copy_and_paste.js index 1ab1752be6..747157c7ce 100644 --- a/static/js/copy_and_paste.js +++ b/static/js/copy_and_paste.js @@ -306,6 +306,19 @@ export function paste_handler_converter(paste_html) { return markdown_text; } +// https://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-a-url +function isValidHttpUrl(string) { + let url; + + try { + url = new URL(string); + } catch { + return false; + } + + return url.protocol === "http:" || url.protocol === "https:"; +} + export function paste_handler(event) { const clipboardData = event.originalEvent.clipboardData; if (!clipboardData) { @@ -318,6 +331,20 @@ export function paste_handler(event) { } if (clipboardData.getData) { + const paste_text = clipboardData.getData("text"); + if (paste_text && isValidHttpUrl(paste_text) && document.getSelection().type === "Range") { + event.preventDefault(); + event.stopPropagation(); + + const textarea = $(this); + const prefix = "["; + const suffix = "](" + paste_text + ")"; + compose_ui.wrap_text_with_markdown(textarea, prefix, suffix); + compose_ui.autosize_textarea(textarea); + + return; + } + const paste_html = clipboardData.getData("text/html"); if (paste_html && page_params.development_environment) { const text = paste_handler_converter(paste_html);