[ui] DomiUi: Rosea's buttons and town search on @domi/ui v1.0.4 (CPAL-1.0, vendored by its own tool into packages/domi-ui), the licence credit at the foot of every screen, the README's copy line and public-domain sources; before-and-after pictures by pnpm look:shots

This commit is contained in:
2026-11-23 00:59:50 +01:00
parent 295e6ba59a
commit 8018268821
79 changed files with 8554 additions and 222 deletions
@@ -0,0 +1,151 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import type { HTMLButtonAttributes } from 'svelte/elements';
import Icon from './Icon.svelte';
import Strike from './Strike.svelte';
import { strike } from '../lib/strike';
import { failureText, type ButtonState } from '../lib/keys';
import type { IconName } from '../lib/icons';
interface Props extends Omit<HTMLButtonAttributes, 'onclick' | 'class' | 'children'> {
/** plate: every ordinary action. primary: the one leaf per screen. quiet: toolbars and third actions. danger: deletes. */
variant?: 'plate' | 'primary' | 'quiet' | 'danger';
size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl';
icon?: IconName;
/** Icon only: the label becomes the accessible name and the tooltip. */
iconOnly?: boolean;
/** The words on the button. Required for iconOnly (it is the accessible name), else use children. */
label?: string;
block?: boolean;
/** Set to drive the state yourself. Left unset, a Promise returned by onclick drives it. */
status?: ButtonState;
/** May return a Promise: the button shows loading, then success (briefly) or error. */
onclick?: (event: MouseEvent) => unknown;
/**
* Two-step confirmation for danger: the first press arms the button and shows this text ("Press again to
* delete"); a second press within confirmFor ms runs onclick. Escape, blur or the timeout disarms it.
*/
confirm?: string;
confirmFor?: number;
/** Announced while working, when done, and when it failed (unless the error is a DomiError with its own text). */
busyText?: string;
doneText?: string;
failText?: string;
/** Showcase and tests only: show hover, press or focus without the pointer. */
force?: string;
class?: string;
children?: Snippet;
}
let {
variant = 'plate',
size = 'md',
icon,
iconOnly = false,
label,
block = false,
status,
onclick,
confirm,
confirmFor = 4000,
busyText = 'Working',
doneText = 'Done',
failText = 'That did not work. Try again.',
force,
class: cls = '',
disabled = false,
type = 'button',
children,
...rest
}: Props = $props();
let auto = $state<ButtonState>('idle');
let armed = $state(false);
let said = $state('');
let timer: ReturnType<typeof setTimeout> | undefined;
let armTimer: ReturnType<typeof setTimeout> | undefined;
const shown = $derived<ButtonState>(status ?? auto);
const busy = $derived(shown === 'loading');
function hold(): number {
const v = getComputedStyle(document.documentElement).getPropertyValue('--domi-dur-hold');
return Math.max(900, parseFloat(v) || 1400);
}
function disarm() {
armed = false;
clearTimeout(armTimer);
}
async function press(event: MouseEvent) {
if (disabled || busy) {
event.preventDefault();
return;
}
if (confirm && !armed) {
armed = true;
said = confirm;
clearTimeout(armTimer);
armTimer = setTimeout(disarm, confirmFor);
return;
}
disarm();
const result = onclick?.(event);
const thenable = result != null && typeof (result as PromiseLike<unknown>).then === 'function';
if (!thenable || status !== undefined) return;
clearTimeout(timer);
auto = 'loading';
said = busyText;
try {
await result;
auto = 'success';
said = doneText;
timer = setTimeout(() => (auto = 'idle'), hold());
} catch (err) {
auto = 'error';
said = failureText(err, failText);
}
}
$effect(() => () => {
clearTimeout(timer);
clearTimeout(armTimer);
});
</script>
<button
{...rest}
{type}
{disabled}
class={[
'domi-btn',
variant !== 'plate' && `domi-btn--${variant}`,
size !== 'md' && `domi-btn--${size}`,
iconOnly && 'domi-btn--icon',
block && 'domi-btn--block',
cls,
]}
data-state={shown === 'idle' ? undefined : shown}
data-armed={armed ? '' : undefined}
data-force={force}
aria-busy={busy ? 'true' : undefined}
aria-disabled={busy ? 'true' : undefined}
aria-label={iconOnly ? (armed ? confirm : label) : undefined}
title={iconOnly ? (armed ? confirm : label) : undefined}
onclick={press}
onkeydown={(e) => e.key === 'Escape' && armed && disarm()}
onblur={disarm}
use:strike
>
<span class="domi-btn__label">
{#if shown === 'error'}<Icon name="alert" />{:else if icon}<Icon name={icon} />{/if}
{#if !iconOnly}
{#if armed}{confirm}{:else if children}{@render children()}{:else}{label}{/if}
{/if}
</span>
<span class="domi-btn__state domi-btn__state--loading"><Strike /></span>
<span class="domi-btn__state domi-btn__state--success">
{#if shown === 'success'}<Icon name="check" draw />{/if}
</span>
</button>
<span class="domi-sr" role="status">{said}</span>
@@ -0,0 +1,59 @@
<script lang="ts">
import type { Snippet } from 'svelte';
import { icons } from '../lib/icons';
interface Props {
checked?: boolean;
/** Part of a group is chosen: shows a bar and reads as "mixed". */
indeterminate?: boolean;
label?: string;
hint?: string;
name?: string;
value?: string;
disabled?: boolean;
required?: boolean;
onchange?: (checked: boolean) => void;
force?: string;
class?: string;
children?: Snippet;
}
let {
checked = $bindable(false),
indeterminate = $bindable(false),
label,
hint,
name,
value,
disabled = false,
required = false,
onchange,
force,
class: cls = '',
children,
}: Props = $props();
const uid = $props.id();
</script>
<label class={['domi-choice', cls]} data-force={force}>
<span class="domi-choice__control">
<input
class="domi-choice__input"
type="checkbox"
bind:checked
bind:indeterminate
{name}
{value}
{disabled}
{required}
aria-describedby={hint ? `domi-hint-${uid}` : undefined}
onchange={() => onchange?.(checked)}
/>
<svg class="domi-choice__mark" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d={indeterminate ? icons.minus : icons.check} />
</svg>
</span>
<span class="domi-choice__text">
<span>{#if children}{@render children()}{:else}{label}{/if}</span>
{#if hint}<span class="domi-choice__hint" id={`domi-hint-${uid}`}>{hint}</span>{/if}
</span>
</label>
@@ -0,0 +1,21 @@
<!-- SPDX-License-Identifier: CPAL-1.0 -->
<!--
The licence credit (CPAL-1.0 Exhibit B): "Built on Domi", the URL and the copyright notice, exactly. Place it where
it is seen when the app starts or a session begins (the first screen's foot, the sign-in screen, a splash), no less
prominent than any other credit there. The words are fixed by the licence: do not translate or shorten them.
-->
<script lang="ts">
import { DOMI_ATTRIBUTION as A } from '../lib/credit';
interface Props {
class?: string;
}
let { class: cls = '' }: Props = $props();
</script>
<p class={['domi-credit', cls]}>
<!-- Real spaces around the dots, so copied text reads as the licence writes it; flex ignores them in layout. -->
<span>{A.phrase}</span> <span class="domi-credit__dot" aria-hidden="true">·</span>
<a href={A.url} target="_blank" rel="noopener noreferrer">{A.url}</a>
<span class="domi-credit__dot" aria-hidden="true">·</span> <span>{A.copyright}</span>
</p>
@@ -0,0 +1,22 @@
<script lang="ts">
import { icons, type IconName } from '../lib/icons';
interface Props {
name: IconName;
/** Draws the path in one stroke when it appears (the check of a finished action). */
draw?: boolean;
class?: string;
}
let { name, draw = false, class: cls = '' }: Props = $props();
</script>
<svg
class={['domi-icon', draw && 'domi-check-draw', cls]}
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.8"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
focusable="false"><path d={icons[name]} /></svg>
@@ -0,0 +1,39 @@
<script lang="ts">
import type { Snippet } from 'svelte';
interface Props {
/** The group's chosen value. Bind the same variable on every radio of the group: bind:group. */
group?: string;
value: string;
name: string;
label?: string;
hint?: string;
disabled?: boolean;
onchange?: (value: string) => void;
force?: string;
class?: string;
children?: Snippet;
}
let { group = $bindable(''), value, name, label, hint, disabled = false, onchange, force, class: cls = '', children }: Props = $props();
const uid = $props.id();
</script>
<label class={['domi-choice', 'domi-choice--radio', cls]} data-force={force}>
<span class="domi-choice__control">
<input
class="domi-choice__input"
type="radio"
bind:group
{value}
{name}
{disabled}
aria-describedby={hint ? `domi-hint-${uid}` : undefined}
onchange={() => onchange?.(value)}
/>
<span class="domi-choice__mark" aria-hidden="true"></span>
</span>
<span class="domi-choice__text">
<span>{#if children}{@render children()}{:else}{label}{/if}</span>
{#if hint}<span class="domi-choice__hint" id={`domi-hint-${uid}`}>{hint}</span>{/if}
</span>
</label>
@@ -0,0 +1,62 @@
<script lang="ts">
import Icon from './Icon.svelte';
import { strike } from '../lib/strike';
import type { DomiOption } from '../types';
interface Props {
value?: string;
/** Names the group for a screen reader: "View". */
label: string;
options: DomiOption[];
disabled?: boolean;
onchange?: (value: string) => void;
/** Showcase only: value → forced state for that segment. */
force?: Record<string, string>;
class?: string;
}
let { value = $bindable(''), label, options, disabled = false, onchange, force = {}, class: cls = '' }: Props = $props();
let group: HTMLDivElement | undefined = $state();
const enabled = $derived(options.filter((o) => !o.disabled && !disabled));
function choose(v: string) {
if (v === value) return;
value = v;
onchange?.(v);
}
// A radio group: one tab stop; arrows move the choice and the focus, Home and End jump.
function keydown(e: KeyboardEvent) {
const i = enabled.findIndex((o) => o.value === value);
let j = i;
if (e.key === 'ArrowRight' || e.key === 'ArrowDown') j = (i + 1) % enabled.length;
else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') j = (i - 1 + enabled.length) % enabled.length;
else if (e.key === 'Home') j = 0;
else if (e.key === 'End') j = enabled.length - 1;
else return;
e.preventDefault();
const next = enabled[j];
if (!next) return;
choose(next.value);
group?.querySelector<HTMLButtonElement>(`[data-value="${CSS.escape(next.value)}"]`)?.focus();
}
</script>
<div bind:this={group} class={['domi-segmented', cls]} role="radiogroup" aria-label={label} tabindex="-1" onkeydown={keydown}>
{#each options as o (o.value)}
<button
type="button"
role="radio"
class="domi-segmented__item"
data-value={o.value}
data-force={force[o.value]}
aria-checked={o.value === value}
tabindex={o.value === value || (!value && o === enabled[0]) ? 0 : -1}
disabled={disabled || o.disabled}
onclick={() => choose(o.value)}
use:strike
>
{#if o.icon}<Icon name={o.icon} />{/if}{o.label}
</button>
{/each}
</div>
@@ -0,0 +1,44 @@
<script lang="ts">
import Icon from './Icon.svelte';
import type { DomiOption } from '../types';
interface Props {
/** Left unset, the first option is chosen. */
value?: string;
label: string;
hideLabel?: boolean;
options: DomiOption[];
hint?: string;
name?: string;
disabled?: boolean;
required?: boolean;
onchange?: (value: string) => void;
force?: string;
class?: string;
}
let { value = $bindable(), label, hideLabel = false, options, hint, name, disabled = false, required = false, onchange, force, class: cls = '' }: Props = $props();
const uid = $props.id();
</script>
<!-- A native select: on Android and iOS it opens the system picker, which is the right control for a thumb. -->
<div class={['domi-field', cls]}>
<label class={['domi-field__label', hideLabel && 'domi-sr']} for={`domi-select-${uid}`}>{label}</label>
<div class="domi-select" data-force={force}>
<select
class="domi-select__input"
id={`domi-select-${uid}`}
bind:value
{name}
{disabled}
{required}
aria-describedby={hint ? `domi-hint-${uid}` : undefined}
onchange={() => onchange?.(value ?? '')}
>
{#each options as o (o.value)}
<option value={o.value} disabled={o.disabled}>{o.label}</option>
{/each}
</select>
<Icon name="chevron-down" />
</div>
{#if hint}<p class="domi-field__hint" id={`domi-hint-${uid}`}>{hint}</p>{/if}
</div>
@@ -0,0 +1,6 @@
<script lang="ts">
// No props. The script block makes this a typed component for consumers whose tsconfig has allowJs off.
</script>
<!-- The loading mark: three Roman interpuncts struck in turn. Decorative; the state is announced in words. -->
<span class="domi-strike" aria-hidden="true"><i></i><i></i><i></i></span>
@@ -0,0 +1,23 @@
<script lang="ts">
interface Props {
checked?: boolean;
/** Says what is on: "Sync over mobile data". The switch reads as on or off after it. */
label: string;
disabled?: boolean;
onchange?: (checked: boolean) => void;
force?: string;
class?: string;
}
let { checked = $bindable(false), label, disabled = false, onchange, force, class: cls = '' }: Props = $props();
function toggle() {
if (disabled) return;
checked = !checked;
onchange?.(checked);
}
</script>
<button type="button" role="switch" class={['domi-switch', cls]} aria-checked={checked} {disabled} data-force={force} onclick={toggle}>
<span class="domi-switch__track" aria-hidden="true"><span class="domi-switch__knob"></span></span>
<span>{label}</span>
</button>
@@ -0,0 +1,324 @@
<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';
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. */
input?: HTMLInputElement | HTMLTextAreaElement | 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),
}: Props = $props();
const uid = $props.id();
const fieldId = $derived(id ?? `domi-field-${uid}`);
const hintId = `domi-hint-${uid}`;
const errorId = `domi-error-${uid}`;
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');
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('type') !== 'hidden',
);
const i = all.indexOf(from);
all[i + 1]?.focus();
}
async function submit() {
if (!sendable || !input) return;
const el = input;
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.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: HTMLInputElement | HTMLTextAreaElement) {
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();
}
}
function typed() {
if (shown === 'error' && status === undefined) {
auto = 'idle';
failure = '';
}
if (shown === 'sent' && status === undefined) auto = 'idle';
grow();
}
// 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) return;
input.style.height = 'auto';
input.style.height = `${input.scrollHeight}px`;
}
$effect(() => {
void value;
grow();
});
$effect(() => () => clearTimeout(timer));
$effect(() => {
if (autofocus) input?.focus();
});
function focusInput(e: MouseEvent) {
if (e.target === e.currentTarget) input?.focus();
}
</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}
>
<label class={['domi-field__label', hideLabel && 'domi-sr']} for={fieldId}>
{label}{#if optional}<span class="domi-field__optional">{" (optional)"}</span>{/if}
</label>
<!-- 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 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>