Maximum contents length: setSelection() causes the error: "The given range isn't in document."
Inspired by how to control the maximum length of the html #688, I wrote an improved version for introducing the html content limit for the Quill editor. The code is as follows:
var limit = 20;
var overflow = {};
function undoOverflow(overflow)
{
quill.setContents(overflow.contents, 'silent');
//setTimeout(function() {
quill.setSelection(overflow.range.index, overflow.range.length, 'silent');
//}, 0);
}
quill.on('text-change', function(delta, oldContents, source) {
var size = quill.root.innerHTML.length;
if(size > limit) {
overflow.contents = oldContents;
undoOverflow(overflow);
return;
}
overflow.range = quill.getSelection();
});
quill.on('selection-change', function(range, oldRange, source) {
overflow.range = quill.getSelection();
});
It works, i.e. does not allow the user to enter text if the limit is exceeded. Since I'm using html and not plain text, only 13 characters are allowed to be entered in a single line - although there is a limit of 20 - this is because of the html markup.
The problem
When the limit is reached, the cursor disappears and the editor loses focus. The console shows this error: The given range isn't in document. The function that causes the error is setSelection() in undoOverflow(). And the main thing is that the range index that is passed to setSelection() is within the length of the contents.
Steps for Reproduction
- Visit Quill playground
- Paste the above code just below
var quill = new Quill(...); - Start typing something in the editor area in one line (do not hit Enter) like this:
aaaaaaaaaaaaaa
Remark about using setTimeout() in undoOverflow()
Uncommenting setTimeout() inside undoOverflow() partially fixes the bug - the cursor does not disappear anymore but the error in console remains.
Platforms:
Chrome 57, Chrome 86 under Windows 7
Version:
Quill 1.3.6
Thank you in advance for any help