TelegramPWA/src/util/focusEditableElement.ts
2025-04-23 18:57:46 +02:00

23 lines
731 B
TypeScript

import { IS_TOUCH_ENV } from './browser/windowEnvironment';
export default function focusEditableElement(element: HTMLElement, force?: boolean, forcePlaceCaretAtEnd?: boolean) {
if (!force && element === document.activeElement) {
return;
}
const selection = window.getSelection()!;
const range = document.createRange();
const lastChild = element.lastChild || element;
if (!IS_TOUCH_ENV && !forcePlaceCaretAtEnd && (!lastChild || !lastChild.nodeValue)) {
element.focus();
return;
}
range.selectNodeContents(forcePlaceCaretAtEnd ? element : lastChild);
// `false` means collapse to the end rather than the start
range.collapse(false);
selection.removeAllRanges();
selection.addRange(range);
}