49 lines
No EOL
1.6 KiB
TypeScript
49 lines
No EOL
1.6 KiB
TypeScript
|
|
// If there is a caret anywhere in the document (user entering text), returns the position of the caret in the focused element
|
|
export function getCaretPosition(): number | undefined {
|
|
const selection = window.getSelection();
|
|
if (selection) {
|
|
const range = selection.getRangeAt(0);
|
|
const clonedRange = range.cloneRange();
|
|
return clonedRange.startOffset;
|
|
}
|
|
}
|
|
|
|
// export function setCursorPosition(elem, pos) {
|
|
// const range = document.createRange();
|
|
// range.selectNode(elem);
|
|
// range.setStart(elem, pos);
|
|
// range.setEnd(elem, pos);
|
|
// const selection = window.getSelection();
|
|
// selection?.removeAllRanges();
|
|
// selection?.addRange(range);
|
|
// }
|
|
|
|
// Move caret all the way to the right in the currently focused element
|
|
export function setRightMostCaretPosition(elem) {
|
|
const range = document.createRange();
|
|
range.selectNode(elem);
|
|
if (elem.lastChild) { // if no text is entered, there is no lastChild
|
|
range.setStart(elem.lastChild, elem.textContent.length);
|
|
range.setEnd(elem.lastChild, elem.textContent.length);
|
|
const selection = window.getSelection();
|
|
selection?.removeAllRanges();
|
|
selection?.addRange(range);
|
|
}
|
|
}
|
|
|
|
export function focusNextElement() {
|
|
const editable = Array.from<any>(document.querySelectorAll('input'));
|
|
const index = editable.indexOf(document.activeElement);
|
|
editable[index+1]?.focus();
|
|
}
|
|
|
|
export function focusPrevElement() {
|
|
const editable = Array.from<any>(document.querySelectorAll('input'));
|
|
const index = editable.indexOf(document.activeElement);
|
|
const prevElem = editable[index-1]
|
|
if (prevElem) {
|
|
prevElem.focus();
|
|
setRightMostCaretPosition(prevElem);
|
|
}
|
|
} |