okami.mom/strata

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

Niko1221apps/host: the owner's UI and the Node App Host0b3299a01

main
9.9 KiB153 linesraw
1import { tr } from '../lib/i18n';
2import { useState } from 'react';
3import { referencePaths } from '../lib/monitor-chart';
4/** Original Monitor chart geometry, including the separate prefill line and sensor gaps. */
5export function ReferenceSpark({ data, maximum, tone = 'var(--st-accent)', secondary, label, unit, timestamps }: {
6    data: (number | null | undefined)[];
7    maximum?: number;
8    tone?: string;
9    secondary?: {
10        data: (number | null | undefined)[];
11        label: string;
12        tone: string;
13    };
14    label: string;
15    unit: string;
16    timestamps: number[];
17}) {
18    const [hover, setHover] = useState<number | null>(null);
19    const primary = referencePaths(data, maximum), other = secondary ? referencePaths(secondary.data) : null;
20    const empty = !data.some(value => typeof value === 'number' && Number.isFinite(value)) && !secondary?.data.some(value => typeof value === 'number' && Number.isFinite(value));
21    const value = (values: (number | null | undefined)[]) => hover !== null && typeof values[hover] === 'number' && Number.isFinite(values[hover]) ? `${Math.round(values[hover]! * 10) / 10} ${unit}` : 'Unavailable';
22    const ago = hover !== null && timestamps[hover] != null ? Math.max(0, Math.round(((timestamps.at(-1) ?? 0) - timestamps[hover]) / 1000)) : 0;
23    const line = (paths: ReturnType<typeof referencePaths>['paths'], color: string) => paths.map((path, i) => <g key={i} style={{ color }}><path d={path.area} fill="currentColor" opacity=".12"/><path d={path.line} fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke"/></g>);
24    return <div className="spark monitor-spark" tabIndex={data.length > 1 ? 0 : undefined} role="group" aria-label={tr("{0}, last 60 seconds. Use arrow keys to inspect samples.", [label])} onMouseMove={event => {
25            const rect = event.currentTarget.getBoundingClientRect();
26            if (rect.width && data.length)
27                setHover(Math.round(Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width)) * (data.length - 1)));
28        }} onMouseLeave={() => setHover(null)} onFocus={() => setHover(data.length - 1)} onBlur={() => setHover(null)} onKeyDown={event => {
29            if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key))
30                return;
31            event.preventDefault();
32            setHover(current => event.key === 'Home' ? 0 : event.key === 'End' ? data.length - 1 : Math.max(0, Math.min(data.length - 1, (current ?? data.length - 1) + (event.key === 'ArrowLeft' ? -1 : 1))));
33        }}>
34    <svg viewBox="0 0 100 32" preserveAspectRatio="none" role="img" aria-label={tr("{0}, last 60 seconds", [label])}>
35 {tr(empty ? <path d="M0,28 L100,28" fill="none" stroke="var(--st-line)" strokeDasharray="3 3" strokeWidth="1" vectorEffect="non-scaling-stroke"/> : null)}
36      {tr(line(primary.paths, tone))}{tr(other && secondary ? line(other.paths, secondary.tone) : null)}
37      {tr(hover !== null && data.length > 1 ? <line x1={hover / (data.length - 1) * 100} x2={hover / (data.length - 1) * 100} y1="2" y2="32" stroke={tone} strokeWidth="1" opacity=".45" vectorEffect="non-scaling-stroke"/> : null)}
38    </svg>
39    {tr(hover !== null ? <span className="spark__readout num" role="status">{tr(secondary ? 'Decode: ' : '')}{tr(value(data))}{tr(secondary ? ` · ${secondary.label}: ${value(secondary.data)}` : '')}<span className="spark__ago"> · {tr(ago ? `${ago}s ago` : 'now')}</span></span> : null)}
40  </div>;
41}
42/**
43 * Charts — drawn to the kit's own recipes.
44 *
45 * `Spark` is the reference sparkline (area at 12% + 1.5px line, 100×28 box).
46 * `Gauge` is the reference 270° arc: r=50, stroke 10, dasharray 235.6 / 314.2,
47 * rotated 135°, solid accent stroke — no gradients.
48 */
49export function Spark({ data, height = 28, tone = 'var(--st-accent)', domain, axisLabel, unit, timestamps, reference = false, }: {
50    data: number[];
51    height?: number;
52    tone?: string;
53    /**
54     * A shared vertical range, in the series' own units.
55     *
56     * Scaling each sparkline to its own min and max makes a flat 2 tok/s series
57     * and a spiky 200 tok/s one draw the identical picture, which is the opposite
58     * of what putting them side by side is for. Passing one domain for a group
59     * makes their shapes comparable.
60     */
61    domain?: [
62        number,
63        number
64    ];
65    /** Spoken and hover description of the span, e.g. "last 60 seconds". */
66    axisLabel?: string;
67    /**
68     * Names the value on hover, e.g. "tok/s". Without it the readout still
69     * appears — a bare figure is more useful than nothing — but a number with no
70     * unit on a chart that could be measuring anything is only half an answer.
71     */
72    unit?: string;
73    /** Actual sample times; index spacing is used only for untimed miniatures. */
74    timestamps?: number[];
75    /** Match the live GitHub interface's 100×32 geometry and line weight. */
76    reference?: boolean;
77}) {
78    const [hover, setHover] = useState<number | null>(null);
79    const series = data.length > 1 ? data : [0, 0];
80    const max = domain ? domain[1] : Math.max(...series);
81    const min = domain ? domain[0] : Math.min(...series);
82    const span = max - min || 1;
83    const points = series.map((v, i) => {
84        const timed = timestamps?.length === series.length && timestamps.at(-1)! > timestamps[0];
85        const x = timed ? ((timestamps[i] - timestamps[0]) / (timestamps.at(-1)! - timestamps[0])) * 100 : (i / (series.length - 1)) * 100;
86        const y = reference ? 30 - ((v - min) / span) * 26 : 25 - ((v - min) / span) * 22;
87        return [x, y] as const;
88    });
89    const flat = max - min < 0.05;
90    const line = points.map((p, i) => `${i ? 'L' : 'M'}${p[0].toFixed(reference ? 2 : 1)} ${(reference ? p[1] : flat ? 26 : p[1]).toFixed(reference ? 2 : 1)}`).join('');
91    const bottom = reference ? 32 : 28;
92    const area = `${line}L100 ${bottom}L0 ${bottom}Z`;
93    /**
94     * Which sample the pointer is nearest.
95     *
96     * The chart is stretched to its container (`preserveAspectRatio="none"`), so
97     * the pointer's fraction of the width maps directly to an index — no need to
98     * read the rendered geometry back.
99     */
100    const onMove = (e: React.MouseEvent<HTMLDivElement>) => {
101        const r = e.currentTarget.getBoundingClientRect();
102        if (r.width === 0)
103            return;
104        const frac = Math.min(1, Math.max(0, (e.clientX - r.left) / r.width));
105        setHover(points.reduce((best, point, i) => Math.abs(point[0] / 100 - frac) < Math.abs(points[best][0] / 100 - frac) ? i : best, 0));
106    };
107    const shown = hover !== null ? series[hover] : null;
108    const secondsAgo = hover !== null ? timestamps?.[hover] !== undefined ? Math.max(0, Math.round(((timestamps.at(-1) ?? 0) - timestamps[hover]) / 1000)) : series.length - 1 - hover : 0;
109    return (<div className="spark" style={{ height }} onMouseMove={onMove} onMouseLeave={() => setHover(null)} tabIndex={0} role="group" aria-label={tr("{0}. Use arrow keys to inspect samples.", [axisLabel ?? 'Chart'])} onFocus={() => setHover(series.length - 1)} onBlur={() => setHover(null)} onKeyDown={e => {
110            if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key))
111                return;
112            e.preventDefault();
113            setHover(current => e.key === 'Home' ? 0 : e.key === 'End' ? series.length - 1 : Math.max(0, Math.min(series.length - 1, (current ?? series.length - 1) + (e.key === 'ArrowLeft' ? -1 : 1))));
114        }}>
115      <svg viewBox={`0 0 100 ${bottom}`} preserveAspectRatio="none" style={{ width: '100%', height, color: tone }} role="img" aria-label={tr(axisLabel ?? `${series.length} samples`)}>
116        {tr(flat && !reference ? null : <path d={area} fill="currentColor" opacity="0.12"/>)}
117        <path d={line} fill="none" stroke="currentColor" strokeWidth={reference ? 1.6 : 1.5} strokeLinecap="round" strokeLinejoin="round" opacity={flat && !reference ? 0.35 : 1} vectorEffect="non-scaling-stroke"/>
118        {tr(hover !== null && !flat ? (
119        /* The marker uses the same 100×28 space as the line, so it lands on
120           the sample rather than near it. */
121        <line x1={points[hover][0]} x2={points[hover][0]} y1={2} y2={bottom} stroke="currentColor" strokeWidth={1} opacity={0.45} vectorEffect="non-scaling-stroke"/>) : null)}
122      </svg>
123      {tr(shown !== null ? (<span className="spark__readout num" role="status">
124          {tr(Math.round(shown * 10) / 10)}
125          {tr(unit ? ` ${unit}` : '')}
126          <span className="spark__ago"> · {tr(secondsAgo === 0 ? 'now' : `${secondsAgo}s ago`)}</span>
127        </span>) : null)}
128    </div>);
129}
130const ARC = 235.6; // 270° of a r=50 circle
131const CIRC = 314.2;
132export function Gauge({ value, size = 150, label, sub, tone = 'var(--st-accent)', }: {
133    value: number; // 0..100
134    size?: number;
135    label?: string;
136    sub?: string;
137    tone?: string;
138}) {
139    const clamped = Math.max(0, Math.min(100, value));
140    const dash = (ARC * clamped) / 100;
141    return (<div className="st-gauge" style={{ width: size, height: size }}>
142      <svg viewBox="0 0 120 120" width={size} height={size} role="img" aria-label={tr(label ?? `${Math.round(clamped)}%`)}>
143        <circle className="st-gauge__track" cx="60" cy="60" r="50" fill="none" strokeWidth="10" strokeLinecap="round" strokeDasharray={`${ARC} ${CIRC}`} transform="rotate(135 60 60)"/>
144        <circle className="st-gauge__fill" cx="60" cy="60" r="50" fill="none" stroke={tone} strokeWidth="10" strokeLinecap="round" strokeDasharray={`${dash} ${CIRC}`} transform="rotate(135 60 60)" style={{ transition: 'stroke-dasharray 400ms var(--st-ease)', opacity: dash >= 3 ? 1 : 0 }}/>
145      </svg>
146      <div className="gauge__readout">
147        <span style={{ fontSize: size * 0.2, fontWeight: 900, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
148          {tr(label ?? `${Math.round(clamped)}%`)}
149        </span>
150        {tr(sub ? <span style={{ fontSize: 12, fontWeight: 500, color: 'var(--st-ink-muted)' }}>{tr(sub)}</span> : null)}
151      </div>
152    </div>);
153}