diff --git a/src/util/dom_trickery.ts b/src/util/dom_trickery.ts new file mode 100644 index 0000000..3187da2 --- /dev/null +++ b/src/util/dom_trickery.ts @@ -0,0 +1,32 @@ + +// 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(document.querySelectorAll('input.editable')); + const index = editable.indexOf(document.activeElement); + const nextElem = editable[index + 1]; + if (nextElem) { + nextElem.focus(); + } +} + +export function focusPrevElement() { + const editable = Array.from(document.querySelectorAll('input.editable')); + const index = editable.indexOf(document.activeElement); + const prevElem = editable[index - 1]; + if (prevElem) { + prevElem.focus(); + setRightMostCaretPosition(prevElem); + } +}