From 7b6d18bc6a2af175471bf9295f2e50928ea61cbe Mon Sep 17 00:00:00 2001 From: Joeri Exelmans Date: Sat, 31 May 2025 11:11:39 +0200 Subject: [PATCH] forgot file --- src/util/dom_trickery.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/util/dom_trickery.ts 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); + } +}