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.
- package/.agents/skills/garden-post-review/SKILL.md +2 -0
- package/.agents/skills/garden-ui/SKILL.md +111 -0
- package/.env.example +8 -0
- package/app/admin/page.tsx +14 -3
- package/app/admin/preview/[...path]/page.tsx +88 -0
- package/app/admin/ui/blocks/page.tsx +16 -0
- package/app/admin/ui/catalog/page.tsx +16 -0
- package/app/admin/ui/evals/page.tsx +19 -0
- package/app/admin/ui/page.tsx +22 -0
- package/app/admin-ui.css +227 -0
- package/app/api/admin/distribution/route.ts +4 -2
- package/app/api/admin/posts/source/route.ts +21 -0
- package/app/api/admin/preview/asset/route.ts +32 -0
- package/app/api/admin/thoughts/route.ts +1 -1
- package/app/api/admin/ui/blocks/route.ts +19 -0
- package/app/api/admin/ui/draft/route.ts +30 -0
- package/app/api/auth/github/route.ts +40 -1
- package/app/blog/page.tsx +6 -5
- package/app/columns/page.tsx +1 -1
- package/app/components/AdminDashboard.tsx +53 -1
- package/app/components/AdminUiPanels.tsx +258 -0
- package/app/components/AdminUiShell.tsx +56 -0
- package/app/components/ContentEmptyState.tsx +6 -6
- package/app/components/MarkdownArticle.tsx +15 -5
- package/app/components/UiBlock.tsx +22 -0
- package/app/components/UiStudio.tsx +422 -0
- package/app/components/ui-studio-keys.ts +3 -0
- package/app/globals.css +2 -0
- package/app/lib/admin-auth.ts +13 -1
- package/app/lib/content.ts +2 -1
- package/app/lib/fallback-site-config.ts +18 -18
- package/app/lib/github-content.ts +47 -4
- package/app/lib/repository-path.mjs +55 -0
- package/app/lib/ui-content.ts +79 -0
- package/app/lib/ui-model.ts +145 -0
- package/app/raw.d.ts +4 -0
- package/app/rss.xml/route.ts +2 -1
- package/app/ui-parity/page.tsx +120 -0
- package/bin/garden.mjs +71 -0
- package/eslint.config.mjs +3 -0
- package/package.json +15 -1
- package/scripts/build-content.mjs +35 -4
- package/scripts/build-ui-preview.mjs +29 -0
- package/scripts/check-post.mjs +26 -4
- package/scripts/ui-cli.mjs +303 -0
- package/site.config.yaml +19 -19
- package/templates/site/site.config.yaml +19 -19
- package/tsconfig.json +1 -1
- package/ui/core/apply.mjs +81 -0
- package/ui/core/catalog.mjs +536 -0
- package/ui/core/compile.mjs +63 -0
- package/ui/core/demos.mjs +223 -0
- package/ui/core/expr.mjs +310 -0
- package/ui/core/fence.mjs +201 -0
- package/ui/core/fix-prompt.mjs +35 -0
- package/ui/core/format.mjs +96 -0
- package/ui/core/index.mjs +37 -0
- package/ui/core/parse.mjs +229 -0
- package/ui/core/scan.mjs +53 -0
- package/ui/core/sha256.mjs +66 -0
- package/ui/core/starters.mjs +18 -0
- package/ui/core/state.mjs +259 -0
- package/ui/core/static.mjs +524 -0
- package/ui/core/transform.mjs +146 -0
- package/ui/core/validate.mjs +665 -0
- package/ui/evals/cases.yaml +155 -0
- package/ui/preview/dist/garden-ui.css +1182 -0
- package/ui/preview/dist/garden-ui.esm.js +367 -0
- package/ui/preview/dist/garden-ui.iife.js +367 -0
- package/ui/preview/index.tsx +191 -0
- package/ui/preview/mermaid-shim.ts +19 -0
- package/ui/prompt/build.mjs +24 -0
- package/ui/prompt/recipes/code-walkthrough.md +68 -0
- package/ui/prompt/recipes/compare.md +48 -0
- package/ui/prompt/recipes/converter.md +55 -0
- package/ui/prompt/recipes/data-chart.md +57 -0
- package/ui/prompt/recipes/inspect-grid.md +45 -0
- package/ui/prompt/recipes/param-bench.md +55 -0
- package/ui/prompt/recipes/plan.md +45 -0
- package/ui/prompt/recipes/stepper.md +52 -0
- package/ui/prompt/recipes/trace.md +62 -0
- package/ui/prompt/rules.md +104 -0
- package/ui/prompt/studio.md +20 -0
- package/ui/react/CatalogPage.tsx +166 -0
- package/ui/react/components/chart.tsx +470 -0
- package/ui/react/components/display.tsx +296 -0
- package/ui/react/components/inputs.tsx +268 -0
- package/ui/react/components/layout.tsx +236 -0
- package/ui/react/components/media.tsx +184 -0
- package/ui/react/index.tsx +59 -0
- package/ui/react/recipes.ts +25 -0
- package/ui/react/runtime.tsx +239 -0
- package/ui/react/types.ts +29 -0
- package/ui/react/ui.css +1182 -0
- package/vite.config.ts +4 -3
|
@@ -0,0 +1,524 @@
|
|
|
1
|
+
import { TONE_LABELS } from "./catalog.mjs";
|
|
2
|
+
import { createBudget, evaluate } from "./expr.mjs";
|
|
3
|
+
import { formatValue } from "./format.mjs";
|
|
4
|
+
import { collectDecls, computeScope, defaultStateValues, isPowerOfTwo, lookupFrom, sampleDomain } from "./state.mjs";
|
|
5
|
+
|
|
6
|
+
const isPlainObject = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
7
|
+
|
|
8
|
+
const text = (value) => ({ k: "t", v: String(value) });
|
|
9
|
+
|
|
10
|
+
/** Builds a format-neutral document of the payload at its default state. */
|
|
11
|
+
export function toDoc(payload) {
|
|
12
|
+
const { root, data = {} } = payload;
|
|
13
|
+
const decls = collectDecls(root);
|
|
14
|
+
const defaults = defaultStateValues(decls);
|
|
15
|
+
const budget = createBudget(800000);
|
|
16
|
+
const scopes = new Map();
|
|
17
|
+
const scopeFor = (stateValues) => {
|
|
18
|
+
const key = JSON.stringify(stateValues);
|
|
19
|
+
if (!scopes.has(key)) scopes.set(key, computeScope(decls, { stateValues, dataValues: data, budget, onError: () => {} }));
|
|
20
|
+
return scopes.get(key);
|
|
21
|
+
};
|
|
22
|
+
const sliders = new Map();
|
|
23
|
+
const findSliders = (node) => {
|
|
24
|
+
if (node?.t === "el" && node.n === "Slider" && node.p.bind?.k === "lit") sliders.set(node.p.bind.v, node);
|
|
25
|
+
node?.c?.forEach?.(findSliders);
|
|
26
|
+
};
|
|
27
|
+
findSliders(root);
|
|
28
|
+
|
|
29
|
+
const makeLookup = (ctx) => lookupFrom(...ctx.locals, scopeFor(ctx.state));
|
|
30
|
+
const value = (node, name, ctx) => {
|
|
31
|
+
const prop = node.p[name];
|
|
32
|
+
if (!prop) return undefined;
|
|
33
|
+
if (prop.k === "lit") return prop.v;
|
|
34
|
+
try {
|
|
35
|
+
return evaluate(prop.e, makeLookup(ctx), budget);
|
|
36
|
+
} catch {
|
|
37
|
+
return undefined;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
const rowValue = (prop, row, ctx) => {
|
|
41
|
+
if (!prop) return undefined;
|
|
42
|
+
if (prop.k === "lit") return prop.v;
|
|
43
|
+
try {
|
|
44
|
+
return evaluate(prop.e, lookupFrom(isPlainObject(row) ? row : {}, ...ctx.locals, scopeFor(ctx.state)), budget);
|
|
45
|
+
} catch {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
const expand = (children, ctx) => {
|
|
51
|
+
const output = [];
|
|
52
|
+
for (const child of children) {
|
|
53
|
+
if (child.t === "el" && child.n === "If") {
|
|
54
|
+
if (value(child, "test", ctx)) output.push(...expand(child.c, ctx));
|
|
55
|
+
} else if (child.t === "el" && child.n === "Each") {
|
|
56
|
+
const items = value(child, "of", ctx);
|
|
57
|
+
if (!Array.isArray(items)) continue;
|
|
58
|
+
items.slice(0, 200).forEach((item, index) => {
|
|
59
|
+
const local = { [child.p.as.v]: item };
|
|
60
|
+
if (child.p.index?.k === "lit") local[child.p.index.v] = index;
|
|
61
|
+
output.push(...expand(child.c, { ...ctx, locals: [local, ...ctx.locals] }));
|
|
62
|
+
});
|
|
63
|
+
} else {
|
|
64
|
+
output.push({ node: child, ctx });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return output;
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const inlines = (nodes, ctx) => nodes.flatMap((node) => {
|
|
71
|
+
switch (node.t) {
|
|
72
|
+
case "text":
|
|
73
|
+
return [text(node.v)];
|
|
74
|
+
case "x": {
|
|
75
|
+
let result;
|
|
76
|
+
try {
|
|
77
|
+
result = evaluate(node.e, makeLookup(ctx), budget);
|
|
78
|
+
} catch {
|
|
79
|
+
result = undefined;
|
|
80
|
+
}
|
|
81
|
+
return [text(formatValue(result))];
|
|
82
|
+
}
|
|
83
|
+
case "strong":
|
|
84
|
+
return [{ k: "b", c: inlines(node.c, ctx) }];
|
|
85
|
+
case "em":
|
|
86
|
+
return [{ k: "i", c: inlines(node.c, ctx) }];
|
|
87
|
+
case "code":
|
|
88
|
+
return [{ k: "code", v: node.v }];
|
|
89
|
+
case "br":
|
|
90
|
+
return [{ k: "br" }];
|
|
91
|
+
case "link":
|
|
92
|
+
return [{ k: "a", href: node.u, c: inlines(node.c, ctx) }];
|
|
93
|
+
case "p":
|
|
94
|
+
return inlines(node.c, ctx);
|
|
95
|
+
case "el":
|
|
96
|
+
if (node.n === "Badge") return [text(`[${plainInline(inlines(node.c, ctx))}]`)];
|
|
97
|
+
if (node.n === "Cite") return [text(value(node, "label", ctx) ?? "")];
|
|
98
|
+
if (node.n === "If" || node.n === "Each") return expand([node], ctx).flatMap((item) => inlines([item.node], item.ctx));
|
|
99
|
+
return [];
|
|
100
|
+
default:
|
|
101
|
+
return [];
|
|
102
|
+
}
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
const cellText = (cell) => formatValue(cell);
|
|
106
|
+
const toneSuffix = (tone, legend) => {
|
|
107
|
+
if (!tone || tone === "plain") return "";
|
|
108
|
+
const label = (isPlainObject(legend) && typeof legend[tone] === "string" && legend[tone]) || TONE_LABELS[tone] || tone;
|
|
109
|
+
return `(${label})`;
|
|
110
|
+
};
|
|
111
|
+
const rowsOf = (node, ctx, legend) => {
|
|
112
|
+
const rows = [];
|
|
113
|
+
const notes = [];
|
|
114
|
+
for (const item of expand(node.c, ctx)) {
|
|
115
|
+
if (item.node.n !== "Row") continue;
|
|
116
|
+
const cells = value(item.node, "cells", item.ctx);
|
|
117
|
+
if (!Array.isArray(cells)) continue;
|
|
118
|
+
const tones = value(item.node, "tones", item.ctx);
|
|
119
|
+
const rowNotes = value(item.node, "notes", item.ctx);
|
|
120
|
+
const label = value(item.node, "label", item.ctx);
|
|
121
|
+
rows.push({
|
|
122
|
+
label: label === undefined ? null : cellText(label),
|
|
123
|
+
cells: cells.map((cell, index) => `${cellText(cell)}${toneSuffix(Array.isArray(tones) ? tones[index] : tones, legend)}`),
|
|
124
|
+
});
|
|
125
|
+
if (Array.isArray(rowNotes)) {
|
|
126
|
+
rowNotes.forEach((note, index) => {
|
|
127
|
+
if (typeof note === "string" && note.trim()) notes.push({ row: label === undefined ? `第 ${rows.length} 行` : cellText(label), index, note });
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return { rows, notes };
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const blocks = (nodes, ctx) => nodes.flatMap((node) => block(node, ctx));
|
|
135
|
+
|
|
136
|
+
function block(node, ctx) {
|
|
137
|
+
switch (node.t) {
|
|
138
|
+
case "p":
|
|
139
|
+
return [{ k: "p", inl: inlines(node.c, ctx) }];
|
|
140
|
+
case "list":
|
|
141
|
+
return [{ k: "list", ordered: node.o, items: node.c.map((item) => blocks(item.c, ctx)) }];
|
|
142
|
+
case "quote":
|
|
143
|
+
return [{ k: "quote", blocks: blocks(node.c, ctx) }];
|
|
144
|
+
case "hr":
|
|
145
|
+
return [{ k: "hr" }];
|
|
146
|
+
case "text":
|
|
147
|
+
case "x":
|
|
148
|
+
return [{ k: "p", inl: inlines([node], ctx) }];
|
|
149
|
+
case "el":
|
|
150
|
+
return element(node, ctx);
|
|
151
|
+
default:
|
|
152
|
+
return [];
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function element(node, ctx) {
|
|
157
|
+
const v = (name) => value(node, name, ctx);
|
|
158
|
+
switch (node.n) {
|
|
159
|
+
case "State":
|
|
160
|
+
case "Let":
|
|
161
|
+
case "Data":
|
|
162
|
+
case "Button":
|
|
163
|
+
return [];
|
|
164
|
+
case "If":
|
|
165
|
+
case "Each":
|
|
166
|
+
return expand([node], ctx).flatMap((item) => block(item.node, item.ctx));
|
|
167
|
+
case "Stack":
|
|
168
|
+
case "Columns":
|
|
169
|
+
return blocks(node.c, ctx);
|
|
170
|
+
case "Card": {
|
|
171
|
+
const title = v("title");
|
|
172
|
+
return [...(title ? [{ k: "p", inl: [{ k: "b", c: [text(title)] }] }] : []), ...blocks(node.c, ctx)];
|
|
173
|
+
}
|
|
174
|
+
case "Tabs":
|
|
175
|
+
return expand(node.c, ctx).flatMap((item) => [
|
|
176
|
+
{ k: "p", inl: [{ k: "b", c: [text(value(item.node, "title", item.ctx) ?? "")] }] },
|
|
177
|
+
...blocks(item.node.c, item.ctx),
|
|
178
|
+
]);
|
|
179
|
+
case "Steps": {
|
|
180
|
+
const bind = node.p.bind?.k === "lit" ? node.p.bind.v : null;
|
|
181
|
+
const items = expand(node.c, ctx);
|
|
182
|
+
return [{
|
|
183
|
+
k: "list",
|
|
184
|
+
ordered: true,
|
|
185
|
+
items: items.map((item, index) => {
|
|
186
|
+
const stepCtx = bind ? { ...item.ctx, state: { ...item.ctx.state, [bind]: index } } : item.ctx;
|
|
187
|
+
const title = value(item.node, "title", stepCtx) ?? "";
|
|
188
|
+
const content = blocks(item.node.c, stepCtx);
|
|
189
|
+
const [firstBlock, ...restBlocks] = content;
|
|
190
|
+
if (firstBlock?.k === "p") return [{ k: "p", inl: [{ k: "b", c: [text(title)] }, text(":"), ...firstBlock.inl] }, ...restBlocks];
|
|
191
|
+
return [{ k: "p", inl: [{ k: "b", c: [text(title)] }] }, ...content];
|
|
192
|
+
}),
|
|
193
|
+
}];
|
|
194
|
+
}
|
|
195
|
+
case "Slider": {
|
|
196
|
+
const current = ctx.state[v("bind")];
|
|
197
|
+
return [{ k: "p", inl: [text(`${v("label")}:${formatValue(current, v("format"))}${v("unit") ? ` ${v("unit")}` : ""}(网页中可调,范围 ${formatValue(v("min"), v("format"))}–${formatValue(v("max"), v("format"))})`)] }];
|
|
198
|
+
}
|
|
199
|
+
case "Choice": {
|
|
200
|
+
const options = Array.isArray(v("options")) ? v("options") : [];
|
|
201
|
+
const labelOf = (option) => (isPlainObject(option) ? String(option.label ?? option.value) : String(option));
|
|
202
|
+
const current = options.find((option) => (isPlainObject(option) ? option.value : option) === ctx.state[v("bind")]);
|
|
203
|
+
return [{ k: "p", inl: [text(`${v("label")}:${current === undefined ? "—" : labelOf(current)}(网页中可选:${options.map(labelOf).join(" / ")})`)] }];
|
|
204
|
+
}
|
|
205
|
+
case "Toggle":
|
|
206
|
+
return [{ k: "p", inl: [text(`${v("label")}:${ctx.state[v("bind")] ? "开" : "关"}(网页中可切换)`)] }];
|
|
207
|
+
case "Checklist": {
|
|
208
|
+
const items = Array.isArray(v("items")) ? v("items") : [];
|
|
209
|
+
const title = v("title");
|
|
210
|
+
return [
|
|
211
|
+
...(title ? [{ k: "p", inl: [{ k: "b", c: [text(title)] }] }] : []),
|
|
212
|
+
{
|
|
213
|
+
k: "list",
|
|
214
|
+
ordered: false,
|
|
215
|
+
items: items.map((item) => {
|
|
216
|
+
const entry = isPlainObject(item) ? item : { title: String(item) };
|
|
217
|
+
const line = `☐ ${entry.time ? `${entry.time} ` : ""}${entry.title ?? ""}${entry.note ? ` —— ${entry.note}` : ""}`;
|
|
218
|
+
return [{ k: "p", inl: [text(line)] }];
|
|
219
|
+
}),
|
|
220
|
+
},
|
|
221
|
+
];
|
|
222
|
+
}
|
|
223
|
+
case "Stepper": {
|
|
224
|
+
const current = ctx.state[v("bind")];
|
|
225
|
+
return [{ k: "p", inl: [text(`${v("label") ?? "数量"}:${formatValue(current)}${v("unit") ? ` ${v("unit")}` : ""}(网页中可调,范围 ${formatValue(v("min"))}–${formatValue(v("max"))})`)] }];
|
|
226
|
+
}
|
|
227
|
+
case "Caption":
|
|
228
|
+
return [{ k: "p", inl: inlines(node.c, ctx) }];
|
|
229
|
+
case "Divider":
|
|
230
|
+
return [{ k: "hr" }];
|
|
231
|
+
case "Cite":
|
|
232
|
+
return [{ k: "p", inl: [text(String(v("label") ?? ""))] }];
|
|
233
|
+
case "Pie": {
|
|
234
|
+
const slices = expand(node.c, ctx).filter((item) => item.node.n === "Slice");
|
|
235
|
+
const title = v("title");
|
|
236
|
+
return [
|
|
237
|
+
...(title ? [{ k: "p", inl: [{ k: "b", c: [text(title)] }] }] : []),
|
|
238
|
+
{
|
|
239
|
+
k: "list",
|
|
240
|
+
ordered: false,
|
|
241
|
+
items: slices.map((item) => [{ k: "p", inl: [text(`${value(item.node, "label", item.ctx) ?? ""}:${formatValue(value(item.node, "value", item.ctx))}`)] }]),
|
|
242
|
+
},
|
|
243
|
+
];
|
|
244
|
+
}
|
|
245
|
+
case "Slice":
|
|
246
|
+
return [];
|
|
247
|
+
case "Stat": {
|
|
248
|
+
const hint = v("hint");
|
|
249
|
+
return [{ k: "p", inl: [text(`${v("label")}:`), { k: "b", c: [text(`${formatValue(v("value"), v("format"))}${v("unit") ? ` ${v("unit")}` : ""}`)] }, ...(hint ? [text(`(${formatValue(hint)})`)] : [])] }];
|
|
250
|
+
}
|
|
251
|
+
case "Meter": {
|
|
252
|
+
const format = v("format");
|
|
253
|
+
const parts = Array.isArray(v("parts")) ? v("parts").filter(isPlainObject) : null;
|
|
254
|
+
const total = parts ? parts.reduce((sum, part) => sum + (typeof part.value === "number" ? part.value : 0), 0) : v("value");
|
|
255
|
+
const detail = parts ? `:${parts.map((part) => `${part.label ?? ""} ${formatValue(part.value, format)}`).join(",")}` : "";
|
|
256
|
+
return [{ k: "p", inl: [text(`${v("label") ?? ""}${v("label") ? ":" : ""}${formatValue(total, format)} / ${formatValue(v("max"), format)}${detail}`)] }];
|
|
257
|
+
}
|
|
258
|
+
case "Badge":
|
|
259
|
+
return [{ k: "p", inl: inlines([node], ctx) }];
|
|
260
|
+
case "Table": {
|
|
261
|
+
const columns = Array.isArray(v("columns")) ? v("columns") : [];
|
|
262
|
+
const head = columns.map((column) => (isPlainObject(column) ? String(column.label ?? column.key ?? "") : String(column)));
|
|
263
|
+
if (node.p.data) {
|
|
264
|
+
const rows = Array.isArray(v("data")) ? v("data").slice(0, 50) : [];
|
|
265
|
+
return [{
|
|
266
|
+
k: "table",
|
|
267
|
+
head,
|
|
268
|
+
rows: rows.map((row) => {
|
|
269
|
+
const tone = rowValue(node.p.rowTone, row, ctx);
|
|
270
|
+
return columns.map((column, index) => {
|
|
271
|
+
const cell = isPlainObject(column) && isPlainObject(row) ? row[column.key] : undefined;
|
|
272
|
+
return `${formatValue(cell, isPlainObject(column) ? column.format : undefined)}${index === 0 ? toneSuffix(tone) : ""}`;
|
|
273
|
+
});
|
|
274
|
+
}),
|
|
275
|
+
}];
|
|
276
|
+
}
|
|
277
|
+
const { rows, notes } = rowsOf(node, ctx, null);
|
|
278
|
+
const hasLabels = rows.some((row) => row.label !== null);
|
|
279
|
+
return [
|
|
280
|
+
{ k: "table", head: hasLabels ? ["", ...head] : head, rows: rows.map((row) => (hasLabels ? [row.label ?? "", ...row.cells] : row.cells)) },
|
|
281
|
+
...notes.map((note) => ({ k: "p", inl: [text(`${note.row} · ${head[note.index] ?? ""}:${note.note}`)] })),
|
|
282
|
+
];
|
|
283
|
+
}
|
|
284
|
+
case "Grid": {
|
|
285
|
+
const cols = Array.isArray(v("cols")) ? v("cols").map(String) : [];
|
|
286
|
+
const legend = v("legend");
|
|
287
|
+
const { rows, notes } = rowsOf(node, ctx, legend);
|
|
288
|
+
return [
|
|
289
|
+
{ k: "table", head: ["", ...cols], rows: rows.map((row) => [row.label ?? "", ...row.cells]) },
|
|
290
|
+
...notes.map((note) => ({ k: "p", inl: [text(`${note.row} · ${cols[note.index] ?? ""}:${note.note}`)] })),
|
|
291
|
+
];
|
|
292
|
+
}
|
|
293
|
+
case "Chart": {
|
|
294
|
+
const series = expand(node.c, ctx).filter((item) => ["Line", "Area", "Bar", "Point"].includes(item.node.n));
|
|
295
|
+
const labels = series.map((item, index) => value(item.node, "label", item.ctx) ?? `系列 ${index + 1}`);
|
|
296
|
+
const formats = series.map((item) => value(item.node, "format", item.ctx) ?? v("yFormat"));
|
|
297
|
+
const note = { k: "p", inl: [text("(网页中为可交互图表)")] };
|
|
298
|
+
if (node.p.data) {
|
|
299
|
+
const rows = Array.isArray(v("data")) ? v("data").slice(0, 50) : [];
|
|
300
|
+
return [note, {
|
|
301
|
+
k: "table",
|
|
302
|
+
head: [v("xLabel") ?? "x", ...labels],
|
|
303
|
+
rows: rows.map((row) => [
|
|
304
|
+
formatValue(rowValue(node.p.x, row, ctx), v("xFormat")),
|
|
305
|
+
...series.map((item, index) => formatValue(rowValue(item.node.p.y, row, item.ctx), formats[index])),
|
|
306
|
+
]),
|
|
307
|
+
}];
|
|
308
|
+
}
|
|
309
|
+
const sweep = v("sweep");
|
|
310
|
+
const slider = sliders.get(sweep);
|
|
311
|
+
const sliderValue = (name) => (slider ? value(slider, name, ctx) : undefined);
|
|
312
|
+
const from = v("from") ?? sliderValue("min");
|
|
313
|
+
const to = v("to") ?? sliderValue("max");
|
|
314
|
+
if (typeof from !== "number" || typeof to !== "number") return [note];
|
|
315
|
+
const scale = v("scale") ?? sliderValue("scale") ?? "linear";
|
|
316
|
+
const snap = sliderValue("snap") ?? (scale === "log" && isPowerOfTwo(from) && isPowerOfTwo(to) ? "pow2" : "none");
|
|
317
|
+
let points = sampleDomain({ from, to, scale, samples: 6 });
|
|
318
|
+
if (snap === "pow2") {
|
|
319
|
+
const powers = sampleDomain({ from, to, pow2: true });
|
|
320
|
+
points = powers.length <= 6 ? powers : Array.from({ length: 6 }, (_, index) => powers[Math.round((index * (powers.length - 1)) / 5)]);
|
|
321
|
+
}
|
|
322
|
+
const rows = points.map((x) => {
|
|
323
|
+
const scope = computeScope(decls, { stateValues: { ...ctx.state, [sweep]: x }, dataValues: data, budget, onError: () => {} });
|
|
324
|
+
return [
|
|
325
|
+
formatValue(x, v("xFormat") ?? sliderValue("format")),
|
|
326
|
+
...series.map((item, index) => {
|
|
327
|
+
const y = item.node.p.y;
|
|
328
|
+
try {
|
|
329
|
+
const expression = y.k === "expr" ? y.e : { type: "Literal", value: y.v };
|
|
330
|
+
return formatValue(evaluate(expression, lookupFrom(...item.ctx.locals, scope), budget), formats[index]);
|
|
331
|
+
} catch {
|
|
332
|
+
return "—";
|
|
333
|
+
}
|
|
334
|
+
}),
|
|
335
|
+
];
|
|
336
|
+
});
|
|
337
|
+
return [note, { k: "table", head: [v("xLabel") ?? (slider ? value(slider, "label", ctx) : sweep), ...labels], rows }];
|
|
338
|
+
}
|
|
339
|
+
case "Image": {
|
|
340
|
+
const hotspots = expand(node.c, ctx).filter((item) => item.node.n === "Hotspot");
|
|
341
|
+
return [
|
|
342
|
+
{ k: "image", src: String(v("src") ?? ""), alt: String(v("alt") ?? "") },
|
|
343
|
+
...(hotspots.length
|
|
344
|
+
? [{
|
|
345
|
+
k: "list",
|
|
346
|
+
ordered: true,
|
|
347
|
+
items: hotspots.map((item) => {
|
|
348
|
+
const content = blocks(item.node.c, item.ctx);
|
|
349
|
+
const lead = { k: "b", c: [text(value(item.node, "title", item.ctx) ?? "")] };
|
|
350
|
+
const [firstBlock, ...restBlocks] = content;
|
|
351
|
+
return firstBlock?.k === "p" ? [{ k: "p", inl: [lead, text(":"), ...firstBlock.inl] }, ...restBlocks] : [{ k: "p", inl: [lead] }, ...content];
|
|
352
|
+
}),
|
|
353
|
+
}]
|
|
354
|
+
: []),
|
|
355
|
+
];
|
|
356
|
+
}
|
|
357
|
+
case "Code": {
|
|
358
|
+
const highlight = v("highlight");
|
|
359
|
+
return [
|
|
360
|
+
...(highlight ? [{ k: "p", inl: [text(`高亮:第 ${String(highlight).replaceAll("-", "–").replaceAll(",", "、")} 行`)] }] : []),
|
|
361
|
+
{ k: "code", lang: String(v("lang") ?? ""), text: String(v("code") ?? "") },
|
|
362
|
+
];
|
|
363
|
+
}
|
|
364
|
+
case "Diagram": {
|
|
365
|
+
const highlight = Array.isArray(v("highlight")) ? v("highlight") : [];
|
|
366
|
+
return [
|
|
367
|
+
...(highlight.length ? [{ k: "p", inl: [text(`高亮:${highlight.join("、")}`)] }] : []),
|
|
368
|
+
{ k: "code", lang: "mermaid", text: String(v("mermaid") ?? "") },
|
|
369
|
+
];
|
|
370
|
+
}
|
|
371
|
+
default:
|
|
372
|
+
return [];
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
return blocks(root.c, { state: defaults, locals: [] });
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export function plainInline(inline) {
|
|
380
|
+
return inline.map((item) => {
|
|
381
|
+
if (item.k === "t") return item.v;
|
|
382
|
+
if (item.k === "code") return item.v;
|
|
383
|
+
if (item.k === "br") return " ";
|
|
384
|
+
if (item.c) return plainInline(item.c);
|
|
385
|
+
return "";
|
|
386
|
+
}).join("");
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
const escapeHtml = (value) =>
|
|
390
|
+
String(value).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
391
|
+
|
|
392
|
+
const safeHref = (href) => (/^(?:https:\/\/|\.{0,2}\/|#)/u.test(href) ? href : "#");
|
|
393
|
+
|
|
394
|
+
function inlineHtml(inline) {
|
|
395
|
+
return inline.map((item) => {
|
|
396
|
+
switch (item.k) {
|
|
397
|
+
case "t":
|
|
398
|
+
return escapeHtml(item.v);
|
|
399
|
+
case "b":
|
|
400
|
+
return `<strong>${inlineHtml(item.c)}</strong>`;
|
|
401
|
+
case "i":
|
|
402
|
+
return `<em>${inlineHtml(item.c)}</em>`;
|
|
403
|
+
case "code":
|
|
404
|
+
return `<code>${escapeHtml(item.v)}</code>`;
|
|
405
|
+
case "br":
|
|
406
|
+
return "<br>";
|
|
407
|
+
case "a":
|
|
408
|
+
return `<a href="${escapeHtml(safeHref(item.href))}">${inlineHtml(item.c)}</a>`;
|
|
409
|
+
default:
|
|
410
|
+
return "";
|
|
411
|
+
}
|
|
412
|
+
}).join("");
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export function docToHtml(doc) {
|
|
416
|
+
return doc.map((block) => {
|
|
417
|
+
switch (block.k) {
|
|
418
|
+
case "p":
|
|
419
|
+
return `<p>${inlineHtml(block.inl)}</p>`;
|
|
420
|
+
case "list": {
|
|
421
|
+
const tag = block.ordered ? "ol" : "ul";
|
|
422
|
+
return `<${tag}>${block.items.map((item) => `<li>${docToHtml(item)}</li>`).join("")}</${tag}>`;
|
|
423
|
+
}
|
|
424
|
+
case "quote":
|
|
425
|
+
return `<blockquote>${docToHtml(block.blocks)}</blockquote>`;
|
|
426
|
+
case "hr":
|
|
427
|
+
return "<hr>";
|
|
428
|
+
case "table": {
|
|
429
|
+
const head = block.head?.length ? `<thead><tr>${block.head.map((cell) => `<th>${escapeHtml(cell)}</th>`).join("")}</tr></thead>` : "";
|
|
430
|
+
return `<table>${head}<tbody>${block.rows.map((row) => `<tr>${row.map((cell) => `<td>${escapeHtml(cell)}</td>`).join("")}</tr>`).join("")}</tbody></table>`;
|
|
431
|
+
}
|
|
432
|
+
case "code":
|
|
433
|
+
return `<pre><code${block.lang ? ` class="language-${escapeHtml(block.lang)}"` : ""}>${escapeHtml(block.text).replaceAll("\n", " ")}</code></pre>`;
|
|
434
|
+
case "image":
|
|
435
|
+
return `<p><img src="${escapeHtml(block.src)}" alt="${escapeHtml(block.alt)}"></p>`;
|
|
436
|
+
default:
|
|
437
|
+
return "";
|
|
438
|
+
}
|
|
439
|
+
}).join("");
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const escapeMarkdown = (value) => String(value).replace(/([\\`*_[\]<>|])/gu, "\\$1");
|
|
443
|
+
|
|
444
|
+
function inlineMarkdown(inline) {
|
|
445
|
+
return inline.map((item) => {
|
|
446
|
+
switch (item.k) {
|
|
447
|
+
case "t":
|
|
448
|
+
return escapeMarkdown(item.v);
|
|
449
|
+
case "b":
|
|
450
|
+
return `**${inlineMarkdown(item.c)}**`;
|
|
451
|
+
case "i":
|
|
452
|
+
return `*${inlineMarkdown(item.c)}*`;
|
|
453
|
+
case "code":
|
|
454
|
+
return `\`${item.v.replaceAll("`", "'")}\``;
|
|
455
|
+
case "br":
|
|
456
|
+
return " \n";
|
|
457
|
+
case "a":
|
|
458
|
+
return `[${inlineMarkdown(item.c)}](${safeHref(item.href)})`;
|
|
459
|
+
default:
|
|
460
|
+
return "";
|
|
461
|
+
}
|
|
462
|
+
}).join("");
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
export function docToMarkdown(doc, indent = "") {
|
|
466
|
+
return doc.map((block) => {
|
|
467
|
+
switch (block.k) {
|
|
468
|
+
case "p":
|
|
469
|
+
return `${indent}${inlineMarkdown(block.inl)}`;
|
|
470
|
+
case "list":
|
|
471
|
+
return block.items.map((item, index) => {
|
|
472
|
+
const bullet = block.ordered ? `${index + 1}. ` : "- ";
|
|
473
|
+
const body = docToMarkdown(item, `${indent}${" ".repeat(bullet.length)}`).trimStart();
|
|
474
|
+
return `${indent}${bullet}${body}`;
|
|
475
|
+
}).join("\n");
|
|
476
|
+
case "quote":
|
|
477
|
+
return docToMarkdown(block.blocks).split("\n").map((line) => `${indent}> ${line}`).join("\n");
|
|
478
|
+
case "hr":
|
|
479
|
+
return `${indent}---`;
|
|
480
|
+
case "table": {
|
|
481
|
+
const head = block.head?.length ? block.head : block.rows[0]?.map(() => "") ?? [];
|
|
482
|
+
const row = (cells) => `${indent}| ${cells.map((cell) => String(cell).replaceAll("|", "\\|").replaceAll("\n", " ")).join(" | ")} |`;
|
|
483
|
+
return [row(head), `${indent}| ${head.map(() => "---").join(" | ")} |`, ...block.rows.map(row)].join("\n");
|
|
484
|
+
}
|
|
485
|
+
case "code": {
|
|
486
|
+
const longest = Math.max(0, ...[...block.text.matchAll(/`+/gu)].map((match) => match[0].length));
|
|
487
|
+
const marker = "`".repeat(Math.max(3, longest + 1));
|
|
488
|
+
return `${indent}${marker}${block.lang}\n${block.text}\n${indent}${marker}`;
|
|
489
|
+
}
|
|
490
|
+
case "image":
|
|
491
|
+
return `${indent}`;
|
|
492
|
+
default:
|
|
493
|
+
return "";
|
|
494
|
+
}
|
|
495
|
+
}).filter(Boolean).join("\n\n");
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
export function docToText(doc) {
|
|
499
|
+
return doc.map((block) => {
|
|
500
|
+
switch (block.k) {
|
|
501
|
+
case "p":
|
|
502
|
+
return plainInline(block.inl);
|
|
503
|
+
case "list":
|
|
504
|
+
return block.items.map((item) => docToText(item)).join(" ");
|
|
505
|
+
case "quote":
|
|
506
|
+
return docToText(block.blocks);
|
|
507
|
+
case "table":
|
|
508
|
+
return [...(block.head ?? []), ...block.rows.flat()].join(" ");
|
|
509
|
+
case "code":
|
|
510
|
+
return block.text;
|
|
511
|
+
case "image":
|
|
512
|
+
return block.alt;
|
|
513
|
+
default:
|
|
514
|
+
return "";
|
|
515
|
+
}
|
|
516
|
+
}).filter(Boolean).join(" ");
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
export function renderStatic(payload, format = "html") {
|
|
520
|
+
const doc = toDoc(payload);
|
|
521
|
+
if (format === "markdown") return docToMarkdown(doc);
|
|
522
|
+
if (format === "text") return docToText(doc);
|
|
523
|
+
return docToHtml(doc);
|
|
524
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { parse as parseYaml } from "yaml";
|
|
2
|
+
import { compileUiBlock, jsonFence, readPayload } from "./compile.mjs";
|
|
3
|
+
import { findBlocks, scanFences } from "./fence.mjs";
|
|
4
|
+
import { renderStatic } from "./static.mjs";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Turns authored `ui` / `intent` fences into what the site renders.
|
|
8
|
+
* - publish: errors are returned so the build can fail; intent is an error.
|
|
9
|
+
* - preview: broken blocks become `ui-error` cards; intent stays as a card.
|
|
10
|
+
*/
|
|
11
|
+
export function transformUiContent(markdown, options = {}) {
|
|
12
|
+
const { mode = "publish", markdownPath = null, readData = null, resolveAsset = null, lineOffset = 0 } = options;
|
|
13
|
+
const errors = [];
|
|
14
|
+
let output = markdown;
|
|
15
|
+
const blocks = findBlocks(markdown).filter((block) => block.lang === "ui" || block.lang === "intent");
|
|
16
|
+
for (const block of [...blocks].reverse()) {
|
|
17
|
+
let replacement = null;
|
|
18
|
+
if (block.lang === "intent") {
|
|
19
|
+
if (mode === "publish") {
|
|
20
|
+
errors.push({ code: "intent-uncompiled", line: block.startLine + lineOffset, message: "还有没编译的 intent 块", severity: "error" });
|
|
21
|
+
}
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
const { payload, check } = compileUiBlock(block.body, {
|
|
25
|
+
lineOffset: block.startLine + lineOffset,
|
|
26
|
+
markdownPath,
|
|
27
|
+
readData,
|
|
28
|
+
resolveAsset,
|
|
29
|
+
});
|
|
30
|
+
if (payload) {
|
|
31
|
+
replacement = jsonFence("ui", payload);
|
|
32
|
+
} else {
|
|
33
|
+
const blocking = check.diagnostics.filter((item) => item.severity === "error");
|
|
34
|
+
if (mode === "publish") {
|
|
35
|
+
errors.push(...blocking);
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
replacement = jsonFence("ui-error", {
|
|
39
|
+
id: check.header?.id ?? null,
|
|
40
|
+
caption: typeof check.header?.caption === "string" ? check.header.caption : "",
|
|
41
|
+
diagnostics: blocking,
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
output = `${output.slice(0, block.start)}${replacement}${output.slice(block.end)}`;
|
|
45
|
+
}
|
|
46
|
+
return { content: output, errors: errors.sort((a, b) => a.line - b.line) };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function widgetCaption(body) {
|
|
50
|
+
try {
|
|
51
|
+
const data = parseYaml(body);
|
|
52
|
+
return {
|
|
53
|
+
caption: typeof data?.caption === "string" ? data.caption.trim() : "",
|
|
54
|
+
src: typeof data?.src === "string" ? data.src.trim() : "",
|
|
55
|
+
};
|
|
56
|
+
} catch {
|
|
57
|
+
return { caption: "", src: "" };
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function replaceFences(content, replacer) {
|
|
62
|
+
let output = content;
|
|
63
|
+
for (const fence of [...scanFences(content)].reverse()) {
|
|
64
|
+
const replacement = replacer(fence);
|
|
65
|
+
if (replacement === undefined) continue;
|
|
66
|
+
output = `${output.slice(0, fence.start)}${replacement}${output.slice(fence.end)}`;
|
|
67
|
+
}
|
|
68
|
+
return output;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const absolute = (src, siteUrl) => (src && siteUrl && src.startsWith("/") ? `${siteUrl.replace(/\/+$/u, "")}${src}` : src);
|
|
72
|
+
|
|
73
|
+
const escapeHtml = (value) =>
|
|
74
|
+
String(value).replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """);
|
|
75
|
+
|
|
76
|
+
/** Readable text for search and word count: captions and snapshot text, never intent. */
|
|
77
|
+
export function contentToSearchText(content) {
|
|
78
|
+
return replaceFences(content, (fence) => {
|
|
79
|
+
if (fence.lang === "ui") {
|
|
80
|
+
const payload = readPayload(fence.body);
|
|
81
|
+
if (!payload) return " ";
|
|
82
|
+
return ` ${payload.caption} ${renderStatic(payload, "text")} `;
|
|
83
|
+
}
|
|
84
|
+
if (fence.lang === "ui-error") {
|
|
85
|
+
const payload = (() => {
|
|
86
|
+
try {
|
|
87
|
+
return JSON.parse(fence.body);
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
})();
|
|
92
|
+
return ` ${payload?.caption ?? ""} `;
|
|
93
|
+
}
|
|
94
|
+
if (fence.lang === "intent") return " ";
|
|
95
|
+
if (fence.lang === "widget") return ` ${widgetCaption(fence.body).caption} `;
|
|
96
|
+
return undefined;
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Markdown for RSS: snapshots become an HTML block, widgets become caption + link. */
|
|
101
|
+
export function contentForFeed(content, { pageUrl = "", siteUrl = "" } = {}) {
|
|
102
|
+
return replaceFences(content, (fence) => {
|
|
103
|
+
if (fence.lang === "ui") {
|
|
104
|
+
const payload = readPayload(fence.body);
|
|
105
|
+
if (!payload) return "";
|
|
106
|
+
const link = pageUrl ? ` · <a href="${escapeHtml(`${pageUrl}#ui-${payload.id}`)}">在网页中交互</a>` : "";
|
|
107
|
+
return `<figure>${renderStatic(payload, "html")}<figcaption>${escapeHtml(payload.caption)}${link}</figcaption></figure>`;
|
|
108
|
+
}
|
|
109
|
+
if (fence.lang === "ui-error" || fence.lang === "intent") return "";
|
|
110
|
+
if (fence.lang === "widget") {
|
|
111
|
+
const { caption, src } = widgetCaption(fence.body);
|
|
112
|
+
const href = absolute(src, siteUrl);
|
|
113
|
+
return `${caption}${href ? `([打开图表](${href}))` : ""}`;
|
|
114
|
+
}
|
|
115
|
+
return undefined;
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Markdown for CSDN / 知乎 / 掘金: snapshot Markdown plus a link back to the block. */
|
|
120
|
+
export function contentForDistribution(content, { pageUrl = "", siteUrl = "" } = {}) {
|
|
121
|
+
return replaceFences(content, (fence) => {
|
|
122
|
+
if (fence.lang === "ui") {
|
|
123
|
+
const payload = readPayload(fence.body);
|
|
124
|
+
if (!payload) return "";
|
|
125
|
+
const link = pageUrl ? `\n\n[在原文中交互](${pageUrl}#ui-${payload.id})` : "";
|
|
126
|
+
return `${renderStatic(payload, "markdown")}\n\n*${payload.caption}*${link}`;
|
|
127
|
+
}
|
|
128
|
+
if (fence.lang === "ui-error" || fence.lang === "intent") return "";
|
|
129
|
+
if (fence.lang === "widget") {
|
|
130
|
+
const { caption, src } = widgetCaption(fence.body);
|
|
131
|
+
const href = absolute(src, siteUrl);
|
|
132
|
+
return `${caption}${href ? `([打开图表](${href}))` : ""}`;
|
|
133
|
+
}
|
|
134
|
+
return undefined;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** `Data` sources referenced by `ui` fences, so callers can prefetch them. */
|
|
139
|
+
export function collectDataSources(markdown) {
|
|
140
|
+
const sources = new Set();
|
|
141
|
+
for (const block of findBlocks(markdown)) {
|
|
142
|
+
if (block.lang !== "ui") continue;
|
|
143
|
+
for (const match of block.body.matchAll(/<Data\b[^>]*\bsrc\s*=\s*"([^"]+)"/gu)) sources.add(match[1]);
|
|
144
|
+
}
|
|
145
|
+
return [...sources];
|
|
146
|
+
}
|