I am writing a custom module for quilljs. It is a simple text macro replacement tool.
ie type “.hi”, it will replace it with “hello”.
I have everything working, but the last step is meant to reposition the cursor at the end of the inserted text, but it leaves the cursor in the original location.
the problem is with line #31 quill.setSelection(…), here is the Quill setSelection API docs
// Implement and register module
Quill.register('modules/quicktext', function(quill, options) {
let cache = '';
quill.on('text-change', (delta, oldDelta, source) => {
if (source === 'api') {
console.log("changing", source)
return
}
let lastkey = delta.ops[delta.ops.length - 1]?.insert || '';
if (delta.ops[delta.ops.length - 1]?.delete) { // handle delete key
cache = cache.slice(0,-1);
return
}
if (lastkey && lastkey !== " ") {
cache += lastkey;
console.log("cache", cache, "lastkey",lastkey)
} else if (cache) { // avoid initial call
console.log("cache", cache, "lastkey",lastkey)
reps.forEach(rep => {
console.log("rep check", cache, rep[cache])
if (rep[cache]) {
console.log("triggered")
let caret = quill.getSelection().index
let start = caret - cache.length - 1;
console.log("doing", caret + (rep[cache].length - cache.length))
quill.deleteText(start, cache.length, 'silent');
quill.insertText(start, rep[cache], 'silent');
console.log(`caret at ${caret}, moving forward ${rep[cache].length - cache.length} spaces, to position ${caret+rep[cache].length - cache.length}.`)
quill.setSelection(caret + (rep[cache].length - cache.length),0, 'silent');
// why does above not work?
console.log("done")
}
})
cache = '';
}
});
});
let reps = [
{".hi": "hello"},
{".bye": "goodbye"},
{".brb": "be right back"}
];
// We can now initialize Quill with something like this:
var quill = new Quill('#editor', {
modules: {
quicktext: {
reps: reps
}
}
});
Code can be run here: Codepen