Last active
October 25, 2016 06:43
-
-
Save oJshua/5164af7223668582a7f1dc2645ffcede to your computer and use it in GitHub Desktop.
Quill JS Link Module
This file contains hidden or 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
var Quill = require('quill'); | |
var Delta = require('quill-delta'); | |
var linkRegex = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/; | |
function addhttp(url) { | |
if (!/^(f|ht)tps?:\/\//i.test(url)) { | |
url = "http://" + url; | |
} | |
return url; | |
} | |
Quill.register('modules/linker', function(quill, options) { | |
quill.clipboard.addMatcher(Node.TEXT_NODE, function(node, delta) { | |
var index = 0; | |
var regex = /https?:\/\/[^\s]+/g; | |
var match = null; | |
var composer = new Delta(); | |
while ((match = regex.exec(node.data)) !== null) { | |
composer.retain(match.index - index); | |
index = regex.lastIndex; | |
composer.retain(match[0].length, { link: match[0] }); | |
} | |
return delta.compose(composer); | |
}); | |
var word = ''; | |
var index = -1; | |
var previousLink = false; | |
function reset() { | |
index = -1; | |
word = ''; | |
previousLink = false; | |
} | |
quill.on('selection-change', function(sel) { | |
if (!sel) { | |
reset(); | |
return; | |
} | |
var format = quill.getFormat(sel.index, sel.length); | |
if (!format.link) { | |
reset(); | |
} | |
}); | |
quill.on('text-change', function(delta, old, source) { | |
if (source !== 'user') { | |
return; | |
} | |
var range = quill.getSelection(); | |
if (!range) { | |
return; | |
} | |
delta.ops.forEach(function(delta) { | |
var insert = false; | |
if (delta.insert && typeof(delta.insert) === 'string') { | |
if (delta.insert === ' ' || delta.insert === "\n") { | |
reset(); | |
return; | |
} | |
word += delta.insert; | |
insert = true; | |
} | |
if (delta.delete) { | |
word = word.slice(0, -delta.delete); | |
} | |
if (index == -1 && insert) { | |
index = range.index - delta.insert.length; | |
} | |
if (range.index < index) { | |
reset(); | |
} | |
}); | |
var length = range.index - index; | |
if (linkRegex.test(word)) { | |
previousLink = true; | |
setTimeout(function() { | |
quill.formatText(index, length, 'link', addhttp(word)); | |
}, 0); | |
} else { | |
if (previousLink) { | |
previousLink = false; | |
setTimeout(function() { | |
quill.formatText(index, length, 'link', false); | |
}, 0); | |
} | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment