small usability changes

This commit is contained in:
Joeri Exelmans 2025-05-28 12:51:37 +02:00
parent 8385f08923
commit 7fafa35b4b
5 changed files with 23 additions and 46 deletions

View file

@ -1,6 +1,7 @@
import { useEffect, useRef, type ReactNode, type KeyboardEvent, useState } from "react";
import "./Input.css";
import { focusPrevElement, focusNextElement, setRightMostCaretPosition } from "../../util/dom_trickery";
interface InputProps {
placeholder: string;
@ -25,38 +26,6 @@ function getCaretPosition(ref: React.RefObject<HTMLInputElement| null>): number
return ref.current?.selectionStart || 0;
}
// Move caret all the way to the right in the currently focused element
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);
}
}
function focusNextElement() {
const editable = Array.from<any>(document.querySelectorAll('input.editable'));
const index = editable.indexOf(document.activeElement);
const nextElem = editable[index+1];
if (nextElem) {
nextElem.focus();
}
}
function focusPrevElement() {
const editable = Array.from<any>(document.querySelectorAll('input.editable'));
const index = editable.indexOf(document.activeElement);
const prevElem = editable[index-1]
if (prevElem) {
prevElem.focus();
setRightMostCaretPosition(prevElem);
}
}
export function Input({placeholder, text, suggestion, onTextChange, onEnter, onCancel, extraHandlers, children}: InputProps) {
const ref = useRef<HTMLInputElement>(null);
const [focus, setFocus] = useState<"yes"|"hide"|"no">("no");