SPB Git

Repository Public

core.tsx 12.1 KB 215 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : MacLustr Social Engine & Remote Navigator8 * File             : apps/social-web/src/ui/core.tsx9 * Module           : ui10 * Repository       : https://git.spboucher.ai/maclustr-social11 * Project Website  : https://social.spboucher.ai12 * Created          : 2026-12-0113 * Last Modified    : 2026-12-0114 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142// Small building blocks shared by every screen. No UI library: plain elements, plain CSS.43import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from 'react';44import { ApiError } from '../../../shared/api.ts';45import { hasLabel } from '../i18n.ts';46import { usePrefs } from '../prefs.tsx';4748/* ── Data loading ── */49export type Loaded<T> = { data: T | undefined; error: unknown; loading: boolean; reload: () => void };50export function useLoad<T>(fn: () => Promise<T>, deps: unknown[]): Loaded<T> {51  const [state, setState] = useState<{ data: T | undefined; error: unknown; loading: boolean }>({ data: undefined, error: null, loading: true });52  const [tick, setTick] = useState(0);53  useEffect(() => {54    let live = true;55    setState((s) => ({ data: s.data, error: null, loading: true }));56    fn().then((data) => { if (live) setState({ data, error: null, loading: false }); }, (error) => { if (live) setState({ data: undefined, error, loading: false }); });57    return () => { live = false; };58    // eslint-disable-next-line react-hooks/exhaustive-deps59  }, [...deps, tick]);60  const reload = useCallback(() => setTick((n) => n + 1), []);61  return { ...state, reload };62}63export type Action = { busy: boolean; error: unknown; done: string | null; run: <T>(fn: () => Promise<T>, okMessage?: string) => Promise<T | undefined>; clear: () => void };64/** Runs a mutating call; the error is kept and shown, never swallowed. */65export function useAction(): Action {66  const [busy, setBusy] = useState(false);67  const [error, setError] = useState<unknown>(null);68  const [done, setDone] = useState<string | null>(null);69  const run = useCallback(async <T,>(fn: () => Promise<T>, okMessage?: string): Promise<T | undefined> => {70    setBusy(true); setError(null); setDone(null);71    try { const r = await fn(); setDone(okMessage ?? null); return r; } catch (e) { setError(e); return undefined; } finally { setBusy(false); }72  }, []);73  const clear = useCallback(() => { setError(null); setDone(null); }, []);74  return { busy, error, done, run, clear };75}7677/* ── Feedback ── */78export function ErrorNote({ error }: { error: unknown }) {79  const { t, tl } = usePrefs();80  if (!error) return null;81  const api = error instanceof ApiError ? error : null;82  const name = error instanceof Error ? error.name : '';83  const webauthn = !api && /NotAllowedError|AbortError|InvalidStateError|SecurityError|WebAuthnError/.test(name);84  const details = api && Array.isArray(api.details) ? (api.details as unknown[]) : api?.details ? [api.details] : [];85  return (86    <div className="note note-error" role="alert">87      <p className="note-head"><strong>{t('err.title')}</strong>{api ? <code>{api.status} · {api.code}</code> : name ? <code>{name}</code> : null}</p>88      <p>{error instanceof Error ? error.message : String(error)}</p>89      {api && hasLabel('err', api.code) ? <p>{tl('err', api.code)}</p> : null}90      {!api ? <p>{webauthn ? t('err.webauthn') : t('err.network')}</p> : null}91      {details.length ? <ul className="plain">{details.map((d, i) => <li key={i}><code>{typeof d === 'object' && d && 'path' in d ? `${String((d as any).path) || '·'} : ${String((d as any).message)}` : typeof d === 'string' ? d : JSON.stringify(d)}</code></li>)}</ul> : null}92      {api?.correlationId ? <p className="small">{t('err.correlation')} : <code>{api.correlationId}</code></p> : null}93    </div>94  );95}96export function Loading() { const { t } = usePrefs(); return <p className="loading" role="status">{t('c.loading')}</p>; }97export function Empty({ children }: { children?: ReactNode }) { const { t } = usePrefs(); return <p className="empty">{children ?? t('c.empty')}</p>; }98/** Live region for the outcome of an action. */99export function ActionStatus({ a }: { a: Action }) {100  const { t } = usePrefs();101  return (<>102    <p className="status" role="status" aria-live="polite">{a.busy ? t('c.working') : a.done ?? ''}</p>103    <ErrorNote error={a.error} />104  </>);105}106/** Standard wrapper: loading, error, then the content. */107export function Await<T>({ of, children }: { of: Loaded<T>; children: (data: T) => ReactNode }) {108  if (of.error) return <ErrorNote error={of.error} />;109  if (of.data === undefined) return <Loading />;110  return <>{children(of.data)}</>;111}112export function Notice({ children, tone = 'info' }: { children: ReactNode; tone?: 'info' | 'warn' }) { return <div className={`note note-${tone}`}>{children}</div>; }113114/* ── State labels: a word and a shape, never colour alone ── */115type Tone = 'ok' | 'hold' | 'alert' | 'run' | 'idle';116const TONES: Record<string, Tone> = {117  VERIFIED: 'ok', APPROVED: 'ok', READY: 'ok', confirmed: 'ok', approved: 'ok', online: 'ok', ok: 'ok', routine: 'ok', active: 'ok', validated: 'ok', pass: 'ok', available: 'ok', resolved: 'ok', posted_manually: 'ok',118  AWAITING_CONFIRMATION: 'hold', REVIEW: 'hold', pending: 'hold', unconfirmed: 'hold', LOGIN_REQUIRED: 'hold', MANUAL_CONTROL: 'hold', human_required: 'hold', drafted: 'hold', warning: 'hold', PAUSED: 'hold', SECURITY_CHALLENGE: 'hold', draft: 'hold', incomplete: 'hold', open: 'hold', acked: 'hold',119  FAILED: 'alert', UNKNOWN_OUTCOME: 'alert', rejected: 'alert', blocked: 'alert', block: 'alert', sensitive: 'alert', critical: 'alert', blocker: 'alert', EXPIRED: 'alert', REVOKED: 'alert', failed: 'alert', provider_unavailable: 'alert', budget_exceeded: 'alert', forbidden: 'alert', denied: 'alert', refused: 'alert', missing: 'alert',120  QUEUED: 'run', PREPARING: 'run', SUBMITTED: 'run', BUSY: 'run', running: 'run', info: 'run',121};122export function Tag({ prefix, value, tone }: { prefix: string; value: string | null | undefined; tone?: Tone }) {123  const { tl } = usePrefs();124  return <span className={`tag tag-${tone ?? TONES[value ?? ''] ?? 'idle'}`}><span className="tag-mark" aria-hidden="true" />{tl(prefix, value)}</span>;125}126127/* ── Text ── */128export function CopyButton({ text, label }: { text: string; label?: string }) {129  const { t } = usePrefs();130  const [msg, setMsg] = useState('');131  const copy = async () => { try { await navigator.clipboard.writeText(text); setMsg(t('c.copied')); } catch { setMsg(t('c.copyFailed')); } };132  return <span className="copy"><button type="button" className="small-btn" onClick={copy}>{label ?? t('c.copy')}</button><span className="small" role="status" aria-live="polite">{msg}</span></span>;133}134/** Hash or identifier: shortened on screen, complete in the title and for copying. */135export function Hash({ value, full }: { value: string | null | undefined; full?: boolean }) {136  if (!value) return <span>—</span>;137  return <code className="hash" title={value}>{full || value.length <= 14 ? value : `${value.slice(0, 10)}…${value.slice(-4)}`}</code>;138}139export function JsonView({ value }: { value: unknown }) { return <pre className="json" tabIndex={0}>{JSON.stringify(value, null, 2)}</pre>; }140export function ExtLink({ href, children }: { href: string; children?: ReactNode }) {141  const safe = /^https?:\/\//i.test(href);142  return safe ? <a href={href} target="_blank" rel="noopener noreferrer" className="ext">{children ?? href}</a> : <span className="ext">{children ?? href}</span>;143}144145/* ── Layout ── */146export function PageHead({ title, lead, children }: { title: string; lead?: ReactNode; children?: ReactNode }) {147  return (148    <header className="page-head">149      <div><h1>{title}</h1>{lead ? <p className="lead">{lead}</p> : null}</div>150      {children ? <div className="page-actions">{children}</div> : null}151    </header>152  );153}154export function Panel({ title, actions, children, id }: { title?: string; actions?: ReactNode; children: ReactNode; id?: string }) {155  return (156    <section className="panel" id={id}>157      {title || actions ? <div className="panel-head">{title ? <h2>{title}</h2> : <span />}{actions ? <div className="row">{actions}</div> : null}</div> : null}158      {children}159    </section>160  );161}162export function KV({ rows }: { rows: [string, ReactNode][] }) {163  return <dl className="kv">{rows.map(([k, v], i) => <div key={i}><dt>{k}</dt><dd>{v}</dd></div>)}</dl>;164}165export function TableWrap({ children, caption }: { children: ReactNode; caption?: string }) {166  return <div className="table-wrap" tabIndex={0} role="group" aria-label={caption}><table>{caption ? <caption>{caption}</caption> : null}{children}</table></div>;167}168169/* ── Forms ── */170export function Field({ label, hint, children, wide }: { label: string; hint?: ReactNode; children: ReactNode; wide?: boolean }) {171  const id = useId();172  return (173    <div className={wide ? 'field field-wide' : 'field'}>174      <label>175        <span className="field-label">{label}</span>176        {children}177      </label>178      {hint ? <p className="hint" id={id}>{hint}</p> : null}179    </div>180  );181}182export function Check({ label, checked, onChange, disabled }: { label: ReactNode; checked: boolean; onChange: (v: boolean) => void; disabled?: boolean }) {183  return <label className="check"><input type="checkbox" checked={checked} disabled={disabled} onChange={(e) => onChange(e.target.checked)} /><span>{label}</span></label>;184}185186/* ── Dialog (native <dialog>: focus trap and Escape come from the browser) ── */187export function Modal({ title, onClose, children, wide }: { title: string; onClose: () => void; children: ReactNode; wide?: boolean }) {188  const { t } = usePrefs();189  const ref = useRef<HTMLDialogElement>(null);190  const id = useId();191  useEffect(() => { const d = ref.current; if (d && !d.open) d.showModal(); return () => { if (d?.open) d.close(); }; }, []);192  return (193    <dialog ref={ref} className={wide ? 'modal modal-wide' : 'modal'} aria-labelledby={id} onCancel={(e) => { e.preventDefault(); onClose(); }}>194      <div className="modal-head"><h2 id={id}>{title}</h2><button type="button" className="small-btn" onClick={onClose}>{t('c.close')}</button></div>195      <div className="modal-body">{children}</div>196    </dialog>197  );198}199/** Plain horizontal bars. Values are shown as text next to every bar; null is never drawn as zero. */200export function Bars({ rows, format }: { rows: { label: string; value: number | null }[]; format: (n: number) => string }) {201  const { t } = usePrefs();202  const max = Math.max(0, ...rows.map((r) => r.value ?? 0));203  return (204    <ul className="bars">205      {rows.map((r, i) => (206        <li key={i}>207          <span className="bars-label">{r.label}</span>208          <span className="bars-track" aria-hidden="true">{r.value === null ? null : <span className="bars-fill" style={{ width: `${max > 0 ? (r.value / max) * 100 : 0}%` }} />}</span>209          <span className="bars-value">{r.value === null ? t('c.unavailable') : format(r.value)}</span>210        </li>211      ))}212    </ul>213  );214}215
Files main
Menu

Theme