I post an incomplete and dirty answer to your question, as you asked for it in the comments:
function getCaretCharacterOffsetWithin(element) {
var caretOffset = 0;
var doc = element.ownerDocument || element.document;
var win = doc.defaultView || doc.parentWindow;
var sel;
if (typeof win.getSelection != "undefined") {
sel = win.getSelection();
if (sel.rangeCount > 0) {
var range = win.getSelection().getRangeAt(0);
var preCaretRange = range.cloneRange();
preCaretRange.selectNodeContents(element);
preCaretRange.setEnd(range.endContainer, range.endOffset);
caretOffset = preCaretRange.toString().length;
}
} else if ( (sel = doc.selection) && sel.type != "Control") {
var textRange = sel.createRange();
var preCaretTextRange = doc.body.createTextRange();
preCaretTextRange.moveToElementText(element);
preCaretTextRange.setEndPoint("EndToEnd", textRange);
caretOffset = preCaretTextRange.text.length;
}
return caretOffset;
}
$(document).ready(function() {
$('#summernote').summernote({
callbacks: {
onKeydown: function(e) {
const editable = document.getElementsByClassName('note-editable')[0]
const pos = getCaretCharacterOffsetWithin(editable)
console.log(pos)
const codable = document.getElementsByClassName('note-codable')[0]
codable.setSelectionRange(pos,pos)
}
}
})
$('#summernote').summernote('fullscreen.toggle');
});
The credits for getCaretCharacterOffsetWithin
goes to Tim Down
getCaretCharacterOffsetWithin()
gets caret position in .note-editable
, but not quite right, and the value is not even consistent when you move over paragraph borders back and forth (as Tim warns in his original post).
setSelectionRange(pos,pos)
mirrors the position in .note-editable
to .note-codable
.
Also
- You need to switch to the
code view
and back before it starts to work. And somehow fix this issue.
- You'll need to set mouse callbacks & Co. to mirror caret position on mouse clicks, etc. Now it works only on
onKeydown
.
- You will need to scroll to caret position in
textarea
Here is https://js-pvbgkh.stackblitz.io
note-editable
and mirror it fornote-codable
, but it's not trivial. I never got to the point of one-to-one correspondence. Cursor is always a several symbols off. Also you need to mirror cursor in the opposite direction - fromnote-codable
tonote-editable
- this I didn't even tried. So I just posted the link that can push you in the right direction. – Sulfanilamide