okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge main (87dfca0e7) into f-own-int: the 0.2.14 app branch, fixtures and CI fixes, the Qwen4-readiness tools, the shape-engine build scriptsffb3d9b31

main
28.1 KiB555 linesraw
1import { tr } from '../lib/i18n';
2/**
3 * Strata primitives.
4 *
5 * These wrap the kit's own component classes (`st-*` from ui/components.css)
6 * rather than inventing a parallel set, so the app and the design reference stay
7 * the same system. Anything added here is a documented extension that only uses
8 * kit tokens — see src/styles/app.css.
9 */
10import { createContext, useContext, useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type AriaAttributes, type CSSProperties, type ReactNode } from 'react';
11import { createPortal } from 'react-dom';
12import { cx, userError } from '../lib/format';
13import { plainFailure } from '../lib/plain-errors';
14import { dismissActionError, dismissToast, holdToast, releaseToast, useStore } from '../lib/store';
15import { isTopSurface, useSurfaceFocus } from '../lib/focus';
16import { measureFrame, placeAnchored } from '../lib/overlay-place';
17/* -------------------------------------------------------------------- icon */
18export type IconName = 'pause' | 'play' | 'activity' | 'plus' | 'shield' | 'computer'
19// Authored for the shell: see docs/design-system-notes.md.
20 | 'panel' | 'search' | 'sliders' | 'folder' | 'folder-plus' | 'file' | 'ellipsis' | 'pencil' | 'pin' | 'x' | 'attach' | 'bolt' | 'branch' | 'chat' | 'check' | 'chevron' | 'clock' | 'copy' | 'cpu' | 'disk' | 'download' | 'error' | 'experts' | 'gauge' | 'gpu' | 'image' | 'info' | 'expand' | 'contract' | 'layers' | 'models' | 'skills' | 'engine' | 'family-qwen' | 'model-file' | 'link' | 'memory' | 'mic' | 'moon' | 'new-chat' | 'refresh' | 'send' | 'settings' | 'stop' | 'sun' | 'thermometer' | 'thinking' | 'tool' | 'trash' | 'warning';
21export function Icon({ name, size, className, style, }: {
22    name: IconName;
23    size?: number;
24    className?: string;
25    style?: CSSProperties;
26}) {
27    return (<svg className={cx('st-icon', className)} style={{ width: size, height: size, ...style }} aria-hidden="true" focusable="false">
28      <use href={`/icons/sprite.svg#i-${name}`}/>
29    </svg>);
30}
31/* ------------------------------------------------------------------ button */
32type BtnProps = AriaAttributes & {
33    children?: ReactNode;
34    variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
35    size?: 'sm' | 'md' | 'lg';
36    icon?: IconName;
37    iconRight?: IconName;
38    block?: boolean;
39    title?: string;
40    disabled?: boolean;
41    active?: boolean;
42    type?: 'button' | 'submit';
43    onClick?: () => void;
44    className?: string;
45};
46export function Btn({ children, variant = 'secondary', size = 'md', icon, iconRight, block, title, disabled, active, type = 'button', onClick, className, ...aria }: BtnProps) {
47    return (<button {...aria} type={type} title={tr(title)} disabled={disabled} onClick={onClick} className={cx('st-btn', `st-btn--${variant}`, size === 'sm' && 'st-btn--sm', size === 'lg' && 'st-btn--lg', block && 'st-btn--block', active && 'st-btn--active', className)}>
48      {tr(icon ? <Icon name={icon}/> : null)}
49      {tr(children)}
50      {tr(iconRight ? <Icon name={iconRight}/> : null)}
51    </button>);
52}
53export function IconBtn({ name, title, onClick, disabled, active, size = 19, }: {
54    name: IconName;
55    title: string;
56    onClick?: () => void;
57    disabled?: boolean;
58    /** Renders in the pressed state — used by the sidebar's search toggle. */
59    active?: boolean;
60    size?: number;
61}) {
62    return (<button type="button" className={cx('st-btn st-btn--icon', active && 'is-on')} aria-pressed={active} title={tr(title)} aria-label={tr(title)} onClick={onClick} disabled={disabled}>
63      <Icon name={name} size={size}/>
64    </button>);
65}
66/* ------------------------------------------------------------------- panel */
67export function Panel({ children, className, pad, }: {
68    children: ReactNode;
69    className?: string;
70    pad?: boolean;
71    accent?: boolean;
72}) {
73    return <section className={cx('st-card', !pad && 'st-card--flush', className)}>{tr(children)}</section>;
74}
75export function PanelHead({ title, sub, right, icon, }: {
76    title: ReactNode;
77    sub?: ReactNode;
78    right?: ReactNode;
79    icon?: IconName;
80}) {
81    return (<header className="st-card__head">
82      {tr(icon ? <Icon name={icon} size={18} className="st-card__headicon"/> : null)}
83      <div className="col" style={{ minWidth: 0, flex: 1 }}>
84        {/* A real h3 so the document has an outline below the h2 section heads;
85            styled exactly as before. */}
86        <h3 className="h4">{tr(title)}</h3>
87        {tr(sub ? <div className="small muted">{tr(sub)}</div> : null)}
88      </div>
89      {tr(right)}
90    </header>);
91}
92/* -------------------------------------------------------------------- pill */
93export function Pill({ children, tone = 'plain', dot, badge, className, }: {
94    children: ReactNode;
95    tone?: 'plain' | 'accent' | 'info' | 'warn' | 'danger';
96    dot?: boolean;
97    /** `badge` renders the 24px badge treatment instead of the 30px status pill. */
98    badge?: boolean;
99    className?: string;
100}) {
101    const toneClass = {
102        plain: undefined,
103        accent: badge ? 'st-badge--generating' : 'st-pill--accent',
104        info: badge ? 'st-badge--reading' : 'st-pill--info',
105        warn: badge ? 'st-badge--queued' : 'st-pill--warn',
106        danger: badge ? 'st-badge--error' : 'st-pill--danger',
107    }[tone];
108    return (<span className={cx(badge ? 'st-badge' : 'st-pill', toneClass, className)}>
109      {tr(dot && !badge ? <span className="st-pill__dot"/> : null)}
110      {tr(children)}
111    </span>);
112}
113/* --------------------------------------------------------------------- bar */
114export function Bar({ value, tone = 'accent', size, indeterminate, label = 'Progress', }: {
115    value: number;
116    tone?: 'accent' | 'info' | 'warn' | 'danger';
117    size?: 'sm' | 'lg';
118    indeterminate?: boolean;
119    label?: string;
120}) {
121    return (<div className={cx('st-progress', size === 'sm' && 'st-progress--sm', size === 'lg' && 'st-progress--lg', indeterminate && 'st-progress--indeterminate')} data-tone={tone === 'accent' ? undefined : tone} role="progressbar" aria-label={tr(label)} aria-valuenow={indeterminate ? undefined : Math.round(value)} aria-valuemin={0} aria-valuemax={100}>
122      <div className="st-progress__bar" style={{ width: `${Math.max(0, Math.min(100, value))}%` }}/>
123    </div>);
124}
125/* ---------------------------------------------------------------- segments */
126export function Seg<T extends string>({ value, options, onChange, ariaLabel, panelId, }: {
127    value: T;
128    /** `title` explains a label that has to stay short to fit the control. */
129    options: {
130        value: T;
131        label: string;
132        icon?: IconName;
133        title?: string;
134        disabled?: boolean;
135    }[];
136    onChange: (v: T) => void;
137    ariaLabel?: string;
138    /** Supply the associated panel ID for actual tabs; omit for segmented values. */
139    panelId?: string;
140}) {
141    return (<div className="st-tabs" role={panelId ? 'tablist' : 'radiogroup'} aria-label={tr(ariaLabel)}>
142      {tr(options.map((o) => (<button key={o.value} type="button" role={panelId ? 'tab' : 'radio'} id={panelId ? `${panelId}-tab-${o.value}` : undefined} className="st-tab" aria-checked={panelId ? undefined : value === o.value} aria-selected={panelId ? value === o.value : undefined} aria-controls={panelId} disabled={o.disabled} tabIndex={value === o.value ? 0 : -1} onKeyDown={e => {
143                if (!['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key))
144                    return;
145                e.preventDefault();
146                const available = options.map((item, index) => ({ item, index })).filter(({ item }) => !item.disabled);
147                const at = available.findIndex(({ item }) => item === o);
148                const nextAt = e.key === 'Home' ? 0 : e.key === 'End' ? available.length - 1 : (at + (e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : -1) + available.length) % available.length;
149                const next = available[nextAt]?.index;
150                if (next === undefined)
151                    return;
152                onChange(options[next].value);
153                (e.currentTarget.parentElement?.children[next] as HTMLElement)?.focus();
154            }} title={tr(o.title)} onClick={() => onChange(o.value)}>
155          {tr(o.icon ? <Icon name={o.icon}/> : null)}{tr(o.label)}
156        </button>)))}
157    </div>);
158}
159/* ------------------------------------------------------------------- steps */
160export interface StepDef {
161    n: number;
162    label: string;
163}
164export function Steps({ steps, current }: {
165    steps: StepDef[];
166    current: number;
167}) {
168    return (<div className="setup-progress"><p className="steps-current small">{tr("Step ")}{tr(current)}{tr(" of ")}{tr(steps.length)} · {tr(steps.find(s => s.n === current)?.label)}</p><div className="steps" role="list" aria-label={tr("Setup progress")}>
169      {tr(steps.map((s) => {
170            const state = s.n < current ? 'done' : s.n === current ? 'active' : 'todo';
171            return (<div key={s.n} className="step" data-state={state} role="listitem" 
172            /* Omitted rather than "false" when not current: the attribute is
173               supposed to mark one thing, and a query for it should find one. */
174            aria-current={state === 'active' ? 'step' : undefined}>
175            <span className="step__n">{tr(s.n)}</span>
176            <span>·</span>
177            <span>{tr(s.label)}</span>
178          </div>);
179        }))}
180    </div></div>);
181}
182/* ------------------------------------------------------------------ fields */
183const FieldContext = createContext<{
184    label: string;
185    description?: string;
186} | null>(null);
187export function Field({ label, hint, impact, children, wide, }: {
188    label: ReactNode;
189    hint?: ReactNode;
190    /** What the current value actually costs. Shown where the choice is made
191     *  rather than only in a summary elsewhere on the screen. */
192    impact?: ReactNode;
193    children: ReactNode;
194    wide?: boolean;
195}) {
196    const id = useId();
197    return (<FieldContext.Provider value={{ label: `${id}-label`, description: hint || impact ? `${id}-description` : undefined }}>
198    <div className="field" role="group" aria-labelledby={`${id}-label`}>
199      <div className="field__main">
200        <div className="field__label" id={`${id}-label`}>{tr(label)}</div>
201        <div id={`${id}-description`}>
202          {tr(hint ? <div className="field__hint">{tr(hint)}</div> : null)}
203          {tr(impact ? <div className="field__impact">{tr(impact)}</div> : null)}
204        </div>
205      </div>
206      <div className={cx('field__control', wide && 'field__control--wide')}>{tr(children)}</div>
207    </div>
208    </FieldContext.Provider>);
209}
210/**
211 * A listbox styled as a Strata field.
212 *
213 * This replaces a native `<select>`, whose popup the OS draws — on macOS a dark
214 * system menu with a blue highlight, which shared nothing with the rest of the
215 * app. Owning the popup means owning the whole interaction, so this implements
216 * the full combobox pattern: focus stays on the trigger with
217 * `aria-activedescendant` tracking the highlighted option, and the popup renders
218 * through a portal so it can never end up nested inside another glass surface.
219 */
220export function Select<T extends string>({ value, valueSuffix, options, onChange, ariaLabel, disabled = false, menuSize = 'standard', menuMinWidth, menuWidth, menuClassName, optionIcon, singleLine = false, translateLabels = true, }: {
221    value: T;
222    valueSuffix?: ReactNode;
223    /** Keep custom names and font families verbatim. */
224    translateLabels?: boolean;
225    /** `title` explains a label that has to stay short to fit the control. */
226    options: {
227        value: T;
228        label: string;
229        title?: string;
230        disabled?: boolean;
231    }[];
232    onChange: (v: T) => void;
233    ariaLabel?: string;
234    disabled?: boolean;
235    menuSize?: 'standard' | 'comfortable';
236    menuMinWidth?: number;
237    /** Override popup width while keeping the trigger unchanged. */
238    menuWidth?: number;
239    menuClassName?: string;
240    optionIcon?: (value: T) => IconName;
241    singleLine?: boolean;
242}) {
243    const field = useContext(FieldContext);
244    const listId = useId();
245    const triggerRef = useRef<HTMLButtonElement>(null);
246    const popupRef = useRef<HTMLDivElement>(null);
247    const [open, setOpen] = useState(false);
248    const [placed, setPlaced] = useState<{
249        left: number;
250        top: number;
251        width: number;
252        maxHeight: number;
253    } | null>(null);
254    const [cursor, setCursor] = useState(0);
255    const [typed, setTyped] = useState('');
256    const current = options.find((o) => o.value === value);
257    const optionLabel = (label: string) => translateLabels ? tr(label) : label;
258    const close = useCallback((refocus = true) => {
259        setOpen(false);
260        setTyped('');
261        if (refocus)
262            triggerRef.current?.focus();
263    }, []);
264    /* Where the list goes, in screen pixels, written in the page's own pixels (lib/overlay-place.ts; the page may be scaled by "Interface size", #4653):
265       below its button when the whole list fits there, else above, else the side with more room; as tall as the list needs, and no taller than
266       the room (it then scrolls, using all of it). It used to be capped at 320 px whatever the window, and opened upward by a transform that
267       sent it off the top of a short window. `measured` is the rendered popup, when there is one. */
268    const placeList = useCallback((measured: HTMLElement | null) => {
269        const el = triggerRef.current;
270        if (!el)
271            return null;
272        const { scale, viewport } = measureFrame();
273        const r = el.getBoundingClientRect();
274        const width = Math.min((menuWidth ?? Math.max(r.width / scale, menuMinWidth ?? (menuSize === 'comfortable' ? 340 : 180))) * scale, viewport.width - 24);
275        const natural = measured
276            ? measured.scrollHeight * scale + (measured.getBoundingClientRect().height - measured.clientHeight * scale)
277            : (options.length * (menuSize === 'comfortable' ? 52 : 38) + 12) * scale;
278        const p = placeAnchored({ anchor: r, size: { width, height: natural }, viewport, scale, gapBelow: 6, gapAbove: 6 });
279        return { left: p.left, top: p.top, width: width / scale, maxHeight: p.maxHeight };
280    }, [options.length, menuSize, menuMinWidth, menuWidth]);
281    const openMenu = useCallback(() => {
282        const next = placeList(null);
283        if (!next)
284            return;
285        setPlaced(next);
286        setCursor(Math.max(0, options.findIndex((o) => o.value === value)));
287        setOpen(true);
288    }, [options, value, placeList]);
289    // Once the list is on the screen its real height is known: place it again with that.
290    useLayoutEffect(() => {
291        if (!open)
292            return;
293        const next = placeList(popupRef.current);
294        if (next)
295            setPlaced(next);
296    }, [open, placeList]);
297    // The popup is fixed-positioned, so it has to follow its trigger.
298    useEffect(() => {
299        if (!open)
300            return undefined;
301        const reposition = () => {
302            const next = placeList(popupRef.current);
303            if (next)
304                setPlaced(next);
305        };
306        const onDocDown = (e: PointerEvent) => {
307            if (!triggerRef.current?.contains(e.target as Node) && !popupRef.current?.contains(e.target as Node))
308                close(false);
309        };
310        window.addEventListener('scroll', reposition, true);
311        window.addEventListener('resize', reposition);
312        document.addEventListener('pointerdown', onDocDown, true);
313        return () => {
314            window.removeEventListener('scroll', reposition, true);
315            window.removeEventListener('resize', reposition);
316            document.removeEventListener('pointerdown', onDocDown, true);
317        };
318    }, [open, close, placeList]);
319    useEffect(() => {
320        if (open)
321            document.getElementById(`${listId}-${cursor}`)?.scrollIntoView({ block: 'nearest' });
322    }, [open, cursor, listId]);
323    function onKeyDown(e: React.KeyboardEvent) {
324        if (!open) {
325            if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Enter' || e.key === ' ') {
326                e.preventDefault();
327                openMenu();
328            }
329            return;
330        }
331        switch (e.key) {
332            case 'Escape':
333                e.preventDefault();
334                e.stopPropagation();
335                close();
336                break;
337            case 'ArrowDown':
338                e.preventDefault();
339                setCursor((c) => (c + 1) % options.length);
340                break;
341            case 'ArrowUp':
342                e.preventDefault();
343                setCursor((c) => (c - 1 + options.length) % options.length);
344                break;
345            case 'Home':
346                e.preventDefault();
347                setCursor(0);
348                break;
349            case 'End':
350                e.preventDefault();
351                setCursor(options.length - 1);
352                break;
353            case 'Enter':
354            case ' ':
355                e.preventDefault();
356                if (!options[cursor].disabled)
357                    onChange(options[cursor].value);
358                close();
359                break;
360            case 'Tab':
361                close(false);
362                break;
363            default: {
364                // Typeahead: consecutive letters narrow the match, as a native select does.
365                if (e.key.length !== 1 || !/\S/.test(e.key))
366                    return;
367                const next = typed + e.key.toLowerCase();
368                const from = next.length === 1 ? cursor + 1 : cursor;
369                const ordered = [...options.slice(from), ...options.slice(0, from)];
370                const hit = ordered.find((o) => optionLabel(o.label).toLowerCase().startsWith(next));
371                const restart = !hit && next.length > 1 ? options.find((o) => optionLabel(o.label).toLowerCase().startsWith(e.key.toLowerCase())) : null;
372                const target = hit ?? restart;
373                setTyped(restart ? e.key.toLowerCase() : next);
374                if (target)
375                    setCursor(options.indexOf(target));
376            }
377        }
378    }
379    return (<>
380      <button ref={triggerRef} type="button" className="st-input select select__trigger" role="combobox" disabled={disabled} aria-expanded={open} aria-haspopup="listbox" aria-controls={open ? listId : undefined} aria-label={tr(ariaLabel)} aria-labelledby={ariaLabel ? undefined : field?.label} aria-describedby={field?.description} aria-activedescendant={open ? `${listId}-${cursor}` : undefined} onClick={() => (open ? close() : openMenu())} onKeyDown={onKeyDown}>
381        <span className="select__value">{valueSuffix ? <><span>{optionLabel(current?.label ?? '')}</span>{valueSuffix}</> : optionLabel(current?.label ?? '')}</span>
382        <Icon name="chevron" size={16}/>
383      </button>
384      {tr(open && placed
385            ? createPortal(<div ref={popupRef} id={listId} className={cx('select__pop', menuSize === 'comfortable' && 'select__pop--comfortable', singleLine && 'select__pop--single-line', menuClassName)} role="listbox" aria-label={tr(ariaLabel)} style={{ left: placed.left, top: placed.top, width: placed.width, maxHeight: placed.maxHeight, zIndex: triggerRef.current?.closest('[role="dialog"]') ? 'var(--layer-dialog-popover)' : 'var(--layer-popover)' }}>
386              {tr(options.map((o, i) => (<div key={o.value} id={`${listId}-${i}`} role="option" aria-selected={o.value === value} aria-disabled={o.disabled || undefined} tabIndex={-1} className="select__opt" data-active={i === cursor || undefined} onMouseEnter={() => setCursor(i)} onMouseDown={(e) => e.preventDefault()} onClick={() => {
387                        if (o.disabled)
388                            return;
389                        onChange(o.value);
390                        close();
391                    }}>
392                  {tr(optionIcon ? <span className="select__option-icon"><Icon name={optionIcon(o.value)} size={20}/></span> : <span className="select__tick">{tr(o.value === value ? <Icon name="check" size={14}/> : null)}</span>)}
393                  <span className="select__option-label" title={o.title ? tr(o.title) : singleLine ? optionLabel(o.label) : undefined}>{optionLabel(o.label)}</span>
394                  {tr(optionIcon && o.value === value ? <Icon name="check" size={15} className="select__option-check"/> : null)}
395                </div>)))}
396            </div>, document.body)
397            : null)}
398    </>);
399}
400/** One modal surface for confirmations and narrow-screen inspectors. */
401export function Dialog({ open, title, onClose, children, actions, headerActions, compact = false, sheet = false, wide = false, hideTitle = false, className, noClose = false }: {
402    open: boolean;
403    title: ReactNode;
404    onClose: () => void;
405    children: ReactNode;
406    actions?: ReactNode;
407    headerActions?: ReactNode;
408    compact?: boolean;
409    sheet?: boolean;
410    wide?: boolean;
411    hideTitle?: boolean;
412    className?: string;
413    /** No close button: the person must use the dialog's own buttons (a move that is running). */
414    noClose?: boolean;
415}) {
416    const ref = useRef<HTMLElement>(null);
417    const id = useId();
418    useSurfaceFocus(open, ref);
419    useEffect(() => {
420        if (!open)
421            return;
422        const close = (e: KeyboardEvent) => {
423            if (e.key === 'Escape' && !e.defaultPrevented && isTopSurface(ref.current)) {
424                e.preventDefault();
425                e.stopImmediatePropagation();
426                onClose();
427            }
428        };
429        document.addEventListener('keydown', close);
430        return () => document.removeEventListener('keydown', close);
431    }, [open, onClose]);
432    if (!open)
433        return null;
434    return createPortal(<div className="dialog-layer">
435    <div className="dialog-scrim" onClick={onClose} aria-hidden="true"/>
436    <section ref={ref} className={cx(`${sheet ? 'dialog-surface dialog-surface--sheet' : 'dialog-surface'}${wide ? ' dialog-surface--wide' : ''}${compact ? ' dialog-surface--compact' : ''}`, className)} role="dialog" aria-modal="true" aria-labelledby={id} tabIndex={-1}>
437      <header className="dialog-head"><h2 className={hideTitle ? 'sr-only' : 'h3'} id={id}>{tr(title)}</h2><div className="dialog-head__actions">{tr(headerActions)}{noClose ? null : <IconBtn name="x" title={typeof title === 'string' ? tr("Close {0}", [title]) : tr("Close")} onClick={onClose}/>}</div></header>
438      <div className="dialog-body">{tr(children)}</div>
439      {tr(actions ? <footer className="dialog-actions">{tr(actions)}</footer> : null)}
440    </section>
441  </div>, document.body);
442}
443/* ------------------------------------------------------------------- empty */
444export function Empty({ icon = 'info', title, body, action, }: {
445    icon?: IconName;
446    title: string;
447    body?: ReactNode;
448    action?: ReactNode;
449}) {
450    return (<div className="empty">
451      <span className="empty__icon">
452        <Icon name={icon} size={22}/>
453      </span>
454      <div className="empty__title">{tr(title)}</div>
455      {tr(body ? (<div className="small muted" style={{ maxWidth: 460 }}>
456          {tr(body)}
457        </div>) : null)}
458      {tr(action ? <div style={{ marginTop: 6 }}>{tr(action)}</div> : null)}
459    </div>);
460}
461/* ------------------------------------------------------- failed actions ---
462   One component for every failure a screen needs to report. The rule this
463   encodes (plan 14): wherever a failure is reported, the surface that failed
464   offers the retry — a toast may summarise but must not be the only record.
465   Kept here so the treatment lands once rather than once per screen. */
466export function ActionError() {
467    const actionError = useStore((s) => s.actionError);
468    if (!actionError)
469        return null;
470    return <div className="verror row row--between"><ErrorNotice message={`${actionError.label}: ${userError(actionError.message)}`} onRetry={() => actionError.retry()}/><Btn variant="ghost" size="sm" onClick={() => dismissActionError()}>{tr("Dismiss")}</Btn></div>;
471}
472/* ------------------------------------------------------------------ toasts */
473export function Toasts() {
474    const toasts = useStore((s) => s.toasts);
475    if (!toasts.length)
476        return null;
477    const iconFor = { success: 'check', info: 'info', warn: 'warning', error: 'error' } as const;
478    return (<div className="st-toasts" aria-live="polite">
479      {tr(toasts.map((t) => (<div key={t.id} className="st-toast st-toast--toned" data-tone={t.tone} data-leaving={t.leaving || undefined} onMouseEnter={() => holdToast(t.id)} onMouseLeave={() => releaseToast(t.id)} onFocusCapture={() => holdToast(t.id)} onBlurCapture={() => releaseToast(t.id)}>
480          <span className="st-toast__icon">
481            <Icon name={iconFor[t.tone]} size={20}/>
482          </span>
483          <div style={{ flex: 1, minWidth: 0 }}>
484            <div className="st-toast__title">{tr(t.title)}</div>
485            {tr(t.body ? <div className="st-toast__body">{tr(t.body)}</div> : null)}
486            {tr(t.action ? <button type="button" className="st-btn st-btn--sm" style={{ marginTop: 8 }} onClick={t.action.run}>{tr(t.action.label)}</button> : null)}
487          </div>
488          <button type="button" className="st-btn st-btn--icon st-btn--sm" onClick={() => dismissToast(t.id)} aria-label={tr("Dismiss")}>
489            <Icon name="chevron" size={15} style={{ transform: 'rotate(90deg)' }}/>
490          </button>
491        </div>)))}
492    </div>);
493}
494/* ------------------------------------------------------------------ metric */
495/**
496 * A metric tile: the kit's `.st-metric` inside a card, which is how the design
497 * reference lays out every number in the app.
498 */
499export function Metric({ label, value, unit, sub, icon, spark, compact, children, }: {
500    label: string;
501    value: ReactNode;
502    unit?: string;
503    sub?: ReactNode;
504    icon?: IconName;
505    spark?: ReactNode;
506    /** Text values read better a step down from the kit's 32px stat size. */
507    compact?: boolean;
508    children?: ReactNode;
509}) {
510    return (<section className="st-card">
511      <div className="st-metric">
512        <div className="st-metric__label">
513          {tr(icon ? <Icon name={icon} size={18}/> : null)}
514          {tr(label)}
515        </div>
516        <div className={cx('st-metric__value', compact && 'st-metric__value--text')}>
517          {tr(value)}
518          {tr(unit ? <span className="st-metric__unit">{tr(unit)}</span> : null)}
519        </div>
520        {tr(sub ? <div className="spec__sub">{tr(sub)}</div> : null)}
521        {tr(children)}
522        {tr(spark ? <div className="st-metric__spark">{tr(spark)}</div> : null)}
523      </div>
524    </section>);
525}
526/** A row of metric tiles. */
527export function MetricGrid({ children, min = 200 }: {
528    children: ReactNode;
529    min?: number;
530}) {
531    return (<div className="metricgrid" style={{ gridTemplateColumns: `repeat(auto-fit, minmax(${min}px, 1fr))` }}>
532      {tr(children)}
533    </div>);
534}
535/** Shared, announced error with a cause and a concrete recovery action. */
536export function ErrorNotice({ message, next, action, onRetry, detail, secondary }: {
537    message: string;
538    next?: string;
539    action?: string;
540    onRetry?: () => void;
541    detail?: string;
542    /** A second way out, beside the first (a context error offers two). */
543    secondary?: { label: string; onClick: () => void };
544}) {
545    // A known failure is shown as a sentence and a next step; the original text stays under Details for experts.
546    const plain = plainFailure(message);
547    const known = plain.kind !== 'plain';
548    const nextStep = known ? (plain.next ? tr(plain.next) : next) : next;
549    const raw = detail ?? (known ? plain.detail : undefined);
550    // An unrecognised failure still goes through plainFailure: it peels an
551    // `{"error":"…"}` body down to the sentence, where userError only capitalised
552    // the JSON and showed an object to the person.
553    return <div className="error-notice" role="alert"><Icon name="error" size={18}/><div><strong>{tr(plain.message)}</strong>{tr(nextStep ? <p>{tr(nextStep)}</p> : null)}{tr(raw ? <details className="error-detail"><summary className="small">{tr("Details")}</summary><pre className="small muted">{raw}</pre></details> : null)}</div>{tr(onRetry ? (secondary ? <div className="row"><Btn size="sm" onClick={onRetry}>{tr(action ?? 'Try again')}</Btn><Btn size="sm" variant="ghost" onClick={secondary.onClick}>{tr(secondary.label)}</Btn></div> : <Btn size="sm" onClick={onRetry}>{tr(action ?? 'Try again')}</Btn>) : null)}</div>;
554}
555export function PreviewBadge() { const demo = useStore(s => s.library?.mode === 'simulated'); return demo ? <span className="preview-badge">{tr("Preview build")}</span> : null; }