@celestia-island/hikari 0.55.413 → 0.55.415

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,236 @@
1
+ import { afterEach, describe, expect, it } from "vitest";
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ import { createApp, h, nextTick, ref } from "vue";
7
+
8
+ import HkUsageFlow from "./HkUsageFlow";
9
+
10
+ const mounts: Array<{ app: ReturnType<typeof createApp>; container: HTMLElement }> = [];
11
+
12
+ function mount(node: ReturnType<typeof h>) {
13
+ const container = document.createElement("div");
14
+ document.body.appendChild(container);
15
+ const app = createApp({ render: () => node });
16
+ app.mount(container);
17
+ mounts.push({ app, container });
18
+ return container;
19
+ }
20
+
21
+ afterEach(() => {
22
+ for (const { app, container } of mounts.splice(0)) {
23
+ app.unmount();
24
+ container.remove();
25
+ }
26
+ });
27
+
28
+ const ROWS = [
29
+ { source: "caller-a", middle: "up-1", target: "model-x", value: 500 },
30
+ { source: "caller-a", middle: "up-1", target: "model-y", value: 300 },
31
+ { source: "caller-b", middle: "up-2", target: "model-x", value: 200 },
32
+ ];
33
+
34
+ function texts(el: HTMLElement, selector: string): string[] {
35
+ return [...el.querySelectorAll(selector)].map((node) => node.textContent ?? "");
36
+ }
37
+
38
+ describe("HkUsageFlow", () => {
39
+ it("renders one bar per staged label and one ribbon per aggregate link", () => {
40
+ const el = mount(<HkUsageFlow rows={ROWS} />);
41
+ // callers (2) + upstreams (2) + models (2)
42
+ expect(el.querySelectorAll(".hk-usage-flow__node")).toHaveLength(6);
43
+ // caller→upstream: a→1, b→2 (2 links); upstream→model: 1→x, 1→y, 2→x (3)
44
+ expect(el.querySelectorAll(".hk-usage-flow__ribbon")).toHaveLength(5);
45
+ const labels = texts(el, ".hk-usage-flow__label");
46
+ expect(labels).toEqual(
47
+ expect.arrayContaining(["caller-a", "caller-b", "up-1", "up-2", "model-x", "model-y"]),
48
+ );
49
+ });
50
+
51
+ it("anchors model labels to the left of their bar and caller labels to the right", () => {
52
+ const el = mount(<HkUsageFlow rows={ROWS} />);
53
+ const labels = [...el.querySelectorAll(".hk-usage-flow__label")];
54
+ const byText = new Map(labels.map((label) => [label.textContent, label]));
55
+ expect(byText.get("caller-a")?.getAttribute("text-anchor")).toBe("start");
56
+ expect(byText.get("model-x")?.getAttribute("text-anchor")).toBe("end");
57
+ });
58
+
59
+ it("renders every roster model, greyed when it served no traffic", () => {
60
+ const el = mount(
61
+ <HkUsageFlow
62
+ rows={ROWS}
63
+ models={[{ label: "model-x" }, { label: "model-y" }, { label: "model-idle" }]}
64
+ />,
65
+ );
66
+ const rows = [...el.querySelectorAll(".hk-usage-flow__legend-row")];
67
+ expect(rows).toHaveLength(3);
68
+ expect(rows.map((row) => row.querySelector(".hk-usage-flow__legend-label")?.textContent)).toEqual([
69
+ "model-x",
70
+ "model-y",
71
+ "model-idle",
72
+ ]);
73
+ expect(rows[2].classList.contains("hk-usage-flow__legend-row--idle")).toBe(true);
74
+ expect(rows[0].classList.contains("hk-usage-flow__legend-row--idle")).toBe(false);
75
+ // Shares are computed over the metric total: x = 700/1000, y = 300/1000.
76
+ expect(rows[0].querySelector(".hk-usage-flow__legend-pct")?.textContent).toBe("70%");
77
+ expect(rows[1].querySelector(".hk-usage-flow__legend-pct")?.textContent).toBe("30%");
78
+ expect(rows[2].querySelector(".hk-usage-flow__legend-pct")?.textContent).toBe("0%");
79
+ });
80
+
81
+ it("draws caller labels right of their bar and model labels left of it", () => {
82
+ const el = mount(<HkUsageFlow rows={ROWS} />);
83
+ const labels = [...el.querySelectorAll(".hk-usage-flow__label")] as SVGTextElement[];
84
+ const byText = new Map(labels.map((label) => [label.textContent, label]));
85
+ const caller = byText.get("caller-a")!;
86
+ const model = byText.get("model-x")!;
87
+ const callerX = Number(caller.getAttribute("x"));
88
+ const modelX = Number(model.getAttribute("x"));
89
+ const callerBar = caller.parentElement!.querySelector("rect")!;
90
+ const modelBar = model.parentElement!.querySelector("rect")!;
91
+ expect(callerX).toBeGreaterThan(Number(callerBar.getAttribute("x")) + Number(callerBar.getAttribute("width")));
92
+ expect(modelX).toBeLessThan(Number(modelBar.getAttribute("x")));
93
+ });
94
+
95
+ it("formats values through the host formatter", () => {
96
+ const el = mount(
97
+ <HkUsageFlow rows={ROWS} models={[{ label: "model-x" }]} formatValue={(v) => `${v / 1000}k`} />,
98
+ );
99
+ const first = el.querySelector(".hk-usage-flow__legend-row .hk-usage-flow__legend-value");
100
+ expect(first?.textContent).toBe("0.7k");
101
+ const bar = el.querySelector(".hk-usage-flow__bar");
102
+ expect(bar?.getAttribute("data-hint")).toContain("caller-a");
103
+ expect(bar?.getAttribute("data-hint")).toContain("k");
104
+ });
105
+
106
+ it("folds overflowing columns into the localized others bucket", () => {
107
+ const rows = ["a", "b", "c", "d", "e"].map((source) => ({
108
+ source,
109
+ middle: "up",
110
+ target: "model-x",
111
+ value: 10,
112
+ }));
113
+ const el = mount(<HkUsageFlow rows={rows} maxNodes={3} othersLabel="其他调用方" />);
114
+ const labels = texts(el, ".hk-usage-flow__label");
115
+ expect(labels).toContain("其他调用方");
116
+ expect(el.querySelectorAll(".hk-usage-flow__node")).toHaveLength(5); // 3 callers + 1 upstream + 1 model
117
+ const others = [...el.querySelectorAll(".hk-usage-flow__label--others")];
118
+ expect(others.map((node) => node.textContent)).toEqual(["其他调用方"]);
119
+ });
120
+
121
+ it("renders the empty state when every row is zero", () => {
122
+ const el = mount(
123
+ <HkUsageFlow rows={[{ source: "a", middle: "b", target: "c", value: 0 }]} emptyText="暂无用量" />,
124
+ );
125
+ expect(el.querySelector(".hk-usage-flow--empty")).toBeTruthy();
126
+ expect(el.querySelector(".hk-usage-flow__empty")?.textContent).toBe("暂无用量");
127
+ expect(el.querySelector(".hk-usage-flow__chart")).toBeNull();
128
+ // No roster passed: no legend either.
129
+ expect(el.querySelector(".hk-usage-flow__legend")).toBeNull();
130
+ });
131
+
132
+ it("summarises the legend for assistive tech, with an explicit override", () => {
133
+ const el = mount(<HkUsageFlow rows={ROWS} models={[{ label: "model-x" }]} />);
134
+ const svg = el.querySelector(".hk-usage-flow__chart");
135
+ expect(svg?.getAttribute("role")).toBe("img");
136
+ expect(svg?.getAttribute("aria-label")).toContain("model-x 70%");
137
+ const overridden = mount(<HkUsageFlow rows={ROWS} ariaLabel="模型用量分布" />);
138
+ expect(
139
+ overridden.querySelector(".hk-usage-flow__chart")?.getAttribute("aria-label"),
140
+ ).toBe("模型用量分布");
141
+ });
142
+
143
+ it("still lists the registered roster when nothing measured", () => {
144
+ const el = mount(
145
+ <HkUsageFlow
146
+ rows={[]}
147
+ emptyText="No usage"
148
+ models={[{ label: "model-x" }, { label: "model-idle" }]}
149
+ />,
150
+ );
151
+ expect(el.querySelector(".hk-usage-flow__empty")?.textContent).toBe("No usage");
152
+ const rows = el.querySelectorAll(".hk-usage-flow__legend-row");
153
+ expect(rows).toHaveLength(2);
154
+ expect(rows[0].classList.contains("hk-usage-flow__legend-row--idle")).toBe(true);
155
+ expect(rows[0].textContent).toContain("0%");
156
+ });
157
+
158
+ it("pins its frame to the width/height props (the viewBox)", () => {
159
+ const el = mount(<HkUsageFlow rows={ROWS} width={800} height={360} />);
160
+ expect(el.querySelector(".hk-usage-flow__chart")?.getAttribute("viewBox")).toBe(
161
+ "0 0 800 360",
162
+ );
163
+ });
164
+
165
+ it("re-renders its geometry when the host swaps the rows", async () => {
166
+ const rows = ref(ROWS);
167
+ const container = document.createElement("div");
168
+ document.body.appendChild(container);
169
+ const app = createApp({ render: () => h(HkUsageFlow, { rows: rows.value }) });
170
+ app.mount(container);
171
+ mounts.push({ app, container });
172
+ expect(container.querySelectorAll(".hk-usage-flow__node")).toHaveLength(6);
173
+ rows.value = [{ source: "x", middle: "y", target: "z", value: 1 }];
174
+ await nextTick();
175
+ expect(container.querySelectorAll(".hk-usage-flow__node")).toHaveLength(3);
176
+ });
177
+
178
+ it("leaves the per-bar accessible name to the svg (no dead aria-labels)", () => {
179
+ const el = mount(<HkUsageFlow rows={ROWS} />);
180
+ const bar = el.querySelector(".hk-usage-flow__bar");
181
+ expect(bar?.getAttribute("aria-label")).toBeNull();
182
+ expect(bar?.getAttribute("data-hint")).toBeTruthy();
183
+ expect(el.querySelector(".hk-usage-flow__chart")?.getAttribute("role")).toBe("img");
184
+ });
185
+
186
+ it("can hide the legend without dropping the chart", () => {
187
+ const el = mount(<HkUsageFlow rows={ROWS} showLegend={false} />);
188
+ expect(el.querySelector(".hk-usage-flow__chart")).toBeTruthy();
189
+ expect(el.querySelector(".hk-usage-flow__legend")).toBeNull();
190
+ });
191
+
192
+ it("omits labels on bars too short to read, keeping their hints", () => {
193
+ const dense = [
194
+ { source: "huge", middle: "up", target: "model-x", value: 9_800_000 },
195
+ ...Array.from({ length: 8 }, (_, i) => ({
196
+ source: `tiny-${i}`,
197
+ middle: "up",
198
+ target: "model-x",
199
+ value: 2_000,
200
+ })),
201
+ ];
202
+ const el = mount(<HkUsageFlow rows={dense} />);
203
+ const nodes = el.querySelectorAll(".hk-usage-flow__node");
204
+ const labels = el.querySelectorAll(".hk-usage-flow__label");
205
+ // 9 callers + 1 upstream + 1 model; only the three tall bars label.
206
+ expect(nodes).toHaveLength(11);
207
+ expect(labels).toHaveLength(3);
208
+ // The omitted labels' identity survives on the hint channel.
209
+ const hints = [...el.querySelectorAll(".hk-usage-flow__bar")].map((bar) =>
210
+ bar.getAttribute("data-hint"),
211
+ );
212
+ expect(hints.some((hint) => hint?.includes("tiny-0"))).toBe(true);
213
+ });
214
+
215
+ it("keeps the hover hint channel on nodes and ribbons", () => {
216
+ const el = mount(<HkUsageFlow rows={ROWS} />);
217
+ const hints = [
218
+ ...el.querySelectorAll(".hk-usage-flow__ribbon"),
219
+ ...el.querySelectorAll(".hk-usage-flow__bar"),
220
+ ].map((node) => node.getAttribute("data-hint"));
221
+ expect(hints.every((hint) => typeof hint === "string" && hint.length > 0)).toBe(true);
222
+ expect(hints.some((hint) => hint?.includes("caller-a → up-1"))).toBe(true);
223
+ });
224
+ });
225
+
226
+ describe("HkUsageFlow sheet contracts", () => {
227
+ /** Source-scan pin for the RTL fix: SVG `text-anchor` start/end resolve
228
+ * against the inline base direction, so the chart MUST declare an LTR
229
+ * base — deleting the declaration would flip the labels in an RTL host
230
+ * and no unit test would notice. */
231
+ it("keeps the chart's inline base direction LTR", () => {
232
+ const here = dirname(fileURLToPath(import.meta.url));
233
+ const sheet = readFileSync(resolve(here, "HkUsageFlow.scss"), "utf8");
234
+ expect(sheet).toMatch(/&__chart\s*\{[^}]*direction:\s*ltr;/s);
235
+ });
236
+ });
@@ -0,0 +1,253 @@
1
+ // HkUsageFlow — the usage-distribution business component: three-stage
2
+ // Sankey (caller → upstream → model) plus the registered-model legend.
3
+ //
4
+ // Upstreamed for the arona console / shittim-chest admin panels' "model
5
+ // usage distribution" view (2026-11-17 user direction: one statistics
6
+ // component in hikari, both admin surfaces show the same picture). The
7
+ // component is DUMB by design — the host owns fetching, metric selection
8
+ // (tokens / requests / cost) and locale strings; this file only renders
9
+ // settled rows through ./usageFlowLayout (pure, pinned by its own tests).
10
+ //
11
+ // DOM contract (kept stable for the Rust mirror when it lands):
12
+ //
13
+ // div.hk-usage-flow
14
+ // div.hk-usage-flow__body (with data)
15
+ // svg.hk-usage-flow__chart[role=img][aria-label][viewBox]
16
+ // path.hk-usage-flow__ribbon[data-hint] (one per link, fill = target)
17
+ // g.hk-usage-flow__node (one per node)
18
+ // rect.hk-usage-flow__bar[fill][data-hint]
19
+ // text.hk-usage-flow__label[.hk-usage-flow__label--others]
20
+ // (omitted when the bar is
21
+ // too short to label)
22
+ // ul.hk-usage-flow__legend (showLegend)
23
+ // li.hk-usage-flow__legend-row[.hk-usage-flow__legend-row--idle]
24
+ // span.hk-usage-flow__legend-swatch
25
+ // span.hk-usage-flow__legend-label
26
+ // span.hk-usage-flow__legend-value
27
+ // span.hk-usage-flow__legend-pct
28
+ // div.hk-usage-flow__empty (no positive rows)
29
+ //
30
+ // Hover hints ride the consumer's own tooltip channel (`data-hint`), the
31
+ // HkBarChart/HkDonutChart convention — no native title bubble, no chart
32
+ // library, no measurement API (the viewBox scales the frame; label text is
33
+ // sized in SVG units so hosts pick a width that matches their column).
34
+ // The `<svg role="img">` owns the accessible name (its aria-label is the
35
+ // legend's share summary); per-bar aria-labels are deliberately absent —
36
+ // an img-role subtree is presentational, so they would be dead markup.
37
+ // The legend list below the chart is real text and is the accessible
38
+ // breakdown.
39
+ //
40
+ // AI-generated (DeepSeek V4.1 via DeepSeek Harness), 2026-11-17 — SySL-1.0 §2.3.
41
+
42
+ import { computed, defineComponent, type PropType } from "vue";
43
+
44
+ import { asPropType } from "../utils/typing";
45
+ import {
46
+ formatFlowPercent,
47
+ usageFlowLayout,
48
+ type HkUsageFlowLayout,
49
+ type HkUsageFlowRosterEntry,
50
+ type HkUsageFlowRow,
51
+ } from "./usageFlowLayout";
52
+ import "./HkUsageFlow.scss";
53
+
54
+ /** Gap between a node bar and its label, in SVG units. */
55
+ const LABEL_GAP = 6;
56
+
57
+ export default defineComponent({
58
+ name: "HkUsageFlow",
59
+ props: {
60
+ /** Settled aggregate rows: caller → upstream → model → metric value.
61
+ * The caller owns aggregation (one row per distinct triple). */
62
+ rows: { type: asPropType<readonly HkUsageFlowRow[]>(Array), required: true },
63
+ /** The complete registered-model roster. Roster order fixes the model
64
+ * colours, so an idle model keeps its swatch; idle models still get a
65
+ * greyed legend row. Models that served traffic without a roster row
66
+ * are appended after it. */
67
+ models: { type: asPropType<readonly HkUsageFlowRosterEntry[] | null>(Array), default: null },
68
+ /** Value formatter for legend numbers and hints. Absent = the runtime
69
+ * locale's `toLocaleString()` — hosts that pin a locale pass their own
70
+ * formatter (the admin panels do). */
71
+ formatValue: {
72
+ type: Function as PropType<(value: number) => string>,
73
+ default: null,
74
+ },
75
+ /** Frame width in SVG units (the viewBox; CSS scales it to the host). */
76
+ width: { type: Number, default: 960 },
77
+ /** Frame height in SVG units. */
78
+ height: { type: Number, default: 420 },
79
+ /** Per-column node cap; the tail folds into one `othersLabel` bucket. */
80
+ maxNodes: { type: Number, default: 10 },
81
+ /** Label for the collapsed bucket (host-localized; e.g. 其他 / Others). */
82
+ othersLabel: { type: String, default: "Others" },
83
+ /** Label truncation budget in character units (CJK counts 2). */
84
+ labelMaxChars: { type: Number, default: 28 },
85
+ /** Colour ladder override (theme-token expressions); absent = the
86
+ * built-in semantic ladder. */
87
+ colors: { type: asPropType<readonly string[] | null>(Array), default: null },
88
+ showLegend: { type: Boolean, default: true },
89
+ emptyText: { type: String, default: "No data" },
90
+ /** Accessible summary; absent = the legend's own share summary. */
91
+ ariaLabel: { type: String, default: null },
92
+ },
93
+ setup(props) {
94
+ const format = (value: number): string =>
95
+ props.formatValue ? props.formatValue(value) : value.toLocaleString();
96
+
97
+ const layout = computed<HkUsageFlowLayout>(() =>
98
+ usageFlowLayout(props.rows ?? [], {
99
+ width: props.width,
100
+ height: props.height,
101
+ maxNodes: props.maxNodes,
102
+ othersLabel: props.othersLabel,
103
+ models: props.models ?? [],
104
+ colors: props.colors ?? undefined,
105
+ labelMaxChars: props.labelMaxChars,
106
+ }),
107
+ );
108
+
109
+ /** Label anchor per column: the first two columns label to the RIGHT of
110
+ * their bar, the model column labels to the LEFT (the d3-sankey
111
+ * convention the design reference uses — the last bar sits at the
112
+ * frame's right edge so its labels have the room). */
113
+ const labelX = (node: { column: number; x: number; width: number }): number =>
114
+ node.column === 2 ? node.x - LABEL_GAP : node.x + node.width + LABEL_GAP;
115
+ const labelAnchor = (column: number): "start" | "end" =>
116
+ column === 2 ? "end" : "start";
117
+
118
+ const nodeHint = (node: { fullLabel: string; value: number }): string =>
119
+ `${node.fullLabel} · ${format(node.value)}`;
120
+
121
+ /** One keyed lookup per render — not two linear scans per link. */
122
+ const nodeByKey = computed(() => {
123
+ const map = new Map<string, { fullLabel: string }>();
124
+ for (const node of layout.value.nodes) map.set(node.key, node);
125
+ return map;
126
+ });
127
+ const linkHint = (link: { sourceKey: string; targetKey: string; value: number }): string => {
128
+ const from = nodeByKey.value.get(link.sourceKey);
129
+ const to = nodeByKey.value.get(link.targetKey);
130
+ return `${from?.fullLabel ?? "?"} → ${to?.fullLabel ?? "?"} · ${format(link.value)}`;
131
+ };
132
+
133
+ const aria = computed(() => {
134
+ if (props.ariaLabel) return props.ariaLabel;
135
+ const shares = layout.value.legend
136
+ .filter((row) => !row.idle)
137
+ .map((row) => `${row.label} ${formatFlowPercent(row.percent)}`)
138
+ .join(", ");
139
+ return shares || props.emptyText;
140
+ });
141
+
142
+ return () => {
143
+ const model = layout.value;
144
+ if (model.empty) {
145
+ // No measured rows: the honest empty face — plus the roster table
146
+ // when the host supplied one, so "all registered models" is still
147
+ // answerable (every row reads 0 / idle).
148
+ return (
149
+ <div
150
+ class="hk-usage-flow hk-usage-flow--empty"
151
+ role="group"
152
+ aria-label={props.ariaLabel ?? undefined}
153
+ >
154
+ <div class="hk-usage-flow__empty">{props.emptyText}</div>
155
+ {props.showLegend && model.legend.length > 0 ? (
156
+ <ul class="hk-usage-flow__legend">
157
+ {model.legend.map((row) => (
158
+ <li
159
+ key={row.label}
160
+ class={["hk-usage-flow__legend-row", { "hk-usage-flow__legend-row--idle": row.idle }]}
161
+ data-hint={`${row.label} · ${format(row.value)} · ${formatFlowPercent(row.percent)}`}
162
+ >
163
+ <span
164
+ class="hk-usage-flow__legend-swatch"
165
+ style={{ background: row.color }}
166
+ aria-hidden="true"
167
+ />
168
+ <span class="hk-usage-flow__legend-label">{row.label}</span>
169
+ <span class="hk-usage-flow__legend-value">{format(row.value)}</span>
170
+ <span class="hk-usage-flow__legend-pct">0%</span>
171
+ </li>
172
+ ))}
173
+ </ul>
174
+ ) : null}
175
+ </div>
176
+ );
177
+ }
178
+ return (
179
+ <div class="hk-usage-flow">
180
+ <div class="hk-usage-flow__body">
181
+ <svg
182
+ class="hk-usage-flow__chart"
183
+ viewBox={`0 0 ${model.width} ${model.height}`}
184
+ preserveAspectRatio="xMidYMid meet"
185
+ role="img"
186
+ aria-label={aria.value}
187
+ >
188
+ {model.links.map((link) => (
189
+ <path
190
+ key={link.key}
191
+ class="hk-usage-flow__ribbon"
192
+ d={link.path}
193
+ fill={link.color}
194
+ data-hint={linkHint(link)}
195
+ />
196
+ ))}
197
+ {model.nodes.map((node) => (
198
+ <g class="hk-usage-flow__node" key={node.key}>
199
+ <rect
200
+ class="hk-usage-flow__bar"
201
+ x={node.x}
202
+ y={node.y}
203
+ width={node.width}
204
+ height={node.height}
205
+ rx={2}
206
+ fill={node.color}
207
+ data-hint={nodeHint(node)}
208
+ />
209
+ {node.labelVisible ? (
210
+ <text
211
+ class={[
212
+ "hk-usage-flow__label",
213
+ { "hk-usage-flow__label--others": node.others },
214
+ ]}
215
+ x={labelX(node)}
216
+ y={node.y + node.height / 2 + 4}
217
+ text-anchor={labelAnchor(node.column)}
218
+ >
219
+ {node.label}
220
+ </text>
221
+ ) : null}
222
+ </g>
223
+ ))}
224
+ </svg>
225
+ {props.showLegend ? (
226
+ <ul class="hk-usage-flow__legend">
227
+ {model.legend.map((row) => (
228
+ <li
229
+ key={row.label}
230
+ class={[
231
+ "hk-usage-flow__legend-row",
232
+ { "hk-usage-flow__legend-row--idle": row.idle },
233
+ ]}
234
+ data-hint={`${row.label} · ${format(row.value)} · ${formatFlowPercent(row.percent)}`}
235
+ >
236
+ <span
237
+ class="hk-usage-flow__legend-swatch"
238
+ style={{ background: row.color }}
239
+ aria-hidden="true"
240
+ />
241
+ <span class="hk-usage-flow__legend-label">{row.label}</span>
242
+ <span class="hk-usage-flow__legend-value">{format(row.value)}</span>
243
+ <span class="hk-usage-flow__legend-pct">{formatFlowPercent(row.percent)}</span>
244
+ </li>
245
+ ))}
246
+ </ul>
247
+ ) : null}
248
+ </div>
249
+ </div>
250
+ );
251
+ };
252
+ },
253
+ });