Created
February 14, 2016 03:47
-
-
Save coffeebite/a20dabf8564b98324a7f to your computer and use it in GitHub Desktop.
Trix Autolink on paste
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$editor = $("trix-editor") | |
$editor.on "paste", (e) -> | |
pastedText = e.originalEvent.clipboardData?.getData?("Text") | |
# we defer so we can get the cursor position after the pasting happens | |
# otherwise trix returns the position before | |
setTimeout( -> | |
if pastedText and !!pastedText.match(/^(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})$/ig) | |
element = $editor.get(0) | |
editor = element.editor | |
currentText = editor.getDocument().toString() | |
currentSelection = editor.getSelectedRange() | |
# text up to the cursor position | |
textWeAreInterestedIn = currentText.substring 0, currentSelection[0] | |
# search for the start of the url | |
startOfPastedText = textWeAreInterestedIn.lastIndexOf pastedText | |
# add an undo entry so people can undo the autolinking | |
editor.recordUndoEntry "Auto Link Paste" | |
# select the url text | |
editor.setSelectedRange [startOfPastedText, currentSelection[0]] | |
# add a hyperlink to it | |
editor.activateAttribute 'href', pastedText | |
# go back to the original selection | |
editor.setSelectedRange currentSelection | |
, 0) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment