SPB Git

Repository Public

Gallery.tsx 14.1 KB 188 lines tsx

1"use client";2import { useMemo, useState, type ReactNode } from "react";3import { ApiError } from "@/api/errors";4import { useI18n } from "@/i18n";5import { useTheme } from "@/shell/theme";6import {7  Badge, Banner, Button, Checkbox, Combobox, ConfirmDialog, CopyButton, Count, DataStamp, DataTable, DateTimeRangePicker, Dialog, Drawer, EmptyState, ErrorState,8  FreshnessBadge, Icon, IconButton, Kbd, KeyValue, Linkified, LogView, Menu, Meter, QrCode, SchemaForm, Segmented, SelectField, Skeleton, SkeletonRows, Sparkline,9  StaleBanner, Stat, StateDot, Switch, TabPanel, Tabs, Tag, TextAreaField, TextField, Tooltip, Unmeasured, useToast,10  type Column, type IconName, type RangeValue, type Tone,11} from "@/ui";12import { TimeSeriesChart } from "@/ui/TimeSeriesChart";13import { initialValues, schemaToFields, validateForm, type FieldError, type FormValues } from "@/lib/schemaForm";1415const TONES: Tone[] = ["ok", "warning", "critical", "info", "stale", "offline", "maintenance", "neutral"];16const ICONS: IconName[] = ["overview", "nodes", "services", "models", "jobs", "network", "storage", "alerts", "maintenance", "activity", "audit", "settings", "search", "ok", "warning", "critical", "info", "stale", "offline", "wrench", "unknown", "unsupported", "denied", "pending", "running", "passkey", "shield", "key", "lock", "freeze", "copy", "refresh", "download", "calendar", "clock", "pin", "note", "terminal", "qr", "monitor", "bolt", "history", "silence"];1718function Block({ title, children }: { title: string; children: ReactNode }) {19  return (20    <section className="section" aria-label={title}>21      <h2>{title}</h2>22      {children}23    </section>24  );25}2627interface Row { alias: string; chip: string; cores: number; mem: number; cpu: number | undefined }28const ROWS: Row[] = [29  { alias: "gallery-node-01", chip: "M3 Ultra", cores: 28, mem: 96, cpu: 43 },30  { alias: "gallery-node-02", chip: "M4 Max", cores: 16, mem: 64, cpu: 91 },31  { alias: "gallery-node-03", chip: "M6", cores: 12, mem: 24, cpu: undefined },32];33const BIG: Row[] = Array.from({ length: 1000 }, (_, i) => ({ alias: `gallery-node-${String(i + 1).padStart(4, "0")}`, chip: i % 3 === 0 ? "M4" : "M2", cores: 8 + (i % 5) * 2, mem: 8 * (1 + (i % 6)), cpu: (i * 37) % 100 }));3435const SCHEMA = { type: "object", required: ["profile"], properties: { profile: { type: "string", enum: ["basic", "network", "disk"], title: "Profile" }, lines: { type: "integer", minimum: 1, maximum: 500, default: 200, description: "1–500" }, follow: { type: "boolean", title: "Follow" } } };3637/** /dev/ui — every component of src/ui in its main states. Synthetic sample values, clearly labelled as such. */38export function Gallery() {39  const { t } = useI18n();40  const toast = useToast();41  const { theme, setTheme } = useTheme();42  const [tab, setTab] = useState<"a" | "b" | "c">("a");43  const [seg, setSeg] = useState<"table" | "grid">("table");44  const [text, setText] = useState("");45  const [sel, setSel] = useState<"fr" | "en">("fr");46  const [on, setOn] = useState(true);47  const [check, setCheck] = useState(false);48  const [dialog, setDialog] = useState<"dialog" | "drawer" | "confirm" | null>(null);49  const [combo, setCombo] = useState<string | null>(null);50  const [multi, setMulti] = useState<string[]>(["gallery-node-01"]);51  const [range, setRange] = useState<RangeValue>({ kind: "preset", preset: "1h" });52  const [picked, setPicked] = useState<Set<string>>(new Set());53  const fields = useMemo(() => schemaToFields(SCHEMA), []);54  const [values, setValues] = useState<FormValues>(() => initialValues(fields));55  const [errors, setErrors] = useState<FieldError[]>([]);5657  const now = 1795000000000;58  const series = useMemo(59    () => [60      { id: "a", label: "gallery-node-01", points: Array.from({ length: 120 }, (_, i) => (i > 60 && i < 75 ? null : [now + i * 30_000, 40 + 20 * Math.sin(i / 9), 30 + 18 * Math.sin(i / 9), 55 + 22 * Math.sin(i / 9)])).filter((p): p is number[] => p !== null) },61      { id: "b", label: "gallery-node-02", points: Array.from({ length: 120 }, (_, i) => [now + i * 30_000, 20 + 10 * Math.cos(i / 14), 15 + 9 * Math.cos(i / 14), 28 + 11 * Math.cos(i / 14)]) },62    ],63    [],64  );65  const columns: Column<Row>[] = [66    { id: "alias", header: "Alias", cell: (r) => r.alias, sortValue: (r) => r.alias, mono: true },67    { id: "chip", header: "Chip", cell: (r) => r.chip, sortValue: (r) => r.chip },68    { id: "cores", header: "Cores", cell: (r) => r.cores, sortValue: (r) => r.cores, align: "right" },69    { id: "mem", header: "Memory (GB)", cell: (r) => r.mem, sortValue: (r) => r.mem, align: "right", hide: "sm" },70    { id: "cpu", header: "CPU", cell: (r) => (r.cpu === undefined ? <Unmeasured availability="unavailable" reason="agent offline" /> : <Meter value={r.cpu} label={`CPU ${r.alias}`} text={`${r.cpu} %`} />), sortValue: (r) => r.cpu },71  ];72  const options = ROWS.map((r) => ({ value: r.alias, label: r.alias, hint: r.chip }));7374  return (75    <main className="page" id="main" data-testid="screen-dev-ui">76      <div className="page-head">77        <div><h1>MCC design system</h1><p className="sub">Component gallery — development only. All values on this page are synthetic samples.</p></div>78        <div className="toolbar"><Button icon={theme === "dark" ? "sun" : "moon"} onClick={() => setTheme(theme === "dark" ? "light" : "dark")}>{theme === "dark" ? "Light" : "Dark"}</Button></div>79      </div>8081      <Block title="Buttons">82        <div className="row-wrap">83          <Button variant="primary">Primary</Button><Button>Secondary</Button><Button variant="ghost">Ghost</Button><Button variant="danger">Danger</Button>84          <Button disabled>Disabled</Button><Button loading>Loading</Button><Button size="sm" icon="refresh">Small</Button><Button size="lg" icon="passkey" variant="primary">Large</Button>85          <IconButton icon="copy" label="Copy" /><IconButton icon="trash" label="Delete" variant="danger" /><CopyButton text="copied text">Copy text</CopyButton>86          <Tooltip content="Explains why the control is disabled" focusable><Button disabled>With reason</Button></Tooltip>87        </div>88      </Block>8990      <Block title="State: tone + icon + text (never colour alone)">91        <div className="row-wrap">{TONES.map((x) => <Badge key={x} tone={x}>{x}</Badge>)}</div>92        <div className="row-wrap">{TONES.map((x) => <StateDot key={x} tone={x} label={x} />)}</div>93        <div className="row-wrap">94          <FreshnessBadge freshness="fresh" /><FreshnessBadge freshness="stale" /><FreshnessBadge freshness="offline" />95          <Unmeasured availability="unsupported" reason="Requires root (powermetrics)" /><Unmeasured availability="permission_denied" /><Unmeasured availability="unavailable" /><Unmeasured availability="not_observed" />96          <Count value={3} /><Count value={12} tone="critical" /><Tag>tag</Tag><Kbd>⌘K</Kbd><DataStamp at={now} freshness="fresh" />97        </div>98      </Block>99100      <Block title="Icons">101        <div className="row-wrap">{ICONS.map((i) => <Tooltip key={i} content={i}><span className="mcc-btn mcc-btn-ghost mcc-btn-icon"><Icon name={i} size={18} /></span></Tooltip>)}</div>102      </Block>103104      <Block title="Fields">105        <div className="mcc-form-row">106          <TextField label="Text" hint="Hint text" value={text} onChange={setText} placeholder="Placeholder" />107          <TextField label="With error" value={text} onChange={setText} error="This field is required." required />108          <TextField label="Search" icon="search" value={text} onChange={setText} type="search" />109          <SelectField label="Select" value={sel} onChange={setSel} options={[{ value: "fr", label: "Français" }, { value: "en", label: "English" }]} />110          <TextAreaField label="Text area" value={text} onChange={setText} />111          <div className="stack">112            <Switch label="Switch" checked={on} onChange={setOn} hint="State is also written as text" />113            <Checkbox label="Checkbox" checked={check} onChange={setCheck} />114            <Segmented label="View" value={seg} onChange={setSeg} options={[{ value: "table", label: "Table", icon: "table" }, { value: "grid", label: "Grid", icon: "grid" }]} />115          </div>116          <Combobox label="Combobox" options={options} value={combo} onChange={setCombo} />117          <Combobox label="Combobox (multiple)" multiple options={options} value={multi} onChange={setMulti} />118        </div>119        <DateTimeRangePicker value={range} onChange={setRange} />120      </Block>121122      <Block title="Schema form (generated from JSON Schema)">123        <SchemaForm schema={SCHEMA} values={values} onChange={setValues} errors={errors} />124        <div className="row"><Button onClick={() => setErrors(validateForm(fields, values).errors)}>Validate</Button></div>125      </Block>126127      <Block title="Tabs, menu, overlays, toasts">128        <Tabs label="Sample tabs" idPrefix="g" value={tab} onChange={setTab} tabs={[{ id: "a", label: "First" }, { id: "b", label: "Second", count: 4 }, { id: "c", label: "Third" }]} />129        <TabPanel idPrefix="g" id={tab}><p className="muted">Panel {tab}</p></TabPanel>130        <div className="row-wrap">131          <Menu label="Sample menu" align="left" trigger={(p) => <Button {...p} icon="more">Menu</Button>} items={[{ id: "1", label: "Restart", icon: "restart" }, { id: "2", label: "Disabled", disabled: true }, { id: "3", label: "Remove", icon: "trash", danger: true, separatorBefore: true }]} />132          <Button onClick={() => setDialog("dialog")}>Dialog</Button><Button onClick={() => setDialog("drawer")}>Drawer</Button><Button onClick={() => setDialog("confirm")}>Confirm</Button>133          <Button onClick={() => toast({ tone: "ok", title: "Saved" })}>Toast ok</Button><Button onClick={() => toast({ tone: "critical", title: "Request failed", detail: "Reference: 019a9c1e-sample" })}>Toast error</Button>134        </div>135        <Dialog open={dialog === "dialog"} onClose={() => setDialog(null)} title="Dialog" description="Native <dialog>: focus trap, Esc, focus restore." footer={<Button variant="primary" onClick={() => setDialog(null)}>{t("common.close")}</Button>}><TextField label="Field" value={text} onChange={setText} /></Dialog>136        <Drawer open={dialog === "drawer"} onClose={() => setDialog(null)} title="Drawer"><p className="muted">Side panel for details.</p></Drawer>137        <ConfirmDialog open={dialog === "confirm"} onClose={() => setDialog(null)} onConfirm={() => setDialog(null)} danger title="Delete this note?" body="This cannot be undone." confirmLabel="Delete" />138      </Block>139140      <Block title="Global states">141        <div className="cols-2">142          <EmptyState icon="nodes" title="No node yet" actions={<Button size="sm">Next step</Button>}>Nodes appear when an agent enrolls.</EmptyState>143          <ErrorState error={new ApiError({ status: 501, code: "not_implemented", message: "This operation is not available." })} />144          <ErrorState error={new ApiError({ status: 403, code: "forbidden", message: "no", correlationId: "019a9c1e-7b10-7c3a-9d54-2f6f1f0f3a11", details: { permission: "audit.read" } })} />145          <ErrorState error={new ApiError({ status: 503, code: "unavailable", message: "db", correlationId: "019a9c1e-7b10-7c3a-9d54-2f6f1f0f3a12" })} onRetry={() => {}} />146          <ErrorState error={new ApiError({ status: 500, code: "internal", message: "Unexpected server error", correlationId: "019a9c1e-7b10-7c3a-9d54-2f6f1f0f3a13" })} onRetry={() => {}} />147          <ErrorState error={new ApiError({ status: 0, code: "network", message: "network" })} onRetry={() => {}} />148        </div>149        <StaleBanner since={now} onRetry={() => {}} />150        <Banner tone="warning" icon="offline" role="alert">Offline banner</Banner>151        <div className="stack"><Skeleton width="40" height="lg" /><Skeleton width="80" /><SkeletonRows rows={3} /></div>152      </Block>153154      <Block title="Data display">155        <div className="cols-3">156          <Stat label="CPU cores" value={379} context="28 of 29 nodes reporting" />157          <Stat label="Memory" value="1 032" unit="GB" context="sample" />158          <KeyValue items={[{ label: "Chip", value: "M6" }, { label: "Perf levels", value: "Super 2 · Performance 4 · Efficiency 6" }, { label: "Temperature", value: <Unmeasured availability="unsupported" /> }]} />159        </div>160        <div className="row-wrap">161          <Sparkline label="Sample sparkline" points={[3, 5, 4, 8, 7, null, 6, 9, 12, 10]} />162          <Sparkline label="Critical sparkline" tone="critical" points={[3, 5, 9, 12, 15, 14, 18]} />163        </div>164        <Meter value={34} label="Disk" text="34 %" /><Meter value={86} label="Disk" text="86 %" /><Meter value={99.7} label="Disk" text="99,7 %" />165        <KeyValue inline items={[{ label: "Model", value: "Mac15,14" }, { label: "OS", value: "macOS 26.6" }, { label: "Agent", value: "1.0.0" }]} />166      </Block>167168      <Block title="Table (sortable, sticky header)">169        <DataTable caption="Sample nodes" columns={columns} rows={ROWS} rowKey={(r) => r.alias} initialSort={{ id: "alias", dir: "asc" }} selected={picked} onSelectedChange={setPicked} selectLabel={(r) => `Select ${r.alias}`} />170      </Block>171      <Block title="Table (virtualized: 1 000 rows)">172        <DataTable caption="Virtualized sample" columns={columns.slice(0, 4)} rows={BIG} rowKey={(r) => r.alias} compact />173      </Block>174175      <Block title="Time-series chart (min/avg/max envelope, gaps, keyboard cursor, table view)">176        <TimeSeriesChart title="CPU usage" unit="percent" series={series} yMax={100} />177        <TimeSeriesChart title="Unsupported metric" unit="celsius" series={[]} size="short" placeholder={<Unmeasured availability="unsupported" reason="Not readable without root on Apple Silicon" />} />178      </Block>179180      <Block title="Text-only renderers">181        <p><Linkified text={"Plain note with a link https://clustr.spboucher.ai/nodes\nsecond line <b>not html</b>"} /></p>182        <LogView label="Sample output" lines={[{ id: 1, text: "starting…" }, { id: 2, text: "warning: sample stderr line", stream: "stderr" }, { id: 3, text: "<script>alert(1)</script> is shown as text" }]} empty={<EmptyState compact title="No output" />} />183        <QrCode value="https://clustr.spboucher.ai/setup#sample-not-a-real-token" label="Sample QR code" />184      </Block>185    </main>186  );187}188
Files main
Menu

Theme