hd-garden 0.3.8 → 0.3.10

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.
Files changed (95) hide show
  1. package/.agents/skills/garden-post-review/SKILL.md +2 -0
  2. package/.agents/skills/garden-ui/SKILL.md +111 -0
  3. package/.env.example +8 -0
  4. package/app/admin/page.tsx +14 -3
  5. package/app/admin/preview/[...path]/page.tsx +88 -0
  6. package/app/admin/ui/blocks/page.tsx +16 -0
  7. package/app/admin/ui/catalog/page.tsx +16 -0
  8. package/app/admin/ui/evals/page.tsx +19 -0
  9. package/app/admin/ui/page.tsx +22 -0
  10. package/app/admin-ui.css +227 -0
  11. package/app/api/admin/distribution/route.ts +4 -2
  12. package/app/api/admin/posts/source/route.ts +21 -0
  13. package/app/api/admin/preview/asset/route.ts +32 -0
  14. package/app/api/admin/thoughts/route.ts +1 -1
  15. package/app/api/admin/ui/blocks/route.ts +19 -0
  16. package/app/api/admin/ui/draft/route.ts +30 -0
  17. package/app/api/auth/github/route.ts +40 -1
  18. package/app/blog/page.tsx +6 -5
  19. package/app/columns/page.tsx +1 -1
  20. package/app/components/AdminDashboard.tsx +53 -1
  21. package/app/components/AdminUiPanels.tsx +258 -0
  22. package/app/components/AdminUiShell.tsx +56 -0
  23. package/app/components/ContentEmptyState.tsx +6 -6
  24. package/app/components/MarkdownArticle.tsx +15 -5
  25. package/app/components/UiBlock.tsx +22 -0
  26. package/app/components/UiStudio.tsx +422 -0
  27. package/app/components/ui-studio-keys.ts +3 -0
  28. package/app/globals.css +2 -0
  29. package/app/lib/admin-auth.ts +13 -1
  30. package/app/lib/content.ts +2 -1
  31. package/app/lib/fallback-site-config.ts +18 -18
  32. package/app/lib/github-content.ts +47 -4
  33. package/app/lib/repository-path.mjs +55 -0
  34. package/app/lib/ui-content.ts +79 -0
  35. package/app/lib/ui-model.ts +145 -0
  36. package/app/raw.d.ts +4 -0
  37. package/app/rss.xml/route.ts +2 -1
  38. package/app/ui-parity/page.tsx +120 -0
  39. package/bin/garden.mjs +71 -0
  40. package/eslint.config.mjs +3 -0
  41. package/package.json +15 -1
  42. package/scripts/build-content.mjs +35 -4
  43. package/scripts/build-ui-preview.mjs +29 -0
  44. package/scripts/check-post.mjs +26 -4
  45. package/scripts/ui-cli.mjs +303 -0
  46. package/site.config.yaml +19 -19
  47. package/templates/site/site.config.yaml +19 -19
  48. package/tsconfig.json +1 -1
  49. package/ui/core/apply.mjs +81 -0
  50. package/ui/core/catalog.mjs +536 -0
  51. package/ui/core/compile.mjs +63 -0
  52. package/ui/core/demos.mjs +223 -0
  53. package/ui/core/expr.mjs +310 -0
  54. package/ui/core/fence.mjs +201 -0
  55. package/ui/core/fix-prompt.mjs +35 -0
  56. package/ui/core/format.mjs +96 -0
  57. package/ui/core/index.mjs +37 -0
  58. package/ui/core/parse.mjs +229 -0
  59. package/ui/core/scan.mjs +53 -0
  60. package/ui/core/sha256.mjs +66 -0
  61. package/ui/core/starters.mjs +18 -0
  62. package/ui/core/state.mjs +259 -0
  63. package/ui/core/static.mjs +524 -0
  64. package/ui/core/transform.mjs +146 -0
  65. package/ui/core/validate.mjs +665 -0
  66. package/ui/evals/cases.yaml +155 -0
  67. package/ui/preview/dist/garden-ui.css +1182 -0
  68. package/ui/preview/dist/garden-ui.esm.js +367 -0
  69. package/ui/preview/dist/garden-ui.iife.js +367 -0
  70. package/ui/preview/index.tsx +191 -0
  71. package/ui/preview/mermaid-shim.ts +19 -0
  72. package/ui/prompt/build.mjs +24 -0
  73. package/ui/prompt/recipes/code-walkthrough.md +68 -0
  74. package/ui/prompt/recipes/compare.md +48 -0
  75. package/ui/prompt/recipes/converter.md +55 -0
  76. package/ui/prompt/recipes/data-chart.md +57 -0
  77. package/ui/prompt/recipes/inspect-grid.md +45 -0
  78. package/ui/prompt/recipes/param-bench.md +55 -0
  79. package/ui/prompt/recipes/plan.md +45 -0
  80. package/ui/prompt/recipes/stepper.md +52 -0
  81. package/ui/prompt/recipes/trace.md +62 -0
  82. package/ui/prompt/rules.md +104 -0
  83. package/ui/prompt/studio.md +20 -0
  84. package/ui/react/CatalogPage.tsx +166 -0
  85. package/ui/react/components/chart.tsx +470 -0
  86. package/ui/react/components/display.tsx +296 -0
  87. package/ui/react/components/inputs.tsx +268 -0
  88. package/ui/react/components/layout.tsx +236 -0
  89. package/ui/react/components/media.tsx +184 -0
  90. package/ui/react/index.tsx +59 -0
  91. package/ui/react/recipes.ts +25 -0
  92. package/ui/react/runtime.tsx +239 -0
  93. package/ui/react/types.ts +29 -0
  94. package/ui/react/ui.css +1182 -0
  95. package/vite.config.ts +4 -3
@@ -0,0 +1,470 @@
1
+ "use client";
2
+
3
+ import { useEffect, useId, useRef, useState } from "react";
4
+ import { TONES } from "../../core/catalog.mjs";
5
+ import { formatValue } from "../../core/format.mjs";
6
+ import { isPowerOfTwo, lookupFrom, sampleDomain } from "../../core/state.mjs";
7
+ import { asNumber, asString, evalExpr, expandChildren, propValue, registerComponents, rowValue, useRuntime } from "../runtime";
8
+ import type { Env, Lookup, UiNode } from "../types";
9
+
10
+ const SERIES = new Set(["Line", "Area", "Bar", "Point"]);
11
+ const DEFAULT_TONES = ["plain", "accent", "new", "same"];
12
+ const MARGIN = { top: 14, right: 16, bottom: 30, left: 60 };
13
+
14
+ type Scale = { map: (value: number) => number; ticks: number[] };
15
+
16
+ function niceTicks(min: number, max: number, count = 5) {
17
+ if (!Number.isFinite(min) || !Number.isFinite(max)) return [];
18
+ if (min === max) {
19
+ min -= 1;
20
+ max += 1;
21
+ }
22
+ const rough = (max - min) / count;
23
+ const magnitude = 10 ** Math.floor(Math.log10(rough));
24
+ const ratio = rough / magnitude;
25
+ const step = (ratio >= 7.5 ? 10 : ratio >= 3.5 ? 5 : ratio >= 1.5 ? 2 : 1) * magnitude;
26
+ const ticks: number[] = [];
27
+ for (let value = Math.ceil(min / step) * step; value <= max + step * 1e-9; value += step) {
28
+ ticks.push(Math.abs(value) < step * 1e-9 ? 0 : Number(value.toPrecision(12)));
29
+ }
30
+ return ticks;
31
+ }
32
+
33
+ /** Ticks that read well in the axis format: nice numbers inside the chosen binary unit for bytes. */
34
+ function formatTicks(min: number, max: number, count: number, format?: string) {
35
+ if (format !== "bytes" || max <= 0) return niceTicks(min, max, count);
36
+ let unit = 1;
37
+ while (max / unit >= 1024 && unit < 1024 ** 5) unit *= 1024;
38
+ return niceTicks(min / unit, max / unit, count).map((tick) => tick * unit);
39
+ }
40
+
41
+ function logTicks(min: number, max: number) {
42
+ const tens: number[] = [];
43
+ for (let exponent = Math.ceil(Math.log10(min)); 10 ** exponent <= max * (1 + 1e-9); exponent += 1) tens.push(10 ** exponent);
44
+ if (tens.length >= 3) return tens;
45
+ const twos: number[] = [];
46
+ for (let exponent = Math.ceil(Math.log2(min)); 2 ** exponent <= max * (1 + 1e-9); exponent += 1) twos.push(2 ** exponent);
47
+ return twos.length > 7 ? twos.filter((_, index) => index % Math.ceil(twos.length / 6) === 0) : twos;
48
+ }
49
+
50
+ // Advance of one character at the 11px monospace tick size; CJK characters take two.
51
+ const TICK_CHAR_WIDTH = 6.8;
52
+ const TICK_GAP = 6;
53
+ type Anchor = "start" | "middle" | "end";
54
+
55
+ const labelWidth = (text: string) => [...text].reduce((sum, char) => sum + ((char.codePointAt(0) ?? 0) > 0x2e80 ? 2 : 1), 0) * TICK_CHAR_WIDTH;
56
+
57
+ /** Every k-th tick, for the smallest k whose labels no longer overlap at this width. */
58
+ function fitTicks(ticks: number[], position: (tick: number) => number, label: (tick: number) => string, anchor: (x: number) => Anchor) {
59
+ const extent = (tick: number) => {
60
+ const x = position(tick);
61
+ const width = labelWidth(label(tick));
62
+ const side = anchor(x);
63
+ return side === "start" ? [x, x + width] : side === "end" ? [x - width, x] : [x - width / 2, x + width / 2];
64
+ };
65
+ for (let stride = 1; stride < ticks.length; stride += 1) {
66
+ const kept = ticks.filter((_, index) => index % stride === 0);
67
+ if (kept.every((tick, index) => index === 0 || extent(kept[index - 1])[1] + TICK_GAP <= extent(tick)[0])) return kept;
68
+ }
69
+ return ticks.slice(0, 1);
70
+ }
71
+
72
+ function makeScale(min: number, max: number, from: number, to: number, kind: "linear" | "log"): Scale {
73
+ if (kind === "log" && min > 0 && max > min) {
74
+ const low = Math.log(min);
75
+ const high = Math.log(max);
76
+ return { map: (value) => from + ((Math.log(value) - low) / (high - low)) * (to - from), ticks: logTicks(min, max) };
77
+ }
78
+ const span = max - min || 1;
79
+ return { map: (value) => from + ((value - min) / span) * (to - from), ticks: niceTicks(min, max, 5) };
80
+ }
81
+
82
+ type Model = {
83
+ categorical: boolean;
84
+ xs: number[];
85
+ categories: string[];
86
+ series: Array<{ kind: string; label: string; tone: string; format?: string; ys: number[] }>;
87
+ marker: number | null;
88
+ xScaleKind: "linear" | "log";
89
+ xFormat?: string;
90
+ };
91
+
92
+ function Chart({ node, env }: { node: UiNode; env: Env }) {
93
+ const runtime = useRuntime();
94
+ const baseId = useId().replaceAll(":", "");
95
+ const wrapRef = useRef<HTMLDivElement>(null);
96
+ const [width, setWidth] = useState(640);
97
+ const [hover, setHover] = useState<number | null>(null);
98
+ const [drawn, setDrawn] = useState(false);
99
+
100
+ useEffect(() => {
101
+ const element = wrapRef.current;
102
+ if (!element || typeof ResizeObserver === "undefined") return;
103
+ const observer = new ResizeObserver(([entry]) => setWidth(Math.max(240, Math.round(entry.contentRect.width))));
104
+ observer.observe(element);
105
+ return () => observer.disconnect();
106
+ }, []);
107
+
108
+ // Draw in once, the first time the chart scrolls into view.
109
+ useEffect(() => {
110
+ const element = wrapRef.current;
111
+ if (!element || typeof IntersectionObserver === "undefined") return;
112
+ const observer = new IntersectionObserver(([entry]) => {
113
+ if (!entry.isIntersecting) return;
114
+ setDrawn(true);
115
+ observer.disconnect();
116
+ }, { threshold: 0.3 });
117
+ observer.observe(element);
118
+ return () => observer.disconnect();
119
+ }, []);
120
+
121
+ const value = (name: string) => propValue(runtime, node, name, env);
122
+ const baseHeight = Math.max(120, Math.min(480, asNumber(value("height")) ?? 200));
123
+ const height = width < 480 ? Math.max(140, Math.round(baseHeight * 0.8)) : baseHeight;
124
+ const seriesNodes = expandChildren(runtime, node.c, env).filter((item) => SERIES.has(item.node.n ?? ""));
125
+
126
+ const model = ((): Model | null => {
127
+ const describe = (item: { node: UiNode; env: Env }, index: number) => ({
128
+ kind: item.node.n ?? "Line",
129
+ label: asString(propValue(runtime, item.node, "label", item.env), `系列 ${index + 1}`),
130
+ tone: (() => {
131
+ const tone = propValue(runtime, item.node, "tone", item.env);
132
+ return typeof tone === "string" && (TONES as string[]).includes(tone) ? tone : DEFAULT_TONES[index % DEFAULT_TONES.length];
133
+ })(),
134
+ format: (propValue(runtime, item.node, "format", item.env) as string | undefined) ?? (value("yFormat") as string | undefined),
135
+ });
136
+ if (node.p?.data) {
137
+ const rows = value("data");
138
+ const list = Array.isArray(rows) ? rows.slice(0, 2000) : [];
139
+ const xValues = list.map((row) => rowValue(runtime, node.p?.x, row, env));
140
+ const categorical = seriesNodes.some((item) => item.node.n === "Bar") || xValues.some((x) => typeof x !== "number");
141
+ const order = list.map((_, index) => index);
142
+ if (!categorical) order.sort((a, b) => (xValues[a] as number) - (xValues[b] as number));
143
+ return {
144
+ categorical,
145
+ xs: categorical ? order.map((_, index) => index) : order.map((index) => xValues[index] as number),
146
+ categories: order.map((index) => formatValue(xValues[index], value("xFormat") as string | undefined)),
147
+ series: seriesNodes.map((item, index) => ({
148
+ ...describe(item, index),
149
+ ys: order.map((rowIndex) => {
150
+ const y = rowValue(runtime, item.node.p?.y, list[rowIndex], item.env);
151
+ return typeof y === "number" ? y : Number.NaN;
152
+ }),
153
+ })),
154
+ marker: null,
155
+ xScaleKind: "linear",
156
+ xFormat: value("xFormat") as string | undefined,
157
+ };
158
+ }
159
+ const sweep = value("sweep");
160
+ if (typeof sweep !== "string") return null;
161
+ const slider = runtime.sliders.get(sweep);
162
+ const sliderValue = (name: string) => (slider ? propValue(runtime, slider, name, { locals: [] }) : undefined);
163
+ const from = asNumber(value("from")) ?? asNumber(sliderValue("min"));
164
+ const to = asNumber(value("to")) ?? asNumber(sliderValue("max"));
165
+ if (from === undefined || to === undefined || from >= to) return null;
166
+ const scaleValue = value("scale") ?? sliderValue("scale");
167
+ const scale = scaleValue === "log" && from > 0 ? "log" : "linear";
168
+ const snap = sliderValue("snap") ?? (scale === "log" && isPowerOfTwo(from) && isPowerOfTwo(to) ? "pow2" : "none");
169
+ const xs = sampleDomain({
170
+ from,
171
+ to,
172
+ scale,
173
+ samples: asNumber(value("samples")) ?? 64,
174
+ pow2: snap === "pow2",
175
+ }) as number[];
176
+ return {
177
+ categorical: false,
178
+ xs,
179
+ categories: [],
180
+ series: seriesNodes.map((item, index) => ({
181
+ ...describe(item, index),
182
+ ys: xs.map((x) => {
183
+ const scope = runtime.scopeFor({ ...runtime.state, [sweep]: x });
184
+ const y = item.node.p?.y;
185
+ const result = y?.k === "expr" ? evalExpr(y.e, lookupFrom(...item.env.locals, scope) as Lookup) : y?.v;
186
+ return typeof result === "number" ? result : Number.NaN;
187
+ }),
188
+ })),
189
+ marker: asNumber(runtime.state[sweep]) ?? null,
190
+ xScaleKind: scale,
191
+ xFormat: (value("xFormat") as string | undefined) ?? (sliderValue("format") as string | undefined),
192
+ };
193
+ })();
194
+
195
+ if (!model || !model.series.length) return <p className="garden-ui-error-inline">图表缺少有效的范围或数据</p>;
196
+
197
+ const innerWidth = width - MARGIN.left - MARGIN.right;
198
+ const innerHeight = height - MARGIN.top - MARGIN.bottom;
199
+ const finite = model.series.flatMap((series) => series.ys.filter((y) => Number.isFinite(y)));
200
+ const yScaleKind = value("yScale") === "log" ? "log" : "linear";
201
+ const hasFill = model.series.some((series) => series.kind === "Bar" || series.kind === "Area");
202
+ let yMin = asNumber(value("yMin")) ?? (yScaleKind === "log" ? Math.min(...finite.filter((y) => y > 0)) : Math.min(hasFill ? 0 : Infinity, ...finite, 0));
203
+ const yMax = asNumber(value("yMax")) ?? Math.max(...finite, yMin + 1);
204
+ if (!Number.isFinite(yMin)) yMin = 0;
205
+ const y = makeScale(yMin, yMax, MARGIN.top + innerHeight, MARGIN.top, yScaleKind);
206
+ const yFormatForTicks = (value("yFormat") as string | undefined) ?? model.series[0]?.format;
207
+ const yTicks = yScaleKind === "linear" ? formatTicks(yMin, yMax, 4, yFormatForTicks) : y.ticks;
208
+
209
+ const categoryCount = model.categories.length || 1;
210
+ const band = innerWidth / categoryCount;
211
+ const x = model.categorical
212
+ ? { map: (index: number) => MARGIN.left + band * index + band / 2, ticks: model.xs }
213
+ : makeScale(model.xs[0], model.xs[model.xs.length - 1], MARGIN.left, MARGIN.left + innerWidth, model.xScaleKind);
214
+ const anchorAt = (px: number): Anchor => (px > MARGIN.left + innerWidth - 24 ? "end" : px < MARGIN.left + 24 ? "start" : "middle");
215
+ const xTickLabel = (tick: number) => (model.categorical ? String(model.categories[tick] ?? "") : formatValue(tick, model.xFormat));
216
+ const xTicks = fitTicks(
217
+ model.categorical
218
+ ? model.xs
219
+ : model.xScaleKind === "log" ? x.ticks : formatTicks(model.xs[0], model.xs[model.xs.length - 1], 5, model.xFormat),
220
+ x.map,
221
+ xTickLabel,
222
+ anchorAt,
223
+ );
224
+
225
+ const yFormat = (value("yFormat") as string | undefined) ?? model.series[0]?.format;
226
+ const xLabel = (index: number) => (model.categorical ? model.categories[index] : formatValue(model.xs[index], model.xFormat));
227
+ const path = (ys: number[]) => {
228
+ let d = "";
229
+ let penDown = false;
230
+ ys.forEach((value, index) => {
231
+ if (!Number.isFinite(value) || (yScaleKind === "log" && value <= 0)) {
232
+ penDown = false;
233
+ return;
234
+ }
235
+ d += `${penDown ? "L" : "M"}${x.map(model.xs[index]).toFixed(1)},${y.map(value).toFixed(1)}`;
236
+ penDown = true;
237
+ });
238
+ return d;
239
+ };
240
+ const barSeries = model.series.filter((series) => series.kind === "Bar");
241
+ const barWidth = Math.max(2, (band - 8) / Math.max(1, barSeries.length) - 2);
242
+
243
+ const nearest = (clientX: number) => {
244
+ const rect = wrapRef.current?.getBoundingClientRect();
245
+ if (!rect) return null;
246
+ const px = ((clientX - rect.left) / rect.width) * width;
247
+ let best = 0;
248
+ model.xs.forEach((xValue, index) => {
249
+ if (Math.abs(x.map(xValue) - px) < Math.abs(x.map(model.xs[best]) - px)) best = index;
250
+ });
251
+ return best;
252
+ };
253
+ const markerX = model.marker !== null ? x.map(model.marker) : null;
254
+ const markerIndex = model.marker !== null ? model.xs.reduce((best, xValue, index) => (Math.abs(xValue - (model.marker as number)) < Math.abs(model.xs[best] - (model.marker as number)) ? index : best), 0) : null;
255
+ const tooltipIndex = hover;
256
+
257
+ return (
258
+ <div className="garden-ui-chart">
259
+ {model.series.length > 1 ? (
260
+ <ul className="garden-ui-legend">
261
+ {model.series.map((series, index) => (
262
+ <li key={index}><span className={`garden-ui-swatch garden-ui-series-${series.tone}`} />{series.label}</li>
263
+ ))}
264
+ </ul>
265
+ ) : null}
266
+ <div
267
+ ref={wrapRef}
268
+ className="garden-ui-chart-canvas"
269
+ tabIndex={0}
270
+ role="group"
271
+ aria-label={`${asString(value("yLabel"), "图表")},左右方向键查看各点`}
272
+ aria-describedby={`${baseId}-table`}
273
+ onPointerMove={(event) => setHover(nearest(event.clientX))}
274
+ onPointerLeave={() => setHover(null)}
275
+ onBlur={() => setHover(null)}
276
+ onKeyDown={(event) => {
277
+ if (event.key !== "ArrowRight" && event.key !== "ArrowLeft") return;
278
+ event.preventDefault();
279
+ const start = hover ?? markerIndex ?? 0;
280
+ setHover(Math.max(0, Math.min(model.xs.length - 1, start + (event.key === "ArrowRight" ? 1 : -1))));
281
+ }}
282
+ >
283
+ <svg viewBox={`0 0 ${width} ${height}`} width="100%" height={height} aria-hidden="true" className={drawn ? "garden-ui-chart-drawn" : undefined}>
284
+ {yTicks.map((tick) => (
285
+ <g key={`y${tick}`}>
286
+ <line className="garden-ui-chart-grid" x1={MARGIN.left} x2={MARGIN.left + innerWidth} y1={y.map(tick)} y2={y.map(tick)} />
287
+ <text className="garden-ui-chart-tick" x={MARGIN.left - 6} y={y.map(tick)} textAnchor="end" dominantBaseline="middle">{formatValue(tick, yFormat)}</text>
288
+ </g>
289
+ ))}
290
+ {xTicks.map((tick) => (
291
+ <text
292
+ key={`x${tick}`}
293
+ className="garden-ui-chart-tick"
294
+ x={x.map(tick)}
295
+ y={MARGIN.top + innerHeight + 18}
296
+ textAnchor={anchorAt(x.map(tick))}
297
+ >
298
+ {xTickLabel(tick)}
299
+ </text>
300
+ ))}
301
+ <line className="garden-ui-chart-axis" x1={MARGIN.left} x2={MARGIN.left + innerWidth} y1={MARGIN.top + innerHeight} y2={MARGIN.top + innerHeight} />
302
+ {value("yLabel") !== undefined ? (
303
+ <text className="garden-ui-chart-label" x={MARGIN.left} y={10}>{asString(value("yLabel"))}</text>
304
+ ) : null}
305
+ {value("xLabel") !== undefined ? (
306
+ <text className="garden-ui-chart-label" x={MARGIN.left + innerWidth} y={height - 2} textAnchor="end">{asString(value("xLabel"))}</text>
307
+ ) : null}
308
+ {model.series.map((series, seriesIndex) => {
309
+ if (series.kind === "Line") {
310
+ const mark = series.ys.length <= 16;
311
+ return (
312
+ <g key={seriesIndex}>
313
+ <path className={`garden-ui-chart-line garden-ui-series-${series.tone}`} d={path(series.ys)} pathLength={1} />
314
+ {mark
315
+ ? series.ys.map((yValue, index) => (
316
+ Number.isFinite(yValue) && !(yScaleKind === "log" && yValue <= 0)
317
+ ? <circle key={index} className={`garden-ui-chart-point garden-ui-series-${series.tone}`} cx={x.map(model.xs[index])} cy={y.map(yValue)} r={3.5} />
318
+ : null
319
+ ))
320
+ : null}
321
+ </g>
322
+ );
323
+ }
324
+ if (series.kind === "Area") {
325
+ const line = path(series.ys);
326
+ const baseline = y.map(yScaleKind === "log" ? yMin : Math.max(yMin, 0));
327
+ const first = x.map(model.xs[0]);
328
+ const last = x.map(model.xs[model.xs.length - 1]);
329
+ return (
330
+ <g key={seriesIndex}>
331
+ <path className={`garden-ui-chart-area garden-ui-series-${series.tone}`} d={`${line}L${last},${baseline}L${first},${baseline}Z`} />
332
+ <path className={`garden-ui-chart-line garden-ui-series-${series.tone}`} d={line} pathLength={1} />
333
+ </g>
334
+ );
335
+ }
336
+ if (series.kind === "Bar") {
337
+ const barIndex = barSeries.indexOf(series);
338
+ return series.ys.map((value, index) => {
339
+ if (!Number.isFinite(value)) return null;
340
+ const center = x.map(model.xs[index]);
341
+ const left = center - ((barWidth + 2) * barSeries.length) / 2 + barIndex * (barWidth + 2);
342
+ const top = y.map(Math.max(value, yMin));
343
+ const base = y.map(yScaleKind === "log" ? yMin : Math.max(yMin, 0));
344
+ return <rect key={`${seriesIndex}-${index}`} className={`garden-ui-chart-bar garden-ui-series-${series.tone}`} x={left} y={Math.min(top, base)} width={barWidth} height={Math.abs(base - top)} rx={Math.min(4, barWidth / 4)} />;
345
+ });
346
+ }
347
+ return series.ys.map((value, index) =>
348
+ Number.isFinite(value) ? <circle key={`${seriesIndex}-${index}`} className={`garden-ui-chart-point garden-ui-series-${series.tone}`} cx={x.map(model.xs[index])} cy={y.map(value)} r={3} /> : null,
349
+ );
350
+ })}
351
+ {markerX !== null && markerIndex !== null ? (
352
+ <g>
353
+ <line className="garden-ui-chart-marker" x1={markerX} x2={markerX} y1={MARGIN.top} y2={MARGIN.top + innerHeight} />
354
+ {model.series.map((series, index) => {
355
+ const yValue = series.ys[markerIndex];
356
+ if (!Number.isFinite(yValue)) return null;
357
+ return (
358
+ <g key={index}>
359
+ <circle className={`garden-ui-chart-dot garden-ui-series-${series.tone}`} cx={x.map(model.xs[markerIndex])} cy={y.map(yValue)} r={4} />
360
+ <text className="garden-ui-chart-value" x={x.map(model.xs[markerIndex]) + (markerX > MARGIN.left + innerWidth * 0.7 ? -8 : 8)} y={y.map(yValue) - 8} textAnchor={markerX > MARGIN.left + innerWidth * 0.7 ? "end" : "start"}>
361
+ {formatValue(yValue, series.format)}
362
+ </text>
363
+ </g>
364
+ );
365
+ })}
366
+ </g>
367
+ ) : null}
368
+ {tooltipIndex !== null ? (
369
+ <line className="garden-ui-chart-cross" x1={x.map(model.xs[tooltipIndex])} x2={x.map(model.xs[tooltipIndex])} y1={MARGIN.top} y2={MARGIN.top + innerHeight} />
370
+ ) : null}
371
+ </svg>
372
+ {tooltipIndex !== null ? (
373
+ <div
374
+ className="garden-ui-chart-tooltip"
375
+ style={{ left: `${(x.map(model.xs[tooltipIndex]) / width) * 100}%` }}
376
+ data-side={x.map(model.xs[tooltipIndex]) > width * 0.6 ? "left" : "right"}
377
+ >
378
+ <strong>{xLabel(tooltipIndex)}</strong>
379
+ {model.series.map((series, index) => (
380
+ <span key={index}>{model.series.length > 1 ? `${series.label}:` : ""}{formatValue(series.ys[tooltipIndex], series.format)}</span>
381
+ ))}
382
+ </div>
383
+ ) : null}
384
+ </div>
385
+ {/* Tables ignore width: 1px, so the hiding box is a wrapper. */}
386
+ <div className="garden-ui-sr-only">
387
+ <table id={`${baseId}-table`}>
388
+ <thead>
389
+ <tr>
390
+ <th>{asString(value("xLabel"), "x")}</th>
391
+ {model.series.map((series, index) => <th key={index}>{series.label}</th>)}
392
+ </tr>
393
+ </thead>
394
+ <tbody>
395
+ {model.xs.slice(0, 200).map((_, index) => (
396
+ <tr key={index}>
397
+ <td>{xLabel(index)}</td>
398
+ {model.series.map((series, seriesIndex) => <td key={seriesIndex}>{formatValue(series.ys[index], series.format)}</td>)}
399
+ </tr>
400
+ ))}
401
+ </tbody>
402
+ </table>
403
+ </div>
404
+ </div>
405
+ );
406
+ }
407
+
408
+ const PIE_COLORS = ["#539af8", "#6bc67f", "#ef8b57", "#0d0d0d", "#8f8f8f"];
409
+ const PIE_VIEW = { width: 742, height: 400, cx: 371, cy: 181, inner: 70.4, outer: 137.28 };
410
+
411
+ function ringPath(cx: number, cy: number, inner: number, outer: number, start: number, end: number): string {
412
+ const tau = Math.PI * 2;
413
+ const sweep = end - start;
414
+ if (sweep >= tau - 1e-4) {
415
+ const mid = start + Math.PI;
416
+ return `${ringPath(cx, cy, inner, outer, start, mid)} ${ringPath(cx, cy, inner, outer, mid, start + tau)}`;
417
+ }
418
+ const point = (radius: number, angle: number) => [cx + radius * Math.cos(angle), cy + radius * Math.sin(angle)];
419
+ const [x0, y0] = point(outer, start);
420
+ const [x1, y1] = point(outer, end);
421
+ const [x2, y2] = point(inner, end);
422
+ const [x3, y3] = point(inner, start);
423
+ const large = sweep > Math.PI ? 1 : 0;
424
+ return `M ${x0} ${y0} A ${outer} ${outer} 0 ${large} 1 ${x1} ${y1} L ${x2} ${y2} A ${inner} ${inner} 0 ${large} 0 ${x3} ${y3} Z`;
425
+ }
426
+
427
+ function Pie({ node, env }: { node: UiNode; env: Env }) {
428
+ const runtime = useRuntime();
429
+ const title = propValue(runtime, node, "title", env);
430
+ const slices = expandChildren(runtime, node.c, env)
431
+ .filter((item) => item.node.n === "Slice")
432
+ .map((item) => ({
433
+ label: asString(propValue(runtime, item.node, "label", item.env)),
434
+ value: Math.max(0, asNumber(propValue(runtime, item.node, "value", item.env)) ?? 0),
435
+ }))
436
+ .filter((slice) => slice.value > 0);
437
+ const total = slices.reduce((sum, slice) => sum + slice.value, 0);
438
+ let angle = -Math.PI / 2;
439
+ const arcs: Array<(typeof slices)[number] & { path: string; color: string }> = [];
440
+ for (const [index, slice] of slices.entries()) {
441
+ const sweep = total > 0 ? (slice.value / total) * Math.PI * 2 : 0;
442
+ const path = ringPath(PIE_VIEW.cx, PIE_VIEW.cy, PIE_VIEW.inner, PIE_VIEW.outer, angle, angle + sweep);
443
+ angle += sweep;
444
+ arcs.push({ ...slice, path, color: PIE_COLORS[index % PIE_COLORS.length] });
445
+ }
446
+ return (
447
+ <figure className="garden-ui-pie">
448
+ {title !== undefined ? <p className="garden-ui-pie-title">{asString(title)}</p> : null}
449
+ <div className="garden-ui-pie-chart">
450
+ <svg viewBox={`0 0 ${PIE_VIEW.width} ${PIE_VIEW.height}`} role="img" aria-label={title !== undefined ? asString(title) : "圆环图"}>
451
+ {arcs.map((arc) => <path key={arc.label} d={arc.path} fill={arc.color} />)}
452
+ </svg>
453
+ <ul className="garden-ui-legend">
454
+ {arcs.map((arc) => (
455
+ <li key={arc.label}>
456
+ <span className="garden-ui-swatch" style={{ background: arc.color }} />
457
+ {arc.label}
458
+ </li>
459
+ ))}
460
+ </ul>
461
+ </div>
462
+ </figure>
463
+ );
464
+ }
465
+
466
+ function Slice() {
467
+ return null;
468
+ }
469
+
470
+ registerComponents({ Chart, Pie, Slice });