/** What Enter does in a field with a send button. Pure, so the flow is tested without a browser. */ export type EnterResult = 'send' | 'newline' | 'ignore'; export interface EnterKey { key: string; shiftKey?: boolean; ctrlKey?: boolean; metaKey?: boolean; altKey?: boolean; /** True while an input method (Chinese, Japanese, a phone keyboard's suggestion) is composing. */ isComposing?: boolean; keyCode?: number; } export interface EnterContext { multiline: boolean; /** * 'auto' (default): Enter sends, except in a multi-line field on a touch-only device, where a soft keyboard has * no Shift: there Enter makes a new line and the seal sends. 'always': Enter always sends (Shift+Enter is a new * line). 'never': Enter never sends (a multi-line field for long writing; Ctrl/Cmd+Enter still sends). */ enterSends?: 'auto' | 'always' | 'never'; /** True on a device whose only pointer is coarse (a phone). */ softKeyboard?: boolean; } export function enterAction(e: EnterKey, ctx: EnterContext): EnterResult { if (e.key !== 'Enter') return 'ignore'; // keyCode 229 is the IME's own Enter on some Android keyboards and Safari. if (e.isComposing || e.keyCode === 229) return 'ignore'; if (e.ctrlKey || e.metaKey) return 'send'; if (!ctx.multiline) return e.altKey ? 'ignore' : 'send'; if (e.shiftKey || e.altKey) return 'newline'; const mode = ctx.enterSends ?? 'auto'; if (mode === 'never') return 'newline'; if (mode === 'auto' && ctx.softKeyboard) return 'newline'; return 'send'; } /** A field can send when it holds more than white space and is not already busy. */ export function canSend(value: string, state: FieldState, disabled = false): boolean { return !disabled && state !== 'sending' && value.trim().length > 0; } export type FieldState = 'idle' | 'sending' | 'sent' | 'error'; export type ButtonState = 'idle' | 'loading' | 'success' | 'error'; /** Only a phone-like device: no fine pointer anywhere. Safe to call during SSR. */ export function isSoftKeyboard(): boolean { if (typeof matchMedia !== 'function') return false; return matchMedia('(pointer: coarse)').matches && !matchMedia('(any-pointer: fine)').matches; } /** The plain message for a failed send: the error's own text when it is meant for people, else a default. */ export function failureText(err: unknown, fallback: string): string { if (err instanceof DomiError) return err.message; if (typeof err === 'string' && err.trim()) return err; return fallback; } /** Throw this from onsend / onclick to show its message to the person. Any other error shows the default. */ export class DomiError extends Error { constructor(message: string) { super(message); this.name = 'DomiError'; } }