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,236 @@
1
+ "use client";
2
+
3
+ import { useEffect, useId, useRef, useState, useSyncExternalStore, type KeyboardEvent } from "react";
4
+ import { asNumber, asString, expandChildren, propValue, registerComponents, RenderNodes, useRuntime } from "../runtime";
5
+ import type { Env, UiNode } from "../types";
6
+
7
+ const GAPS = [0, 4, 8, 12, 16];
8
+ const gapOf = (value: unknown, fallback = 3) => GAPS[typeof value === "number" && value >= 0 && value <= 4 ? value : fallback];
9
+
10
+ function subscribeReducedMotion(callback: () => void) {
11
+ if (typeof window === "undefined" || !window.matchMedia) return () => {};
12
+ const query = window.matchMedia("(prefers-reduced-motion: reduce)");
13
+ query.addEventListener("change", callback);
14
+ return () => query.removeEventListener("change", callback);
15
+ }
16
+
17
+ export function useReducedMotion() {
18
+ return useSyncExternalStore(
19
+ subscribeReducedMotion,
20
+ () => (typeof window !== "undefined" && window.matchMedia ? window.matchMedia("(prefers-reduced-motion: reduce)").matches : false),
21
+ () => false,
22
+ );
23
+ }
24
+
25
+ function Stack({ node, env }: { node: UiNode; env: Env }) {
26
+ const runtime = useRuntime();
27
+ const direction = asString(propValue(runtime, node, "direction", env), "col") === "row" ? "row" : "col";
28
+ return (
29
+ <div className="garden-ui-stack" data-direction={direction} style={{ gap: gapOf(propValue(runtime, node, "gap", env)) }}>
30
+ <RenderNodes nodes={node.c} env={env} />
31
+ </div>
32
+ );
33
+ }
34
+
35
+ function Columns({ node, env }: { node: UiNode; env: Env }) {
36
+ const runtime = useRuntime();
37
+ const min = asNumber(propValue(runtime, node, "min", env)) ?? 220;
38
+ return (
39
+ <div
40
+ className="garden-ui-columns"
41
+ style={{ gap: gapOf(propValue(runtime, node, "gap", env)), ["--garden-ui-col-min" as string]: `${min}px` }}
42
+ >
43
+ {(node.c ?? []).map((child, index) => (
44
+ <div className="garden-ui-column" key={index}>
45
+ <RenderNodes nodes={[child]} env={env} />
46
+ </div>
47
+ ))}
48
+ </div>
49
+ );
50
+ }
51
+
52
+ function Card({ node, env }: { node: UiNode; env: Env }) {
53
+ const runtime = useRuntime();
54
+ const title = propValue(runtime, node, "title", env);
55
+ const tone = asString(propValue(runtime, node, "tone", env), "plain");
56
+ return (
57
+ <section className={`garden-ui-card garden-ui-tone-${tone}`}>
58
+ {title !== undefined ? <p className="garden-ui-card-title">{asString(title)}</p> : null}
59
+ <RenderNodes nodes={node.c} env={env} />
60
+ </section>
61
+ );
62
+ }
63
+
64
+ /** Index of a bound Steps / Tabs lives in block state; unbound ones keep it locally. */
65
+ function useIndex(node: UiNode, count: number) {
66
+ const runtime = useRuntime();
67
+ const bind = node.p?.bind?.k === "lit" ? String(node.p.bind.v) : null;
68
+ const [local, setLocal] = useState(0);
69
+ const raw = bind ? asNumber(runtime.state[bind]) ?? 0 : local;
70
+ const index = Math.max(0, Math.min(count - 1, Math.trunc(raw)));
71
+ const setIndex = (next: number) => {
72
+ const clamped = Math.max(0, Math.min(count - 1, next));
73
+ if (bind) runtime.setState({ [bind]: clamped });
74
+ else setLocal(clamped);
75
+ };
76
+ return [index, setIndex] as const;
77
+ }
78
+
79
+ function Tabs({ node, env }: { node: UiNode; env: Env }) {
80
+ const runtime = useRuntime();
81
+ const tabs = expandChildren(runtime, node.c, env).filter((item) => item.node.n === "Tab");
82
+ const [index, setIndex] = useIndex(node, tabs.length);
83
+ const baseId = useId().replaceAll(":", "");
84
+ const refs = useRef<Array<HTMLButtonElement | null>>([]);
85
+ const move = (event: KeyboardEvent, next: number) => {
86
+ event.preventDefault();
87
+ const target = (next + tabs.length) % tabs.length;
88
+ setIndex(target);
89
+ refs.current[target]?.focus();
90
+ };
91
+ return (
92
+ <div className="garden-ui-tabs">
93
+ <div className="garden-ui-tablist" role="tablist">
94
+ {tabs.map((tab, tabIndex) => (
95
+ <button
96
+ key={tabIndex}
97
+ ref={(element) => {
98
+ refs.current[tabIndex] = element;
99
+ }}
100
+ type="button"
101
+ role="tab"
102
+ id={`${baseId}-tab-${tabIndex}`}
103
+ aria-selected={tabIndex === index}
104
+ aria-controls={`${baseId}-panel-${tabIndex}`}
105
+ tabIndex={tabIndex === index ? 0 : -1}
106
+ onClick={() => setIndex(tabIndex)}
107
+ onKeyDown={(event) => {
108
+ if (event.key === "ArrowRight") move(event, tabIndex + 1);
109
+ if (event.key === "ArrowLeft") move(event, tabIndex - 1);
110
+ if (event.key === "Home") move(event, 0);
111
+ if (event.key === "End") move(event, tabs.length - 1);
112
+ }}
113
+ >
114
+ {asString(propValue(runtime, tab.node, "title", tab.env))}
115
+ </button>
116
+ ))}
117
+ </div>
118
+ {tabs.map((tab, tabIndex) => (
119
+ <div
120
+ key={tabIndex}
121
+ role="tabpanel"
122
+ id={`${baseId}-panel-${tabIndex}`}
123
+ aria-labelledby={`${baseId}-tab-${tabIndex}`}
124
+ hidden={tabIndex !== index}
125
+ className="garden-ui-tabpanel"
126
+ >
127
+ <RenderNodes nodes={tab.node.c} env={tab.env} />
128
+ </div>
129
+ ))}
130
+ </div>
131
+ );
132
+ }
133
+
134
+ function Steps({ node, env }: { node: UiNode; env: Env }) {
135
+ const runtime = useRuntime();
136
+ const steps = expandChildren(runtime, node.c, env).filter((item) => item.node.n === "Step");
137
+ const [index, setIndex] = useIndex(node, steps.length);
138
+ const autoplay = asNumber(propValue(runtime, node, "autoplay", env));
139
+ const reducedMotion = useReducedMotion();
140
+ const [playing, setPlaying] = useState(Boolean(autoplay));
141
+ const [visible, setVisible] = useState(true);
142
+ const rootRef = useRef<HTMLDivElement>(null);
143
+ const indexRef = useRef(index);
144
+ const setIndexRef = useRef(setIndex);
145
+ useEffect(() => {
146
+ indexRef.current = index;
147
+ setIndexRef.current = setIndex;
148
+ });
149
+
150
+ useEffect(() => {
151
+ const element = rootRef.current;
152
+ if (!element || typeof IntersectionObserver === "undefined") return;
153
+ const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting), { threshold: 0.2 });
154
+ observer.observe(element);
155
+ return () => observer.disconnect();
156
+ }, []);
157
+
158
+ const active = Boolean(autoplay) && playing && visible && !reducedMotion;
159
+ useEffect(() => {
160
+ if (!active || !autoplay) return;
161
+ const timer = window.setInterval(() => {
162
+ if (indexRef.current >= steps.length - 1) {
163
+ setPlaying(false);
164
+ return;
165
+ }
166
+ setIndexRef.current(indexRef.current + 1);
167
+ }, Math.max(800, autoplay));
168
+ return () => window.clearInterval(timer);
169
+ }, [active, autoplay, steps.length]);
170
+
171
+ const [animate, setAnimate] = useState(false);
172
+ const go = (next: number) => {
173
+ setPlaying(false);
174
+ setAnimate(true);
175
+ setIndex(next);
176
+ };
177
+ const current = steps[index];
178
+ return (
179
+ <div
180
+ ref={rootRef}
181
+ className="garden-ui-steps"
182
+ data-animate={animate || active ? "true" : undefined}
183
+ tabIndex={-1}
184
+ onKeyDown={(event) => {
185
+ if (event.target !== event.currentTarget && (event.target as HTMLElement).tagName === "INPUT") return;
186
+ if (event.key === "ArrowRight") go(index + 1);
187
+ if (event.key === "ArrowLeft") go(index - 1);
188
+ }}
189
+ >
190
+ <div className="garden-ui-steps-head">
191
+ <strong>{current ? asString(propValue(runtime, current.node, "title", current.env)) : ""}</strong>
192
+ <span>{steps.length ? `${index + 1} / ${steps.length}` : ""}</span>
193
+ </div>
194
+ <div className="garden-ui-progress" aria-hidden="true">
195
+ <span style={{ width: `${steps.length ? ((index + 1) / steps.length) * 100 : 0}%` }} />
196
+ </div>
197
+ <div className="garden-ui-steps-stage">
198
+ {steps.map((step, stepIndex) => (
199
+ <div
200
+ key={stepIndex}
201
+ className="garden-ui-step"
202
+ data-active={stepIndex === index ? "true" : undefined}
203
+ aria-hidden={stepIndex !== index}
204
+ inert={stepIndex !== index}
205
+ >
206
+ <RenderNodes nodes={step.node.c} env={step.env} />
207
+ </div>
208
+ ))}
209
+ </div>
210
+ <div className="garden-ui-steps-controls">
211
+ <button type="button" className="garden-ui-round" aria-label="上一步" onClick={() => go(index - 1)} disabled={index === 0}>
212
+ <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M10 3.5 5.5 8l4.5 4.5" /></svg>
213
+ </button>
214
+ <span className="garden-ui-steps-dots">
215
+ {steps.map((step, stepIndex) => (
216
+ <button
217
+ key={stepIndex}
218
+ type="button"
219
+ aria-label={`第 ${stepIndex + 1} 步:${asString(propValue(runtime, step.node, "title", step.env))}`}
220
+ aria-current={stepIndex === index ? "step" : undefined}
221
+ onClick={() => go(stepIndex)}
222
+ />
223
+ ))}
224
+ </span>
225
+ <button type="button" className="garden-ui-round" aria-label="下一步" onClick={() => go(index + 1)} disabled={index >= steps.length - 1}>
226
+ <svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6 3.5 10.5 8 6 12.5" /></svg>
227
+ </button>
228
+ {autoplay && !reducedMotion ? (
229
+ <button type="button" className="garden-ui-button" onClick={() => setPlaying((value) => !value)}>{playing ? "暂停" : "播放"}</button>
230
+ ) : null}
231
+ </div>
232
+ </div>
233
+ );
234
+ }
235
+
236
+ registerComponents({ Stack, Columns, Card, Tabs, Steps });
@@ -0,0 +1,184 @@
1
+ "use client";
2
+
3
+ import { useEffect, useId, useRef, useState } from "react";
4
+ import { asNumber, asString, expandChildren, propValue, registerComponents, RenderNodes, useRuntime } from "../runtime";
5
+ import type { Env, UiNode } from "../types";
6
+
7
+ function Image({ node, env }: { node: UiNode; env: Env }) {
8
+ const runtime = useRuntime();
9
+ const src = asString(propValue(runtime, node, "src", env));
10
+ const alt = asString(propValue(runtime, node, "alt", env));
11
+ const ratio = asString(propValue(runtime, node, "ratio", env));
12
+ const hotspots = expandChildren(runtime, node.c, env).filter((item) => item.node.n === "Hotspot");
13
+ const [selected, setSelected] = useState<number | null>(null);
14
+ const refs = useRef<Array<HTMLButtonElement | null>>([]);
15
+ const ratioMatch = /^(\d+(?:\.\d+)?):(\d+(?:\.\d+)?)$/u.exec(ratio);
16
+ const current = selected !== null ? hotspots[selected] : null;
17
+ return (
18
+ <div className="garden-ui-image">
19
+ <div className="garden-ui-image-stage" style={ratioMatch ? { aspectRatio: `${ratioMatch[1]} / ${ratioMatch[2]}` } : undefined}>
20
+ {/* eslint-disable-next-line @next/next/no-img-element */}
21
+ <img src={src} alt={alt} />
22
+ {hotspots.map((item, index) => {
23
+ const x = Math.max(0, Math.min(1, asNumber(propValue(runtime, item.node, "x", item.env)) ?? 0));
24
+ const y = Math.max(0, Math.min(1, asNumber(propValue(runtime, item.node, "y", item.env)) ?? 0));
25
+ return (
26
+ <button
27
+ key={index}
28
+ ref={(element) => {
29
+ refs.current[index] = element;
30
+ }}
31
+ type="button"
32
+ className="garden-ui-hotspot"
33
+ style={{ left: `${x * 100}%`, top: `${y * 100}%` }}
34
+ aria-pressed={selected === index}
35
+ aria-label={`${index + 1}. ${asString(propValue(runtime, item.node, "title", item.env))}`}
36
+ onClick={() => setSelected(index)}
37
+ onKeyDown={(event) => {
38
+ if (event.key !== "ArrowRight" && event.key !== "ArrowLeft") return;
39
+ event.preventDefault();
40
+ const next = (index + (event.key === "ArrowRight" ? 1 : -1) + hotspots.length) % hotspots.length;
41
+ setSelected(next);
42
+ refs.current[next]?.focus();
43
+ }}
44
+ >
45
+ {index + 1}
46
+ </button>
47
+ );
48
+ })}
49
+ </div>
50
+ <div className="garden-ui-note" aria-live="polite">
51
+ {current ? (
52
+ <>
53
+ <strong>{`${(selected ?? 0) + 1}. ${asString(propValue(runtime, current.node, "title", current.env))}`}</strong>
54
+ <RenderNodes nodes={current.node.c} env={current.env} />
55
+ </>
56
+ ) : (
57
+ <p>点图上的序号看说明。</p>
58
+ )}
59
+ </div>
60
+ </div>
61
+ );
62
+ }
63
+
64
+ function parseHighlight(value: unknown) {
65
+ const lines = new Set<number>();
66
+ for (const part of String(value ?? "").split(",")) {
67
+ const match = /^\s*(\d+)\s*(?:-\s*(\d+))?\s*$/u.exec(part);
68
+ if (!match) continue;
69
+ const start = Number(match[1]);
70
+ const end = Number(match[2] ?? match[1]);
71
+ for (let line = start; line <= end && line - start < 200; line += 1) lines.add(line);
72
+ }
73
+ return lines;
74
+ }
75
+
76
+ function Code({ node, env }: { node: UiNode; env: Env }) {
77
+ const runtime = useRuntime();
78
+ const lang = asString(propValue(runtime, node, "lang", env));
79
+ const code = asString(propValue(runtime, node, "code", env)).replace(/^\n/u, "");
80
+ const highlight = parseHighlight(propValue(runtime, node, "highlight", env));
81
+ return (
82
+ <pre className="garden-ui-code" data-language={lang.toUpperCase()}>
83
+ <code>
84
+ {code.split("\n").map((line, index) => (
85
+ <span key={index} className="garden-ui-code-line" data-highlight={highlight.has(index + 1) ? "true" : undefined}>
86
+ <span className="garden-ui-code-number" aria-hidden="true">{index + 1}</span>
87
+ {line || " "}
88
+ {"\n"}
89
+ </span>
90
+ ))}
91
+ </code>
92
+ </pre>
93
+ );
94
+ }
95
+
96
+ let mermaidQueue: Promise<unknown> = Promise.resolve();
97
+
98
+ const MERMAID_FONT = 'ui-sans-serif, -apple-system, system-ui, "Segoe UI", Helvetica, Arial, "PingFang SC", sans-serif';
99
+ const MERMAID_THEMES = {
100
+ light: { background: "#f9f9f9", primaryColor: "#ffffff", primaryBorderColor: "#dddddd", primaryTextColor: "#171717", lineColor: "#888888", secondaryColor: "#f5f5f5", tertiaryColor: "#f5f5f5" },
101
+ dark: { background: "#171717", primaryColor: "#2a2a2a", primaryBorderColor: "#ffffff33", primaryTextColor: "#ededed", lineColor: "#afafaf", secondaryColor: "#303030", tertiaryColor: "#303030" },
102
+ };
103
+
104
+ function renderMermaid(source: string, id: string, dark: boolean) {
105
+ const task = mermaidQueue.then(async () => {
106
+ const mermaid = (await import("mermaid")).default;
107
+ mermaid.initialize({
108
+ startOnLoad: false,
109
+ theme: "base",
110
+ themeVariables: { ...MERMAID_THEMES[dark ? "dark" : "light"], fontFamily: MERMAID_FONT, fontSize: "14px" },
111
+ fontFamily: MERMAID_FONT,
112
+ flowchart: { htmlLabels: true, padding: 16 },
113
+ securityLevel: "strict",
114
+ suppressErrorRendering: true,
115
+ });
116
+ return mermaid.render(id, source);
117
+ });
118
+ mermaidQueue = task.then(() => undefined, () => undefined);
119
+ return task;
120
+ }
121
+
122
+ function Diagram({ node, env }: { node: UiNode; env: Env }) {
123
+ const runtime = useRuntime();
124
+ const source = asString(propValue(runtime, node, "mermaid", env)).trim();
125
+ const highlightValue = propValue(runtime, node, "highlight", env);
126
+ const edgesValue = propValue(runtime, node, "edges", env);
127
+ const highlight = (Array.isArray(highlightValue) ? highlightValue : []).map(String);
128
+ const edges = (Array.isArray(edgesValue) ? edgesValue : []).map(String);
129
+ const reactId = useId().replaceAll(":", "");
130
+ const [svg, setSvg] = useState("");
131
+ const [failed, setFailed] = useState(false);
132
+ const canvasRef = useRef<HTMLDivElement>(null);
133
+
134
+ useEffect(() => {
135
+ let active = true;
136
+ const dark = canvasRef.current?.closest("[data-theme]")?.getAttribute("data-theme") === "dark";
137
+ renderMermaid(source, `garden-ui-mermaid-${reactId}`, dark).then(
138
+ (result) => {
139
+ if (!active) return;
140
+ setSvg((result as { svg: string }).svg);
141
+ setFailed(false);
142
+ },
143
+ () => {
144
+ if (active) setFailed(true);
145
+ },
146
+ );
147
+ return () => {
148
+ active = false;
149
+ };
150
+ }, [source, reactId]);
151
+
152
+ const highlightKey = highlight.join("|");
153
+ const edgesKey = edges.join("|");
154
+ useEffect(() => {
155
+ const canvas = canvasRef.current;
156
+ if (!canvas) return;
157
+ canvas.querySelectorAll(".garden-ui-diagram-on").forEach((element) => element.classList.remove("garden-ui-diagram-on"));
158
+ const clean = (value: string) => value.replace(/[^\w-]/gu, "");
159
+ for (const id of highlightKey.split("|").map(clean).filter(Boolean)) {
160
+ canvas.querySelectorAll(`[id*="-${id}-"], [id$="-${id}"], [data-id="${id}"]`).forEach((element) => {
161
+ (element.closest(".node, .statediagram-state") ?? element).classList.add("garden-ui-diagram-on");
162
+ });
163
+ }
164
+ for (const edge of edgesKey.split("|").filter(Boolean)) {
165
+ const [from, to] = edge.split("->").map((part) => clean(part.trim()));
166
+ if (!from || !to) continue;
167
+ canvas
168
+ .querySelectorAll(`[id*="L-${from}-${to}"], [id*="L_${from}_${to}"], [data-id*="${from}_${to}"]`)
169
+ .forEach((element) => element.classList.add("garden-ui-diagram-on"));
170
+ }
171
+ }, [svg, highlightKey, edgesKey]);
172
+
173
+ return (
174
+ <div className="garden-ui-diagram">
175
+ {failed ? <p className="garden-ui-error-inline">图没能画出来(语法有误,或这里没有 Mermaid)。下面是源码。</p> : null}
176
+ {failed ? <pre className="garden-ui-code"><code>{source}</code></pre> : null}
177
+ {!svg && !failed ? <p className="garden-ui-note">正在绘制图…</p> : null}
178
+ <div ref={canvasRef} className="garden-ui-diagram-canvas" dangerouslySetInnerHTML={{ __html: svg }} />
179
+ {highlight.length ? <p className="garden-ui-sr-only" aria-live="polite">{`当前高亮:${highlight.join("、")}`}</p> : null}
180
+ </div>
181
+ );
182
+ }
183
+
184
+ registerComponents({ Image, Code, Diagram });
@@ -0,0 +1,59 @@
1
+ "use client";
2
+
3
+ import "./components/layout";
4
+ import "./components/inputs";
5
+ import "./components/display";
6
+ import "./components/chart";
7
+ import "./components/media";
8
+ import { UiRuntime } from "./runtime";
9
+ import type { Diagnostic, UiPayload } from "./types";
10
+
11
+ export { UiRuntime } from "./runtime";
12
+ export type { Diagnostic, UiNode, UiPayload } from "./types";
13
+
14
+ export function UiFigure({ payload }: { payload: UiPayload }) {
15
+ return (
16
+ <figure className="garden-ui" lang="en-US" id={`ui-${payload.id}`}>
17
+ <UiRuntime payload={payload} />
18
+ <figcaption>{payload.caption}</figcaption>
19
+ </figure>
20
+ );
21
+ }
22
+
23
+ export function UiErrorCard({ caption, diagnostics, id }: { caption: string; diagnostics: Diagnostic[]; id?: string | null }) {
24
+ return (
25
+ <figure className="garden-ui garden-ui-error" lang="en-US" id={id ? `ui-${id}` : undefined}>
26
+ <div className="garden-ui-body">
27
+ <p className="garden-ui-error-title">这块交互有错误</p>
28
+ <ul className="garden-ui-diagnostics">
29
+ {diagnostics.map((item, index) => (
30
+ <li key={index}>
31
+ <code>{item.code}</code>
32
+ <span>第 {item.line} 行</span>
33
+ <span>{item.message}</span>
34
+ </li>
35
+ ))}
36
+ </ul>
37
+ </div>
38
+ <figcaption>{caption || "(缺少 caption)"}</figcaption>
39
+ </figure>
40
+ );
41
+ }
42
+
43
+ export function IntentCard({ text, id, onCopyPrompt }: { text: string; id?: string | null; onCopyPrompt?: () => void }) {
44
+ return (
45
+ <figure className="garden-ui garden-ui-intent">
46
+ <div className="garden-ui-body">
47
+ <div className="garden-ui-intent-head">
48
+ <strong>想法{id ? ` · ${id}` : ""}</strong>
49
+ <span className="garden-ui-badge garden-ui-tone-accent">未编译</span>
50
+ </div>
51
+ <p className="garden-ui-intent-text">{text}</p>
52
+ {onCopyPrompt ? (
53
+ <button type="button" className="garden-ui-button" onClick={onCopyPrompt}>复制编译提示词</button>
54
+ ) : null}
55
+ </div>
56
+ <figcaption>编译后这里会变成可交互的组件。</figcaption>
57
+ </figure>
58
+ );
59
+ }
@@ -0,0 +1,25 @@
1
+ import { scanFences } from "../core/fence.mjs";
2
+
3
+ export type RecipeSource = { file: string; markdown: string };
4
+ export type Recipe = { file: string; title: string; intro: string; fence: string | null };
5
+
6
+ /** Title, introduction and the first complete `ui` example of a recipe file. */
7
+ export function parseRecipe(source: RecipeSource): Recipe {
8
+ const title = /^#\s+(?:配方:)?(.+)$/mu.exec(source.markdown)?.[1]?.trim() ?? source.file;
9
+ const outer = scanFences(source.markdown);
10
+ let fence: string | null = null;
11
+ for (const item of outer) {
12
+ if (item.lang === "ui") {
13
+ fence = item.raw;
14
+ break;
15
+ }
16
+ const inner = scanFences(item.body).find((candidate) => candidate.lang === "ui");
17
+ if (inner) {
18
+ fence = inner.raw;
19
+ break;
20
+ }
21
+ }
22
+ const firstFence = outer[0]?.start ?? source.markdown.length;
23
+ const intro = source.markdown.slice(0, firstFence).replace(/^#.+$/mu, "").trim();
24
+ return { file: source.file, title, intro, fence };
25
+ }