refactor(ui): finish the Preact port and delete the imperative DOM layer

The dashboard was a hybrid: a Preact page per route rendered into a shell
built by a hand-rolled el() helper. Every route was Preact and the shell was
not, which is why nothing failed -- the last of the vanilla layer was the
part that composed the app.

Removed:
- ui/src/base/dom.jsx -- el/append/mount, the unused pill/empty pair, and a
  statusKind re-export that duplicated task-meta for one caller
- ui/src/chat/chat-tools.jsx and the el-based bubble builders in
  chat-render.jsx: nothing in src/ called them, only their own tests did
- the chatPage() DOM bridge, which existed so an imperative shell could embed
  a VNode

Ported:
- base/icons.jsx: icon() -> <Icon>; the glyph path table stays data
- base/gauge.jsx, base/statTile.jsx, base/log-row.jsx: DOM builders ->
  components, with inline SVG instead of innerHTML
- base/format.jsx: ago/compact, which never were DOM
- chat/markdown.jsx: renderMarkdown() -> <ChatMarkdown>, so a streamed reply
  is diffed rather than rebuilt block by block
- main.jsx: shell, nav, jump-to search, theme and chat drawer are one App;
  pages still render into one long-lived outlet

Routing stays wired at import rather than from an effect. A page installs its
own hash-sensitive state as it mounts, and task detail writes its tab
selection back with replaceState as it settles: if the outgoing page is still
mounted when the hashchange lands it canonicalises the URL back to its own
route and the navigation is silently lost. The outlet and the two
navigation-owned pieces of chrome are published through a callback ref, which
runs at commit time, before any page effect.

Tests: dom.test.js (el) and chat-tools.test.js are gone. The statTile cases
in dom.test.js were not dropped -- they pinned the zero-value headline bug
that made fresh installs look broken, and moved to test/statTile.test.js
against the component. log-row and chat-markdown render their components.

ui/dist rebuilt: index.js 146977 -> 146010 bytes.

Closes archie-core-v9gv.2 and archie-core-v9gv.
This commit is contained in:
sam committed 2026-09-19 03:35:14 +10:00
1 parent 22a34eae13
commit b5e9831dea
26 files changed
+697 -940

No files matched your search

-89
View File
@@ -1,89 +0,0 @@
// Tiny DOM helpers. Deliberately not a framework: the dashboard is a handful
// of pages over a read-mostly API, and a build-free vanilla layer keeps the
// embedded bundle small.
/**
* el("div.card", {onclick}, child, child) -> HTMLElement
* The tag string accepts CSS-ish shorthand: "button.btn.btn-primary".
*/
export function el(spec, attrs, ...children) {
const [tag, ...classes] = spec.split(".");
const node = document.createElement(tag || "div");
if (classes.length) node.className = classes.join(" ");
// A falsy scalar first child (0, "", false) is a value, not a missing
// attrs object: unshift it so append() renders it instead of dropping it.
// undefined stays "no attrs" so `el("div", undefined, child)` still works.
if (attrs !== undefined && (typeof attrs !== "object" || attrs instanceof Node)) {
children.unshift(attrs);
attrs = null;
}
for (const [k, v] of Object.entries(attrs || {})) {
if (v == null || v === false) continue;
if (k.startsWith("on") && typeof v === "function") {
node.addEventListener(k.slice(2).toLowerCase(), v);
} else if (k === "class") {
node.className = [node.className, v].filter(Boolean).join(" ");
} else if (k === "html") {
node.innerHTML = v;
} else {
node.setAttribute(k, v === true ? "" : String(v));
}
}
append(node, children);
return node;
}
function append(node, children) {
for (const c of children.flat(Infinity)) {
if (c == null || c === false) continue;
node.append(c instanceof Node ? c : document.createTextNode(String(c)));
}
}
export function mount(parent, ...children) {
parent.replaceChildren();
append(parent, children);
return parent;
}
/** Status pill. Kind maps to the semantic colour tokens. */
export function pill(text, kind = "idle") {
return el(`span.pill.pill-${kind}`, text);
}
// Re-exported from task-meta.js so the pill severity vocabulary has a single
// source (the server catalog). Importers that pull statusKind from dom.js --
// e.g. dashboard.js -- keep working, and the hardcoded switch is gone.
export { statusKind } from "./task-meta.jsx";
/** Humanised relative time: "2 min ago". Raw timestamps make people do maths. */
export function ago(value) {
if (!value) return "—";
const then = value instanceof Date ? value : new Date(value);
const secs = Math.floor((Date.now() - then.getTime()) / 1000);
if (!Number.isFinite(secs)) return "—";
if (secs < 45) return "just now";
const units = [
["min", 60],
["hr", 3600],
["day", 86400],
["wk", 604800],
];
let label = "min", size = 60;
for (const [l, s] of units) {
if (secs >= s) [label, size] = [l, s];
}
const n = Math.floor(secs / size);
return `${n} ${label}${n === 1 ? "" : "s"} ago`;
}
/** Compact number: 2_400_000 -> "2.4M". Long digit strings do not scan. */
export function compact(n) {
if (n == null || Number.isNaN(n)) return "—";
return new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n);
}
export function empty(title, detail) {
return el("div.empty", el("div.empty-title", title), detail && el("div", detail));
}
+32
View File
@@ -0,0 +1,32 @@
/**
* Display formatting shared across the dashboard pages. Pure functions: no
* DOM, no framework.
*/
/** Humanised relative time: "2 min ago". Raw timestamps make people do maths. */
export function ago(value) {
if (!value) return "—";
const then = value instanceof Date ? value : new Date(value);
const secs = Math.floor((Date.now() - then.getTime()) / 1000);
if (!Number.isFinite(secs)) return "—";
if (secs < 45) return "just now";
const units = [
["min", 60],
["hr", 3600],
["day", 86400],
["wk", 604800],
];
let label = "min",
size = 60;
for (const [l, s] of units) {
if (secs >= s) [label, size] = [l, s];
}
const n = Math.floor(secs / size);
return `${n} ${label}${n === 1 ? "" : "s"} ago`;
}
/** Compact number: 2_400_000 -> "2.4M". Long digit strings do not scan. */
export function compact(n) {
if (n == null || Number.isNaN(n)) return "—";
return new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 }).format(n);
}
+46 -45
View File
@@ -1,4 +1,4 @@
import { el } from "./dom.jsx";
import { h } from "preact";
/**
* Arc gauge for a single headline percentage.
@@ -8,7 +8,7 @@ import { el } from "./dom.jsx";
* number is not. Colour follows the value, so "is this bad" is answered before
* the digits are read.
*/
export function gauge({ value, label, size = 168 }) {
export function Gauge({ value, label, size = 168 }) {
const pct = Math.max(0, Math.min(100, Number(value) || 0));
const stroke = pct >= 90 ? "var(--ok)" : pct >= 70 ? "var(--warn)" : "var(--danger)";
@@ -30,24 +30,26 @@ export function gauge({ value, label, size = 168 }) {
].join(" ");
};
const svg = el("svg.gauge", {
viewBox: `0 0 ${size} ${size * 0.78}`,
role: "img",
"aria-label": `${label}: ${pct}%`,
});
svg.innerHTML = `
<path d="${arc(start, sweep)}" fill="none" stroke="var(--border)"
stroke-width="12" stroke-linecap="round"/>
<path d="${arc(start, sweep)}" fill="none" stroke="${stroke}"
stroke-width="12" stroke-linecap="round"
stroke-dasharray="${circumference}"
stroke-dashoffset="${circumference * (1 - pct / 100)}"
class="gauge-value"/>`;
return el(
"div.gauge-wrap",
svg,
el("div.gauge-center", el("div.gauge-pct", `${Math.round(pct)}%`), el("div.gauge-label", label)),
return (
<div className="gauge-wrap">
<svg className="gauge" viewBox={`0 0 ${size} ${size * 0.78}`} role="img" aria-label={`${label}: ${pct}%`}>
<path d={arc(start, sweep)} fill="none" stroke="var(--border)" stroke-width="12" stroke-linecap="round" />
<path
d={arc(start, sweep)}
fill="none"
stroke={stroke}
stroke-width="12"
stroke-linecap="round"
stroke-dasharray={circumference}
stroke-dashoffset={circumference * (1 - pct / 100)}
className="gauge-value"
/>
</svg>
<div className="gauge-center">
<div className="gauge-pct">{`${Math.round(pct)}%`}</div>
<div className="gauge-label">{label}</div>
</div>
</div>
);
}
@@ -59,31 +61,30 @@ export function gauge({ value, label, size = 168 }) {
* because three related quantities are easier to compare in one bar than in
* three separate numbers.
*/
export function segmentBar(segments) {
export function SegmentBar({ segments }) {
const total = segments.reduce((a, s) => a + (s.value || 0), 0) || 1;
return el(
"div",
el(
"div.segbar",
...segments
.filter((s) => s.value > 0)
.map((s) =>
el("span", {
class: `segbar-part segbar-${s.kind || "idle"}`,
style: `width:${((s.value / total) * 100).toFixed(1)}%`,
title: `${s.label}: ${s.value}`,
}),
),
),
el(
"div.segbar-legend",
...segments.map((s) =>
el(
"span.segbar-key",
el("span", { class: `segbar-dot segbar-${s.kind || "idle"}` }),
s.label,
),
),
),
return (
<div>
<div className="segbar">
{segments
.filter((s) => s.value > 0)
.map((s) => (
<span
key={s.label}
className={`segbar-part segbar-${s.kind || "idle"}`}
style={`width:${((s.value / total) * 100).toFixed(1)}%`}
title={`${s.label}: ${s.value}`}
/>
))}
</div>
<div className="segbar-legend">
{segments.map((s) => (
<span className="segbar-key" key={s.label}>
<span className={`segbar-dot segbar-${s.kind || "idle"}`} />
{s.label}
</span>
))}
</div>
</div>
);
}
+25 -16
View File
@@ -1,3 +1,5 @@
import { h } from "preact";
/**
* Icon set.
*
@@ -34,21 +36,28 @@ const paths = {
};
/**
* icon("tasks") -> SVGElement. size is the rendered box; the grid is always 24
* so stroke weight stays optically consistent at any size.
* Icon draws one glyph from the set. size is the rendered box; the grid is
* always 24 so stroke weight stays optically consistent at any size.
*
* The glyph bodies are the `paths` strings above, injected as raw SVG. They are
* in-repo constants and Preact cannot turn markup into elements, so re-authoring
* twenty multi-element glyphs as JSX would trade a data table for code without
* changing a single drawn pixel.
*/
export function icon(name, { size = 18, className = "" } = {}) {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("width", String(size));
svg.setAttribute("height", String(size));
svg.setAttribute("fill", "none");
svg.setAttribute("stroke", "currentColor");
svg.setAttribute("stroke-width", "1.6");
svg.setAttribute("stroke-linecap", "round");
svg.setAttribute("stroke-linejoin", "round");
svg.setAttribute("aria-hidden", "true");
svg.setAttribute("class", `ico ${className}`.trim());
svg.innerHTML = paths[name] || paths.dashboard;
return svg;
export function Icon({ name, size = 18, className = "" }) {
return (
<svg
viewBox="0 0 24 24"
width={size}
height={size}
fill="none"
stroke="currentColor"
stroke-width="1.6"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
className={`ico ${className}`.trim()}
dangerouslySetInnerHTML={{ __html: paths[name] || paths.dashboard }}
/>
);
}
+18 -15
View File
@@ -1,9 +1,9 @@
import { el } from "./dom.jsx";
import { h } from "preact";
/**
* Shared log-entry rendering. Both the daemon-wide log page
* (ui/src/logs/logs.js) and a task's own attempt log
* (ui/src/tasks/task-logs.js) render the same Entry shape from
* (ui/src/logs/logs.jsx) and a task's own attempt log
* (ui/src/tasks/task-logs.jsx) render the same Entry shape from
* internal/logging, so the row markup lives here rather than being
* duplicated a second time -- see CLAUDE.md's "extract to base on the
* second distinct consumer".
@@ -34,19 +34,22 @@ export function levelKind(level) {
}
}
export function logRow(entry) {
export function LogRow({ entry }) {
const fields = entry.fields || {};
return el(
`div.log-row.log-${levelKind(entry.level)}`,
el("span.log-time.mono", shortTime(entry.time)),
el("span.log-level", (entry.level || "info").toUpperCase()),
el(
"span.log-body",
el("span.log-msg", entry.message || entry.msg || ""),
...Object.entries(fields).map(([k, v]) =>
el("span.log-field", el("span.log-field-key", k), String(fmtValue(v))),
),
),
return (
<div className={`log-row log-${levelKind(entry.level)}`}>
<span className="log-time mono">{shortTime(entry.time)}</span>
<span className="log-level">{(entry.level || "info").toUpperCase()}</span>
<span className="log-body">
<span className="log-msg">{entry.message || entry.msg || ""}</span>
{Object.entries(fields).map(([k, v]) => (
<span className="log-field" key={k}>
<span className="log-field-key">{k}</span>
{String(fmtValue(v))}
</span>
))}
</span>
</div>
);
}
+39 -28
View File
@@ -1,5 +1,5 @@
import { el } from "./dom.jsx";
import { icon } from "./icons.jsx";
import { h } from "preact";
import { Icon } from "./icons.jsx";
/**
* A KPI tile: label, big value, trend against a stated comparison window, and
@@ -8,26 +8,33 @@ import { icon } from "./icons.jsx";
*
* trend > 0 renders as an increase. `goodDirection` says whether that is good,
* because rising latency and rising success rate are not the same news.
*
* The headline value is rendered whatever its type, including 0 and "": a tile
* that showed a label and a comparison line with no number above them read as
* a broken dashboard on every fresh install.
*/
export function statTile({ label, value, unit, trend, compare, series = [], goodDirection = "up" }) {
export function StatTile({ label, value, unit, trend, compare, series = [], goodDirection = "up" }) {
const dir = trend == null ? null : trend >= 0 ? "up" : "down";
const good = dir == null ? null : dir === goodDirection;
return el(
"div.card.stat",
el(
"div.stat-head",
el("span.stat-label", label),
dir &&
el(
`span.stat-trend.${good ? "up" : "down"}`,
icon(dir === "up" ? "trendUp" : "trendDown", { size: 13 }),
`${Math.abs(trend).toFixed(1)}%`,
),
),
el("div.stat-value", value, unit && el("span.stat-unit", unit)),
compare && el("div.stat-compare", compare),
series.length > 1 && sparkline(series, good === false ? "var(--danger)" : "var(--ok)"),
return (
<div className="card stat">
<div className="stat-head">
<span className="stat-label">{label}</span>
{dir ? (
<span className={`stat-trend ${good ? "up" : "down"}`}>
<Icon name={dir === "up" ? "trendUp" : "trendDown"} size={13} />
{`${Math.abs(trend).toFixed(1)}%`}
</span>
) : null}
</div>
<div className="stat-value">
{value}
{unit ? <span className="stat-unit">{unit}</span> : null}
</div>
{compare ? <div className="stat-compare">{compare}</div> : null}
{series.length > 1 ? <Sparkline series={series} stroke={good === false ? "var(--danger)" : "var(--ok)"} /> : null}
</div>
);
}
@@ -35,7 +42,7 @@ export function statTile({ label, value, unit, trend, compare, series = [], good
* Inline SVG sparkline. Shows shape, not exact values -- the tile's headline
* number carries the precision.
*/
export function sparkline(series, stroke = "var(--ok)", { width = 220, height = 34 } = {}) {
export function Sparkline({ series, stroke = "var(--ok)", width = 220, height = 34 }) {
const max = Math.max(...series, 1);
const min = Math.min(...series, 0);
const span = max - min || 1;
@@ -45,13 +52,17 @@ export function sparkline(series, stroke = "var(--ok)", { width = 220, height =
.map((v, i) => `${(i * step).toFixed(1)},${(height - ((v - min) / span) * height).toFixed(1)}`)
.join(" ");
const svg = el("svg.spark", {
viewBox: `0 0 ${width} ${height}`,
preserveAspectRatio: "none",
"aria-hidden": "true",
});
svg.innerHTML =
`<polyline points="${points}" fill="none" stroke="${stroke}" stroke-width="1.5" ` +
`stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke"/>`;
return svg;
return (
<svg className="spark" viewBox={`0 0 ${width} ${height}`} preserveAspectRatio="none" aria-hidden="true">
<polyline
points={points}
fill="none"
stroke={stroke}
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
vector-effect="non-scaling-stroke"
/>
</svg>
);
}