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,296 @@
1
+ "use client";
2
+
3
+ import { useId, useRef, useState, type KeyboardEvent } from "react";
4
+ import { TONE_LABELS, TONES } from "../../core/catalog.mjs";
5
+ import { formatValue } from "../../core/format.mjs";
6
+ import { asNumber, asString, expandChildren, propValue, registerComponents, RenderNodes, rowValue, useRuntime, type Runtime } from "../runtime";
7
+ import type { Env, UiNode } from "../types";
8
+
9
+ const isPlainObject = (value: unknown): value is Record<string, unknown> =>
10
+ Boolean(value) && typeof value === "object" && !Array.isArray(value);
11
+
12
+ const toneOf = (value: unknown, fallback = "plain") => (typeof value === "string" && (TONES as string[]).includes(value) ? value : fallback);
13
+
14
+ function Stat({ node, env }: { node: UiNode; env: Env }) {
15
+ const runtime = useRuntime();
16
+ const format = propValue(runtime, node, "format", env) as string | undefined;
17
+ const unit = propValue(runtime, node, "unit", env);
18
+ const hint = propValue(runtime, node, "hint", env);
19
+ const size = asString(propValue(runtime, node, "size", env), "md");
20
+ const tone = toneOf(propValue(runtime, node, "tone", env));
21
+ return (
22
+ <div className={`garden-ui-stat garden-ui-stat-${size} garden-ui-tone-${tone}`}>
23
+ <span className="garden-ui-stat-label">{asString(propValue(runtime, node, "label", env))}</span>
24
+ <span className="garden-ui-stat-value" aria-live="polite">
25
+ {formatValue(propValue(runtime, node, "value", env), format)}
26
+ {unit !== undefined ? <small>{` ${asString(unit)}`}</small> : null}
27
+ </span>
28
+ {hint !== undefined ? <span className="garden-ui-stat-hint">{formatValue(hint)}</span> : null}
29
+ </div>
30
+ );
31
+ }
32
+
33
+ function Meter({ node, env }: { node: UiNode; env: Env }) {
34
+ const runtime = useRuntime();
35
+ const format = propValue(runtime, node, "format", env) as string | undefined;
36
+ const max = asNumber(propValue(runtime, node, "max", env)) ?? 0;
37
+ const rawParts = propValue(runtime, node, "parts", env);
38
+ const parts = Array.isArray(rawParts)
39
+ ? rawParts.filter(isPlainObject).map((part) => ({ label: asString(part.label), value: asNumber(part.value) ?? 0, tone: toneOf(part.tone, "muted") }))
40
+ : null;
41
+ const total = parts ? parts.reduce((sum, part) => sum + part.value, 0) : asNumber(propValue(runtime, node, "value", env)) ?? 0;
42
+ const over = max > 0 && total > max;
43
+ const label = propValue(runtime, node, "label", env);
44
+ const width = (value: number) => `${max > 0 ? Math.max(0, Math.min(100, (value / max) * 100)) : 0}%`;
45
+ const tone = toneOf(propValue(runtime, node, "tone", env), "accent");
46
+ return (
47
+ <div className="garden-ui-meter" data-over={over ? "true" : undefined}>
48
+ <div className="garden-ui-meter-head" aria-live="polite">
49
+ <span>{label !== undefined ? asString(label) : ""}</span>
50
+ <span>
51
+ {formatValue(total, format)} / {formatValue(max, format)}
52
+ {over ? <strong>{` 超出 ${formatValue(total - max, format)}`}</strong> : null}
53
+ </span>
54
+ </div>
55
+ <div className="garden-ui-meter-track" role="meter" aria-valuemin={0} aria-valuemax={max} aria-valuenow={total} aria-label={label !== undefined ? asString(label) : undefined}>
56
+ {over ? (
57
+ <span className="garden-ui-meter-fill garden-ui-tone-accent" style={{ width: "100%" }} />
58
+ ) : parts ? (
59
+ parts.map((part, index) => <span key={index} className={`garden-ui-meter-fill garden-ui-tone-${part.tone}`} style={{ width: width(part.value) }} />)
60
+ ) : (
61
+ <span className={`garden-ui-meter-fill garden-ui-tone-${tone}`} style={{ width: width(total) }} />
62
+ )}
63
+ </div>
64
+ {parts ? (
65
+ <ul className="garden-ui-legend">
66
+ {parts.map((part, index) => (
67
+ <li key={index}><span className={`garden-ui-swatch garden-ui-tone-${part.tone}`} />{part.label} {formatValue(part.value, format)}</li>
68
+ ))}
69
+ </ul>
70
+ ) : null}
71
+ </div>
72
+ );
73
+ }
74
+
75
+ function Badge({ node, env }: { node: UiNode; env: Env }) {
76
+ const runtime = useRuntime();
77
+ return (
78
+ <span className={`garden-ui-badge garden-ui-tone-${toneOf(propValue(runtime, node, "tone", env), "muted")}`}>
79
+ <RenderNodes nodes={node.c} env={env} />
80
+ </span>
81
+ );
82
+ }
83
+
84
+ type RowModel = { label: string | null; cells: unknown[]; tones: string[]; notes: string[] };
85
+
86
+ function rowsOf(runtime: Runtime, node: UiNode, env: Env): RowModel[] {
87
+ return expandChildren(runtime, node.c, env)
88
+ .filter((item) => item.node.n === "Row")
89
+ .map((item) => {
90
+ const cellsValue = propValue(runtime, item.node, "cells", item.env);
91
+ const cells = Array.isArray(cellsValue) ? cellsValue : [];
92
+ const tonesValue = propValue(runtime, item.node, "tones", item.env);
93
+ const notesValue = propValue(runtime, item.node, "notes", item.env);
94
+ const label = propValue(runtime, item.node, "label", item.env);
95
+ return {
96
+ label: label === undefined ? null : asString(label),
97
+ cells,
98
+ tones: cells.map((_, index) => toneOf(Array.isArray(tonesValue) ? tonesValue[index] : tonesValue)),
99
+ notes: cells.map((_, index) => (Array.isArray(notesValue) && typeof notesValue[index] === "string" ? notesValue[index] : "")),
100
+ };
101
+ });
102
+ }
103
+
104
+ function NoteArea({ text }: { text: string }) {
105
+ return <p className="garden-ui-note" aria-live="polite">{text}</p>;
106
+ }
107
+
108
+ function Table({ node, env }: { node: UiNode; env: Env }) {
109
+ const runtime = useRuntime();
110
+ const columnsValue = propValue(runtime, node, "columns", env);
111
+ const columns = (Array.isArray(columnsValue) ? columnsValue : []).map((column) =>
112
+ isPlainObject(column)
113
+ ? { label: asString(column.label ?? column.key), key: typeof column.key === "string" ? column.key : null, format: column.format as string | undefined, align: column.align as string | undefined }
114
+ : { label: asString(column), key: null, format: undefined, align: undefined },
115
+ );
116
+ const [selected, setSelected] = useState<{ row: number; col: number } | null>(null);
117
+ let rows: RowModel[];
118
+ if (node.p?.data) {
119
+ const data = propValue(runtime, node, "data", env);
120
+ rows = (Array.isArray(data) ? data.slice(0, 50) : []).map((row) => {
121
+ const tone = toneOf(rowValue(runtime, node.p?.rowTone, row, env));
122
+ return {
123
+ label: null,
124
+ cells: columns.map((column) => (column.key && isPlainObject(row) ? row[column.key] : undefined)),
125
+ tones: columns.map(() => tone),
126
+ notes: columns.map(() => ""),
127
+ };
128
+ });
129
+ } else {
130
+ rows = rowsOf(runtime, node, env);
131
+ }
132
+ const hasLabels = rows.some((row) => row.label !== null);
133
+ // The first column is the row key unless rows carry their own labels; keys stay left even when numeric.
134
+ const numeric = columns.map((_, index) => (index > 0 || hasLabels) && rows.length > 0 && rows.every((row) => typeof row.cells[index] === "number"));
135
+ const note = selected ? rows[selected.row]?.notes[selected.col] : "";
136
+ // A label column plus one value column reads as a list of quantities: value on the right, emphasized.
137
+ const keyValue = hasLabels && columns.length === 1;
138
+ return (
139
+ <div className="garden-ui-table-wrap">
140
+ <table className={`garden-ui-table${keyValue ? " garden-ui-table-kv" : ""}`}>
141
+ <thead>
142
+ <tr>
143
+ {hasLabels ? <th aria-hidden="true" /> : null}
144
+ {columns.map((column, index) => (
145
+ <th key={index} scope="col" data-align={column.align ?? (numeric[index] ? "right" : "left")}>{column.label}</th>
146
+ ))}
147
+ </tr>
148
+ </thead>
149
+ <tbody>
150
+ {rows.map((row, rowIndex) => {
151
+ const rowTone = row.tones.length > 0 && row.tones.every((tone) => tone === row.tones[0]) && row.tones[0] !== "plain" ? row.tones[0] : null;
152
+ return (
153
+ <tr key={rowIndex} className={rowTone ? `garden-ui-tone-${rowTone}` : undefined} data-tone={rowTone ? "row" : undefined}>
154
+ {hasLabels ? <th scope="row">{row.label ?? ""}</th> : null}
155
+ {row.cells.map((cell, colIndex) => {
156
+ const text = formatValue(cell, columns[colIndex]?.format);
157
+ const hasNote = Boolean(row.notes[colIndex]);
158
+ return (
159
+ <td key={colIndex} className={`garden-ui-tone-${row.tones[colIndex]}`} data-align={columns[colIndex]?.align ?? (numeric[colIndex] ? "right" : "left")}>
160
+ {hasNote ? (
161
+ <button type="button" className="garden-ui-note-trigger" aria-pressed={selected?.row === rowIndex && selected?.col === colIndex} onClick={() => setSelected({ row: rowIndex, col: colIndex })}>
162
+ {text}
163
+ </button>
164
+ ) : text}
165
+ </td>
166
+ );
167
+ })}
168
+ </tr>
169
+ );
170
+ })}
171
+ </tbody>
172
+ </table>
173
+ {rows.some((row) => row.notes.some(Boolean)) ? <NoteArea text={note ?? ""} /> : null}
174
+ </div>
175
+ );
176
+ }
177
+
178
+ function Grid({ node, env }: { node: UiNode; env: Env }) {
179
+ const runtime = useRuntime();
180
+ const colsValue = propValue(runtime, node, "cols", env);
181
+ const cols = (Array.isArray(colsValue) ? colsValue : []).map((col) => asString(col));
182
+ const legendValue = propValue(runtime, node, "legend", env);
183
+ const legend = isPlainObject(legendValue) ? legendValue : {};
184
+ const rows = rowsOf(runtime, node, env);
185
+ const [focus, setFocus] = useState({ row: 0, col: 0 });
186
+ const [selected, setSelected] = useState<{ row: number; col: number } | null>(null);
187
+ const cellRefs = useRef(new Map<string, HTMLButtonElement>());
188
+ const baseId = useId().replaceAll(":", "");
189
+ const usedTones = [...new Set(rows.flatMap((row) => row.tones))].filter((tone) => tone !== "plain");
190
+ const moveFocus = (event: KeyboardEvent, row: number, col: number) => {
191
+ const next = { row: Math.max(0, Math.min(rows.length - 1, row)), col: Math.max(0, Math.min(cols.length - 1, col)) };
192
+ event.preventDefault();
193
+ setFocus(next);
194
+ cellRefs.current.get(`${next.row}:${next.col}`)?.focus();
195
+ };
196
+ const current = selected ? rows[selected.row] : null;
197
+ const note = current && selected
198
+ ? `${current.label ?? `第 ${selected.row + 1} 行`} · ${cols[selected.col] ?? ""}:${current.notes[selected.col] || formatValue(current.cells[selected.col])}`
199
+ : "";
200
+ return (
201
+ <div className="garden-ui-grid-wrap">
202
+ <table className="garden-ui-grid" role="grid" aria-describedby={`${baseId}-note`}>
203
+ <thead>
204
+ <tr>
205
+ <th aria-hidden="true" />
206
+ {cols.map((col, index) => <th key={index} scope="col">{col}</th>)}
207
+ </tr>
208
+ </thead>
209
+ <tbody>
210
+ {rows.map((row, rowIndex) => (
211
+ <tr key={rowIndex}>
212
+ <th scope="row">{row.label ?? ""}</th>
213
+ {row.cells.map((cell, colIndex) => {
214
+ const isFocus = focus.row === rowIndex && focus.col === colIndex;
215
+ return (
216
+ <td key={colIndex}>
217
+ <button
218
+ ref={(element) => {
219
+ if (element) cellRefs.current.set(`${rowIndex}:${colIndex}`, element);
220
+ }}
221
+ type="button"
222
+ className={`garden-ui-cell garden-ui-tone-${row.tones[colIndex]}`}
223
+ tabIndex={isFocus ? 0 : -1}
224
+ aria-pressed={selected?.row === rowIndex && selected?.col === colIndex}
225
+ aria-label={`${row.label ?? ""} ${cols[colIndex] ?? ""}:${formatValue(cell)}${row.tones[colIndex] !== "plain" ? `,${asString(legend[row.tones[colIndex]], TONE_LABELS[row.tones[colIndex] as keyof typeof TONE_LABELS])}` : ""}`}
226
+ onFocus={() => setFocus({ row: rowIndex, col: colIndex })}
227
+ onClick={() => setSelected({ row: rowIndex, col: colIndex })}
228
+ onKeyDown={(event) => {
229
+ if (event.key === "ArrowRight") moveFocus(event, rowIndex, colIndex + 1);
230
+ if (event.key === "ArrowLeft") moveFocus(event, rowIndex, colIndex - 1);
231
+ if (event.key === "ArrowDown") moveFocus(event, rowIndex + 1, colIndex);
232
+ if (event.key === "ArrowUp") moveFocus(event, rowIndex - 1, colIndex);
233
+ }}
234
+ >
235
+ {formatValue(cell)}
236
+ </button>
237
+ </td>
238
+ );
239
+ })}
240
+ </tr>
241
+ ))}
242
+ </tbody>
243
+ </table>
244
+ <p className="garden-ui-note" id={`${baseId}-note`} aria-live="polite">{note || "点一格看说明。"}</p>
245
+ {usedTones.length ? (
246
+ <ul className="garden-ui-legend">
247
+ {usedTones.map((tone) => (
248
+ <li key={tone}><span className={`garden-ui-swatch garden-ui-tone-${tone}`} />{asString(legend[tone], TONE_LABELS[tone as keyof typeof TONE_LABELS])}</li>
249
+ ))}
250
+ </ul>
251
+ ) : null}
252
+ </div>
253
+ );
254
+ }
255
+
256
+ function Caption({ node, env }: { node: UiNode; env: Env }) {
257
+ return (
258
+ <p className="garden-ui-caption">
259
+ <RenderNodes nodes={node.c} env={env} />
260
+ </p>
261
+ );
262
+ }
263
+
264
+ function Divider() {
265
+ return <hr className="garden-ui-divider" />;
266
+ }
267
+
268
+ function faviconSrc(href: string) {
269
+ try {
270
+ const url = new URL(href);
271
+ if (url.protocol !== "http:" && url.protocol !== "https:") return null;
272
+ return `https://www.google.com/s2/favicons?domain=${encodeURIComponent(url.hostname)}&sz=32`;
273
+ } catch {
274
+ return null;
275
+ }
276
+ }
277
+
278
+ function Cite({ node, env }: { node: UiNode; env: Env }) {
279
+ const runtime = useRuntime();
280
+ const label = asString(propValue(runtime, node, "label", env));
281
+ const href = asString(propValue(runtime, node, "href", env), "");
282
+ const icon = href ? faviconSrc(href) : null;
283
+ const body = (
284
+ <>
285
+ {icon ? <img src={icon} alt="" width={12} height={12} /> : null}
286
+ {label}
287
+ </>
288
+ );
289
+ return href ? (
290
+ <a className="garden-ui-cite" href={href}>{body}</a>
291
+ ) : (
292
+ <span className="garden-ui-cite">{body}</span>
293
+ );
294
+ }
295
+
296
+ registerComponents({ Stat, Meter, Badge, Table, Grid, Caption, Divider, Cite });
@@ -0,0 +1,268 @@
1
+ "use client";
2
+
3
+ import { useId, useState } from "react";
4
+ import { formatValue } from "../../core/format.mjs";
5
+ import { isPowerOfTwo } from "../../core/state.mjs";
6
+ import { asNumber, asString, evalExpr, expandChildren, lookupFor, propValue, registerComponents, RenderNodes, useRuntime, type Runtime } from "../runtime";
7
+ import type { Env, UiNode } from "../types";
8
+
9
+ const isPlainObject = (value: unknown): value is Record<string, unknown> =>
10
+ Boolean(value) && typeof value === "object" && !Array.isArray(value);
11
+
12
+ type SliderModel = {
13
+ min: number;
14
+ max: number;
15
+ scale: "linear" | "log";
16
+ snap: "none" | "int" | "pow2";
17
+ step: number;
18
+ };
19
+
20
+ export function sliderModel(runtime: Runtime, node: UiNode, env: Env): SliderModel | null {
21
+ const min = asNumber(propValue(runtime, node, "min", env));
22
+ const max = asNumber(propValue(runtime, node, "max", env));
23
+ if (min === undefined || max === undefined || min >= max) return null;
24
+ const scale = propValue(runtime, node, "scale", env) === "log" && min > 0 ? "log" : "linear";
25
+ const snapProp = propValue(runtime, node, "snap", env);
26
+ const snap = snapProp === "int" || snapProp === "pow2" || snapProp === "none"
27
+ ? snapProp
28
+ : scale === "log" && isPowerOfTwo(min) && isPowerOfTwo(max) ? "pow2" : "none";
29
+ const step = asNumber(propValue(runtime, node, "step", env)) ?? (Number.isInteger(min) && Number.isInteger(max) ? 1 : (max - min) / 100);
30
+ return { min, max, scale, snap, step };
31
+ }
32
+
33
+ export function clampToSlider(model: SliderModel, value: number) {
34
+ let next = Math.min(model.max, Math.max(model.min, value));
35
+ if (model.snap === "pow2") next = 2 ** Math.round(Math.log2(next));
36
+ else if (model.snap === "int" || (model.scale === "linear" && Number.isInteger(model.step) && Number.isInteger(model.min))) next = Math.round(next);
37
+ return Math.min(model.max, Math.max(model.min, next));
38
+ }
39
+
40
+ const LOG_RESOLUTION = 1000;
41
+
42
+ function Slider({ node, env }: { node: UiNode; env: Env }) {
43
+ const runtime = useRuntime();
44
+ const id = useId();
45
+ const bind = String(node.p?.bind && node.p.bind.k === "lit" ? node.p.bind.v : "");
46
+ const model = sliderModel(runtime, node, env);
47
+ const label = asString(propValue(runtime, node, "label", env));
48
+ const format = propValue(runtime, node, "format", env) as string | undefined;
49
+ const unit = asString(propValue(runtime, node, "unit", env));
50
+ const value = asNumber(runtime.state[bind]) ?? model?.min ?? 0;
51
+ if (!model) return <p className="garden-ui-error-inline">滑杆 {label} 的范围无效</p>;
52
+
53
+ let position: number;
54
+ let inputMin = model.min;
55
+ let inputMax = model.max;
56
+ let inputStep: number | "any" = model.step;
57
+ if (model.snap === "pow2") {
58
+ inputMin = Math.log2(model.min);
59
+ inputMax = Math.log2(model.max);
60
+ inputStep = 1;
61
+ position = Math.round(Math.log2(value));
62
+ } else if (model.scale === "log") {
63
+ inputMin = 0;
64
+ inputMax = LOG_RESOLUTION;
65
+ inputStep = 1;
66
+ position = Math.round(((Math.log(value) - Math.log(model.min)) / (Math.log(model.max) - Math.log(model.min))) * LOG_RESOLUTION);
67
+ } else {
68
+ position = value;
69
+ inputStep = model.step > 0 ? model.step : "any";
70
+ }
71
+
72
+ const fromPosition = (raw: number) => {
73
+ if (model.snap === "pow2") return 2 ** raw;
74
+ if (model.scale === "log") return Math.exp(Math.log(model.min) + (raw / LOG_RESOLUTION) * (Math.log(model.max) - Math.log(model.min)));
75
+ return raw;
76
+ };
77
+
78
+ return (
79
+ <div className="garden-ui-slider">
80
+ <label htmlFor={id}>
81
+ <span>{label}</span>
82
+ <output htmlFor={id} aria-live="polite">{formatValue(value, format)}{unit ? ` ${unit}` : ""}</output>
83
+ </label>
84
+ <div className="garden-ui-slider-track">
85
+ <input
86
+ id={id}
87
+ type="range"
88
+ min={inputMin}
89
+ max={inputMax}
90
+ step={inputStep}
91
+ value={position}
92
+ aria-valuetext={`${formatValue(value, format)}${unit ? ` ${unit}` : ""}`}
93
+ onChange={(event) => runtime.setState({ [bind]: clampToSlider(model, fromPosition(Number(event.target.value))) })}
94
+ />
95
+ </div>
96
+ </div>
97
+ );
98
+ }
99
+
100
+ function Choice({ node, env }: { node: UiNode; env: Env }) {
101
+ const runtime = useRuntime();
102
+ const id = useId();
103
+ const bind = String(node.p?.bind && node.p.bind.k === "lit" ? node.p.bind.v : "");
104
+ const label = asString(propValue(runtime, node, "label", env));
105
+ const rawOptions = propValue(runtime, node, "options", env);
106
+ const options = (Array.isArray(rawOptions) ? rawOptions : []).map((option) =>
107
+ isPlainObject(option) ? { value: option.value, label: asString(option.label ?? option.value) } : { value: option, label: asString(option) },
108
+ );
109
+ const style = propValue(runtime, node, "style", env) ?? (options.length <= 5 ? "segmented" : "select");
110
+ const current = runtime.state[bind];
111
+ if (style === "select") {
112
+ return (
113
+ <div className="garden-ui-choice">
114
+ <label htmlFor={id}>{label}</label>
115
+ <select
116
+ id={id}
117
+ value={String(options.findIndex((option) => option.value === current))}
118
+ onChange={(event) => runtime.setState({ [bind]: options[Number(event.target.value)]?.value })}
119
+ >
120
+ {options.map((option, index) => (
121
+ <option key={index} value={String(index)}>{option.label}</option>
122
+ ))}
123
+ </select>
124
+ </div>
125
+ );
126
+ }
127
+ return (
128
+ <div className="garden-ui-choice" role="group" aria-labelledby={`${id}-label`}>
129
+ <span id={`${id}-label`}>{label}</span>
130
+ <span className="garden-ui-segmented">
131
+ {options.map((option, index) => (
132
+ <button
133
+ key={index}
134
+ type="button"
135
+ aria-pressed={option.value === current}
136
+ onClick={() => runtime.setState({ [bind]: option.value })}
137
+ >
138
+ {option.label}
139
+ </button>
140
+ ))}
141
+ </span>
142
+ </div>
143
+ );
144
+ }
145
+
146
+ function Toggle({ node, env }: { node: UiNode; env: Env }) {
147
+ const runtime = useRuntime();
148
+ const bind = String(node.p?.bind && node.p.bind.k === "lit" ? node.p.bind.v : "");
149
+ const on = Boolean(runtime.state[bind]);
150
+ return (
151
+ <button type="button" role="switch" aria-checked={on} className="garden-ui-toggle" onClick={() => runtime.setState({ [bind]: !on })}>
152
+ <span className="garden-ui-switch" aria-hidden="true" />
153
+ <span>{asString(propValue(runtime, node, "label", env))}</span>
154
+ </button>
155
+ );
156
+ }
157
+
158
+ /** Clamps values set by a Button to the input or switcher that owns the state. */
159
+ function clampForState(runtime: Runtime, name: string, value: unknown) {
160
+ if (typeof value !== "number") return value;
161
+ const slider = runtime.sliders.get(name);
162
+ if (slider) {
163
+ const model = sliderModel(runtime, slider, { locals: [] });
164
+ if (model) return clampToSlider(model, value);
165
+ }
166
+ let count: number | null = null;
167
+ const visit = (node: UiNode) => {
168
+ if (count !== null) return;
169
+ if (node.t === "el" && (node.n === "Steps" || node.n === "Tabs") && node.p?.bind?.k === "lit" && node.p.bind.v === name) {
170
+ count = expandChildren(runtime, node.c, { locals: [] }).length;
171
+ return;
172
+ }
173
+ node.c?.forEach(visit);
174
+ };
175
+ visit(runtime.root);
176
+ return count === null ? value : Math.max(0, Math.min((count as number) - 1, Math.trunc(value)));
177
+ }
178
+
179
+ function Button({ node, env }: { node: UiNode; env: Env }) {
180
+ const runtime = useRuntime();
181
+ const tone = asString(propValue(runtime, node, "tone", env), "plain");
182
+ const onClick = () => {
183
+ if (node.p?.reset) {
184
+ runtime.reset();
185
+ return;
186
+ }
187
+ const prop = node.p?.set;
188
+ if (!prop || prop.k !== "expr") return;
189
+ const patch = evalExpr(prop.e, lookupFor(runtime, env));
190
+ if (!isPlainObject(patch)) return;
191
+ const next: Record<string, unknown> = {};
192
+ for (const [name, value] of Object.entries(patch)) {
193
+ if (!Object.hasOwn(runtime.defaults, name) || typeof runtime.defaults[name] !== typeof value) continue;
194
+ next[name] = clampForState(runtime, name, value);
195
+ }
196
+ runtime.setState(next);
197
+ };
198
+ return (
199
+ <button type="button" className={`garden-ui-button garden-ui-tone-${tone}`} onClick={onClick}>
200
+ <RenderNodes nodes={node.c} env={env} />
201
+ </button>
202
+ );
203
+ }
204
+
205
+ function Stepper({ node, env }: { node: UiNode; env: Env }) {
206
+ const runtime = useRuntime();
207
+ const bind = String(node.p?.bind && node.p.bind.k === "lit" ? node.p.bind.v : "");
208
+ const min = asNumber(propValue(runtime, node, "min", env)) ?? 0;
209
+ const max = asNumber(propValue(runtime, node, "max", env)) ?? min;
210
+ const step = asNumber(propValue(runtime, node, "step", env)) ?? 1;
211
+ const label = propValue(runtime, node, "label", env);
212
+ const unit = propValue(runtime, node, "unit", env);
213
+ const current = asNumber(runtime.state[bind]) ?? min;
214
+ const set = (next: number) => runtime.setState({ [bind]: Math.max(min, Math.min(max, next)) });
215
+ return (
216
+ <div className="garden-ui-stepper">
217
+ {label !== undefined ? <span className="garden-ui-stepper-label">{asString(label)}</span> : null}
218
+ <div className="garden-ui-stepper-row">
219
+ <button type="button" className="garden-ui-round" aria-label="减少" onClick={() => set(current - step)} disabled={current <= min}>−</button>
220
+ <span className="garden-ui-stepper-value" aria-live="polite">{current}</span>
221
+ {unit !== undefined ? <span className="garden-ui-stepper-unit">{asString(unit)}</span> : null}
222
+ <button type="button" className="garden-ui-round" aria-label="增加" onClick={() => set(current + step)} disabled={current >= max}>+</button>
223
+ </div>
224
+ </div>
225
+ );
226
+ }
227
+
228
+ function Checklist({ node, env }: { node: UiNode; env: Env }) {
229
+ const runtime = useRuntime();
230
+ const raw = propValue(runtime, node, "items", env);
231
+ const items: Record<string, unknown>[] = (Array.isArray(raw) ? raw : []).map((item) => (isPlainObject(item) ? item : { title: item }));
232
+ const title = propValue(runtime, node, "title", env);
233
+ const [checked, setChecked] = useState<Set<number>>(() => new Set());
234
+ const toggle = (index: number) =>
235
+ setChecked((current) => {
236
+ const next = new Set(current);
237
+ if (next.has(index)) next.delete(index);
238
+ else next.add(index);
239
+ return next;
240
+ });
241
+ const detailed = items.some((item) => item.time !== undefined || item.note !== undefined);
242
+ const progress = items.length ? (checked.size / items.length) * 100 : 0;
243
+ return (
244
+ <div className={`garden-ui-checklist${detailed ? " garden-ui-checklist-detailed" : ""}`}>
245
+ <div className="garden-ui-checklist-head">
246
+ {title !== undefined ? <strong>{asString(title)}</strong> : <span />}
247
+ <span aria-live="polite">{checked.size} / {items.length}</span>
248
+ </div>
249
+ <div className="garden-ui-progress" aria-hidden="true"><span style={{ width: `${progress}%` }} /></div>
250
+ <ul>
251
+ {items.map((item, index) => (
252
+ <li key={index} data-done={checked.has(index) ? "true" : undefined}>
253
+ <label>
254
+ <input type="checkbox" checked={checked.has(index)} onChange={() => toggle(index)} />
255
+ <span className="garden-ui-checklist-text">
256
+ {item.time !== undefined ? <span className="garden-ui-checklist-time">{asString(item.time)}</span> : null}
257
+ <span className="garden-ui-checklist-title">{asString(item.title)}</span>
258
+ {item.note !== undefined ? <span className="garden-ui-checklist-note">{asString(item.note)}</span> : null}
259
+ </span>
260
+ </label>
261
+ </li>
262
+ ))}
263
+ </ul>
264
+ </div>
265
+ );
266
+ }
267
+
268
+ registerComponents({ Slider, Choice, Toggle, Button, Checklist, Stepper });