import { tr } from '../lib/i18n';
/**
* Strata primitives.
*
* These wrap the kit's own component classes (`st-*` from ui/components.css)
* rather than inventing a parallel set, so the app and the design reference stay
* the same system. Anything added here is a documented extension that only uses
* kit tokens — see src/styles/app.css.
*/
import { createContext, useContext, useCallback, useEffect, useId, useLayoutEffect, useRef, useState, type AriaAttributes, type CSSProperties, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { cx, userError } from '../lib/format';
import { plainFailure } from '../lib/plain-errors';
import { dismissActionError, dismissToast, holdToast, releaseToast, useStore } from '../lib/store';
import { isTopSurface, useSurfaceFocus } from '../lib/focus';
import { measureFrame, placeAnchored } from '../lib/overlay-place';
/* -------------------------------------------------------------------- icon */
export type IconName = 'pause' | 'play' | 'activity' | 'plus' | 'shield' | 'computer'
// Authored for the shell: see docs/design-system-notes.md.
| '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';
export function Icon({ name, size, className, style, }: {
name: IconName;
size?: number;
className?: string;
style?: CSSProperties;
}) {
return (
);
}
/* ------------------------------------------------------------------ button */
type BtnProps = AriaAttributes & {
children?: ReactNode;
variant?: 'primary' | 'secondary' | 'danger' | 'ghost';
size?: 'sm' | 'md' | 'lg';
icon?: IconName;
iconRight?: IconName;
block?: boolean;
title?: string;
disabled?: boolean;
active?: boolean;
type?: 'button' | 'submit';
onClick?: () => void;
className?: string;
};
export function Btn({ children, variant = 'secondary', size = 'md', icon, iconRight, block, title, disabled, active, type = 'button', onClick, className, ...aria }: BtnProps) {
return (
{tr(icon ? : null)}
{tr(children)}
{tr(iconRight ? : null)}
);
}
export function IconBtn({ name, title, onClick, disabled, active, size = 19, }: {
name: IconName;
title: string;
onClick?: () => void;
disabled?: boolean;
/** Renders in the pressed state — used by the sidebar's search toggle. */
active?: boolean;
size?: number;
}) {
return (
);
}
/* ------------------------------------------------------------------- panel */
export function Panel({ children, className, pad, }: {
children: ReactNode;
className?: string;
pad?: boolean;
accent?: boolean;
}) {
return ;
}
export function PanelHead({ title, sub, right, icon, }: {
title: ReactNode;
sub?: ReactNode;
right?: ReactNode;
icon?: IconName;
}) {
return ();
}
/* -------------------------------------------------------------------- pill */
export function Pill({ children, tone = 'plain', dot, badge, className, }: {
children: ReactNode;
tone?: 'plain' | 'accent' | 'info' | 'warn' | 'danger';
dot?: boolean;
/** `badge` renders the 24px badge treatment instead of the 30px status pill. */
badge?: boolean;
className?: string;
}) {
const toneClass = {
plain: undefined,
accent: badge ? 'st-badge--generating' : 'st-pill--accent',
info: badge ? 'st-badge--reading' : 'st-pill--info',
warn: badge ? 'st-badge--queued' : 'st-pill--warn',
danger: badge ? 'st-badge--error' : 'st-pill--danger',
}[tone];
return (
{tr(dot && !badge ? : null)}
{tr(children)}
);
}
/* --------------------------------------------------------------------- bar */
export function Bar({ value, tone = 'accent', size, indeterminate, label = 'Progress', }: {
value: number;
tone?: 'accent' | 'info' | 'warn' | 'danger';
size?: 'sm' | 'lg';
indeterminate?: boolean;
label?: string;
}) {
return (
);
}
/* ---------------------------------------------------------------- segments */
export function Seg({ value, options, onChange, ariaLabel, panelId, }: {
value: T;
/** `title` explains a label that has to stay short to fit the control. */
options: {
value: T;
label: string;
icon?: IconName;
title?: string;
disabled?: boolean;
}[];
onChange: (v: T) => void;
ariaLabel?: string;
/** Supply the associated panel ID for actual tabs; omit for segmented values. */
panelId?: string;
}) {
return (
{tr(options.map((o) => ( {
if (!['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp', 'Home', 'End'].includes(e.key))
return;
e.preventDefault();
const available = options.map((item, index) => ({ item, index })).filter(({ item }) => !item.disabled);
const at = available.findIndex(({ item }) => item === o);
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;
const next = available[nextAt]?.index;
if (next === undefined)
return;
onChange(options[next].value);
(e.currentTarget.parentElement?.children[next] as HTMLElement)?.focus();
}} title={tr(o.title)} onClick={() => onChange(o.value)}>
{tr(o.icon ? : null)}{tr(o.label)}
)))}
);
}
/* ------------------------------------------------------------------- steps */
export interface StepDef {
n: number;
label: string;
}
export function Steps({ steps, current }: {
steps: StepDef[];
current: number;
}) {
return ({tr("Step ")}{tr(current)}{tr(" of ")}{tr(steps.length)} · {tr(steps.find(s => s.n === current)?.label)}
{tr(steps.map((s) => {
const state = s.n < current ? 'done' : s.n === current ? 'active' : 'todo';
return (
{tr(s.n)}
·
{tr(s.label)}
);
}))}
);
}
/* ------------------------------------------------------------------ fields */
const FieldContext = createContext<{
label: string;
description?: string;
} | null>(null);
export function Field({ label, hint, impact, children, wide, }: {
label: ReactNode;
hint?: ReactNode;
/** What the current value actually costs. Shown where the choice is made
* rather than only in a summary elsewhere on the screen. */
impact?: ReactNode;
children: ReactNode;
wide?: boolean;
}) {
const id = useId();
return (
{tr(label)}
{tr(hint ?
{tr(hint)}
: null)}
{tr(impact ?
{tr(impact)}
: null)}
{tr(children)}
);
}
/**
* A listbox styled as a Strata field.
*
* This replaces a native ``, whose popup the OS draws — on macOS a dark
* system menu with a blue highlight, which shared nothing with the rest of the
* app. Owning the popup means owning the whole interaction, so this implements
* the full combobox pattern: focus stays on the trigger with
* `aria-activedescendant` tracking the highlighted option, and the popup renders
* through a portal so it can never end up nested inside another glass surface.
*/
export function Select({ value, valueSuffix, options, onChange, ariaLabel, disabled = false, menuSize = 'standard', menuMinWidth, menuWidth, menuClassName, optionIcon, singleLine = false, translateLabels = true, }: {
value: T;
valueSuffix?: ReactNode;
/** Keep custom names and font families verbatim. */
translateLabels?: boolean;
/** `title` explains a label that has to stay short to fit the control. */
options: {
value: T;
label: string;
title?: string;
disabled?: boolean;
}[];
onChange: (v: T) => void;
ariaLabel?: string;
disabled?: boolean;
menuSize?: 'standard' | 'comfortable';
menuMinWidth?: number;
/** Override popup width while keeping the trigger unchanged. */
menuWidth?: number;
menuClassName?: string;
optionIcon?: (value: T) => IconName;
singleLine?: boolean;
}) {
const field = useContext(FieldContext);
const listId = useId();
const triggerRef = useRef(null);
const popupRef = useRef(null);
const [open, setOpen] = useState(false);
const [placed, setPlaced] = useState<{
left: number;
top: number;
width: number;
maxHeight: number;
} | null>(null);
const [cursor, setCursor] = useState(0);
const [typed, setTyped] = useState('');
const current = options.find((o) => o.value === value);
const optionLabel = (label: string) => translateLabels ? tr(label) : label;
const close = useCallback((refocus = true) => {
setOpen(false);
setTyped('');
if (refocus)
triggerRef.current?.focus();
}, []);
/* 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):
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
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
sent it off the top of a short window. `measured` is the rendered popup, when there is one. */
const placeList = useCallback((measured: HTMLElement | null) => {
const el = triggerRef.current;
if (!el)
return null;
const { scale, viewport } = measureFrame();
const r = el.getBoundingClientRect();
const width = Math.min((menuWidth ?? Math.max(r.width / scale, menuMinWidth ?? (menuSize === 'comfortable' ? 340 : 180))) * scale, viewport.width - 24);
const natural = measured
? measured.scrollHeight * scale + (measured.getBoundingClientRect().height - measured.clientHeight * scale)
: (options.length * (menuSize === 'comfortable' ? 52 : 38) + 12) * scale;
const p = placeAnchored({ anchor: r, size: { width, height: natural }, viewport, scale, gapBelow: 6, gapAbove: 6 });
return { left: p.left, top: p.top, width: width / scale, maxHeight: p.maxHeight };
}, [options.length, menuSize, menuMinWidth, menuWidth]);
const openMenu = useCallback(() => {
const next = placeList(null);
if (!next)
return;
setPlaced(next);
setCursor(Math.max(0, options.findIndex((o) => o.value === value)));
setOpen(true);
}, [options, value, placeList]);
// Once the list is on the screen its real height is known: place it again with that.
useLayoutEffect(() => {
if (!open)
return;
const next = placeList(popupRef.current);
if (next)
setPlaced(next);
}, [open, placeList]);
// The popup is fixed-positioned, so it has to follow its trigger.
useEffect(() => {
if (!open)
return undefined;
const reposition = () => {
const next = placeList(popupRef.current);
if (next)
setPlaced(next);
};
const onDocDown = (e: PointerEvent) => {
if (!triggerRef.current?.contains(e.target as Node) && !popupRef.current?.contains(e.target as Node))
close(false);
};
window.addEventListener('scroll', reposition, true);
window.addEventListener('resize', reposition);
document.addEventListener('pointerdown', onDocDown, true);
return () => {
window.removeEventListener('scroll', reposition, true);
window.removeEventListener('resize', reposition);
document.removeEventListener('pointerdown', onDocDown, true);
};
}, [open, close, placeList]);
useEffect(() => {
if (open)
document.getElementById(`${listId}-${cursor}`)?.scrollIntoView({ block: 'nearest' });
}, [open, cursor, listId]);
function onKeyDown(e: React.KeyboardEvent) {
if (!open) {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp' || e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
openMenu();
}
return;
}
switch (e.key) {
case 'Escape':
e.preventDefault();
e.stopPropagation();
close();
break;
case 'ArrowDown':
e.preventDefault();
setCursor((c) => (c + 1) % options.length);
break;
case 'ArrowUp':
e.preventDefault();
setCursor((c) => (c - 1 + options.length) % options.length);
break;
case 'Home':
e.preventDefault();
setCursor(0);
break;
case 'End':
e.preventDefault();
setCursor(options.length - 1);
break;
case 'Enter':
case ' ':
e.preventDefault();
if (!options[cursor].disabled)
onChange(options[cursor].value);
close();
break;
case 'Tab':
close(false);
break;
default: {
// Typeahead: consecutive letters narrow the match, as a native select does.
if (e.key.length !== 1 || !/\S/.test(e.key))
return;
const next = typed + e.key.toLowerCase();
const from = next.length === 1 ? cursor + 1 : cursor;
const ordered = [...options.slice(from), ...options.slice(0, from)];
const hit = ordered.find((o) => optionLabel(o.label).toLowerCase().startsWith(next));
const restart = !hit && next.length > 1 ? options.find((o) => optionLabel(o.label).toLowerCase().startsWith(e.key.toLowerCase())) : null;
const target = hit ?? restart;
setTyped(restart ? e.key.toLowerCase() : next);
if (target)
setCursor(options.indexOf(target));
}
}
}
return (<>
(open ? close() : openMenu())} onKeyDown={onKeyDown}>
{valueSuffix ? <>{optionLabel(current?.label ?? '')} {valueSuffix}> : optionLabel(current?.label ?? '')}
{tr(open && placed
? createPortal(
{tr(options.map((o, i) => (
setCursor(i)} onMouseDown={(e) => e.preventDefault()} onClick={() => {
if (o.disabled)
return;
onChange(o.value);
close();
}}>
{tr(optionIcon ? : {tr(o.value === value ? : null)} )}
{optionLabel(o.label)}
{tr(optionIcon && o.value === value ? : null)}
)))}
, document.body)
: null)}
>);
}
/** One modal surface for confirmations and narrow-screen inspectors. */
export function Dialog({ open, title, onClose, children, actions, headerActions, compact = false, sheet = false, wide = false, hideTitle = false, className, noClose = false }: {
open: boolean;
title: ReactNode;
onClose: () => void;
children: ReactNode;
actions?: ReactNode;
headerActions?: ReactNode;
compact?: boolean;
sheet?: boolean;
wide?: boolean;
hideTitle?: boolean;
className?: string;
/** No close button: the person must use the dialog's own buttons (a move that is running). */
noClose?: boolean;
}) {
const ref = useRef(null);
const id = useId();
useSurfaceFocus(open, ref);
useEffect(() => {
if (!open)
return;
const close = (e: KeyboardEvent) => {
if (e.key === 'Escape' && !e.defaultPrevented && isTopSurface(ref.current)) {
e.preventDefault();
e.stopImmediatePropagation();
onClose();
}
};
document.addEventListener('keydown', close);
return () => document.removeEventListener('keydown', close);
}, [open, onClose]);
if (!open)
return null;
return createPortal(
{tr(children)}
{tr(actions ? : null)}
, document.body);
}
/* ------------------------------------------------------------------- empty */
export function Empty({ icon = 'info', title, body, action, }: {
icon?: IconName;
title: string;
body?: ReactNode;
action?: ReactNode;
}) {
return (
{tr(title)}
{tr(body ? (
{tr(body)}
) : null)}
{tr(action ?
{tr(action)}
: null)}
);
}
/* ------------------------------------------------------- failed actions ---
One component for every failure a screen needs to report. The rule this
encodes (plan 14): wherever a failure is reported, the surface that failed
offers the retry — a toast may summarise but must not be the only record.
Kept here so the treatment lands once rather than once per screen. */
export function ActionError() {
const actionError = useStore((s) => s.actionError);
if (!actionError)
return null;
return actionError.retry()}/> dismissActionError()}>{tr("Dismiss")}
;
}
/* ------------------------------------------------------------------ toasts */
export function Toasts() {
const toasts = useStore((s) => s.toasts);
if (!toasts.length)
return null;
const iconFor = { success: 'check', info: 'info', warn: 'warning', error: 'error' } as const;
return (
{tr(toasts.map((t) => (
holdToast(t.id)} onMouseLeave={() => releaseToast(t.id)} onFocusCapture={() => holdToast(t.id)} onBlurCapture={() => releaseToast(t.id)}>
{tr(t.title)}
{tr(t.body ?
{tr(t.body)}
: null)}
{tr(t.action ?
{tr(t.action.label)} : null)}
dismissToast(t.id)} aria-label={tr("Dismiss")}>
)))}
);
}
/* ------------------------------------------------------------------ metric */
/**
* A metric tile: the kit's `.st-metric` inside a card, which is how the design
* reference lays out every number in the app.
*/
export function Metric({ label, value, unit, sub, icon, spark, compact, children, }: {
label: string;
value: ReactNode;
unit?: string;
sub?: ReactNode;
icon?: IconName;
spark?: ReactNode;
/** Text values read better a step down from the kit's 32px stat size. */
compact?: boolean;
children?: ReactNode;
}) {
return (
{tr(icon ? : null)}
{tr(label)}
{tr(value)}
{tr(unit ? {tr(unit)} : null)}
{tr(sub ?
{tr(sub)}
: null)}
{tr(children)}
{tr(spark ?
{tr(spark)}
: null)}
);
}
/** A row of metric tiles. */
export function MetricGrid({ children, min = 200 }: {
children: ReactNode;
min?: number;
}) {
return (
{tr(children)}
);
}
/** Shared, announced error with a cause and a concrete recovery action. */
export function ErrorNotice({ message, next, action, onRetry, detail, secondary }: {
message: string;
next?: string;
action?: string;
onRetry?: () => void;
detail?: string;
/** A second way out, beside the first (a context error offers two). */
secondary?: { label: string; onClick: () => void };
}) {
// A known failure is shown as a sentence and a next step; the original text stays under Details for experts.
const plain = plainFailure(message);
const known = plain.kind !== 'plain';
const nextStep = known ? (plain.next ? tr(plain.next) : next) : next;
const raw = detail ?? (known ? plain.detail : undefined);
// An unrecognised failure still goes through plainFailure: it peels an
// `{"error":"…"}` body down to the sentence, where userError only capitalised
// the JSON and showed an object to the person.
return {tr(plain.message)} {tr(nextStep ?
{tr(nextStep)}
: null)}{tr(raw ?
{tr("Details")} {raw} : null)}
{tr(onRetry ? (secondary ? {tr(action ?? 'Try again')} {tr(secondary.label)}
: {tr(action ?? 'Try again')} ) : null)} ;
}
export function PreviewBadge() { const demo = useStore(s => s.library?.mode === 'simulated'); return demo ? {tr("Preview build")} : null; }