@lionlang/ui 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1572 @@
1
+ import { isUiNode } from "./types.mjs";
2
+ //#region src/render-rich.ts
3
+ /**
4
+ * Extended rich UI element renderers (`hero`, `split`, `tabs`, `accordion`,
5
+ * `kv`, `list`, `link`, `graph`, `textarea`, `checkbox`) for `@lionlang/ui/dom`.
6
+ *
7
+ * Every text value is inserted via `textContent` (never `innerHTML`), and
8
+ * `ui/link` enforces a strict safe-URL protocol allowlist.
9
+ */
10
+ const SVG_NS = "http://www.w3.org/2000/svg";
11
+ const TONES$1 = new Set([
12
+ "ok",
13
+ "warn",
14
+ "error",
15
+ "muted",
16
+ "accent"
17
+ ]);
18
+ const SAFE_HREF_RE = /^(?:https?:\/\/|\/|#)/i;
19
+ const ACTION_STORE = /* @__PURE__ */ new WeakMap();
20
+ const WIRED_CONTROLS = /* @__PURE__ */ new WeakSet();
21
+ const str$1 = (value, fallback = "") => {
22
+ if (typeof value === "string") return value;
23
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
24
+ return fallback;
25
+ };
26
+ const num$1 = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
27
+ const toneClass$1 = (tone) => {
28
+ const value = str$1(tone);
29
+ return TONES$1.has(value) ? `is-${value}` : "";
30
+ };
31
+ const keyOf$1 = (node) => {
32
+ const key = node.props.key ?? node.props.id ?? node.props.label;
33
+ return typeof key === "string" || typeof key === "number" ? String(key) : "";
34
+ };
35
+ const matchesExisting$1 = (existing, kind, key) => existing !== void 0 && existing.dataset.uiKind === kind && (existing.dataset.uiKey ?? "") === key;
36
+ const nodeClass$1 = (ctx, slot, base, node, extra) => {
37
+ const parts = [];
38
+ if (!ctx.unstyled && base) parts.push(base);
39
+ const custom = ctx.classes?.[slot];
40
+ if (custom) parts.push(custom);
41
+ const propClass = str$1(node.props.className);
42
+ if (extra) parts.push(extra);
43
+ if (propClass) parts.push(propClass);
44
+ return parts.join(" ").trim();
45
+ };
46
+ const makeEl$1 = (doc, tag, className) => {
47
+ const el = doc.createElement(tag);
48
+ if (className) el.className = className;
49
+ return el;
50
+ };
51
+ const appendText$1 = (doc, parent, tag, text, className) => {
52
+ const el = makeEl$1(doc, tag, className);
53
+ el.textContent = text;
54
+ parent.append(el);
55
+ return el;
56
+ };
57
+ const makeSvg = (doc, tag, attrs) => {
58
+ const el = doc.createElementNS(SVG_NS, tag);
59
+ for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, String(v));
60
+ return el;
61
+ };
62
+ /** Returns a sanitized URL or `"#"` when a URL uses a disallowed scheme. */
63
+ const sanitizeHref = (raw) => {
64
+ const href = str$1(raw).trim();
65
+ return SAFE_HREF_RE.test(href) ? href : "#";
66
+ };
67
+ const renderHero = (node, ctx) => {
68
+ const { doc } = ctx;
69
+ const root = makeEl$1(doc, "header", nodeClass$1(ctx, "hero", "lion-ui-hero", node));
70
+ root.dataset.uiKind = "hero";
71
+ root.dataset.uiKey = keyOf$1(node);
72
+ if (node.props.eyebrow) appendText$1(doc, root, "div", str$1(node.props.eyebrow), "lion-ui-hero-eyebrow");
73
+ if (node.props.title) appendText$1(doc, root, "h1", str$1(node.props.title), "lion-ui-hero-title");
74
+ if (node.props.subtitle) appendText$1(doc, root, "p", str$1(node.props.subtitle), "lion-ui-hero-subtitle");
75
+ if (Array.isArray(node.props.badges) && node.props.badges.length > 0) {
76
+ const row = makeEl$1(doc, "div", "lion-ui-hero-badges");
77
+ for (const item of node.props.badges) if (typeof item === "object" && item !== null && !Array.isArray(item)) {
78
+ const rec = item;
79
+ appendText$1(doc, row, "span", str$1(rec.label), `lion-ui-badge ${toneClass$1(rec.tone)}`.trim());
80
+ } else appendText$1(doc, row, "span", str$1(item), "lion-ui-badge");
81
+ root.append(row);
82
+ }
83
+ if (node.children.length > 0) {
84
+ const body = makeEl$1(doc, "div", "lion-ui-hero-actions");
85
+ ctx.patchChildren(body, node.children);
86
+ root.append(body);
87
+ }
88
+ return root;
89
+ };
90
+ const SPLIT_RATIOS = {
91
+ "1:1": "1fr 1fr",
92
+ "1:2": "1fr 2fr",
93
+ "1:3": "1fr 3fr",
94
+ "2:1": "2fr 1fr",
95
+ "3:1": "3fr 1fr"
96
+ };
97
+ const renderSplit = (node, ctx, existing) => {
98
+ const key = keyOf$1(node);
99
+ const ratio = SPLIT_RATIOS[str$1(node.props.ratio, "1:1")] ?? "1fr 1fr";
100
+ const gap = str$1(node.props.gap, "md");
101
+ const el = matchesExisting$1(existing, "split", key) ? existing : makeEl$1(ctx.doc, "div");
102
+ el.dataset.uiKind = "split";
103
+ el.dataset.uiKey = key;
104
+ el.className = nodeClass$1(ctx, "split", "lion-ui-split", node, `gap-${gap}`);
105
+ el.style.setProperty("--ui-split", ratio);
106
+ ctx.patchChildren(el, node.children);
107
+ return el;
108
+ };
109
+ const renderTabs = (node, ctx) => {
110
+ const { doc } = ctx;
111
+ const wrap = makeEl$1(doc, "div", nodeClass$1(ctx, "tabs", "lion-ui-tabs", node));
112
+ wrap.dataset.uiKind = "tabs";
113
+ wrap.dataset.uiKey = keyOf$1(node);
114
+ const bar = makeEl$1(doc, "div", "lion-ui-tabs-bar");
115
+ bar.setAttribute("role", "tablist");
116
+ const active = str$1(node.props.active);
117
+ const action = node.props.onChange ?? node.props.action;
118
+ const tabs = Array.isArray(node.props.tabs) ? node.props.tabs : [];
119
+ for (const tab of tabs) {
120
+ const id = str$1(tab.id ?? tab.value ?? tab.label);
121
+ const isSelected = id === active;
122
+ const btn = makeEl$1(doc, "button", `lion-ui-tab ${isSelected ? "is-active" : ""}`.trim());
123
+ btn.type = "button";
124
+ btn.setAttribute("role", "tab");
125
+ btn.setAttribute("aria-selected", String(isSelected));
126
+ appendText$1(doc, btn, "span", str$1(tab.label, id));
127
+ if (tab.badge !== void 0) appendText$1(doc, btn, "span", str$1(tab.badge), "lion-ui-tab-badge");
128
+ if (action !== void 0 && ctx.onAction) btn.addEventListener("click", () => ctx.onAction?.(action, id));
129
+ bar.append(btn);
130
+ }
131
+ wrap.append(bar);
132
+ if (node.children.length > 0) {
133
+ const panel = makeEl$1(doc, "div", "lion-ui-tabs-panel");
134
+ panel.setAttribute("role", "tabpanel");
135
+ ctx.patchChildren(panel, node.children);
136
+ wrap.append(panel);
137
+ }
138
+ return wrap;
139
+ };
140
+ const renderAccordion = (node, ctx) => {
141
+ const { doc } = ctx;
142
+ const details = makeEl$1(doc, "details", nodeClass$1(ctx, "accordion", "lion-ui-accordion", node, toneClass$1(node.props.tone)));
143
+ details.dataset.uiKind = "accordion";
144
+ details.dataset.uiKey = keyOf$1(node);
145
+ details.open = node.props.open === true;
146
+ const summary = makeEl$1(doc, "summary", "lion-ui-accordion-summary");
147
+ appendText$1(doc, summary, "span", str$1(node.props.title, "Details"), "lion-ui-accordion-title");
148
+ if (node.props.badge !== void 0) appendText$1(doc, summary, "span", str$1(node.props.badge), `lion-ui-badge ${toneClass$1(node.props.tone)}`.trim());
149
+ details.append(summary);
150
+ if (node.props.subtitle) appendText$1(doc, details, "p", str$1(node.props.subtitle), "lion-ui-accordion-subtitle");
151
+ const body = makeEl$1(doc, "div", "lion-ui-accordion-body");
152
+ ctx.patchChildren(body, node.children);
153
+ details.append(body);
154
+ return details;
155
+ };
156
+ const renderKv = (node, ctx) => {
157
+ const { doc } = ctx;
158
+ const wrap = makeEl$1(doc, "div", nodeClass$1(ctx, "kv", "lion-ui-kv", node));
159
+ wrap.dataset.uiKind = "kv";
160
+ wrap.dataset.uiKey = keyOf$1(node);
161
+ if (node.props.title) appendText$1(doc, wrap, "div", str$1(node.props.title), "lion-ui-kv-title");
162
+ const cols = Math.max(1, Math.min(6, Math.round(num$1(node.props.columns, 2))));
163
+ const dl = makeEl$1(doc, "dl", "lion-ui-kv-grid");
164
+ dl.style.setProperty("--ui-kv-cols", String(cols));
165
+ const items = Array.isArray(node.props.items) ? node.props.items : [];
166
+ for (const item of items) {
167
+ const cell = makeEl$1(doc, "div", `lion-ui-kv-item ${toneClass$1(item.tone)}`.trim());
168
+ appendText$1(doc, cell, "dt", str$1(item.label), "lion-ui-kv-label");
169
+ appendText$1(doc, cell, "dd", str$1(item.value), `lion-ui-kv-value ${item.mono === true ? "is-mono" : ""}`.trim());
170
+ dl.append(cell);
171
+ }
172
+ wrap.append(dl);
173
+ return wrap;
174
+ };
175
+ const renderList = (node, ctx) => {
176
+ const { doc } = ctx;
177
+ const wrap = makeEl$1(doc, "div", nodeClass$1(ctx, "list", "lion-ui-list", node));
178
+ wrap.dataset.uiKind = "list";
179
+ wrap.dataset.uiKey = keyOf$1(node);
180
+ if (node.props.title) appendText$1(doc, wrap, "div", str$1(node.props.title), "lion-ui-list-title");
181
+ const selected = str$1(node.props.selected);
182
+ const action = node.props.onSelect ?? node.props.action;
183
+ const items = Array.isArray(node.props.items) ? node.props.items : [];
184
+ const ul = makeEl$1(doc, "ul", "lion-ui-list-items");
185
+ for (const item of items) {
186
+ const id = str$1(item.id ?? item.title);
187
+ const isSel = selected !== "" && id === selected;
188
+ const li = makeEl$1(doc, "li", "lion-ui-list-li");
189
+ const rowTag = action !== void 0 && ctx.onAction ? "button" : "div";
190
+ const row = makeEl$1(doc, rowTag, `lion-ui-list-row ${isSel ? "is-selected" : ""} ${toneClass$1(item.tone)}`.trim());
191
+ if (rowTag === "button") {
192
+ row.type = "button";
193
+ row.addEventListener("click", () => ctx.onAction?.(action, id));
194
+ }
195
+ const main = makeEl$1(doc, "div", "lion-ui-list-main");
196
+ appendText$1(doc, main, "span", str$1(item.title, id), "lion-ui-list-heading");
197
+ if (item.subtitle) appendText$1(doc, main, "span", str$1(item.subtitle), "lion-ui-list-sub");
198
+ row.append(main);
199
+ const side = makeEl$1(doc, "div", "lion-ui-list-side");
200
+ if (item.meta !== void 0) appendText$1(doc, side, "span", str$1(item.meta), "lion-ui-list-meta");
201
+ if (item.badge !== void 0) appendText$1(doc, side, "span", str$1(item.badge), `lion-ui-badge ${toneClass$1(item.tone)}`.trim());
202
+ row.append(side);
203
+ li.append(row);
204
+ ul.append(li);
205
+ }
206
+ wrap.append(ul);
207
+ return wrap;
208
+ };
209
+ const renderLink = (node, ctx) => {
210
+ const { doc } = ctx;
211
+ const a = makeEl$1(doc, "a", nodeClass$1(ctx, "link", "lion-ui-link", node));
212
+ a.dataset.uiKind = "link";
213
+ a.dataset.uiKey = keyOf$1(node);
214
+ a.href = sanitizeHref(node.props.href);
215
+ if (node.props.external === true) {
216
+ a.target = "_blank";
217
+ a.rel = "noopener noreferrer";
218
+ }
219
+ if (node.children.length > 0 && !node.children.every((c) => isUiNode(c))) ctx.patchChildren(a, node.children);
220
+ else a.textContent = str$1(node.props.label, a.href);
221
+ return a;
222
+ };
223
+ const measureNodeBox = (n) => {
224
+ const subText = n.subtitle || n.group || n.metric;
225
+ const titleW = n.label.length * 8.4;
226
+ const subW = subText.length * 6.8;
227
+ const w = Math.max(128, Math.min(232, Math.ceil(Math.max(titleW, subW) + 36)));
228
+ return {
229
+ h: subText ? 54 : 38,
230
+ w
231
+ };
232
+ };
233
+ const computeNodeRanks = (nodes, edges) => {
234
+ const rank = /* @__PURE__ */ new Map();
235
+ for (const n of nodes) rank.set(n.id, 0);
236
+ for (const _pass of nodes) for (const e of edges) {
237
+ const rFrom = rank.get(e.from);
238
+ const rTo = rank.get(e.to);
239
+ if (rFrom !== void 0 && rTo !== void 0 && rFrom + 1 > rTo) rank.set(e.to, Math.min(nodes.length - 1, rFrom + 1));
240
+ }
241
+ return rank;
242
+ };
243
+ const hasSkipOrBackEdge = (edges, ranks) => edges.some((e) => {
244
+ const r1 = ranks.get(e.from);
245
+ const r2 = ranks.get(e.to);
246
+ return r1 !== void 0 && r2 !== void 0 && (r2 <= r1 || Math.abs(r2 - r1) > 1);
247
+ });
248
+ const layoutLayeredGraph = (nodes, edges, minWidth, minHeight) => {
249
+ const ranks = computeNodeRanks(nodes, edges);
250
+ const layers = /* @__PURE__ */ new Map();
251
+ const sizes = /* @__PURE__ */ new Map();
252
+ for (const n of nodes) {
253
+ sizes.set(n.id, measureNodeBox(n));
254
+ const r = ranks.get(n.id) ?? 0;
255
+ const bucket = layers.get(r) ?? [];
256
+ bucket.push(n);
257
+ layers.set(r, bucket);
258
+ }
259
+ const sortedRanks = [...layers.keys()].sort((a, b) => a - b);
260
+ const colWidths = sortedRanks.map((r) => Math.max(...(layers.get(r) ?? []).map((n) => sizes.get(n.id)?.w ?? 140)));
261
+ const maxAdjLabel = Math.max(0, ...edges.filter((e) => {
262
+ const r1 = ranks.get(e.from) ?? 0;
263
+ return (ranks.get(e.to) ?? 0) === r1 + 1;
264
+ }).map((e) => e.label.length * 6.8 + 28));
265
+ const colGap = Math.max(76, Math.min(148, Math.ceil(maxAdjLabel)));
266
+ const rowGap = 36;
267
+ const padX = 36;
268
+ const topArcPad = hasSkipOrBackEdge(edges, ranks) ? 84 : 36;
269
+ const padBottom = 36;
270
+ const contentW = colWidths.reduce((sum, w) => sum + w, 0) + Math.max(0, sortedRanks.length - 1) * colGap;
271
+ const maxLayerH = Math.max(54, ...sortedRanks.map((r) => {
272
+ const bucket = layers.get(r) ?? [];
273
+ return bucket.reduce((acc, n) => acc + (sizes.get(n.id)?.h ?? 54), 0) + Math.max(0, bucket.length - 1) * rowGap;
274
+ }));
275
+ const width = Math.max(minWidth, contentW + padX * 2);
276
+ const height = Math.max(minHeight, maxLayerH + topArcPad + padBottom);
277
+ const startX = (width - contentW) / 2;
278
+ const centerY = topArcPad + (height - topArcPad - padBottom) / 2;
279
+ const positions = /* @__PURE__ */ new Map();
280
+ let cursorX = startX;
281
+ sortedRanks.forEach((r, ci) => {
282
+ const bucket = layers.get(r) ?? [];
283
+ const colW = colWidths[ci] ?? 140;
284
+ let cursorY = centerY - (bucket.reduce((acc, n) => acc + (sizes.get(n.id)?.h ?? 54), 0) + Math.max(0, bucket.length - 1) * rowGap) / 2;
285
+ for (const n of bucket) {
286
+ const box = sizes.get(n.id) ?? {
287
+ h: 54,
288
+ w: 140
289
+ };
290
+ positions.set(n.id, {
291
+ h: box.h,
292
+ id: n.id,
293
+ rank: r,
294
+ w: box.w,
295
+ x: cursorX + colW / 2,
296
+ y: cursorY + box.h / 2
297
+ });
298
+ cursorY += box.h + rowGap;
299
+ }
300
+ cursorX += colW + colGap;
301
+ });
302
+ return {
303
+ height,
304
+ positions,
305
+ width
306
+ };
307
+ };
308
+ const computeGraphLayout = (nodes, edges, layout, minWidth, minHeight) => {
309
+ if (nodes.length === 0) return {
310
+ height: minHeight,
311
+ positions: /* @__PURE__ */ new Map(),
312
+ width: minWidth
313
+ };
314
+ if (layout === "layered") return layoutLayeredGraph(nodes, edges, minWidth, minHeight);
315
+ const sizes = nodes.map((n) => ({
316
+ box: measureNodeBox(n),
317
+ n
318
+ }));
319
+ const maxW = Math.max(...sizes.map((s) => s.box.w));
320
+ const maxH = Math.max(...sizes.map((s) => s.box.h));
321
+ const sinHalf = Math.max(.01, Math.sin(Math.PI / Math.max(2, nodes.length)));
322
+ const rx = Math.max(120, Math.ceil((maxW + 28) / (Math.SQRT2 * sinHalf)), minWidth / 2 - maxW / 2 - 40);
323
+ const ry = Math.max(90, Math.ceil((maxH + 28) / (Math.SQRT2 * sinHalf)), minHeight / 2 - maxH / 2 - 40);
324
+ const width = Math.max(minWidth, Math.ceil(rx * 2 + maxW + 80));
325
+ const height = Math.max(minHeight, Math.ceil(ry * 2 + maxH + 80));
326
+ const cx = width / 2;
327
+ const cy = height / 2;
328
+ const positions = /* @__PURE__ */ new Map();
329
+ sizes.forEach(({ box, n }, idx) => {
330
+ const angle = 2 * Math.PI * idx / nodes.length - Math.PI / 2;
331
+ positions.set(n.id, {
332
+ h: box.h,
333
+ id: n.id,
334
+ rank: idx,
335
+ w: box.w,
336
+ x: cx + rx * Math.cos(angle),
337
+ y: cy + ry * Math.sin(angle)
338
+ });
339
+ });
340
+ return {
341
+ height,
342
+ positions,
343
+ width
344
+ };
345
+ };
346
+ const parseGraphNodes = (raw) => Array.isArray(raw) ? raw.filter((x) => typeof x === "object" && x !== null).map((n) => ({
347
+ group: str$1(n.group),
348
+ id: str$1(n.id ?? n.label),
349
+ label: str$1(n.label ?? n.id),
350
+ metric: str$1(n.metric),
351
+ subtitle: str$1(n.subtitle),
352
+ tone: str$1(n.tone)
353
+ })) : [];
354
+ const parseGraphEdges = (raw) => Array.isArray(raw) ? raw.filter((x) => typeof x === "object" && x !== null).map((e) => ({
355
+ from: str$1(e.from),
356
+ label: str$1(e.label),
357
+ to: str$1(e.to),
358
+ tone: str$1(e.tone)
359
+ })) : [];
360
+ const clipRayToBox = (box, targetX, targetY, pad = 0) => {
361
+ const dx = targetX - box.x;
362
+ const dy = targetY - box.y;
363
+ if (dx === 0 && dy === 0) return {
364
+ x: box.x,
365
+ y: box.y
366
+ };
367
+ const hw = box.w / 2 + pad;
368
+ const hh = box.h / 2 + pad;
369
+ const sx = dx === 0 ? Number.POSITIVE_INFINITY : hw / Math.abs(dx);
370
+ const sy = dy === 0 ? Number.POSITIVE_INFINITY : hh / Math.abs(dy);
371
+ const t = Math.min(sx, sy);
372
+ return {
373
+ x: box.x + dx * t,
374
+ y: box.y + dy * t
375
+ };
376
+ };
377
+ const appendEdgeLabel = (doc, svg, text, x, y, tone) => {
378
+ const pillW = Math.ceil(text.length * 6.5 + 14);
379
+ const pillH = 18;
380
+ svg.append(makeSvg(doc, "rect", {
381
+ class: `lion-ui-graph-edge-pill ${toneClass$1(tone)}`.trim(),
382
+ height: pillH,
383
+ rx: 5,
384
+ width: pillW,
385
+ x: x - pillW / 2,
386
+ y: y - pillH / 2
387
+ }));
388
+ const label = makeSvg(doc, "text", {
389
+ class: `lion-ui-graph-edge-label ${toneClass$1(tone)}`.trim(),
390
+ "dominant-baseline": "central",
391
+ "text-anchor": "middle",
392
+ x,
393
+ y
394
+ });
395
+ label.textContent = text;
396
+ svg.append(label);
397
+ };
398
+ const edgeMarkerId = (tone) => {
399
+ if (tone === "ok" || tone === "accent" || tone === "warn" || tone === "error") return `lion-graph-arrow-${tone}`;
400
+ return "lion-graph-arrow";
401
+ };
402
+ const edgeFocusClass = (hasFocus, edge, selected) => {
403
+ if (edge.tone === "warn" || edge.tone === "error") return "is-related";
404
+ if (!hasFocus) return "";
405
+ return edge.from === selected || edge.to === selected ? "is-related" : "is-dimmed";
406
+ };
407
+ const appendGraphEdges = (doc, svg, edges, positions, selected) => {
408
+ const hasFocus = selected !== "" && positions.has(selected);
409
+ for (const edge of edges) {
410
+ const p1 = positions.get(edge.from);
411
+ const p2 = positions.get(edge.to);
412
+ if (!(p1 && p2)) continue;
413
+ const focusCls = edgeFocusClass(hasFocus, edge, selected);
414
+ const isSkipOrBack = p2.rank <= p1.rank || Math.abs(p2.rank - p1.rank) > 1;
415
+ let d;
416
+ let labelX;
417
+ let labelY;
418
+ if (isSkipOrBack) {
419
+ const startX = p1.x;
420
+ const startY = p1.y - p1.h / 2;
421
+ const endX = p2.x;
422
+ const endY = p2.y - p2.h / 2 - 4;
423
+ const archLift = Math.min(92, 48 + Math.abs(p2.rank - p1.rank) * 12);
424
+ const ctrlX = (startX + endX) / 2;
425
+ const ctrlY = Math.min(startY, endY) - archLift;
426
+ d = `M ${startX} ${startY} Q ${ctrlX} ${ctrlY} ${endX} ${endY}`;
427
+ labelX = ctrlX;
428
+ labelY = (startY + 2 * ctrlY + endY) / 4;
429
+ } else {
430
+ const start = clipRayToBox(p1, p2.x, p2.y, 1);
431
+ const end = clipRayToBox(p2, p1.x, p1.y, 4);
432
+ const mx = (start.x + end.x) / 2;
433
+ const my = (start.y + end.y) / 2;
434
+ d = `M ${start.x} ${start.y} L ${end.x} ${end.y}`;
435
+ labelX = mx;
436
+ labelY = my - 15;
437
+ }
438
+ const edgeGroup = makeSvg(doc, "g", { class: `lion-ui-graph-edge-group ${focusCls}`.trim() });
439
+ edgeGroup.append(makeSvg(doc, "path", {
440
+ class: `lion-ui-graph-edge ${toneClass$1(edge.tone)} ${isSkipOrBack ? "is-arc" : ""} ${focusCls}`.trim(),
441
+ d,
442
+ fill: "none",
443
+ "marker-end": `url(#${edgeMarkerId(edge.tone)})`
444
+ }));
445
+ if (edge.label) appendEdgeLabel(doc, edgeGroup, edge.label, labelX, labelY, edge.tone);
446
+ svg.append(edgeGroup);
447
+ }
448
+ };
449
+ const connectedNeighbors = (edges, selected) => {
450
+ const neighbors = /* @__PURE__ */ new Set();
451
+ if (selected === "") return neighbors;
452
+ for (const e of edges) {
453
+ if (e.from === selected) neighbors.add(e.to);
454
+ if (e.to === selected) neighbors.add(e.from);
455
+ }
456
+ return neighbors;
457
+ };
458
+ const nodeFocusClass = (hasFocus, id, selected, neighbors) => {
459
+ if (!hasFocus) return "";
460
+ if (id === selected) return "is-selected";
461
+ return neighbors.has(id) ? "is-neighbor" : "is-dimmed";
462
+ };
463
+ const appendGraphNodes = (doc, svg, nodes, edges, positions, selected, action, onAction) => {
464
+ const hasFocus = selected !== "" && positions.has(selected);
465
+ const neighbors = connectedNeighbors(edges, selected);
466
+ for (const n of nodes) {
467
+ const p = positions.get(n.id);
468
+ if (!p) continue;
469
+ const focusCls = nodeFocusClass(hasFocus, n.id, selected, neighbors);
470
+ const g = makeSvg(doc, "g", {
471
+ class: `lion-ui-graph-node ${toneClass$1(n.tone)} ${focusCls}`.trim(),
472
+ "data-node-id": n.id,
473
+ transform: `translate(${p.x}, ${p.y})`
474
+ });
475
+ if (action !== void 0 && onAction) {
476
+ g.setAttribute("tabindex", "0");
477
+ g.setAttribute("role", "button");
478
+ g.addEventListener("click", () => onAction(action, n.id));
479
+ }
480
+ const hasSub = Boolean(n.subtitle || n.group || n.metric);
481
+ g.append(makeSvg(doc, "rect", {
482
+ class: "lion-ui-graph-rect",
483
+ height: p.h,
484
+ rx: 10,
485
+ width: p.w,
486
+ x: -p.w / 2,
487
+ y: -p.h / 2
488
+ }));
489
+ g.append(makeSvg(doc, "circle", {
490
+ class: `lion-ui-graph-dot ${toneClass$1(n.tone)}`.trim(),
491
+ cx: -p.w / 2 + 12,
492
+ cy: -p.h / 2 + 12,
493
+ r: 3.2
494
+ }));
495
+ const title = makeSvg(doc, "text", {
496
+ class: "lion-ui-graph-label",
497
+ "text-anchor": "middle",
498
+ y: hasSub ? -4 : 4
499
+ });
500
+ title.textContent = n.label;
501
+ g.append(title);
502
+ const subText = n.subtitle || n.group || n.metric;
503
+ if (subText) {
504
+ const sub = makeSvg(doc, "text", {
505
+ class: "lion-ui-graph-sub",
506
+ "text-anchor": "middle",
507
+ y: 14
508
+ });
509
+ sub.textContent = subText;
510
+ g.append(sub);
511
+ }
512
+ svg.append(g);
513
+ }
514
+ };
515
+ const appendArrowMarkers = (doc, defs) => {
516
+ for (const [id, cls] of [
517
+ ["lion-graph-arrow", "lion-ui-graph-arrow-fill"],
518
+ ["lion-graph-arrow-ok", "lion-ui-graph-arrow-fill is-ok"],
519
+ ["lion-graph-arrow-accent", "lion-ui-graph-arrow-fill is-accent"],
520
+ ["lion-graph-arrow-warn", "lion-ui-graph-arrow-fill is-warn"],
521
+ ["lion-graph-arrow-error", "lion-ui-graph-arrow-fill is-error"]
522
+ ]) {
523
+ const marker = makeSvg(doc, "marker", {
524
+ id,
525
+ markerHeight: 8,
526
+ markerWidth: 8,
527
+ orient: "auto-start-reverse",
528
+ refX: 6.5,
529
+ refY: 4
530
+ });
531
+ marker.append(makeSvg(doc, "path", {
532
+ class: cls,
533
+ d: "M0,1 L7,4 L0,7 z"
534
+ }));
535
+ defs.append(marker);
536
+ }
537
+ };
538
+ const renderGraph = (node, ctx) => {
539
+ const { doc } = ctx;
540
+ const wrap = makeEl$1(doc, "div", nodeClass$1(ctx, "graph", "lion-ui-graph", node));
541
+ wrap.dataset.uiKind = "graph";
542
+ wrap.dataset.uiKey = keyOf$1(node);
543
+ if (node.props.title) appendText$1(doc, wrap, "div", str$1(node.props.title), "lion-ui-graph-title");
544
+ const nodes = parseGraphNodes(node.props.nodes);
545
+ const edges = parseGraphEdges(node.props.edges);
546
+ const minWidth = num$1(node.props.width, 720);
547
+ const minHeight = num$1(node.props.height, 220);
548
+ const layoutMode = str$1(node.props.layout, "layered");
549
+ const selected = str$1(node.props.selected);
550
+ const action = node.props.onSelect ?? node.props.action;
551
+ const laid = computeGraphLayout(nodes, edges, layoutMode, minWidth, minHeight);
552
+ const svg = makeSvg(doc, "svg", {
553
+ class: "lion-ui-graph-svg",
554
+ preserveAspectRatio: "xMidYMid meet",
555
+ role: "img",
556
+ viewBox: `0 0 ${laid.width} ${laid.height}`
557
+ });
558
+ const defs = makeSvg(doc, "defs", {});
559
+ appendArrowMarkers(doc, defs);
560
+ svg.append(defs);
561
+ appendGraphEdges(doc, svg, edges, laid.positions, selected);
562
+ appendGraphNodes(doc, svg, nodes, edges, laid.positions, selected, action, ctx.onAction);
563
+ wrap.append(svg);
564
+ if (action !== void 0 && ctx.onAction) {
565
+ const hint = makeEl$1(doc, "div", "lion-ui-graph-hint");
566
+ hint.textContent = selected === "" ? "Click any node to inspect its details and highlight connected paths" : "Highlighted edges show direct connections to the selected node · click any node to shift focus";
567
+ wrap.append(hint);
568
+ }
569
+ return wrap;
570
+ };
571
+ const renderSection = (node, ctx) => {
572
+ const { doc } = ctx;
573
+ const sec = makeEl$1(doc, "section", nodeClass$1(ctx, "section", "lion-ui-section", node, toneClass$1(node.props.tone)));
574
+ sec.dataset.uiKind = "section";
575
+ sec.dataset.uiKey = keyOf$1(node);
576
+ const step = str$1(node.props.step);
577
+ const title = str$1(node.props.title);
578
+ const subtitle = str$1(node.props.subtitle);
579
+ const badge = str$1(node.props.badge);
580
+ if (step || title || subtitle || badge) {
581
+ const head = makeEl$1(doc, "header", "lion-ui-section-head");
582
+ const top = makeEl$1(doc, "div", "lion-ui-section-top");
583
+ const titleGroup = makeEl$1(doc, "div", "lion-ui-section-title-group");
584
+ if (step) appendText$1(doc, titleGroup, "span", step, "lion-ui-section-step");
585
+ if (title) appendText$1(doc, titleGroup, "h3", title, "lion-ui-section-title");
586
+ top.append(titleGroup);
587
+ if (badge) appendText$1(doc, top, "span", badge, `lion-ui-badge ${toneClass$1(node.props.tone)}`.trim());
588
+ head.append(top);
589
+ if (subtitle) appendText$1(doc, head, "p", subtitle, "lion-ui-section-subtitle");
590
+ sec.append(head);
591
+ }
592
+ const body = makeEl$1(doc, "div", "lion-ui-section-body");
593
+ ctx.patchChildren(body, node.children);
594
+ sec.append(body);
595
+ return sec;
596
+ };
597
+ const renderTextarea = (node, ctx, existing) => {
598
+ const key = keyOf$1(node);
599
+ const wrap = matchesExisting$1(existing, "textarea", key) ? existing : makeEl$1(ctx.doc, "label");
600
+ wrap.dataset.uiKind = "textarea";
601
+ wrap.dataset.uiKey = key;
602
+ wrap.className = nodeClass$1(ctx, "textarea", "lion-ui-control", node);
603
+ let labelEl = wrap.querySelector("[data-textarea-label]");
604
+ if (!labelEl) {
605
+ labelEl = makeEl$1(ctx.doc, "span", "lion-ui-control-label");
606
+ labelEl.dataset.textareaLabel = "";
607
+ wrap.append(labelEl);
608
+ }
609
+ labelEl.textContent = str$1(node.props.label);
610
+ let area = wrap.querySelector("textarea");
611
+ if (!area) {
612
+ area = makeEl$1(ctx.doc, "textarea", "lion-ui-textarea");
613
+ wrap.append(area);
614
+ }
615
+ area.rows = Math.max(2, Math.round(num$1(node.props.rows, 4)));
616
+ if (node.props.placeholder !== void 0) area.placeholder = str$1(node.props.placeholder);
617
+ const nextVal = str$1(node.props.value);
618
+ if (ctx.doc.activeElement !== area && area.value !== nextVal) area.value = nextVal;
619
+ const action = node.props.onChange ?? node.props.action;
620
+ ACTION_STORE.set(area, action);
621
+ if (!WIRED_CONTROLS.has(area)) {
622
+ WIRED_CONTROLS.add(area);
623
+ const target = area;
624
+ target.addEventListener("input", () => {
625
+ const bound = ACTION_STORE.get(target);
626
+ if (bound !== void 0) ctx.onAction?.(bound, target.value);
627
+ });
628
+ }
629
+ return wrap;
630
+ };
631
+ const renderCheckbox = (node, ctx, existing) => {
632
+ const key = keyOf$1(node);
633
+ const wrap = matchesExisting$1(existing, "checkbox", key) ? existing : makeEl$1(ctx.doc, "label");
634
+ wrap.dataset.uiKind = "checkbox";
635
+ wrap.dataset.uiKey = key;
636
+ wrap.className = nodeClass$1(ctx, "checkbox", "lion-ui-checkbox", node);
637
+ let input = wrap.querySelector("input[type='checkbox']");
638
+ if (!input) {
639
+ input = makeEl$1(ctx.doc, "input", "lion-ui-checkbox-input");
640
+ input.type = "checkbox";
641
+ wrap.append(input);
642
+ }
643
+ input.checked = node.props.checked === true || node.props.value === true;
644
+ let textEl = wrap.querySelector("[data-checkbox-label]");
645
+ if (!textEl) {
646
+ textEl = makeEl$1(ctx.doc, "span", "lion-ui-checkbox-label");
647
+ textEl.dataset.checkboxLabel = "";
648
+ wrap.append(textEl);
649
+ }
650
+ textEl.textContent = str$1(node.props.label);
651
+ const action = node.props.onChange ?? node.props.action;
652
+ ACTION_STORE.set(input, action);
653
+ if (!WIRED_CONTROLS.has(input)) {
654
+ WIRED_CONTROLS.add(input);
655
+ const target = input;
656
+ target.addEventListener("change", () => {
657
+ const bound = ACTION_STORE.get(target);
658
+ if (bound !== void 0) ctx.onAction?.(bound, target.checked);
659
+ });
660
+ }
661
+ return wrap;
662
+ };
663
+ //#endregion
664
+ //#region src/dom.ts
665
+ /**
666
+ * Zero-dependency, XSS-safe DOM renderer and in-place patcher for Lion UI
667
+ * trees (`@lionlang/ui/dom`).
668
+ *
669
+ * Every string is inserted via `textContent` (never `innerHTML`). Interactive
670
+ * controls (`input`, `number`, `slider`, `select`, `toggle`, `button`) keep
671
+ * their DOM elements and focus across re-renders by matching on `data-ui-kind`
672
+ * and `data-ui-key`.
673
+ *
674
+ * Styling is fully configurable:
675
+ * - Import `@lionlang/ui/styles.css` and override `--lion-ui-*` CSS variables
676
+ * (or set `theme: "light" | "dark"`), OR
677
+ * - Omit the default stylesheet and pass `classes: { card: "...", ... }` for
678
+ * Tailwind / CSS Modules / custom design systems.
679
+ */
680
+ const ACTION_MAP = /* @__PURE__ */ new WeakMap();
681
+ const WIRED = /* @__PURE__ */ new WeakSet();
682
+ const OPEN_SELECTS = /* @__PURE__ */ new Set();
683
+ const OUTSIDE_WIRED = /* @__PURE__ */ new WeakSet();
684
+ const str = (value, fallback = "") => {
685
+ if (typeof value === "string") return value;
686
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
687
+ return fallback;
688
+ };
689
+ const num = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? value : fallback;
690
+ const bool = (value, fallback = false) => typeof value === "boolean" ? value : fallback;
691
+ const keyOf = (node) => {
692
+ const key = node.props.key ?? node.props.id ?? node.props.label;
693
+ return typeof key === "string" || typeof key === "number" ? String(key) : "";
694
+ };
695
+ const TONES = new Set([
696
+ "ok",
697
+ "warn",
698
+ "error",
699
+ "muted",
700
+ "accent"
701
+ ]);
702
+ const toneClass = (tone) => {
703
+ const value = str(tone);
704
+ return TONES.has(value) ? `is-${value}` : "";
705
+ };
706
+ const cx = (ctx, slot, base, extra) => {
707
+ const parts = [];
708
+ if (!ctx.unstyled && base) parts.push(base);
709
+ const custom = ctx.classes?.[slot];
710
+ if (custom) parts.push(custom);
711
+ if (extra) parts.push(extra);
712
+ return parts.join(" ").trim();
713
+ };
714
+ const nodeClass = (ctx, slot, base, node, extra) => {
715
+ return cx(ctx, slot, base, [extra, str(node.props.className)].filter(Boolean).join(" "));
716
+ };
717
+ const matchesExisting = (existing, kind, key) => existing !== void 0 && existing.dataset.uiKind === kind && (existing.dataset.uiKey ?? "") === key;
718
+ const makeEl = (doc, tag, className) => {
719
+ const el = doc.createElement(tag);
720
+ if (className) el.className = className;
721
+ return el;
722
+ };
723
+ const appendText = (doc, parent, tag, text, className) => {
724
+ const el = makeEl(doc, tag, className);
725
+ el.textContent = text;
726
+ parent.append(el);
727
+ return el;
728
+ };
729
+ const formatAtom = (value) => {
730
+ if (Array.isArray(value)) return `[${value.map((item) => JSON.stringify(item)).join(", ")}]`;
731
+ return typeof value === "string" ? value : JSON.stringify(value);
732
+ };
733
+ const closeSelect = (root) => {
734
+ root.classList.remove("is-open");
735
+ const trigger = root.querySelector("[data-select-trigger]");
736
+ const menu = root.querySelector("[data-select-menu]");
737
+ trigger?.setAttribute("aria-expanded", "false");
738
+ if (menu) menu.hidden = true;
739
+ OPEN_SELECTS.delete(root);
740
+ };
741
+ const ensureOutsideDismiss = (doc) => {
742
+ if (OUTSIDE_WIRED.has(doc)) return;
743
+ OUTSIDE_WIRED.add(doc);
744
+ doc.addEventListener("pointerdown", (event) => {
745
+ const target = event.target;
746
+ for (const root of [...OPEN_SELECTS]) if (!(target && root.contains(target))) closeSelect(root);
747
+ });
748
+ doc.addEventListener("keydown", (event) => {
749
+ if (event.key === "Escape") for (const root of [...OPEN_SELECTS]) closeSelect(root);
750
+ });
751
+ };
752
+ const renderWhyHeader = (doc, rec) => {
753
+ const header = makeEl(doc, "div", "lion-ui-why-head");
754
+ if ("fact" in rec) {
755
+ const tag = rec.given === true ? "given" : "derived";
756
+ appendText(doc, header, "span", tag, `lion-ui-why-tag ${tag === "given" ? "is-ok" : "is-accent"}`);
757
+ appendText(doc, header, "code", formatAtom(rec.fact), "lion-ui-why-atom");
758
+ } else if ("absent" in rec) {
759
+ appendText(doc, header, "span", "absent", "lion-ui-why-tag is-error");
760
+ appendText(doc, header, "code", formatAtom(rec.absent), "lion-ui-why-atom");
761
+ } else if ("check" in rec) {
762
+ appendText(doc, header, "span", "check", "lion-ui-why-tag is-ok");
763
+ appendText(doc, header, "code", formatAtom(rec.check), "lion-ui-why-atom");
764
+ } else if ("rule" in rec) {
765
+ appendText(doc, header, "span", "rule", "lion-ui-why-tag is-muted");
766
+ appendText(doc, header, "code", formatAtom(rec.rule), "lion-ui-why-atom");
767
+ } else appendText(doc, header, "code", JSON.stringify(rec), "lion-ui-why-atom");
768
+ return header;
769
+ };
770
+ const renderWhyTree = (doc, data, depth = 0) => {
771
+ const root = makeEl(doc, "div", `lion-ui-why-node depth-${Math.min(depth, 4)}`);
772
+ if (typeof data !== "object" || data === null) {
773
+ appendText(doc, root, "span", str(data, "No explanation"), "lion-ui-why-empty");
774
+ return root;
775
+ }
776
+ const rec = data;
777
+ root.append(renderWhyHeader(doc, rec));
778
+ if ("but" in rec && rec.but !== void 0) {
779
+ const blocked = makeEl(doc, "div", "lion-ui-why-but");
780
+ appendText(doc, blocked, "span", "blocked by", "lion-ui-why-label");
781
+ blocked.append(renderWhyTree(doc, rec.but, depth + 1));
782
+ root.append(blocked);
783
+ }
784
+ if (Array.isArray(rec.because) && rec.because.length > 0) {
785
+ const list = makeEl(doc, "div", "lion-ui-why-children");
786
+ for (const item of rec.because) list.append(renderWhyTree(doc, item, depth + 1));
787
+ root.append(list);
788
+ }
789
+ return root;
790
+ };
791
+ const isObjRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
792
+ const proofBadge = (props, data) => {
793
+ if (props.valid === true) return ["kernel verified", "is-ok"];
794
+ if (data?.kind === "optimize") {
795
+ if (data.status === "optimal") return props.valid === false ? ["tampered", "is-error"] : ["optimal certified", "is-ok"];
796
+ return [str(data.status, "optimize"), "is-warn"];
797
+ }
798
+ if (data?.holds === true || data?.refines === true) return ["proved", "is-ok"];
799
+ if (data?.holds === false || data?.refines === false) return ["counterexample", "is-error"];
800
+ if (data?.satisfiable === false) return ["unsat · proved", "is-ok"];
801
+ if (data?.satisfiable === true && !("min" in data)) return ["sat · counterexample", "is-error"];
802
+ if (data?.proved === true) return ["proved", "is-ok"];
803
+ if (data?.proved === false) return ["refuted", "is-error"];
804
+ if (data && "min" in data && "max" in data) return props.valid === false ? ["bound failed", "is-error"] : ["exact bounds", "is-ok"];
805
+ return ["unchecked", "is-muted"];
806
+ };
807
+ const summarizeProofKind = (data) => {
808
+ const inner = isObjRecord(data?.proof) ? data.proof : data;
809
+ if (!(inner && typeof inner.kind === "string")) return;
810
+ const parts = [inner.kind];
811
+ if (inner.kind === "dpll-t" && Array.isArray(inner.lemmas)) parts.push(`${inner.lemmas.length} theory lemmas`);
812
+ if (inner.kind === "k-induction" && typeof inner.k === "number") parts.push(`k = ${inner.k}`);
813
+ if (Array.isArray(data?.strengthened) && data.strengthened.length > 0) parts.push(`lemmas: ${data.strengthened.join(", ")}`);
814
+ return parts.join(" · ");
815
+ };
816
+ const formatModelValue = (val) => {
817
+ if (typeof val === "boolean" || typeof val === "number") return String(val);
818
+ if (typeof val === "string") return val;
819
+ return JSON.stringify(val);
820
+ };
821
+ const LEADING_QMARK = /^\?/;
822
+ const renderAssignmentStrip = (doc, label, rec, tone) => {
823
+ const entries = Object.entries(rec).filter(([, v]) => v !== void 0);
824
+ if (entries.length === 0) return null;
825
+ const box = makeEl(doc, "div", `lion-ui-proof-model ${tone === "error" ? "is-error" : "is-ok"}`);
826
+ appendText(doc, box, "div", label, "lion-ui-proof-model-label");
827
+ const grid = makeEl(doc, "div", "lion-ui-proof-kvs");
828
+ for (const [key, val] of entries.slice(0, 16)) {
829
+ const kv = makeEl(doc, "span", "lion-ui-proof-kv");
830
+ appendText(doc, kv, "span", key.replace(LEADING_QMARK, ""), "lion-ui-proof-k");
831
+ appendText(doc, kv, "span", "=", "lion-ui-proof-eq");
832
+ appendText(doc, kv, "span", formatModelValue(val), "lion-ui-proof-v");
833
+ grid.append(kv);
834
+ }
835
+ box.append(grid);
836
+ return box;
837
+ };
838
+ const inferLemmaKind = (cert) => {
839
+ if (typeof cert.kind === "string") return cert.kind;
840
+ if ("constraints" in cert && "steps" in cert) return "linear";
841
+ return "lemma";
842
+ };
843
+ const describeForallLemma = (cert) => {
844
+ let sub = null;
845
+ if (isObjRecord(cert.substitution)) sub = cert.substitution;
846
+ else if (isObjRecord(cert.bindings)) sub = cert.bindings;
847
+ if (!sub) return "quantifier E-matching instance";
848
+ const bind = Object.entries(sub).map(([k, v]) => `${k} ↦ ${formatModelValue(v)}`).join(", ");
849
+ return bind ? `E-matching instantiation: ${bind}` : "quantifier E-matching instance";
850
+ };
851
+ const describeRupLemma = (cert) => {
852
+ let steps = 0;
853
+ if (Array.isArray(cert.steps)) steps = cert.steps.length;
854
+ else if (Array.isArray(cert.clauses)) steps = cert.clauses.length;
855
+ return steps > 0 ? `${steps} CDCL RUP derivation steps` : "CDCL reverse unit propagation proof";
856
+ };
857
+ const describeLemma = (raw) => {
858
+ const cert = isObjRecord(raw.certificate) ? raw.certificate : raw;
859
+ const kind = inferLemmaKind(cert);
860
+ if (kind === "forall-inst") return [kind, describeForallLemma(cert)];
861
+ if (kind === "array-axiom") return [kind, str(cert.rule, "QF_AUFLIA read-over-write axiom")];
862
+ if (kind === "congruence") {
863
+ const steps = Array.isArray(cert.steps) ? cert.steps.length : 0;
864
+ return [kind, steps > 0 ? `${steps} EUF congruence steps` : "EUF congruence closure"];
865
+ }
866
+ if (kind === "linear" || kind === "split") {
867
+ const steps = Array.isArray(cert.steps) ? cert.steps.length : 0;
868
+ const lines = Array.isArray(cert.constraints) ? cert.constraints.length : 0;
869
+ return [kind, steps > 0 ? `${steps} Farkas / CG steps over ${lines} constraints` : "linear arithmetic refutation"];
870
+ }
871
+ if (kind === "rup") return [kind, describeRupLemma(cert)];
872
+ if (kind === "sos") return [kind, "sum-of-squares polynomial certificate"];
873
+ return [kind, str(cert.summary, str(cert.formula, "verified theory lemma"))];
874
+ };
875
+ const renderTheoryLemmas = (doc, card, data) => {
876
+ const inner = isObjRecord(data?.proof) ? data.proof : data;
877
+ const rows = [];
878
+ if (inner?.kind === "dpll-t" && Array.isArray(inner.lemmas)) {
879
+ for (const item of inner.lemmas) if (isObjRecord(item)) rows.push(describeLemma(item));
880
+ if (isObjRecord(inner.rup)) rows.push(describeLemma({
881
+ kind: "rup",
882
+ ...inner.rup
883
+ }));
884
+ } else if (inner?.kind === "rup") rows.push(describeLemma(inner));
885
+ if (Array.isArray(data?.strengthened)) for (const inv of data.strengthened) rows.push(["pdr-lemma", str(inv)]);
886
+ if (rows.length === 0) return;
887
+ const details = makeEl(doc, "details", "lion-ui-proof-lemmas");
888
+ const kinds = [...new Set(rows.map(([k]) => k))].join(", ");
889
+ appendText(doc, details, "summary", `Inspect ${rows.length} kernel lemma${rows.length === 1 ? "" : "s"} (${kinds})`, "lion-ui-proof-lemmas-summary");
890
+ const list = makeEl(doc, "div", "lion-ui-proof-lemma-list");
891
+ for (const [kind, text] of rows) {
892
+ const row = makeEl(doc, "div", "lion-ui-proof-lemma");
893
+ appendText(doc, row, "span", kind, "lion-ui-proof-lemma-kind");
894
+ appendText(doc, row, "span", text, "lion-ui-proof-lemma-text");
895
+ list.append(row);
896
+ }
897
+ details.append(list);
898
+ card.append(details);
899
+ };
900
+ const renderOptimizeBody = (doc, card, data) => {
901
+ const row = makeEl(doc, "div", "lion-ui-proof-bounds");
902
+ const dir = str(data.direction, "min").toUpperCase();
903
+ if (data.status === "optimal") {
904
+ appendText(doc, row, "span", `${dir} = ${str(data.optimal)}`, "lion-ui-proof-stat");
905
+ appendText(doc, row, "span", data.inclusive === true ? "attained" : "strict inf/sup", "lion-ui-proof-stat is-muted");
906
+ if (Array.isArray(data.proof)) appendText(doc, row, "span", `${data.proof.length} duality cert${data.proof.length === 1 ? "" : "s"}`, "lion-ui-proof-stat is-ok");
907
+ } else appendText(doc, row, "span", `${dir}: ${str(data.status)}`, "lion-ui-proof-stat");
908
+ card.append(row);
909
+ if (isObjRecord(data.witness)) {
910
+ const strip = renderAssignmentStrip(doc, "Optimal Witness", data.witness, "ok");
911
+ if (strip) card.append(strip);
912
+ }
913
+ };
914
+ const firstArrayField = (a, b, key) => {
915
+ if (a && Array.isArray(a[key])) return a[key];
916
+ if (Array.isArray(b[key])) return b[key];
917
+ return null;
918
+ };
919
+ const renderTemporalStats = (doc, card, data) => {
920
+ const row = makeEl(doc, "div", "lion-ui-proof-bounds");
921
+ const states = typeof data.checkedStates === "number" ? data.checkedStates : data.states;
922
+ if (typeof states === "number") appendText(doc, row, "span", `${states} reachable states`, "lion-ui-proof-stat");
923
+ const inner = isObjRecord(data.proof) ? data.proof : data;
924
+ if (typeof inner.kind === "string") appendText(doc, row, "span", inner.kind, "lion-ui-proof-stat is-ok");
925
+ for (const [key, label] of [["wf", "WF"], ["sf", "SF"]]) {
926
+ const items = data[key];
927
+ if (Array.isArray(items) && items.length > 0) appendText(doc, row, "span", `${label}(${items.map((w) => str(w)).join(", ")})`, "lion-ui-proof-stat is-muted");
928
+ }
929
+ if (row.childNodes.length > 0) card.append(row);
930
+ };
931
+ const renderTemporalBody = (doc, card, data) => {
932
+ renderTemporalStats(doc, card, data);
933
+ const ce = isObjRecord(data.counterexample) ? data.counterexample : null;
934
+ const stem = firstArrayField(ce, data, "stem");
935
+ const cycle = firstArrayField(ce, data, "cycle");
936
+ if (stem || cycle) {
937
+ const fmt = (items) => items.map((s) => JSON.stringify(s)).join(" → ");
938
+ appendText(doc, card, "p", stem && stem.length > 0 ? `Lasso counterexample: ${fmt(stem)} → ↻ [ ${fmt(cycle ?? [])} ]` : `Cycle counterexample: ↻ [ ${fmt(cycle ?? [])} ]`, "lion-ui-proof-note is-error");
939
+ return;
940
+ }
941
+ if (ce) {
942
+ const strip = renderAssignmentStrip(doc, "Refinement Violation Witness", ce, "error");
943
+ if (strip) card.append(strip);
944
+ return;
945
+ }
946
+ if (Array.isArray(data.trace) && data.trace.length > 0) appendText(doc, card, "p", `Trace (${data.trace.length} steps): ${data.trace.map((s, i) => `s${i}=${JSON.stringify(s)}`).join(" → ")}`, "lion-ui-proof-note is-error");
947
+ };
948
+ const renderBoundsBody = (doc, card, data) => {
949
+ const row = makeEl(doc, "div", "lion-ui-proof-bounds");
950
+ appendText(doc, row, "span", `min ${str(data.min)}`, "lion-ui-proof-stat");
951
+ appendText(doc, row, "span", `max ${str(data.max)}`, "lion-ui-proof-stat");
952
+ card.append(row);
953
+ if (isObjRecord(data.witnessMin)) {
954
+ const strip = renderAssignmentStrip(doc, "Worst-Case Witness (min)", data.witnessMin, "ok");
955
+ if (strip) card.append(strip);
956
+ }
957
+ };
958
+ const renderCounterexampleBody = (doc, card, data) => {
959
+ if (data.satisfiable === true && (isObjRecord(data.model) || isObjRecord(data.assignment))) {
960
+ const strip = renderAssignmentStrip(doc, "Live Counterexample Model", isObjRecord(data.model) ? data.model : data.assignment, "error");
961
+ if (strip) card.append(strip);
962
+ return true;
963
+ }
964
+ if ("counterexample" in data && data.counterexample !== null) {
965
+ if (isObjRecord(data.counterexample)) {
966
+ const strip = renderAssignmentStrip(doc, "Counterexample", data.counterexample, "error");
967
+ if (strip) card.append(strip);
968
+ } else appendText(doc, card, "p", `Counterexample: ${JSON.stringify(data.counterexample)}`, "lion-ui-proof-note is-error");
969
+ return true;
970
+ }
971
+ if (Array.isArray(data.trace) && data.trace.length > 0) {
972
+ appendText(doc, card, "p", `Trace (${data.trace.length} steps): ${data.trace.map((s, i) => `s${i}=${JSON.stringify(s)}`).join(" → ")}`, "lion-ui-proof-note is-error");
973
+ return true;
974
+ }
975
+ return false;
976
+ };
977
+ const renderProofPrimary = (doc, card, data) => {
978
+ if (!data) return;
979
+ if (data.kind === "optimize") {
980
+ renderOptimizeBody(doc, card, data);
981
+ return;
982
+ }
983
+ if ("min" in data && "max" in data) {
984
+ renderBoundsBody(doc, card, data);
985
+ return;
986
+ }
987
+ if ("holds" in data || "refines" in data) {
988
+ renderTemporalBody(doc, card, data);
989
+ return;
990
+ }
991
+ if (renderCounterexampleBody(doc, card, data)) return;
992
+ const kindNote = summarizeProofKind(data);
993
+ if (kindNote !== void 0) appendText(doc, card, "p", kindNote, "lion-ui-proof-note");
994
+ };
995
+ const renderProofBody = (doc, card, props, data) => {
996
+ renderProofPrimary(doc, card, data);
997
+ renderTheoryLemmas(doc, card, data);
998
+ if (props.summary) appendText(doc, card, "p", str(props.summary), "lion-ui-proof-note");
999
+ };
1000
+ const renderProof = (node, ctx) => {
1001
+ const { doc } = ctx;
1002
+ const card = makeEl(doc, "div", nodeClass(ctx, "proof", "lion-ui-proof", node));
1003
+ card.dataset.uiKind = node.$ui;
1004
+ card.dataset.uiKey = keyOf(node);
1005
+ const data = typeof node.props.data === "object" && node.props.data !== null ? node.props.data : null;
1006
+ const head = makeEl(doc, "div", "lion-ui-proof-head");
1007
+ appendText(doc, head, "span", str(node.props.title, "Formal proof"), "lion-ui-proof-title");
1008
+ const [badgeText, badgeTone] = proofBadge(node.props, data);
1009
+ appendText(doc, head, "span", badgeText, cx(ctx, "badge", "lion-ui-badge", badgeTone));
1010
+ card.append(head);
1011
+ renderProofBody(doc, card, node.props, data);
1012
+ return card;
1013
+ };
1014
+ const renderButton = (node, ctx, existing) => {
1015
+ const { doc, onAction } = ctx;
1016
+ const key = keyOf(node);
1017
+ const button = matchesExisting(existing, "button", key) ? existing : makeEl(doc, "button");
1018
+ button.type = "button";
1019
+ button.dataset.uiKind = "button";
1020
+ button.dataset.uiKey = key;
1021
+ button.className = nodeClass(ctx, "button", "lion-ui-button", node, toneClass(node.props.tone));
1022
+ button.disabled = bool(node.props.disabled, false);
1023
+ button.textContent = str(node.props.label) || node.children.map((child) => str(child)).join(" ") || "Run";
1024
+ ACTION_MAP.set(button, node.props.onClick ?? node.props.action);
1025
+ if (!WIRED.has(button)) {
1026
+ WIRED.add(button);
1027
+ button.addEventListener("click", () => {
1028
+ const action = ACTION_MAP.get(button);
1029
+ if (action !== void 0) onAction?.(action);
1030
+ });
1031
+ }
1032
+ return button;
1033
+ };
1034
+ const renderToggle = (node, ctx, existing) => {
1035
+ const { doc, onAction } = ctx;
1036
+ const key = keyOf(node);
1037
+ const wrapper = matchesExisting(existing, "toggle", key) ? existing : makeEl(doc, "label");
1038
+ wrapper.dataset.uiKind = "toggle";
1039
+ wrapper.dataset.uiKey = key;
1040
+ wrapper.className = nodeClass(ctx, "toggle", "lion-ui-toggle", node);
1041
+ let input = wrapper.querySelector("input");
1042
+ let text = wrapper.querySelector(".lion-ui-toggle-label");
1043
+ if (!(input && text)) {
1044
+ wrapper.textContent = "";
1045
+ input = doc.createElement("input");
1046
+ input.type = "checkbox";
1047
+ input.className = "lion-ui-toggle-input";
1048
+ const track = makeEl(doc, "span", "lion-ui-toggle-track");
1049
+ text = makeEl(doc, "span", "lion-ui-toggle-label");
1050
+ wrapper.append(input, track, text);
1051
+ }
1052
+ input.checked = bool(node.props.checked ?? node.props.value, false);
1053
+ text.textContent = str(node.props.label);
1054
+ ACTION_MAP.set(input, node.props.onChange ?? node.props.action);
1055
+ if (!WIRED.has(input)) {
1056
+ WIRED.add(input);
1057
+ input.addEventListener("change", () => {
1058
+ const target = input;
1059
+ const action = ACTION_MAP.get(target);
1060
+ if (action !== void 0) onAction?.(action, target.checked);
1061
+ });
1062
+ }
1063
+ return wrapper;
1064
+ };
1065
+ const ensureFieldShell = (ctx, kind, key, label, node, tag, existing) => {
1066
+ const { doc } = ctx;
1067
+ const field = matchesExisting(existing, kind, key) ? existing : makeEl(doc, tag);
1068
+ field.dataset.uiKind = kind;
1069
+ field.dataset.uiKey = key;
1070
+ field.className = nodeClass(ctx, "field", `lion-ui-field is-${kind}`, node);
1071
+ let head = field.querySelector(".lion-ui-field-head");
1072
+ let labelEl = field.querySelector(".lion-ui-field-label");
1073
+ let valueBadge = field.querySelector(".lion-ui-field-value");
1074
+ if (!(head && labelEl)) {
1075
+ field.textContent = "";
1076
+ head = makeEl(doc, "span", "lion-ui-field-head");
1077
+ labelEl = makeEl(doc, "span", "lion-ui-field-label");
1078
+ head.append(labelEl);
1079
+ if (kind === "slider") {
1080
+ valueBadge = makeEl(doc, "span", "lion-ui-field-value");
1081
+ head.append(valueBadge);
1082
+ }
1083
+ field.append(head);
1084
+ }
1085
+ labelEl.textContent = label;
1086
+ return {
1087
+ field,
1088
+ valueBadge
1089
+ };
1090
+ };
1091
+ const normalizeOptions = (raw) => {
1092
+ if (!Array.isArray(raw)) return [];
1093
+ return raw.map((opt) => typeof opt === "object" && opt !== null ? {
1094
+ label: str(opt.label),
1095
+ value: str(opt.value)
1096
+ } : {
1097
+ label: str(opt),
1098
+ value: str(opt)
1099
+ });
1100
+ };
1101
+ const makeChevronSvg = (doc) => {
1102
+ const svg = doc.createElementNS("http://www.w3.org/2000/svg", "svg");
1103
+ svg.setAttribute("aria-hidden", "true");
1104
+ svg.setAttribute("width", "14");
1105
+ svg.setAttribute("height", "14");
1106
+ svg.setAttribute("viewBox", "0 0 24 24");
1107
+ svg.setAttribute("fill", "none");
1108
+ svg.setAttribute("stroke", "currentColor");
1109
+ svg.setAttribute("stroke-width", "2");
1110
+ svg.setAttribute("stroke-linecap", "round");
1111
+ svg.setAttribute("stroke-linejoin", "round");
1112
+ svg.setAttribute("class", "lion-ui-select-chevron");
1113
+ const path = doc.createElementNS("http://www.w3.org/2000/svg", "polyline");
1114
+ path.setAttribute("points", "6 9 12 15 18 9");
1115
+ svg.append(path);
1116
+ return svg;
1117
+ };
1118
+ const populateSelectMenu = (menu, root, options, currentValue, ctx) => {
1119
+ const { doc, onAction } = ctx;
1120
+ menu.textContent = "";
1121
+ for (const opt of options) {
1122
+ const selected = opt.value === currentValue;
1123
+ const item = makeEl(doc, "button", cx(ctx, "selectOption", "lion-ui-select-option", selected ? "is-selected" : ""));
1124
+ item.type = "button";
1125
+ item.setAttribute("role", "option");
1126
+ item.setAttribute("aria-selected", String(selected));
1127
+ const check = makeEl(doc, "span", "lion-ui-select-check");
1128
+ check.textContent = selected ? "✓" : "";
1129
+ const text = makeEl(doc, "span", "lion-ui-select-option-label");
1130
+ text.textContent = opt.label;
1131
+ item.append(text, check);
1132
+ item.addEventListener("click", () => {
1133
+ closeSelect(root);
1134
+ const action = ACTION_MAP.get(root);
1135
+ if (action !== void 0) onAction?.(action, opt.value);
1136
+ });
1137
+ menu.append(item);
1138
+ }
1139
+ };
1140
+ const renderSelect = (node, ctx, existing) => {
1141
+ const { doc } = ctx;
1142
+ ensureOutsideDismiss(doc);
1143
+ const { field } = ensureFieldShell(ctx, "select", keyOf(node), str(node.props.label), node, "div", existing);
1144
+ let root = field.querySelector("[data-select-root]");
1145
+ let trigger = field.querySelector("[data-select-trigger]");
1146
+ let triggerLabel = field.querySelector("[data-select-value]");
1147
+ let menu = field.querySelector("[data-select-menu]");
1148
+ if (!(root && trigger && triggerLabel && menu)) {
1149
+ root = makeEl(doc, "div", cx(ctx, "select", "lion-ui-select-root"));
1150
+ root.dataset.selectRoot = "";
1151
+ trigger = makeEl(doc, "button", cx(ctx, "selectTrigger", "lion-ui-select-trigger"));
1152
+ trigger.type = "button";
1153
+ trigger.dataset.selectTrigger = "";
1154
+ trigger.setAttribute("aria-haspopup", "listbox");
1155
+ trigger.setAttribute("aria-expanded", "false");
1156
+ triggerLabel = makeEl(doc, "span", "lion-ui-select-value");
1157
+ triggerLabel.dataset.selectValue = "";
1158
+ trigger.append(triggerLabel, makeChevronSvg(doc));
1159
+ menu = makeEl(doc, "div", cx(ctx, "selectMenu", "lion-ui-select-menu"));
1160
+ menu.dataset.selectMenu = "";
1161
+ menu.setAttribute("role", "listbox");
1162
+ menu.hidden = true;
1163
+ root.append(trigger, menu);
1164
+ field.append(root);
1165
+ }
1166
+ const options = normalizeOptions(node.props.options);
1167
+ const currentValue = str(node.props.value);
1168
+ const currentOption = options.find((opt) => opt.value === currentValue);
1169
+ triggerLabel.textContent = currentOption?.label ?? currentValue;
1170
+ ACTION_MAP.set(root, node.props.onChange ?? node.props.action);
1171
+ populateSelectMenu(menu, root, options, currentValue, ctx);
1172
+ if (!WIRED.has(trigger)) {
1173
+ WIRED.add(trigger);
1174
+ const selectRoot = root;
1175
+ const selectTrigger = trigger;
1176
+ const selectMenu = menu;
1177
+ selectTrigger.addEventListener("click", () => {
1178
+ const opening = selectMenu.hidden;
1179
+ for (const other of [...OPEN_SELECTS]) if (other !== selectRoot) closeSelect(other);
1180
+ selectMenu.hidden = !opening;
1181
+ selectRoot.classList.toggle("is-open", opening);
1182
+ selectTrigger.setAttribute("aria-expanded", String(opening));
1183
+ if (opening) OPEN_SELECTS.add(selectRoot);
1184
+ else OPEN_SELECTS.delete(selectRoot);
1185
+ });
1186
+ }
1187
+ return field;
1188
+ };
1189
+ const syncInputAttributes = (input, kind, props, doc, valueBadge) => {
1190
+ if (kind === "slider") {
1191
+ input.type = "range";
1192
+ input.min = String(num(props.min, 0));
1193
+ input.max = String(num(props.max, 100));
1194
+ input.step = String(num(props.step, 1));
1195
+ const current = num(props.value, num(props.min, 0));
1196
+ if (input.value !== String(current)) input.value = String(current);
1197
+ if (valueBadge) valueBadge.textContent = `${str(props.prefix)}${current}${str(props.suffix)}`;
1198
+ return;
1199
+ }
1200
+ input.type = kind === "number" ? "number" : "text";
1201
+ if (kind === "number") {
1202
+ if (props.min !== void 0) input.min = String(num(props.min, 0));
1203
+ if (props.max !== void 0) input.max = String(num(props.max, 100));
1204
+ if (props.step !== void 0) input.step = String(num(props.step, 1));
1205
+ } else input.placeholder = str(props.placeholder);
1206
+ const nextVal = str(props.value);
1207
+ if (doc.activeElement !== input && input.value !== nextVal) input.value = nextVal;
1208
+ };
1209
+ const renderInputControl = (kind) => (node, ctx, existing) => {
1210
+ const { doc, onAction } = ctx;
1211
+ const { field, valueBadge } = ensureFieldShell(ctx, kind, keyOf(node), str(node.props.label), node, "label", existing);
1212
+ let input = field.querySelector("input");
1213
+ if (!input) {
1214
+ input = doc.createElement("input");
1215
+ input.className = cx(ctx, kind, kind === "slider" ? "lion-ui-slider" : "lion-ui-input");
1216
+ field.append(input);
1217
+ }
1218
+ syncInputAttributes(input, kind, node.props, doc, valueBadge);
1219
+ ACTION_MAP.set(input, node.props.onChange ?? node.props.action);
1220
+ if (!WIRED.has(input)) {
1221
+ WIRED.add(input);
1222
+ input.addEventListener("input", () => {
1223
+ const target = input;
1224
+ const action = ACTION_MAP.get(target);
1225
+ if (action === void 0) return;
1226
+ if (kind === "slider" || kind === "number") {
1227
+ const parsed = Number(target.value);
1228
+ if (Number.isFinite(parsed)) onAction?.(action, parsed);
1229
+ } else onAction?.(action, target.value);
1230
+ });
1231
+ }
1232
+ return field;
1233
+ };
1234
+ const renderChild = (child, ctx, existing) => {
1235
+ if (!isUiNode(child)) {
1236
+ const text = String(child);
1237
+ if (existing?.nodeType === 3) {
1238
+ if (existing.textContent !== text) existing.textContent = text;
1239
+ return existing;
1240
+ }
1241
+ return ctx.doc.createTextNode(text);
1242
+ }
1243
+ return renderElement(child, ctx, existing?.nodeType === 1 ? existing : void 0);
1244
+ };
1245
+ const patchChildren = (container, children, ctx) => {
1246
+ for (let i = 0; i < children.length; i += 1) {
1247
+ const child = children[i];
1248
+ if (child === void 0) continue;
1249
+ const existing = container.childNodes[i];
1250
+ const next = renderChild(child, ctx, existing);
1251
+ if (!existing) container.append(next);
1252
+ else if (next !== existing) container.replaceChild(next, existing);
1253
+ }
1254
+ while (container.childNodes.length > children.length) container.lastChild?.remove();
1255
+ };
1256
+ const renderLayout = (kind) => (node, ctx, existing) => {
1257
+ const key = keyOf(node);
1258
+ const el = matchesExisting(existing, kind, key) ? existing : makeEl(ctx.doc, "div");
1259
+ el.dataset.uiKind = kind;
1260
+ el.dataset.uiKey = key;
1261
+ const gap = str(node.props.gap, "md");
1262
+ const align = str(node.props.align);
1263
+ el.className = nodeClass(ctx, kind, `lion-ui-${kind}`, node, [`gap-${gap}`, align ? `align-${align}` : ""].filter(Boolean).join(" "));
1264
+ if (kind === "grid") el.style.setProperty("--ui-cols", String(num(node.props.columns ?? node.props.cols, 2)));
1265
+ patchChildren(el, node.children, ctx);
1266
+ return el;
1267
+ };
1268
+ const renderCard = (node, ctx, existing) => {
1269
+ const { doc } = ctx;
1270
+ const key = keyOf(node);
1271
+ const el = matchesExisting(existing, "card", key) ? existing : makeEl(doc, "section");
1272
+ el.dataset.uiKind = "card";
1273
+ el.dataset.uiKey = key;
1274
+ el.className = nodeClass(ctx, "card", "lion-ui-card", node, toneClass(node.props.tone));
1275
+ const title = str(node.props.title);
1276
+ const subtitle = str(node.props.subtitle);
1277
+ let body = el.querySelector(":scope > .lion-ui-card-body");
1278
+ if (body) {
1279
+ const titleEl = el.querySelector(":scope > .lion-ui-card-head .lion-ui-card-title");
1280
+ if (titleEl && titleEl.textContent !== title) titleEl.textContent = title;
1281
+ const subEl = el.querySelector(":scope > .lion-ui-card-head .lion-ui-card-subtitle");
1282
+ if (subEl && subEl.textContent !== subtitle) subEl.textContent = subtitle;
1283
+ } else {
1284
+ el.textContent = "";
1285
+ if (title || subtitle) {
1286
+ const header = makeEl(doc, "header", "lion-ui-card-head");
1287
+ if (title) appendText(doc, header, "h4", title, "lion-ui-card-title");
1288
+ if (subtitle) appendText(doc, header, "p", subtitle, "lion-ui-card-subtitle");
1289
+ el.append(header);
1290
+ }
1291
+ body = makeEl(doc, "div", "lion-ui-card-body");
1292
+ el.append(body);
1293
+ }
1294
+ patchChildren(body, node.children, ctx);
1295
+ return el;
1296
+ };
1297
+ const renderMetric = (node, ctx) => {
1298
+ const { doc } = ctx;
1299
+ const el = makeEl(doc, "div", nodeClass(ctx, "metric", "lion-ui-metric", node, toneClass(node.props.tone)));
1300
+ el.dataset.uiKind = "metric";
1301
+ el.dataset.uiKey = keyOf(node);
1302
+ appendText(doc, el, "span", str(node.props.label), "lion-ui-metric-label");
1303
+ appendText(doc, el, "strong", str(node.props.value), "lion-ui-metric-value");
1304
+ if (node.props.delta !== void 0 && node.props.delta !== null && node.props.delta !== "") appendText(doc, el, "span", str(node.props.delta), "lion-ui-metric-delta");
1305
+ if (node.props.caption !== void 0 && node.props.caption !== null && node.props.caption !== "") appendText(doc, el, "span", str(node.props.caption), "lion-ui-metric-caption");
1306
+ return el;
1307
+ };
1308
+ const renderAlert = (node, ctx) => {
1309
+ const el = makeEl(ctx.doc, "div", nodeClass(ctx, "alert", "lion-ui-alert", node, toneClass(node.props.tone)));
1310
+ el.dataset.uiKind = "alert";
1311
+ el.dataset.uiKey = keyOf(node);
1312
+ if (node.props.title) appendText(ctx.doc, el, "strong", str(node.props.title), "lion-ui-alert-title");
1313
+ if (node.children.length > 0) {
1314
+ const body = makeEl(ctx.doc, "div", "lion-ui-alert-body");
1315
+ patchChildren(body, node.children, ctx);
1316
+ el.append(body);
1317
+ }
1318
+ return el;
1319
+ };
1320
+ const renderProgress = (node, ctx) => {
1321
+ const { doc } = ctx;
1322
+ const el = makeEl(doc, "div", nodeClass(ctx, "progress", "lion-ui-progress", node, toneClass(node.props.tone)));
1323
+ el.dataset.uiKind = "progress";
1324
+ el.dataset.uiKey = keyOf(node);
1325
+ const value = num(node.props.value, 0);
1326
+ const max = Math.max(1, num(node.props.max, 100));
1327
+ const pct = Math.max(0, Math.min(100, value / max * 100));
1328
+ const head = makeEl(doc, "div", "lion-ui-progress-head");
1329
+ appendText(doc, head, "span", str(node.props.label), "lion-ui-progress-label");
1330
+ appendText(doc, head, "span", str(node.props.display, `${Math.round(pct)}%`), "lion-ui-progress-value");
1331
+ const track = makeEl(doc, "div", "lion-ui-progress-track");
1332
+ const fill = makeEl(doc, "div", "lion-ui-progress-fill");
1333
+ fill.style.width = `${pct}%`;
1334
+ track.append(fill);
1335
+ el.append(head, track);
1336
+ return el;
1337
+ };
1338
+ const tableColumnLabel = (col) => typeof col === "object" && col !== null && "label" in col ? str(col.label) : str(col);
1339
+ const tableColumnKey = (col) => typeof col === "object" && col !== null && "key" in col ? str(col.key) : str(col);
1340
+ const tableRowCells = (row, columnKeys) => {
1341
+ if (Array.isArray(row)) return row;
1342
+ if (typeof row === "object" && row !== null && !isUiNode(row)) {
1343
+ const rec = row;
1344
+ return columnKeys.length > 0 ? columnKeys.map((k) => rec[k]) : Object.values(rec);
1345
+ }
1346
+ return [row];
1347
+ };
1348
+ const rowKeyValue = (row, rowKey, firstCell) => {
1349
+ if (rowKey !== "" && typeof row === "object" && row !== null && !Array.isArray(row) && rowKey in row) return str(row[rowKey]);
1350
+ return str(firstCell);
1351
+ };
1352
+ const renderTable = (node, ctx) => {
1353
+ const { doc } = ctx;
1354
+ const wrap = makeEl(doc, "div", nodeClass(ctx, "tableWrap", "lion-ui-table-wrap", node));
1355
+ wrap.dataset.uiKind = "table";
1356
+ wrap.dataset.uiKey = keyOf(node);
1357
+ if (node.props.title) appendText(doc, wrap, "div", str(node.props.title), "lion-ui-table-title");
1358
+ const table = makeEl(doc, "table", cx(ctx, "table", "lion-ui-table"));
1359
+ const columns = Array.isArray(node.props.columns) ? node.props.columns : [];
1360
+ const rows = Array.isArray(node.props.rows) ? node.props.rows : [];
1361
+ const selectAction = node.props.onSelect ?? node.props.action;
1362
+ const selectedRow = str(node.props.selected);
1363
+ const rowKey = str(node.props.rowKey, "id");
1364
+ if (columns.length > 0) {
1365
+ const thead = doc.createElement("thead");
1366
+ const tr = doc.createElement("tr");
1367
+ for (const col of columns) appendText(doc, tr, "th", tableColumnLabel(col));
1368
+ thead.append(tr);
1369
+ table.append(thead);
1370
+ }
1371
+ const tbody = doc.createElement("tbody");
1372
+ const columnKeys = columns.map(tableColumnKey);
1373
+ for (const row of rows) {
1374
+ const tr = doc.createElement("tr");
1375
+ const cells = tableRowCells(row, columnKeys);
1376
+ const idVal = rowKeyValue(row, rowKey, cells[0]);
1377
+ if (selectedRow !== "" && idVal === selectedRow) tr.classList.add("is-selected");
1378
+ if (selectAction !== void 0 && ctx.onAction) {
1379
+ tr.classList.add("is-clickable");
1380
+ tr.addEventListener("click", () => ctx.onAction?.(selectAction, idVal));
1381
+ }
1382
+ for (const cell of cells) {
1383
+ const td = doc.createElement("td");
1384
+ if (isUiNode(cell)) td.append(renderElement(cell, ctx));
1385
+ else td.textContent = str(cell);
1386
+ tr.append(td);
1387
+ }
1388
+ tbody.append(tr);
1389
+ }
1390
+ table.append(tbody);
1391
+ wrap.append(table);
1392
+ return wrap;
1393
+ };
1394
+ const renderWhy = (node, ctx) => {
1395
+ const { doc } = ctx;
1396
+ const el = makeEl(doc, "div", nodeClass(ctx, "why", "lion-ui-why", node));
1397
+ el.dataset.uiKind = "why";
1398
+ el.dataset.uiKey = keyOf(node);
1399
+ if (node.props.title) appendText(doc, el, "div", str(node.props.title), "lion-ui-why-title");
1400
+ el.append(renderWhyTree(doc, node.props.data));
1401
+ return el;
1402
+ };
1403
+ const renderSimple = (tag, slot, baseClass) => (node, ctx) => {
1404
+ const el = makeEl(ctx.doc, tag, nodeClass(ctx, slot, baseClass, node, toneClass(node.props.tone)));
1405
+ el.dataset.uiKind = node.$ui;
1406
+ el.dataset.uiKey = keyOf(node);
1407
+ patchChildren(el, node.children, ctx);
1408
+ return el;
1409
+ };
1410
+ const renderHeading = (node, ctx) => {
1411
+ const level = Math.min(4, Math.max(1, num(node.props.level, 3)));
1412
+ const el = makeEl(ctx.doc, `h${level}`, nodeClass(ctx, "heading", "lion-ui-heading", node, `level-${level}`));
1413
+ el.dataset.uiKind = "heading";
1414
+ el.dataset.uiKey = keyOf(node);
1415
+ patchChildren(el, node.children, ctx);
1416
+ return el;
1417
+ };
1418
+ const renderCode = (node, ctx) => {
1419
+ const { doc } = ctx;
1420
+ const pre = makeEl(doc, "pre", nodeClass(ctx, "code", "lion-ui-code", node));
1421
+ pre.dataset.uiKind = "code";
1422
+ const code = doc.createElement("code");
1423
+ code.textContent = node.children.map((child) => str(child)).join("");
1424
+ pre.append(code);
1425
+ return pre;
1426
+ };
1427
+ const renderDivider = (node, ctx) => {
1428
+ const hr = makeEl(ctx.doc, "hr", nodeClass(ctx, "divider", "lion-ui-divider", node));
1429
+ hr.dataset.uiKind = "divider";
1430
+ return hr;
1431
+ };
1432
+ const renderChart = (node, ctx) => {
1433
+ const { doc } = ctx;
1434
+ const wrap = makeEl(doc, "div", nodeClass(ctx, "chart", "lion-ui-chart", node));
1435
+ wrap.dataset.uiKind = "chart";
1436
+ wrap.dataset.uiKey = keyOf(node);
1437
+ if (node.props.title) appendText(doc, wrap, "div", str(node.props.title), "lion-ui-chart-title");
1438
+ const rows = Array.isArray(node.props.data) ? node.props.data : [];
1439
+ const maxVal = Math.max(1, ...rows.map((r) => Math.abs(num(r.max ?? r.value, 0))));
1440
+ const list = makeEl(doc, "div", "lion-ui-chart-bars");
1441
+ for (const row of rows) {
1442
+ const item = makeEl(doc, "div", "lion-ui-chart-row");
1443
+ appendText(doc, item, "span", str(row.label), "lion-ui-chart-label");
1444
+ const track = makeEl(doc, "div", "lion-ui-chart-track");
1445
+ const fill = makeEl(doc, "div", `lion-ui-chart-fill ${toneClass(row.tone)}`.trim());
1446
+ const val = num(row.value, 0);
1447
+ fill.style.width = `${Math.min(100, Math.max(0, Math.abs(val) / maxVal * 100))}%`;
1448
+ track.append(fill);
1449
+ item.append(track);
1450
+ appendText(doc, item, "span", str(row.display ?? val), "lion-ui-chart-value");
1451
+ list.append(item);
1452
+ }
1453
+ wrap.append(list);
1454
+ return wrap;
1455
+ };
1456
+ const renderTimeline = (node, ctx) => {
1457
+ const { doc } = ctx;
1458
+ const wrap = makeEl(doc, "div", nodeClass(ctx, "timeline", "lion-ui-timeline", node));
1459
+ wrap.dataset.uiKind = "timeline";
1460
+ wrap.dataset.uiKey = keyOf(node);
1461
+ if (node.props.title) appendText(doc, wrap, "div", str(node.props.title), "lion-ui-timeline-title");
1462
+ const list = makeEl(doc, "ol", "lion-ui-timeline-list");
1463
+ const items = Array.isArray(node.props.items) ? node.props.items : [];
1464
+ for (const entry of items) {
1465
+ const li = makeEl(doc, "li", `lion-ui-timeline-item ${toneClass(entry.tone)}`.trim());
1466
+ if (entry.time !== void 0) appendText(doc, li, "time", str(entry.time), "lion-ui-timeline-time");
1467
+ appendText(doc, li, "div", str(entry.title), "lion-ui-timeline-heading");
1468
+ if (entry.detail !== void 0) appendText(doc, li, "p", str(entry.detail), "lion-ui-timeline-detail");
1469
+ list.append(li);
1470
+ }
1471
+ wrap.append(list);
1472
+ return wrap;
1473
+ };
1474
+ const renderDiff = (node, ctx) => {
1475
+ const { doc } = ctx;
1476
+ const wrap = makeEl(doc, "div", nodeClass(ctx, "diff", "lion-ui-diff", node));
1477
+ wrap.dataset.uiKind = "diff";
1478
+ wrap.dataset.uiKey = keyOf(node);
1479
+ if (node.props.title) appendText(doc, wrap, "div", str(node.props.title), "lion-ui-diff-title");
1480
+ const removed = Array.isArray(node.props.removed) ? node.props.removed : [];
1481
+ const added = Array.isArray(node.props.added) ? node.props.added : [];
1482
+ for (const item of removed) appendText(doc, wrap, "div", `- ${typeof item === "string" ? item : JSON.stringify(item)}`, "lion-ui-diff-line is-removed");
1483
+ for (const item of added) appendText(doc, wrap, "div", `+ ${typeof item === "string" ? item : JSON.stringify(item)}`, "lion-ui-diff-line is-added");
1484
+ return wrap;
1485
+ };
1486
+ const renderSource = (node, ctx) => {
1487
+ const { doc } = ctx;
1488
+ const wrap = makeEl(doc, "blockquote", nodeClass(ctx, "source", "lion-ui-source", node));
1489
+ wrap.dataset.uiKind = "source";
1490
+ wrap.dataset.uiKey = keyOf(node);
1491
+ if (node.props.title || node.props.publisher) appendText(doc, wrap, "div", [str(node.props.publisher), str(node.props.title)].filter(Boolean).join(" — "), "lion-ui-source-header");
1492
+ const text = str(node.props.text);
1493
+ const quote = str(node.props.quote);
1494
+ const body = makeEl(doc, "p", "lion-ui-source-body");
1495
+ if (quote && text.includes(quote)) {
1496
+ const at = text.indexOf(quote);
1497
+ body.append(doc.createTextNode(text.slice(0, at)));
1498
+ const mark = makeEl(doc, "mark", "lion-ui-source-quote");
1499
+ mark.textContent = quote;
1500
+ body.append(mark);
1501
+ body.append(doc.createTextNode(text.slice(at + quote.length)));
1502
+ } else body.textContent = text || quote;
1503
+ wrap.append(body);
1504
+ return wrap;
1505
+ };
1506
+ const wrapRich = (fn) => (node, ctx, existing) => fn(node, {
1507
+ classes: ctx.classes,
1508
+ doc: ctx.doc,
1509
+ onAction: ctx.onAction,
1510
+ patchChildren: (parent, children) => patchChildren(parent, children, ctx),
1511
+ unstyled: ctx.unstyled
1512
+ }, existing);
1513
+ const RENDERERS = {
1514
+ accordion: wrapRich(renderAccordion),
1515
+ alert: renderAlert,
1516
+ badge: renderSimple("span", "badge", "lion-ui-badge"),
1517
+ button: renderButton,
1518
+ card: renderCard,
1519
+ chart: renderChart,
1520
+ checkbox: wrapRich(renderCheckbox),
1521
+ code: renderCode,
1522
+ diff: renderDiff,
1523
+ divider: renderDivider,
1524
+ graph: wrapRich(renderGraph),
1525
+ grid: renderLayout("grid"),
1526
+ heading: renderHeading,
1527
+ hero: wrapRich(renderHero),
1528
+ input: renderInputControl("input"),
1529
+ kv: wrapRich(renderKv),
1530
+ link: wrapRich(renderLink),
1531
+ list: wrapRich(renderList),
1532
+ metric: renderMetric,
1533
+ number: renderInputControl("number"),
1534
+ progress: renderProgress,
1535
+ proof: renderProof,
1536
+ row: renderLayout("row"),
1537
+ section: wrapRich(renderSection),
1538
+ select: renderSelect,
1539
+ slider: renderInputControl("slider"),
1540
+ source: renderSource,
1541
+ split: wrapRich(renderSplit),
1542
+ stack: renderLayout("stack"),
1543
+ table: renderTable,
1544
+ tabs: wrapRich(renderTabs),
1545
+ text: renderSimple("p", "text", "lion-ui-text"),
1546
+ textarea: wrapRich(renderTextarea),
1547
+ timeline: renderTimeline,
1548
+ toggle: renderToggle,
1549
+ why: renderWhy
1550
+ };
1551
+ const renderElement = (node, ctx, existing) => RENDERERS[node.$ui](node, ctx, existing);
1552
+ /**
1553
+ * Renders (or patches in place) a Lion UI node into `container`.
1554
+ */
1555
+ const renderUi = (node, container, options = {}) => {
1556
+ if (options.theme) container.dataset.lionTheme = options.theme;
1557
+ const ctx = {
1558
+ classes: options.classes,
1559
+ doc: container.ownerDocument,
1560
+ onAction: options.onAction,
1561
+ unstyled: options.unstyled ?? false
1562
+ };
1563
+ const existing = container.firstElementChild;
1564
+ const next = renderElement(node, ctx, existing ?? void 0);
1565
+ if (!existing) container.replaceChildren(next);
1566
+ else if (next !== existing) container.replaceChild(next, existing);
1567
+ while (container.children.length > 1) container.lastElementChild?.remove();
1568
+ };
1569
+ //#endregion
1570
+ export { renderUi as t };
1571
+
1572
+ //# sourceMappingURL=dom-KrgvYUCe.mjs.map