Files
ianitor/packages/domi-ui/src/components/TextField.svelte
T

430 lines
15 KiB
Svelte

<script lang="ts">
import type { HTMLInputAttributes } from 'svelte/elements';
import Icon from './Icon.svelte';
import Strike from './Strike.svelte';
import { strike } from '../lib/strike';
import { canSend, enterAction, failureText, isSoftKeyboard, type FieldState } from '../lib/keys';
import type { IconName } from '../lib/icons';
import { caretToEnd, inputmodeFor, insertPlainText, isAndroid, readText, writeText } from '../lib/editable';
type Action = 'send' | 'search' | 'next' | 'save';
interface Props {
/** The text. Bind it: bind:value. */
value?: string;
/** The visible label. Every field has one; hideLabel keeps it for screen readers only (a chat composer). */
label: string;
hideLabel?: boolean;
hint?: string;
/** An error you show (validation). The field also shows its own when onsend fails. */
error?: string;
placeholder?: string;
type?: 'text' | 'email' | 'url' | 'password' | 'search' | 'tel' | 'number';
/** A multi-line field that grows with its text up to `rows` lines. */
multiline?: boolean;
rows?: number;
/**
* What the seal does. send (arrow): sends and clears. search (glass): searches. save (check): saves and keeps
* the text. next (chevron): in a form, goes to the next field; the last field of a form uses send or save.
*/
action?: Action;
/** The seal's accessible name, the words a screen reader says: "Send message", "Search books". */
actionLabel?: string;
/** Runs on Enter or the seal. Return a Promise to show sending, then sent or the error. */
onsend?: (value: string) => unknown;
/** Empty the field after a successful send. Default: true for send, false otherwise. */
clearOnSend?: boolean;
enterSends?: 'auto' | 'always' | 'never';
/** Set to drive the state yourself. */
status?: FieldState;
sendingText?: string;
sentText?: string;
failText?: string;
size?: 'md' | 'lg';
optional?: boolean;
disabled?: boolean;
readonly?: boolean;
required?: boolean;
name?: string;
id?: string;
autocomplete?: HTMLInputAttributes['autocomplete'];
inputmode?: HTMLInputAttributes['inputmode'];
maxlength?: number;
spellcheck?: boolean;
autofocus?: boolean;
/** Showcase and tests only: 'hover', 'focus' on the field, 'press'/'hover'/'focus' on the seal via sendForce. */
force?: string;
sendForce?: string;
class?: string;
/** The input element, for focusing it from outside (null in editable mode: see editor). */
input?: HTMLInputElement | HTMLTextAreaElement | null;
/**
* input (default): a native <input>/<textarea>. editable: a contenteditable box with role="textbox": on Android
* the WebView sends an Autofill request to Google whenever a native text field gets focus; an editable box does
* not. auto: editable on Android, native elsewhere. Passwords are always native (masking, password managers).
*/
as?: 'input' | 'editable' | 'auto';
/** The editable box in editable mode, for focusing it from outside. */
editor?: HTMLElement | null;
}
let {
value = $bindable(''),
label,
hideLabel = false,
hint,
error,
placeholder,
type = 'text',
multiline = false,
rows = 6,
action = 'send',
actionLabel,
onsend,
clearOnSend,
enterSends = 'auto',
status,
sendingText,
sentText,
failText,
size = 'md',
optional = false,
disabled = false,
readonly = false,
required = false,
name,
id,
autocomplete,
inputmode,
maxlength,
spellcheck,
autofocus = false,
force,
sendForce,
class: cls = '',
input = $bindable(null),
as = 'input',
editor = $bindable(null),
}: Props = $props();
const uid = $props.id();
const fieldId = $derived(id ?? `domi-field-${uid}`);
const hintId = `domi-hint-${uid}`;
const errorId = `domi-error-${uid}`;
const labelId = `domi-label-${uid}`;
const android = isAndroid();
const words: Record<Action, { label: string; icon: IconName; key: 'send' | 'search' | 'next' | 'done'; busy: string; done: string; fail: string }> = {
send: { label: 'Send', icon: 'send', key: 'send', busy: 'Sending', done: 'Sent', fail: 'Could not send. Try again.' },
search: { label: 'Search', icon: 'search', key: 'search', busy: 'Searching', done: 'Searched', fail: 'Could not search. Try again.' },
save: { label: 'Save', icon: 'save', key: 'done', busy: 'Saving', done: 'Saved', fail: 'Could not save. Try again.' },
next: { label: 'Next field', icon: 'next', key: 'next', busy: 'Checking', done: '', fail: 'Check this field.' },
};
const w = $derived(words[action]);
let auto = $state<FieldState>('idle');
let failure = $state('');
let said = $state('');
let revealed = $state(false);
let timer: ReturnType<typeof setTimeout> | undefined;
const shown = $derived<FieldState>(status ?? auto);
const empty = $derived(value.trim().length === 0);
const sendable = $derived(canSend(value, shown, disabled || readonly));
// While sending and just after, the seal stays lit (with the interpuncts, then the check) though it cannot be pressed.
const lit = $derived(sendable || shown === 'sending' || shown === 'sent');
const message = $derived(error ?? (shown === 'error' ? failure : ''));
const described = $derived([hint && hintId, message && errorId].filter(Boolean).join(' ') || undefined);
const inputType = $derived(type === 'password' && revealed ? 'text' : type);
const clears = $derived(clearOnSend ?? action === 'send');
const editable = $derived(type !== 'password' && (as === 'editable' || (as === 'auto' && android)));
/** The element that takes the text, whichever kind it is. */
const box = $derived<HTMLElement | null>(editable ? editor : input);
const locked = $derived(disabled || readonly || shown === 'sending');
function hold(): number {
const v = getComputedStyle(document.documentElement).getPropertyValue('--domi-dur-hold');
return Math.max(900, parseFloat(v) || 1400);
}
function nextField(from: HTMLElement) {
const scope = from.closest('form') ?? document;
const all = [...scope.querySelectorAll<HTMLElement>('.domi-field__input, input, textarea, select')].filter(
(el) => !el.hasAttribute('disabled') && el.getAttribute('aria-disabled') !== 'true' && el.getAttribute('type') !== 'hidden',
);
const i = all.indexOf(from);
all[i + 1]?.focus();
}
async function submit() {
if (!sendable || !box) return;
const el = box;
const text = value;
clearTimeout(timer);
failure = '';
if (!onsend) {
// No handler: behave like the form's own submit (or, for next, move on).
if (action === 'next') nextField(el);
else el.closest('form')?.requestSubmit();
return;
}
const result = onsend(text);
const thenable = result != null && typeof (result as PromiseLike<unknown>).then === 'function';
if (status !== undefined) return;
if (!thenable) return done(el);
auto = 'sending';
said = sendingText ?? w.busy;
try {
await result;
done(el);
} catch (err) {
auto = 'error';
failure = failureText(err, failText ?? w.fail);
said = failure;
el.focus();
}
}
function done(el: HTMLElement) {
if (clears) value = '';
if (action === 'next') {
auto = 'idle';
nextField(el);
return;
}
auto = 'sent';
said = sentText ?? w.done;
timer = setTimeout(() => (auto = 'idle'), hold());
if (document.activeElement !== el && el.isConnected) el.focus();
}
function keydown(e: KeyboardEvent) {
if (e.key === 'Escape' && shown === 'error' && status === undefined) {
auto = 'idle';
failure = '';
return;
}
const r = enterAction(e, { multiline, enterSends, softKeyboard: isSoftKeyboard() });
if (r === 'send') {
e.preventDefault();
if (shown !== 'sending') void submit();
} else if (r === 'ignore' && e.key === 'Enter' && e.altKey && !multiline) {
// Alt+Enter must not submit the form. An Enter that ends an input method's composition is left alone.
e.preventDefault();
} else if (editable && !multiline && e.key === 'Enter' && !e.isComposing && e.keyCode !== 229) {
// A single-line editable box never takes a line break.
e.preventDefault();
}
}
function typed() {
if (shown === 'error' && status === undefined) {
auto = 'idle';
failure = '';
}
if (shown === 'sent' && status === undefined) auto = 'idle';
grow();
}
// Editable mode: the box's text is the value. Typing, paste and drop bring plain text only.
function edited() {
if (!editor) return;
let t = readText(editor);
let rewrite = false;
if (!multiline && /\n/.test(t)) {
t = t.replace(/\r?\n/g, ' ');
rewrite = true;
}
if (maxlength !== undefined && t.length > maxlength) {
t = t.slice(0, maxlength);
rewrite = true;
}
if (t === '' && editor.childNodes.length > 0) rewrite = true; // a stray <br> would hide the placeholder
if (rewrite) {
writeText(editor, t);
if (t) caretToEnd(editor);
}
value = t;
typed();
}
function pasted(e: ClipboardEvent) {
if (!editor) return;
e.preventDefault();
if (locked) return;
let t = e.clipboardData?.getData('text/plain') ?? '';
if (!multiline) t = t.replace(/\r?\n/g, ' ');
insertPlainText(editor, t);
edited();
}
function dropped(e: DragEvent) {
if (!editor) return;
e.preventDefault();
const t = e.dataTransfer?.getData('text/plain') ?? '';
if (!t || locked) return;
editor.focus();
insertPlainText(editor, multiline ? t : t.replace(/\r?\n/g, ' '));
edited();
}
// A value set from outside (bind:value, a field cleared after sending) is written into the box.
$effect(() => {
const v = value;
if (editable && editor && readText(editor) !== v) writeText(editor, v);
});
// field-sizing: content grows the textarea in Chromium (WebView2, Android WebView); elsewhere, grow it here.
const sizesItself = typeof CSS !== 'undefined' && CSS.supports?.('field-sizing', 'content');
function grow() {
if (!multiline || sizesItself || !(input instanceof HTMLTextAreaElement)) return;
input.style.height = 'auto';
input.style.height = `${input.scrollHeight}px`;
}
$effect(() => {
void value;
grow();
});
$effect(() => () => clearTimeout(timer));
$effect(() => {
if (autofocus) box?.focus();
});
function focusBox() {
if (!box) return;
box.focus();
if (editable) caretToEnd(box);
}
function focusInput(e: MouseEvent) {
if (e.target === e.currentTarget) focusBox();
}
</script>
<div
class={['domi-field', multiline && 'domi-field--multiline', size === 'lg' && 'domi-field--lg', cls]}
data-state={shown === 'idle' ? undefined : shown}
data-empty={empty ? '' : undefined}
data-disabled={disabled ? '' : undefined}
>
{#if editable}
<!-- An editable box is not a labelable element: the label names it through aria-labelledby; a click focuses it. -->
<!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
<span class={['domi-field__label', hideLabel && 'domi-sr']} id={labelId} role="presentation" onclick={focusBox}>
{label}{#if optional}<span class="domi-field__optional">{" (optional)"}</span>{/if}
</span>
{:else}
<label class={['domi-field__label', hideLabel && 'domi-sr']} for={fieldId} id={labelId}>
{label}{#if optional}<span class="domi-field__optional">{" (optional)"}</span>{/if}
</label>
{/if}
<!-- svelte-ignore a11y_click_events_have_key_events a11y_no_static_element_interactions -->
<div class="domi-field__well" role="presentation" data-force={force} onclick={focusInput}>
{#if editable}
<div
bind:this={editor}
class={['domi-field__input', 'domi-field__input--editable', multiline && 'domi-field__input--lines']}
id={fieldId}
role="textbox"
tabindex={disabled ? -1 : 0}
contenteditable={locked ? 'false' : 'plaintext-only'}
aria-labelledby={labelId}
aria-multiline={multiline ? 'true' : 'false'}
aria-describedby={described}
aria-invalid={message ? 'true' : undefined}
aria-required={required ? 'true' : undefined}
aria-readonly={readonly || shown === 'sending' ? 'true' : undefined}
aria-disabled={disabled ? 'true' : undefined}
aria-placeholder={placeholder}
data-placeholder={placeholder}
inputmode={inputmode ?? inputmodeFor(type)}
enterkeyhint={multiline ? (w.key === 'done' ? 'done' : 'enter') : w.key === 'done' ? 'done' : w.key}
spellcheck={spellcheck ?? true}
style:--_rows-max={rows}
onkeydown={keydown}
oninput={edited}
onpaste={pasted}
ondrop={dropped}
></div>
{#if name}<input type="hidden" {name} {value} />{/if}
{:else if multiline}
<textarea
bind:this={input}
bind:value
class="domi-field__input"
id={fieldId}
{name}
{placeholder}
{disabled}
readonly={readonly || shown === 'sending'}
{required}
{maxlength}
{spellcheck}
rows="1"
style:--_rows-max={rows}
enterkeyhint={w.key === 'done' ? 'done' : 'enter'}
aria-invalid={message ? 'true' : undefined}
aria-describedby={described}
onkeydown={keydown}
oninput={typed}
></textarea>
{:else}
<input
bind:this={input}
bind:value
class="domi-field__input"
id={fieldId}
type={inputType}
{name}
{placeholder}
{disabled}
readonly={readonly || shown === 'sending'}
{required}
{maxlength}
{spellcheck}
{autocomplete}
{inputmode}
enterkeyhint={w.key === 'done' ? 'done' : w.key}
aria-invalid={message ? 'true' : undefined}
aria-describedby={described}
onkeydown={keydown}
oninput={typed}
/>
{/if}
{#if type === 'password'}
<button
type="button"
class="domi-field__tool"
aria-label={revealed ? 'Hide password' : 'Show password'}
aria-pressed={revealed}
aria-controls={fieldId}
{disabled}
onclick={() => (revealed = !revealed)}
>
<Icon name={revealed ? 'eye-off' : 'eye'} />
</button>
{/if}
<button
type="button"
class="domi-send"
aria-label={actionLabel ?? w.label}
aria-disabled={lit ? undefined : 'true'}
aria-busy={shown === 'sending' ? 'true' : undefined}
aria-controls={fieldId}
tabindex={lit ? undefined : -1}
title={actionLabel ?? w.label}
data-state={shown === 'sending' ? 'sending' : undefined}
data-force={sendForce}
onclick={() => void submit()}
use:strike
>
{#if shown === 'sending'}
<Strike />
{:else if shown === 'sent'}
<Icon name="check" draw />
{:else}
<Icon name={w.icon} />
{/if}
</button>
</div>
{#if hint}<p class="domi-field__hint" id={hintId}>{hint}</p>{/if}
{#if message}<p class="domi-field__error" id={errorId}><Icon name="alert" />{message}</p>{/if}
<span class="domi-sr" role="status">{said}</span>
</div>