Files
Rosea/packages/domi-ui/src/lib/editable.ts
T

72 lines
2.7 KiB
TypeScript

// SPDX-License-Identifier: CPAL-1.0
/**
* Helpers for TextField's editable mode: a contenteditable box with role="textbox" in place of <input>/<textarea>.
* Why: on Android the WebView asks Google's Autofill service (a network request) as soon as a text <input> or
* <textarea> gets focus, and no attribute stops it (found by Amicitia). A contenteditable box is not an autofill
* target. Plain text only: paste and drop never bring markup.
*/
/** True in an Android WebView or browser, where editable mode avoids the Autofill request. Safe during SSR. */
export function isAndroid(): boolean {
return typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
}
/** The box's text, with line breaks as \n. An emptied box that only holds a stray line break reads as ''. */
export function readText(el: HTMLElement): string {
const raw = typeof el.innerText === 'string' ? el.innerText : (el.textContent ?? '');
return raw === '\n' ? '' : raw;
}
/** Replaces the box's content with plain text (no markup can enter). */
export function writeText(el: HTMLElement, text: string): void {
el.textContent = text;
}
/** Puts the caret after the last character. */
export function caretToEnd(el: HTMLElement): void {
const sel = typeof getSelection === 'function' ? getSelection() : null;
if (!sel || typeof document.createRange !== 'function') return;
const range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
}
/**
* Inserts plain text at the caret. Uses the browser's own insertion where it exists, so undo keeps working;
* otherwise inserts a text node at the selection.
*/
export function insertPlainText(el: HTMLElement, text: string): void {
try {
if (typeof document.execCommand === 'function' && document.execCommand('insertText', false, text)) return;
} catch {
// Fall through to the Range insertion.
}
const sel = typeof getSelection === 'function' ? getSelection() : null;
const node = document.createTextNode(text);
if (!sel || sel.rangeCount === 0 || !el.contains(sel.getRangeAt(0).commonAncestorContainer)) {
el.append(node);
return;
}
const range = sel.getRangeAt(0);
range.deleteContents();
range.insertNode(node);
range.setStartAfter(node);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
/** The soft keyboard a type asks for, as inputmode (an editable box has no type attribute). */
export function inputmodeFor(type: string): 'text' | 'email' | 'url' | 'tel' | 'decimal' | 'search' {
const map: Record<string, 'email' | 'url' | 'tel' | 'decimal' | 'search'> = {
email: 'email',
url: 'url',
tel: 'tel',
number: 'decimal',
search: 'search',
};
return map[type] ?? 'text';
}