getCaretPosition considering all html elements (#1246)

This commit is contained in:
Meisam 2021-07-23 20:20:59 +02:00 committed by GitHub
parent e1c4b452e6
commit 7867260b9c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -4,31 +4,18 @@ import {
CHAT_PLACEHOLDER_OFFLINE, CHAT_PLACEHOLDER_OFFLINE,
} from './constants.js'; } from './constants.js';
// Taken from https://stackoverflow.com/questions/3972014/get-contenteditable-caret-index-position // Taken from https://stackoverflow.com/a/46902361
export function getCaretPosition(editableDiv) { export function getCaretPosition(node) {
var caretPos = 0, var range = window.getSelection().getRangeAt(0),
sel, preCaretRange = range.cloneRange(),
range; caretPosition,
if (window.getSelection) { tmp = document.createElement("div");
sel = window.getSelection();
if (sel.rangeCount) { preCaretRange.selectNodeContents(node);
range = sel.getRangeAt(0); preCaretRange.setEnd(range.endContainer, range.endOffset);
if (range.commonAncestorContainer.parentNode == editableDiv) { tmp.appendChild(preCaretRange.cloneContents());
caretPos = range.endOffset; caretPosition = tmp.innerHTML.length;
} return caretPosition;
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
if (range.parentElement() == editableDiv) {
var tempEl = document.createElement('span');
editableDiv.insertBefore(tempEl, editableDiv.firstChild);
var tempRange = range.duplicate();
tempRange.moveToElementText(tempEl);
tempRange.setEndPoint('EndToEnd', range);
caretPos = tempRange.text.length;
}
}
return caretPos;
} }
// Might not need this anymore // Might not need this anymore
@ -113,7 +100,7 @@ export function convertToText(str = '') {
You would call this when a user pastes from You would call this when a user pastes from
the clipboard into a `contenteditable` area. the clipboard into a `contenteditable` area.
*/ */
export function convertOnPaste(event = { preventDefault() {} }, emojiList) { export function convertOnPaste(event = { preventDefault() { } }, emojiList) {
// Prevent paste. // Prevent paste.
event.preventDefault(); event.preventDefault();