mintfig 0.2.0__py3-none-any.whl
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.
- mintfig/__init__.py +162 -0
- mintfig/_explain/__init__.py +1 -0
- mintfig/_explain/change.py +392 -0
- mintfig/_explain/compare.py +1308 -0
- mintfig/_explain/compare_grouped.py +472 -0
- mintfig/_explain/core.py +2005 -0
- mintfig/_explain/distribution.py +1268 -0
- mintfig/_explain/flow.py +508 -0
- mintfig/_explain/layout.py +2012 -0
- mintfig/_explain/matrix.py +623 -0
- mintfig/_explain/relate.py +1318 -0
- mintfig/_explain/timeline.py +595 -0
- mintfig/_explain/trend.py +2557 -0
- mintfig/_explain/waterfall.py +459 -0
- mintfig/_table.py +691 -0
- mintfig/_tabular.py +738 -0
- mintfig/annotations.py +1165 -0
- mintfig/assets/AGENTS_SNIPPET.md +11 -0
- mintfig/assets/SKILL.md +143 -0
- mintfig/assets/__init__.py +1 -0
- mintfig/assets/references/publication.md +79 -0
- mintfig/assets/references/scientific_and_recipes.md +213 -0
- mintfig/audit.py +179 -0
- mintfig/brief.py +518 -0
- mintfig/bundle.py +333 -0
- mintfig/cli.py +1300 -0
- mintfig/edit.py +347 -0
- mintfig/epistemic.py +1083 -0
- mintfig/explainer.py +194 -0
- mintfig/export.py +247 -0
- mintfig/inspect_data.py +583 -0
- mintfig/interactive.py +1028 -0
- mintfig/palettes.py +233 -0
- mintfig/plate.py +784 -0
- mintfig/preflight.py +2398 -0
- mintfig/proof.py +627 -0
- mintfig/runner.py +403 -0
- mintfig/skill.py +167 -0
- mintfig/specs.py +291 -0
- mintfig/style.py +151 -0
- mintfig/terminal.py +785 -0
- mintfig/themes.py +660 -0
- mintfig-0.2.0.dist-info/METADATA +239 -0
- mintfig-0.2.0.dist-info/RECORD +47 -0
- mintfig-0.2.0.dist-info/WHEEL +4 -0
- mintfig-0.2.0.dist-info/entry_points.txt +2 -0
- mintfig-0.2.0.dist-info/licenses/LICENSE +21 -0
mintfig/interactive.py
ADDED
|
@@ -0,0 +1,1028 @@
|
|
|
1
|
+
"""Self-contained interactive HTML delivery ("Martini-glass" view) for mintfig figures.
|
|
2
|
+
|
|
3
|
+
Emits a zero-dependency, zero-CDN HTML5 document (or embeddable fragment for
|
|
4
|
+
Jupyter ``_repr_html_()``) with:
|
|
5
|
+
|
|
6
|
+
* Crisp inline SVG rendered directly from ``Explanation.fig`` under its theme.
|
|
7
|
+
* Automatic light/dark surface theming matching ``Explanation.theme``.
|
|
8
|
+
* Interactive toolbar, toggleable Facts & Data drawer (computed panel facts +
|
|
9
|
+
raw spec data tables), Download SVG, Copy Spec JSON, and a "Critique / Ask
|
|
10
|
+
Agent" panel that generates structured feedback JSON and ``mint.edit(...)``
|
|
11
|
+
snippets.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import hashlib
|
|
17
|
+
import html
|
|
18
|
+
import io
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import re
|
|
22
|
+
from collections.abc import Mapping, Sequence
|
|
23
|
+
from typing import Any
|
|
24
|
+
|
|
25
|
+
from ._explain.core import Panel, _GlyphCapture
|
|
26
|
+
from ._explain.layout import Explanation, explain_from_spec
|
|
27
|
+
from .themes import Theme, relative_luminance
|
|
28
|
+
|
|
29
|
+
__all__ = ["render_html", "render_html_fragment"]
|
|
30
|
+
|
|
31
|
+
_XML_DECL_RE = re.compile(r"^\s*<\?xml[^>]*\?>\s*", re.IGNORECASE)
|
|
32
|
+
_DOCTYPE_RE = re.compile(r"^\s*<!DOCTYPE[^>]*>\s*", re.IGNORECASE)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _ensure_explanation(exp_or_spec: Explanation | Mapping[str, Any]) -> Explanation:
|
|
36
|
+
"""Resolve an ``Explanation`` instance or build one from a JSON spec dict."""
|
|
37
|
+
if isinstance(exp_or_spec, Explanation):
|
|
38
|
+
return exp_or_spec
|
|
39
|
+
if isinstance(exp_or_spec, Mapping):
|
|
40
|
+
return explain_from_spec(exp_or_spec)
|
|
41
|
+
raise TypeError(
|
|
42
|
+
"Expected an Explanation or a spec mapping, "
|
|
43
|
+
f"got {type(exp_or_spec).__name__}."
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _safe_json_for_script(obj: Any) -> str:
|
|
48
|
+
"""Serialize ``obj`` to JSON safe for embedding inside an HTML ``<script>`` tag.
|
|
49
|
+
|
|
50
|
+
Replaces ``<``, ``>``, ``&``, and Unicode line separators so untrusted data
|
|
51
|
+
can never terminate a ``<script>`` block or inject HTML comments.
|
|
52
|
+
"""
|
|
53
|
+
raw = json.dumps(obj, ensure_ascii=False, indent=2)
|
|
54
|
+
return (
|
|
55
|
+
raw.replace("&", "\\u0026")
|
|
56
|
+
.replace("<", "\\u003c")
|
|
57
|
+
.replace(">", "\\u003e")
|
|
58
|
+
.replace("\u2028", "\\u2028")
|
|
59
|
+
.replace("\u2029", "\\u2029")
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _render_inline_svg(exp: Explanation) -> str:
|
|
64
|
+
"""Export ``exp.fig`` to a clean, embeddable inline ``<svg>`` string."""
|
|
65
|
+
buf = io.BytesIO()
|
|
66
|
+
with exp.theme.rc_context(exp.spec), _GlyphCapture():
|
|
67
|
+
exp.fig.savefig(
|
|
68
|
+
buf,
|
|
69
|
+
format="svg",
|
|
70
|
+
facecolor=exp.theme.background,
|
|
71
|
+
edgecolor=exp.theme.background,
|
|
72
|
+
)
|
|
73
|
+
svg = buf.getvalue().decode("utf-8")
|
|
74
|
+
svg = _XML_DECL_RE.sub("", svg)
|
|
75
|
+
svg = _DOCTYPE_RE.sub("", svg)
|
|
76
|
+
return svg.strip()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _fmt_cell(val: Any) -> str:
|
|
80
|
+
"""Format a scalar cell cleanly for data-drawer tables."""
|
|
81
|
+
if val is None:
|
|
82
|
+
return "—"
|
|
83
|
+
if isinstance(val, bool):
|
|
84
|
+
return "true" if val else "false"
|
|
85
|
+
if isinstance(val, float):
|
|
86
|
+
if not math.isfinite(val):
|
|
87
|
+
return "—"
|
|
88
|
+
if abs(val - round(val)) < 1e-9 and abs(val) < 1e12:
|
|
89
|
+
return f"{round(val):,}"
|
|
90
|
+
return f"{val:.4g}"
|
|
91
|
+
if isinstance(val, int):
|
|
92
|
+
return f"{val:,}"
|
|
93
|
+
return str(val)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _is_numeric_cell(val: Any) -> bool:
|
|
97
|
+
if isinstance(val, bool) or val is None:
|
|
98
|
+
return False
|
|
99
|
+
if isinstance(val, (int, float)):
|
|
100
|
+
return math.isfinite(float(val))
|
|
101
|
+
return False
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _panel_data_table(panel: Panel) -> tuple[list[str], list[list[str]], list[bool], str | None]:
|
|
105
|
+
"""Extract ``(headers, rows, numeric_flags, note)`` from a panel's spec."""
|
|
106
|
+
spec = panel.spec
|
|
107
|
+
kind = panel.kind
|
|
108
|
+
unit_suffix = f" ({panel.unit})" if panel.unit else ""
|
|
109
|
+
|
|
110
|
+
if kind == "compare":
|
|
111
|
+
values = spec.get("values")
|
|
112
|
+
if isinstance(values, Mapping) and values:
|
|
113
|
+
first_val = next(iter(values.values()))
|
|
114
|
+
if isinstance(first_val, Mapping):
|
|
115
|
+
series_names: list[str] = []
|
|
116
|
+
for sub in values.values():
|
|
117
|
+
if isinstance(sub, Mapping):
|
|
118
|
+
for sk in sub:
|
|
119
|
+
if str(sk) not in series_names:
|
|
120
|
+
series_names.append(str(sk))
|
|
121
|
+
headers = ["Item", *[f"{s}{unit_suffix}" for s in series_names]]
|
|
122
|
+
rows = [
|
|
123
|
+
[
|
|
124
|
+
str(item),
|
|
125
|
+
*[_fmt_cell(sub.get(s) if isinstance(sub, Mapping) else None) for s in series_names],
|
|
126
|
+
]
|
|
127
|
+
for item, sub in values.items()
|
|
128
|
+
]
|
|
129
|
+
return headers, rows, [False, *([True] * len(series_names))], None
|
|
130
|
+
items = list(values.items())
|
|
131
|
+
if spec.get("sort", True):
|
|
132
|
+
items.sort(
|
|
133
|
+
key=lambda kv: float(kv[1]) if _is_numeric_cell(kv[1]) else float("-inf"),
|
|
134
|
+
reverse=True,
|
|
135
|
+
)
|
|
136
|
+
val_col = (panel.label or "Value") + unit_suffix
|
|
137
|
+
headers = ["Item", val_col]
|
|
138
|
+
rows = [[str(k), _fmt_cell(v)] for k, v in items]
|
|
139
|
+
return headers, rows, [False, True], None
|
|
140
|
+
|
|
141
|
+
if kind == "share":
|
|
142
|
+
parts = spec.get("parts")
|
|
143
|
+
if isinstance(parts, Mapping) and parts:
|
|
144
|
+
items = sorted(
|
|
145
|
+
parts.items(),
|
|
146
|
+
key=lambda kv: float(kv[1]) if _is_numeric_cell(kv[1]) else float("-inf"),
|
|
147
|
+
reverse=True,
|
|
148
|
+
)
|
|
149
|
+
total = sum(float(v) for _, v in items if _is_numeric_cell(v))
|
|
150
|
+
val_col = (panel.label or "Value") + unit_suffix
|
|
151
|
+
headers = ["Part", val_col, "Share"]
|
|
152
|
+
rows = []
|
|
153
|
+
for k, v in items:
|
|
154
|
+
pct = f"{(float(v) / total * 100.0):.1f}%" if total > 0 and _is_numeric_cell(v) else "—"
|
|
155
|
+
rows.append([str(k), _fmt_cell(v), pct])
|
|
156
|
+
return headers, rows, [False, True, True], None
|
|
157
|
+
|
|
158
|
+
if kind == "table":
|
|
159
|
+
cols = [str(c) for c in (spec.get("columns") or [])]
|
|
160
|
+
raw_rows = spec.get("rows") or []
|
|
161
|
+
if cols and isinstance(raw_rows, Sequence):
|
|
162
|
+
num_flags = []
|
|
163
|
+
for c_idx in range(len(cols)):
|
|
164
|
+
col_vals = [r[c_idx] for r in raw_rows if isinstance(r, Sequence) and c_idx < len(r)]
|
|
165
|
+
num_flags.append(bool(col_vals) and all(_is_numeric_cell(v) or v is None for v in col_vals))
|
|
166
|
+
rows = [
|
|
167
|
+
[_fmt_cell(r[c]) if c < len(r) else "—" for c in range(len(cols))]
|
|
168
|
+
for r in raw_rows
|
|
169
|
+
if isinstance(r, Sequence)
|
|
170
|
+
]
|
|
171
|
+
return cols, rows, num_flags, None
|
|
172
|
+
|
|
173
|
+
if kind == "trend":
|
|
174
|
+
x_vals = spec.get("x") or []
|
|
175
|
+
series = spec.get("series")
|
|
176
|
+
x_hdr = str(spec.get("x_label") or "x")
|
|
177
|
+
if isinstance(series, Mapping) and series:
|
|
178
|
+
names = [str(k) for k in series]
|
|
179
|
+
headers = [x_hdr, *[f"{n}{unit_suffix}" for n in names]]
|
|
180
|
+
n_rows = max((len(v) for v in series.values() if isinstance(v, Sequence)), default=0)
|
|
181
|
+
max_show = 40
|
|
182
|
+
rows = []
|
|
183
|
+
for idx in range(min(n_rows, max_show)):
|
|
184
|
+
xv = _fmt_cell(x_vals[idx]) if idx < len(x_vals) else str(idx)
|
|
185
|
+
row = [xv]
|
|
186
|
+
for n in names:
|
|
187
|
+
seq = series.get(n)
|
|
188
|
+
val = seq[idx] if isinstance(seq, Sequence) and idx < len(seq) else None
|
|
189
|
+
row.append(_fmt_cell(val))
|
|
190
|
+
rows.append(row)
|
|
191
|
+
note = f"Showing first {max_show} of {n_rows} points." if n_rows > max_show else None
|
|
192
|
+
return headers, rows, [False, *([True] * len(names))], note
|
|
193
|
+
if isinstance(series, Sequence) and not isinstance(series, (str, bytes)):
|
|
194
|
+
val_col = (panel.label or "Value") + unit_suffix
|
|
195
|
+
headers = [x_hdr, val_col]
|
|
196
|
+
max_show = 40
|
|
197
|
+
rows = [
|
|
198
|
+
[_fmt_cell(x_vals[i]) if i < len(x_vals) else str(i), _fmt_cell(series[i])]
|
|
199
|
+
for i in range(min(len(series), max_show))
|
|
200
|
+
]
|
|
201
|
+
note = f"Showing first {max_show} of {len(series)} points." if len(series) > max_show else None
|
|
202
|
+
return headers, rows, [False, True], note
|
|
203
|
+
points = spec.get("points")
|
|
204
|
+
if isinstance(points, Mapping) and points:
|
|
205
|
+
raw_names = [str(k) for k in points]
|
|
206
|
+
disp_names = [n if n else (panel.label or "Value") for n in raw_names]
|
|
207
|
+
headers = [x_hdr, *[f"{dn}{unit_suffix}" for dn in disp_names]]
|
|
208
|
+
n_rows = max(
|
|
209
|
+
(len(v) for v in points.values() if isinstance(v, Sequence)),
|
|
210
|
+
default=0,
|
|
211
|
+
)
|
|
212
|
+
max_show = 40
|
|
213
|
+
rows = []
|
|
214
|
+
for idx in range(min(n_rows, max_show)):
|
|
215
|
+
xv = _fmt_cell(x_vals[idx]) if idx < len(x_vals) else str(idx)
|
|
216
|
+
row = [xv]
|
|
217
|
+
for rname in raw_names:
|
|
218
|
+
buckets = points.get(rname)
|
|
219
|
+
mean_val: float | None = None
|
|
220
|
+
if isinstance(buckets, Sequence) and idx < len(buckets):
|
|
221
|
+
bucket = buckets[idx]
|
|
222
|
+
if isinstance(bucket, Sequence) and not isinstance(bucket, (str, bytes)):
|
|
223
|
+
nums = [float(v) for v in bucket if _is_numeric_cell(v)]
|
|
224
|
+
if nums:
|
|
225
|
+
mean_val = sum(nums) / len(nums)
|
|
226
|
+
elif _is_numeric_cell(bucket):
|
|
227
|
+
mean_val = float(bucket)
|
|
228
|
+
row.append(_fmt_cell(mean_val))
|
|
229
|
+
rows.append(row)
|
|
230
|
+
note = (
|
|
231
|
+
f"Showing per-x replicate means (first {max_show} of {n_rows} points)."
|
|
232
|
+
if n_rows > max_show
|
|
233
|
+
else "Values show per-x replicate means."
|
|
234
|
+
)
|
|
235
|
+
return headers, rows, [False, *([True] * len(raw_names))], note
|
|
236
|
+
|
|
237
|
+
if kind == "matrix":
|
|
238
|
+
r_labels = [str(r) for r in (spec.get("rows") or [])]
|
|
239
|
+
c_labels = [str(c) for c in (spec.get("cols") or [])]
|
|
240
|
+
vals = spec.get("values") or []
|
|
241
|
+
if c_labels and isinstance(vals, Sequence):
|
|
242
|
+
headers = ["", *c_labels]
|
|
243
|
+
rows = []
|
|
244
|
+
for r_idx, row_vals in enumerate(vals):
|
|
245
|
+
rl = r_labels[r_idx] if r_idx < len(r_labels) else f"r{r_idx + 1}"
|
|
246
|
+
if isinstance(row_vals, Sequence):
|
|
247
|
+
rows.append([rl, *[_fmt_cell(v) for v in row_vals]])
|
|
248
|
+
return headers, rows, [False, *([True] * len(c_labels))], None
|
|
249
|
+
|
|
250
|
+
if kind == "change":
|
|
251
|
+
before = spec.get("before") or {}
|
|
252
|
+
after = spec.get("after") or {}
|
|
253
|
+
labels = spec.get("labels") or ["Before", "After"]
|
|
254
|
+
lbl_b = str(labels[0]) if len(labels) >= 1 else "Before"
|
|
255
|
+
lbl_a = str(labels[1]) if len(labels) >= 2 else "After"
|
|
256
|
+
if isinstance(before, Mapping) and isinstance(after, Mapping):
|
|
257
|
+
headers = ["Item", f"{lbl_b}{unit_suffix}", f"{lbl_a}{unit_suffix}", f"Delta{unit_suffix}"]
|
|
258
|
+
rows = []
|
|
259
|
+
for item, bv in before.items():
|
|
260
|
+
av = after.get(item)
|
|
261
|
+
if _is_numeric_cell(bv) and _is_numeric_cell(av):
|
|
262
|
+
delta = float(av) - float(bv)
|
|
263
|
+
delta_str = f"{delta:+.4g}" if abs(delta) < 1e12 else _fmt_cell(delta)
|
|
264
|
+
else:
|
|
265
|
+
delta_str = "—"
|
|
266
|
+
rows.append([str(item), _fmt_cell(bv), _fmt_cell(av), delta_str])
|
|
267
|
+
return headers, rows, [False, True, True, True], None
|
|
268
|
+
|
|
269
|
+
if kind == "distribution":
|
|
270
|
+
groups = spec.get("groups")
|
|
271
|
+
if isinstance(groups, Mapping):
|
|
272
|
+
headers = ["Group", "n", f"Min{unit_suffix}", f"Median{unit_suffix}", f"Max{unit_suffix}"]
|
|
273
|
+
rows = []
|
|
274
|
+
for gname, vals in groups.items():
|
|
275
|
+
nums = sorted(float(v) for v in vals if _is_numeric_cell(v))
|
|
276
|
+
if nums:
|
|
277
|
+
mid = len(nums) // 2
|
|
278
|
+
med = nums[mid] if len(nums) % 2 else 0.5 * (nums[mid - 1] + nums[mid])
|
|
279
|
+
rows.append([str(gname), str(len(nums)), _fmt_cell(nums[0]), _fmt_cell(med), _fmt_cell(nums[-1])])
|
|
280
|
+
return headers, rows, [False, True, True, True, True], None
|
|
281
|
+
if isinstance(groups, Sequence) and not isinstance(groups, (str, bytes)):
|
|
282
|
+
nums = sorted(float(v) for v in groups if _is_numeric_cell(v))
|
|
283
|
+
if nums:
|
|
284
|
+
mid = len(nums) // 2
|
|
285
|
+
med = nums[mid] if len(nums) % 2 else 0.5 * (nums[mid - 1] + nums[mid])
|
|
286
|
+
headers = ["Series", "n", f"Min{unit_suffix}", f"Median{unit_suffix}", f"Max{unit_suffix}"]
|
|
287
|
+
rows = [[panel.label or "Values", str(len(nums)), _fmt_cell(nums[0]), _fmt_cell(med), _fmt_cell(nums[-1])]]
|
|
288
|
+
return headers, rows, [False, True, True, True, True], None
|
|
289
|
+
|
|
290
|
+
if kind == "relate":
|
|
291
|
+
xs = spec.get("x") or []
|
|
292
|
+
ys = spec.get("y") or []
|
|
293
|
+
names = spec.get("names")
|
|
294
|
+
groups = spec.get("groups")
|
|
295
|
+
xh = str(spec.get("x_label") or "x")
|
|
296
|
+
yh = str(spec.get("y_label") or panel.label or "y") + unit_suffix
|
|
297
|
+
headers = []
|
|
298
|
+
num_flags = []
|
|
299
|
+
if names:
|
|
300
|
+
headers.append("Name")
|
|
301
|
+
num_flags.append(False)
|
|
302
|
+
headers.extend([xh, yh])
|
|
303
|
+
num_flags.extend([True, True])
|
|
304
|
+
if groups:
|
|
305
|
+
headers.append("Group")
|
|
306
|
+
num_flags.append(False)
|
|
307
|
+
n = min(len(xs), len(ys))
|
|
308
|
+
max_show = 40
|
|
309
|
+
rows = []
|
|
310
|
+
for i in range(min(n, max_show)):
|
|
311
|
+
row = []
|
|
312
|
+
if names:
|
|
313
|
+
row.append(str(names[i]) if i < len(names) else "")
|
|
314
|
+
row.extend([_fmt_cell(xs[i]), _fmt_cell(ys[i])])
|
|
315
|
+
if groups:
|
|
316
|
+
row.append(str(groups[i]) if i < len(groups) else "")
|
|
317
|
+
rows.append(row)
|
|
318
|
+
note = f"Showing first {max_show} of {n} observations." if n > max_show else None
|
|
319
|
+
return headers, rows, num_flags, note
|
|
320
|
+
|
|
321
|
+
if kind == "waterfall":
|
|
322
|
+
steps = spec.get("steps") or {}
|
|
323
|
+
if isinstance(steps, Mapping) and steps:
|
|
324
|
+
rows = []
|
|
325
|
+
running = 0.0
|
|
326
|
+
start_val = spec.get("start")
|
|
327
|
+
if isinstance(start_val, Sequence) and not isinstance(start_val, (str, bytes)) and len(start_val) == 2:
|
|
328
|
+
running = float(start_val[1])
|
|
329
|
+
rows.append([str(start_val[0]), "—", _fmt_cell(running)])
|
|
330
|
+
for step_nm, delta in steps.items():
|
|
331
|
+
d_val = float(delta)
|
|
332
|
+
running += d_val
|
|
333
|
+
sign = "+" if d_val > 0 else ""
|
|
334
|
+
rows.append([str(step_nm), f"{sign}{_fmt_cell(d_val)}", _fmt_cell(running)])
|
|
335
|
+
if spec.get("show_total", True):
|
|
336
|
+
rows.append([str(spec.get("total_label") or "Total"), "—", _fmt_cell(running)])
|
|
337
|
+
return (
|
|
338
|
+
["Step", f"Delta{unit_suffix}", f"Cumulative{unit_suffix}"],
|
|
339
|
+
rows,
|
|
340
|
+
[False, True, True],
|
|
341
|
+
None,
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
if kind == "timeline":
|
|
345
|
+
spans = spec.get("spans") or []
|
|
346
|
+
if isinstance(spans, Sequence) and spans:
|
|
347
|
+
has_group = any(isinstance(s, Sequence) and len(s) >= 4 and s[3] is not None for s in spans)
|
|
348
|
+
headers = ["Stage", f"Start{unit_suffix}", f"End{unit_suffix}", f"Duration{unit_suffix}"]
|
|
349
|
+
num_flags = [False, True, True, True]
|
|
350
|
+
if has_group:
|
|
351
|
+
headers.append("Group")
|
|
352
|
+
num_flags.append(False)
|
|
353
|
+
rows = []
|
|
354
|
+
for sp in spans:
|
|
355
|
+
if not isinstance(sp, Sequence) or len(sp) < 3:
|
|
356
|
+
continue
|
|
357
|
+
dur = float(sp[2]) - float(sp[1])
|
|
358
|
+
row = [str(sp[0]), _fmt_cell(sp[1]), _fmt_cell(sp[2]), _fmt_cell(dur)]
|
|
359
|
+
if has_group:
|
|
360
|
+
row.append(str(sp[3]) if len(sp) >= 4 and sp[3] is not None else "—")
|
|
361
|
+
rows.append(row)
|
|
362
|
+
return headers, rows, num_flags, None
|
|
363
|
+
|
|
364
|
+
if kind == "flow":
|
|
365
|
+
stages = spec.get("stages") or []
|
|
366
|
+
if isinstance(stages, Sequence) and stages:
|
|
367
|
+
has_reason = any(isinstance(s, Sequence) and len(s) >= 3 and s[2] for s in stages[1:])
|
|
368
|
+
headers = ["Stage", f"Remaining{unit_suffix}", "% of start", "Step change"]
|
|
369
|
+
num_flags = [False, True, True, True]
|
|
370
|
+
if has_reason:
|
|
371
|
+
headers.append("Reason")
|
|
372
|
+
num_flags.append(False)
|
|
373
|
+
rows = []
|
|
374
|
+
start_v = float(stages[0][1]) if isinstance(stages[0], Sequence) and len(stages[0]) >= 2 else 1.0
|
|
375
|
+
prev_v: float | None = None
|
|
376
|
+
for idx_s, st in enumerate(stages):
|
|
377
|
+
if not isinstance(st, Sequence) or len(st) < 2:
|
|
378
|
+
continue
|
|
379
|
+
val = float(st[1])
|
|
380
|
+
pct = f"{(100.0 * val / start_v):.1f}%" if start_v > 0 else "—"
|
|
381
|
+
if prev_v is None:
|
|
382
|
+
chg = "—"
|
|
383
|
+
else:
|
|
384
|
+
d = val - prev_v
|
|
385
|
+
sign = "+" if d > 0 else ""
|
|
386
|
+
chg = f"{sign}{_fmt_cell(d)}"
|
|
387
|
+
row = [str(st[0]), _fmt_cell(val), pct, chg]
|
|
388
|
+
if has_reason:
|
|
389
|
+
row.append(str(st[2]) if idx_s > 0 and len(st) >= 3 and st[2] else "—")
|
|
390
|
+
rows.append(row)
|
|
391
|
+
prev_v = val
|
|
392
|
+
return headers, rows, num_flags, None
|
|
393
|
+
|
|
394
|
+
return [], [], [], None
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _render_table_html(
|
|
398
|
+
headers: list[str],
|
|
399
|
+
rows: list[list[str]],
|
|
400
|
+
num_flags: list[bool],
|
|
401
|
+
note: str | None = None,
|
|
402
|
+
) -> str:
|
|
403
|
+
if not headers or not rows:
|
|
404
|
+
return ""
|
|
405
|
+
th_cells = "".join(
|
|
406
|
+
('<th class="fm-num">' if num_flags[i] else "<th>") + f"{html.escape(h, quote=True)}</th>"
|
|
407
|
+
for i, h in enumerate(headers)
|
|
408
|
+
)
|
|
409
|
+
body_rows = []
|
|
410
|
+
for row in rows:
|
|
411
|
+
td_cells = "".join(
|
|
412
|
+
('<td class="fm-num">' if i < len(num_flags) and num_flags[i] else "<td>")
|
|
413
|
+
+ f"{html.escape(cell, quote=True)}</td>"
|
|
414
|
+
for i, cell in enumerate(row)
|
|
415
|
+
)
|
|
416
|
+
body_rows.append(f"<tr>{td_cells}</tr>")
|
|
417
|
+
note_html = (
|
|
418
|
+
f'<p class="fm-table-note">{html.escape(note, quote=True)}</p>' if note else ""
|
|
419
|
+
)
|
|
420
|
+
return (
|
|
421
|
+
'<div class="fm-table-wrap">'
|
|
422
|
+
'<table class="fm-data-table">'
|
|
423
|
+
f"<thead><tr>{th_cells}</tr></thead>"
|
|
424
|
+
f"<tbody>{''.join(body_rows)}</tbody>"
|
|
425
|
+
"</table>"
|
|
426
|
+
f"{note_html}"
|
|
427
|
+
"</div>"
|
|
428
|
+
)
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
def _theme_tokens(theme: Theme) -> dict[str, str]:
|
|
432
|
+
"""Derive light- or dark-aware UI surface tokens from ``theme``."""
|
|
433
|
+
is_dark = relative_luminance(theme.background) < 0.2
|
|
434
|
+
accent = theme.accent_colors[0] if theme.accent_colors else "#CD4324"
|
|
435
|
+
primary = theme.series_colors[0] if theme.series_colors else "#1F5A9D"
|
|
436
|
+
if is_dark:
|
|
437
|
+
surface = "#1C222C"
|
|
438
|
+
surface_alt = "#232A36"
|
|
439
|
+
border = theme.grid if theme.grid != theme.background else "#2E3746"
|
|
440
|
+
button_bg = "#252D3A"
|
|
441
|
+
button_hover = "#303A4B"
|
|
442
|
+
input_bg = "#11151B"
|
|
443
|
+
shadow = "0 10px 30px rgba(0, 0, 0, 0.45)"
|
|
444
|
+
mode = "dark"
|
|
445
|
+
else:
|
|
446
|
+
surface = "#F7F8FA" if theme.background.upper() == "#FFFFFF" else theme.background
|
|
447
|
+
surface_alt = "#EFF2F6" if theme.background.upper() == "#FFFFFF" else "#E9E5DC"
|
|
448
|
+
border = theme.grid if theme.grid != theme.background else "#D9DFE6"
|
|
449
|
+
button_bg = "#FFFFFF"
|
|
450
|
+
button_hover = "#EEF2F6"
|
|
451
|
+
input_bg = "#FFFFFF"
|
|
452
|
+
shadow = "0 6px 24px rgba(15, 23, 42, 0.08)"
|
|
453
|
+
mode = "light"
|
|
454
|
+
return {
|
|
455
|
+
"mode": mode,
|
|
456
|
+
"bg": theme.background,
|
|
457
|
+
"ink": theme.ink,
|
|
458
|
+
"muted": theme.muted,
|
|
459
|
+
"axis": theme.axis,
|
|
460
|
+
"grid": theme.grid,
|
|
461
|
+
"accent": accent,
|
|
462
|
+
"primary": primary,
|
|
463
|
+
"surface": surface,
|
|
464
|
+
"surface_alt": surface_alt,
|
|
465
|
+
"border": border,
|
|
466
|
+
"button_bg": button_bg,
|
|
467
|
+
"button_hover": button_hover,
|
|
468
|
+
"input_bg": input_bg,
|
|
469
|
+
"shadow": shadow,
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def _css_block(root_id: str, tokens: dict[str, str], max_width_px: int) -> str:
|
|
474
|
+
sel = f"#{root_id}"
|
|
475
|
+
return f"""<style>
|
|
476
|
+
{sel} {{
|
|
477
|
+
--fm-bg: {tokens['bg']};
|
|
478
|
+
--fm-ink: {tokens['ink']};
|
|
479
|
+
--fm-muted: {tokens['muted']};
|
|
480
|
+
--fm-border: {tokens['border']};
|
|
481
|
+
--fm-surface: {tokens['surface']};
|
|
482
|
+
--fm-surface-alt: {tokens['surface_alt']};
|
|
483
|
+
--fm-accent: {tokens['accent']};
|
|
484
|
+
--fm-primary: {tokens['primary']};
|
|
485
|
+
--fm-btn-bg: {tokens['button_bg']};
|
|
486
|
+
--fm-btn-hover: {tokens['button_hover']};
|
|
487
|
+
--fm-input-bg: {tokens['input_bg']};
|
|
488
|
+
--fm-shadow: {tokens['shadow']};
|
|
489
|
+
color: var(--fm-ink);
|
|
490
|
+
background: var(--fm-bg);
|
|
491
|
+
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
|
|
492
|
+
max-width: {max_width_px}px;
|
|
493
|
+
margin: 0 auto;
|
|
494
|
+
border: 1px solid var(--fm-border);
|
|
495
|
+
border-radius: 10px;
|
|
496
|
+
box-shadow: var(--fm-shadow);
|
|
497
|
+
overflow: hidden;
|
|
498
|
+
box-sizing: border-box;
|
|
499
|
+
}}
|
|
500
|
+
{sel} *, {sel} *::before, {sel} *::after {{ box-sizing: border-box; }}
|
|
501
|
+
{sel} .fm-figure-stage {{
|
|
502
|
+
background: var(--fm-bg);
|
|
503
|
+
padding: 12px 12px 8px;
|
|
504
|
+
}}
|
|
505
|
+
{sel} .fm-svg-wrap {{
|
|
506
|
+
width: 100%;
|
|
507
|
+
overflow-x: auto;
|
|
508
|
+
}}
|
|
509
|
+
{sel} .fm-svg-wrap svg {{
|
|
510
|
+
width: 100%;
|
|
511
|
+
height: auto;
|
|
512
|
+
display: block;
|
|
513
|
+
}}
|
|
514
|
+
{sel} .fm-toolbar {{
|
|
515
|
+
display: flex;
|
|
516
|
+
flex-wrap: wrap;
|
|
517
|
+
align-items: center;
|
|
518
|
+
justify-content: space-between;
|
|
519
|
+
gap: 8px;
|
|
520
|
+
padding: 10px 14px;
|
|
521
|
+
background: var(--fm-surface);
|
|
522
|
+
border-top: 1px solid var(--fm-border);
|
|
523
|
+
font-size: 12.5px;
|
|
524
|
+
}}
|
|
525
|
+
{sel} .fm-toolbar-group {{
|
|
526
|
+
display: flex;
|
|
527
|
+
flex-wrap: wrap;
|
|
528
|
+
align-items: center;
|
|
529
|
+
gap: 6px;
|
|
530
|
+
}}
|
|
531
|
+
{sel} .fm-btn {{
|
|
532
|
+
appearance: none;
|
|
533
|
+
border: 1px solid var(--fm-border);
|
|
534
|
+
background: var(--fm-btn-bg);
|
|
535
|
+
color: var(--fm-ink);
|
|
536
|
+
padding: 5px 10px;
|
|
537
|
+
border-radius: 6px;
|
|
538
|
+
font-size: 12px;
|
|
539
|
+
font-weight: 500;
|
|
540
|
+
cursor: pointer;
|
|
541
|
+
transition: background 0.12s ease, border-color 0.12s ease;
|
|
542
|
+
}}
|
|
543
|
+
{sel} .fm-btn:hover {{
|
|
544
|
+
background: var(--fm-btn-hover);
|
|
545
|
+
border-color: var(--fm-muted);
|
|
546
|
+
}}
|
|
547
|
+
{sel} .fm-btn[aria-expanded="true"], {sel} .fm-btn-accent {{
|
|
548
|
+
border-color: var(--fm-accent);
|
|
549
|
+
color: var(--fm-accent);
|
|
550
|
+
}}
|
|
551
|
+
{sel} .fm-status {{
|
|
552
|
+
font-size: 11.5px;
|
|
553
|
+
color: var(--fm-muted);
|
|
554
|
+
margin-left: 4px;
|
|
555
|
+
}}
|
|
556
|
+
{sel} .fm-drawer {{
|
|
557
|
+
border-top: 1px solid var(--fm-border);
|
|
558
|
+
background: var(--fm-surface);
|
|
559
|
+
padding: 14px 16px;
|
|
560
|
+
font-size: 13px;
|
|
561
|
+
line-height: 1.45;
|
|
562
|
+
}}
|
|
563
|
+
{sel} .fm-drawer[hidden] {{ display: none; }}
|
|
564
|
+
{sel} .fm-drawer h3 {{
|
|
565
|
+
margin: 0 0 10px;
|
|
566
|
+
font-size: 13.5px;
|
|
567
|
+
font-weight: 600;
|
|
568
|
+
color: var(--fm-ink);
|
|
569
|
+
}}
|
|
570
|
+
{sel} .fm-panel-card {{
|
|
571
|
+
background: var(--fm-bg);
|
|
572
|
+
border: 1px solid var(--fm-border);
|
|
573
|
+
border-radius: 8px;
|
|
574
|
+
padding: 10px 12px;
|
|
575
|
+
margin-bottom: 10px;
|
|
576
|
+
}}
|
|
577
|
+
{sel} .fm-panel-card:last-child {{ margin-bottom: 0; }}
|
|
578
|
+
{sel} .fm-panel-head {{
|
|
579
|
+
display: flex;
|
|
580
|
+
flex-wrap: wrap;
|
|
581
|
+
align-items: baseline;
|
|
582
|
+
gap: 8px;
|
|
583
|
+
margin-bottom: 6px;
|
|
584
|
+
}}
|
|
585
|
+
{sel} .fm-badge {{
|
|
586
|
+
display: inline-block;
|
|
587
|
+
font-size: 11px;
|
|
588
|
+
font-weight: 600;
|
|
589
|
+
padding: 1px 6px;
|
|
590
|
+
border-radius: 4px;
|
|
591
|
+
background: var(--fm-surface-alt);
|
|
592
|
+
color: var(--fm-accent);
|
|
593
|
+
border: 1px solid var(--fm-border);
|
|
594
|
+
}}
|
|
595
|
+
{sel} .fm-panel-title {{
|
|
596
|
+
font-weight: 600;
|
|
597
|
+
color: var(--fm-ink);
|
|
598
|
+
}}
|
|
599
|
+
{sel} .fm-panel-kind {{
|
|
600
|
+
font-size: 11.5px;
|
|
601
|
+
color: var(--fm-muted);
|
|
602
|
+
}}
|
|
603
|
+
{sel} .fm-facts {{
|
|
604
|
+
margin: 6px 0 8px 18px;
|
|
605
|
+
padding: 0;
|
|
606
|
+
color: var(--fm-ink);
|
|
607
|
+
}}
|
|
608
|
+
{sel} .fm-facts li {{ margin-bottom: 3px; }}
|
|
609
|
+
{sel} .fm-table-wrap {{
|
|
610
|
+
overflow-x: auto;
|
|
611
|
+
margin-top: 6px;
|
|
612
|
+
}}
|
|
613
|
+
{sel} .fm-data-table {{
|
|
614
|
+
width: 100%;
|
|
615
|
+
border-collapse: collapse;
|
|
616
|
+
font-size: 12px;
|
|
617
|
+
font-variant-numeric: tabular-nums;
|
|
618
|
+
}}
|
|
619
|
+
{sel} .fm-data-table th, {sel} .fm-data-table td {{
|
|
620
|
+
text-align: left;
|
|
621
|
+
padding: 4px 8px;
|
|
622
|
+
border-bottom: 1px solid var(--fm-border);
|
|
623
|
+
color: var(--fm-ink);
|
|
624
|
+
}}
|
|
625
|
+
{sel} .fm-data-table th {{
|
|
626
|
+
font-weight: 600;
|
|
627
|
+
color: var(--fm-muted);
|
|
628
|
+
background: var(--fm-surface);
|
|
629
|
+
}}
|
|
630
|
+
{sel} .fm-data-table th.fm-num, {sel} .fm-data-table td.fm-num {{
|
|
631
|
+
text-align: right;
|
|
632
|
+
}}
|
|
633
|
+
{sel} .fm-table-note {{
|
|
634
|
+
margin: 4px 0 0;
|
|
635
|
+
font-size: 11px;
|
|
636
|
+
color: var(--fm-muted);
|
|
637
|
+
}}
|
|
638
|
+
{sel} .fm-meta-row {{
|
|
639
|
+
display: flex;
|
|
640
|
+
flex-wrap: wrap;
|
|
641
|
+
gap: 12px;
|
|
642
|
+
margin-top: 10px;
|
|
643
|
+
font-size: 11.5px;
|
|
644
|
+
color: var(--fm-muted);
|
|
645
|
+
}}
|
|
646
|
+
{sel} .fm-critique-grid {{
|
|
647
|
+
display: grid;
|
|
648
|
+
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
|
649
|
+
gap: 10px;
|
|
650
|
+
margin-bottom: 10px;
|
|
651
|
+
}}
|
|
652
|
+
{sel} .fm-field label {{
|
|
653
|
+
display: block;
|
|
654
|
+
font-size: 11.5px;
|
|
655
|
+
font-weight: 600;
|
|
656
|
+
color: var(--fm-muted);
|
|
657
|
+
margin-bottom: 4px;
|
|
658
|
+
}}
|
|
659
|
+
{sel} .fm-field select, {sel} .fm-field textarea {{
|
|
660
|
+
width: 100%;
|
|
661
|
+
background: var(--fm-input-bg);
|
|
662
|
+
color: var(--fm-ink);
|
|
663
|
+
border: 1px solid var(--fm-border);
|
|
664
|
+
border-radius: 6px;
|
|
665
|
+
padding: 6px 8px;
|
|
666
|
+
font-family: inherit;
|
|
667
|
+
font-size: 12.5px;
|
|
668
|
+
}}
|
|
669
|
+
{sel} .fm-field textarea {{
|
|
670
|
+
min-height: 62px;
|
|
671
|
+
resize: vertical;
|
|
672
|
+
}}
|
|
673
|
+
{sel} .fm-preview {{
|
|
674
|
+
background: var(--fm-input-bg);
|
|
675
|
+
border: 1px solid var(--fm-border);
|
|
676
|
+
border-radius: 6px;
|
|
677
|
+
padding: 8px 10px;
|
|
678
|
+
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
|
679
|
+
font-size: 11.5px;
|
|
680
|
+
white-space: pre-wrap;
|
|
681
|
+
word-break: break-word;
|
|
682
|
+
margin: 8px 0;
|
|
683
|
+
color: var(--fm-ink);
|
|
684
|
+
}}
|
|
685
|
+
{sel} .fm-sr-only {{
|
|
686
|
+
position: absolute;
|
|
687
|
+
width: 1px;
|
|
688
|
+
height: 1px;
|
|
689
|
+
padding: 0;
|
|
690
|
+
margin: -1px;
|
|
691
|
+
overflow: hidden;
|
|
692
|
+
clip: rect(0, 0, 0, 0);
|
|
693
|
+
white-space: nowrap;
|
|
694
|
+
border: 0;
|
|
695
|
+
}}
|
|
696
|
+
</style>"""
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def _js_block(root_id: str, spec_json_safe: str, takeaway_json_safe: str) -> str:
|
|
700
|
+
return f"""<script>
|
|
701
|
+
(function() {{
|
|
702
|
+
var root = document.getElementById({json.dumps(root_id)});
|
|
703
|
+
if (!root) return;
|
|
704
|
+
var SPEC = {spec_json_safe};
|
|
705
|
+
var TAKEAWAY = {takeaway_json_safe};
|
|
706
|
+
var statusEl = root.querySelector('[data-fm-status]');
|
|
707
|
+
|
|
708
|
+
function setStatus(msg) {{
|
|
709
|
+
if (!statusEl) return;
|
|
710
|
+
statusEl.textContent = msg;
|
|
711
|
+
window.setTimeout(function() {{
|
|
712
|
+
if (statusEl.textContent === msg) statusEl.textContent = '';
|
|
713
|
+
}}, 2600);
|
|
714
|
+
}}
|
|
715
|
+
|
|
716
|
+
function copyText(text, label) {{
|
|
717
|
+
if (navigator.clipboard && navigator.clipboard.writeText) {{
|
|
718
|
+
navigator.clipboard.writeText(text).then(function() {{
|
|
719
|
+
setStatus('Copied ' + label);
|
|
720
|
+
}}, function() {{
|
|
721
|
+
fallbackCopy(text, label);
|
|
722
|
+
}});
|
|
723
|
+
}} else {{
|
|
724
|
+
fallbackCopy(text, label);
|
|
725
|
+
}}
|
|
726
|
+
}}
|
|
727
|
+
|
|
728
|
+
function fallbackCopy(text, label) {{
|
|
729
|
+
var ta = document.createElement('textarea');
|
|
730
|
+
ta.value = text;
|
|
731
|
+
ta.setAttribute('readonly', '');
|
|
732
|
+
ta.style.position = 'fixed';
|
|
733
|
+
ta.style.opacity = '0';
|
|
734
|
+
document.body.appendChild(ta);
|
|
735
|
+
ta.select();
|
|
736
|
+
try {{
|
|
737
|
+
document.execCommand('copy');
|
|
738
|
+
setStatus('Copied ' + label);
|
|
739
|
+
}} catch (e) {{
|
|
740
|
+
setStatus('Copy failed');
|
|
741
|
+
}}
|
|
742
|
+
document.body.removeChild(ta);
|
|
743
|
+
}}
|
|
744
|
+
|
|
745
|
+
function toggleDrawer(btnAttr, drawerAttr) {{
|
|
746
|
+
var btn = root.querySelector('[' + btnAttr + ']');
|
|
747
|
+
var drawer = root.querySelector('[' + drawerAttr + ']');
|
|
748
|
+
if (!btn || !drawer) return;
|
|
749
|
+
btn.addEventListener('click', function() {{
|
|
750
|
+
var open = drawer.hasAttribute('hidden');
|
|
751
|
+
if (open) {{
|
|
752
|
+
drawer.removeAttribute('hidden');
|
|
753
|
+
btn.setAttribute('aria-expanded', 'true');
|
|
754
|
+
}} else {{
|
|
755
|
+
drawer.setAttribute('hidden', '');
|
|
756
|
+
btn.setAttribute('aria-expanded', 'false');
|
|
757
|
+
}}
|
|
758
|
+
}});
|
|
759
|
+
}}
|
|
760
|
+
|
|
761
|
+
toggleDrawer('data-fm-toggle-facts', 'data-fm-drawer-facts');
|
|
762
|
+
toggleDrawer('data-fm-toggle-critique', 'data-fm-drawer-critique');
|
|
763
|
+
|
|
764
|
+
var dlBtn = root.querySelector('[data-fm-download-svg]');
|
|
765
|
+
if (dlBtn) {{
|
|
766
|
+
dlBtn.addEventListener('click', function() {{
|
|
767
|
+
var svg = root.querySelector('.fm-svg-wrap svg');
|
|
768
|
+
if (!svg) return;
|
|
769
|
+
var xml = new XMLSerializer().serializeToString(svg);
|
|
770
|
+
var blob = new Blob([xml], {{ type: 'image/svg+xml;charset=utf-8' }});
|
|
771
|
+
var url = URL.createObjectURL(blob);
|
|
772
|
+
var a = document.createElement('a');
|
|
773
|
+
a.href = url;
|
|
774
|
+
a.download = 'mintfig-figure.svg';
|
|
775
|
+
document.body.appendChild(a);
|
|
776
|
+
a.click();
|
|
777
|
+
document.body.removeChild(a);
|
|
778
|
+
URL.revokeObjectURL(url);
|
|
779
|
+
setStatus('Downloaded SVG');
|
|
780
|
+
}});
|
|
781
|
+
}}
|
|
782
|
+
|
|
783
|
+
var copySpecBtn = root.querySelector('[data-fm-copy-spec]');
|
|
784
|
+
if (copySpecBtn) {{
|
|
785
|
+
copySpecBtn.addEventListener('click', function() {{
|
|
786
|
+
copyText(JSON.stringify(SPEC, null, 2), 'spec JSON');
|
|
787
|
+
}});
|
|
788
|
+
}}
|
|
789
|
+
|
|
790
|
+
var panelSel = root.querySelector('[data-fm-critique-panel]');
|
|
791
|
+
var actionSel = root.querySelector('[data-fm-critique-action]');
|
|
792
|
+
var noteInput = root.querySelector('[data-fm-critique-note]');
|
|
793
|
+
var previewEl = root.querySelector('[data-fm-critique-preview]');
|
|
794
|
+
var copyJsonBtn = root.querySelector('[data-fm-copy-feedback]');
|
|
795
|
+
var copyEditBtn = root.querySelector('[data-fm-copy-edit]');
|
|
796
|
+
|
|
797
|
+
function buildCritique() {{
|
|
798
|
+
var panel = panelSel ? panelSel.value : 'figure';
|
|
799
|
+
var action = actionSel ? actionSel.value : 'highlight';
|
|
800
|
+
var note = noteInput ? noteInput.value.trim() : '';
|
|
801
|
+
var payload = {{
|
|
802
|
+
target: panel,
|
|
803
|
+
action: action,
|
|
804
|
+
note: note,
|
|
805
|
+
takeaway: TAKEAWAY
|
|
806
|
+
}};
|
|
807
|
+
var snippet = 'mint.edit(fig, panel=' + JSON.stringify(panel) +
|
|
808
|
+
', action=' + JSON.stringify(action) +
|
|
809
|
+
', note=' + JSON.stringify(note) + ')';
|
|
810
|
+
return {{ payload: payload, snippet: snippet }};
|
|
811
|
+
}}
|
|
812
|
+
|
|
813
|
+
function refreshPreview() {{
|
|
814
|
+
if (!previewEl) return;
|
|
815
|
+
var c = buildCritique();
|
|
816
|
+
previewEl.textContent = c.snippet + '\\n\\n' + JSON.stringify(c.payload, null, 2);
|
|
817
|
+
}}
|
|
818
|
+
|
|
819
|
+
[panelSel, actionSel, noteInput].forEach(function(el) {{
|
|
820
|
+
if (el) el.addEventListener('input', refreshPreview);
|
|
821
|
+
if (el) el.addEventListener('change', refreshPreview);
|
|
822
|
+
}});
|
|
823
|
+
refreshPreview();
|
|
824
|
+
|
|
825
|
+
if (copyJsonBtn) {{
|
|
826
|
+
copyJsonBtn.addEventListener('click', function() {{
|
|
827
|
+
copyText(JSON.stringify(buildCritique().payload, null, 2), 'feedback JSON');
|
|
828
|
+
}});
|
|
829
|
+
}}
|
|
830
|
+
if (copyEditBtn) {{
|
|
831
|
+
copyEditBtn.addEventListener('click', function() {{
|
|
832
|
+
copyText(buildCritique().snippet, 'mint.edit(...) snippet');
|
|
833
|
+
}});
|
|
834
|
+
}}
|
|
835
|
+
}})();
|
|
836
|
+
</script>"""
|
|
837
|
+
|
|
838
|
+
|
|
839
|
+
def render_html_fragment(
|
|
840
|
+
exp_or_spec: Explanation | Mapping[str, Any],
|
|
841
|
+
*,
|
|
842
|
+
interactive: bool = True,
|
|
843
|
+
) -> str:
|
|
844
|
+
"""Render a self-contained embeddable HTML fragment (for Jupyter ``_repr_html_()``).
|
|
845
|
+
|
|
846
|
+
Contains zero external CDN references; all CSS, SVG, and vanilla JS are
|
|
847
|
+
inlined and scoped to a unique root container ID.
|
|
848
|
+
"""
|
|
849
|
+
exp = _ensure_explanation(exp_or_spec)
|
|
850
|
+
svg_markup = _render_inline_svg(exp)
|
|
851
|
+
spec_dict = exp.to_spec()
|
|
852
|
+
tokens = _theme_tokens(exp.theme)
|
|
853
|
+
|
|
854
|
+
digest = hashlib.sha256(
|
|
855
|
+
json.dumps(spec_dict, sort_keys=True, ensure_ascii=False).encode("utf-8")
|
|
856
|
+
).hexdigest()[:10]
|
|
857
|
+
root_id = f"fm-{digest}"
|
|
858
|
+
max_width_px = max(480, int(exp.display_width_px) + 48)
|
|
859
|
+
|
|
860
|
+
css = _css_block(root_id, tokens, max_width_px)
|
|
861
|
+
escaped_alt = html.escape(exp.alt_text, quote=True)
|
|
862
|
+
escaped_takeaway = html.escape(exp.takeaway, quote=True)
|
|
863
|
+
|
|
864
|
+
figure_section = (
|
|
865
|
+
'<div class="fm-figure-stage">'
|
|
866
|
+
f'<div class="fm-svg-wrap" role="img" aria-label="{escaped_alt}">{svg_markup}</div>'
|
|
867
|
+
f'<figcaption class="fm-sr-only">{escaped_takeaway}</figcaption>'
|
|
868
|
+
"</div>"
|
|
869
|
+
)
|
|
870
|
+
|
|
871
|
+
if not interactive:
|
|
872
|
+
return (
|
|
873
|
+
f"{css}\n"
|
|
874
|
+
f'<figure id="{root_id}" class="fm-root" data-fm-theme="{html.escape(exp.theme.name, quote=True)}" '
|
|
875
|
+
f'data-fm-mode="{tokens["mode"]}">'
|
|
876
|
+
f"{figure_section}"
|
|
877
|
+
"</figure>"
|
|
878
|
+
)
|
|
879
|
+
|
|
880
|
+
# Facts & Data drawer
|
|
881
|
+
panel_cards: list[str] = []
|
|
882
|
+
panel_options: list[str] = ['<option value="figure">Whole figure</option>']
|
|
883
|
+
for key, panel in exp.panels.items():
|
|
884
|
+
esc_key = html.escape(key, quote=True)
|
|
885
|
+
esc_kind = html.escape(panel.kind, quote=True)
|
|
886
|
+
esc_title = html.escape(panel.title or panel.describe, quote=True)
|
|
887
|
+
opt_label = f"Panel {key}: {panel.title}" if panel.title else f"Panel {key} ({panel.kind})"
|
|
888
|
+
panel_options.append(
|
|
889
|
+
f'<option value="{esc_key}">{html.escape(opt_label, quote=True)}</option>'
|
|
890
|
+
)
|
|
891
|
+
facts_items = "".join(
|
|
892
|
+
f"<li>{html.escape(fact, quote=True)}</li>" for fact in panel.facts
|
|
893
|
+
)
|
|
894
|
+
facts_html = f'<ul class="fm-facts">{facts_items}</ul>' if facts_items else ""
|
|
895
|
+
headers, rows, num_flags, t_note = _panel_data_table(panel)
|
|
896
|
+
table_html = _render_table_html(headers, rows, num_flags, t_note)
|
|
897
|
+
panel_cards.append(
|
|
898
|
+
'<div class="fm-panel-card">'
|
|
899
|
+
'<div class="fm-panel-head">'
|
|
900
|
+
f'<span class="fm-badge">Panel {esc_key}</span>'
|
|
901
|
+
f'<span class="fm-panel-title">{esc_title}</span>'
|
|
902
|
+
f'<span class="fm-panel-kind">({esc_kind})</span>'
|
|
903
|
+
"</div>"
|
|
904
|
+
f"{facts_html}"
|
|
905
|
+
f"{table_html}"
|
|
906
|
+
"</div>"
|
|
907
|
+
)
|
|
908
|
+
|
|
909
|
+
meta_parts = [
|
|
910
|
+
f"Style: {exp.theme.name}",
|
|
911
|
+
f"Palette: {exp.palette or 'default'}",
|
|
912
|
+
f"Size: {exp.width_mm:.0f} × {exp.height_mm:.0f} mm",
|
|
913
|
+
]
|
|
914
|
+
if exp.source:
|
|
915
|
+
meta_parts.append(f"Source: {exp.source}")
|
|
916
|
+
if exp.note:
|
|
917
|
+
meta_parts.append(f"Note: {exp.note}")
|
|
918
|
+
meta_html = (
|
|
919
|
+
'<div class="fm-meta-row">'
|
|
920
|
+
+ "".join(f"<span>{html.escape(part, quote=True)}</span>" for part in meta_parts)
|
|
921
|
+
+ "</div>"
|
|
922
|
+
)
|
|
923
|
+
|
|
924
|
+
facts_drawer = (
|
|
925
|
+
'<section class="fm-drawer" data-fm-drawer-facts hidden aria-label="Facts and Data">'
|
|
926
|
+
"<h3>Facts & Underlying Data</h3>"
|
|
927
|
+
f"{''.join(panel_cards)}"
|
|
928
|
+
f"{meta_html}"
|
|
929
|
+
"</section>"
|
|
930
|
+
)
|
|
931
|
+
|
|
932
|
+
critique_actions = [
|
|
933
|
+
("highlight", "Highlight item / series"),
|
|
934
|
+
("drop", "Drop panel or item"),
|
|
935
|
+
("zoom", "Zoom / focus range"),
|
|
936
|
+
("style", "Adjust style / palette"),
|
|
937
|
+
("re-title", "Re-title takeaway / panel"),
|
|
938
|
+
("question", "Ask question about data"),
|
|
939
|
+
]
|
|
940
|
+
action_options = "".join(
|
|
941
|
+
f'<option value="{val}">{html.escape(lbl, quote=True)}</option>'
|
|
942
|
+
for val, lbl in critique_actions
|
|
943
|
+
)
|
|
944
|
+
critique_drawer = (
|
|
945
|
+
'<section class="fm-drawer" data-fm-drawer-critique hidden aria-label="Critique or ask agent">'
|
|
946
|
+
"<h3>Click to Critique / Ask Agent</h3>"
|
|
947
|
+
'<div class="fm-critique-grid">'
|
|
948
|
+
'<div class="fm-field">'
|
|
949
|
+
f'<label for="{root_id}-panel">Panel</label>'
|
|
950
|
+
f'<select id="{root_id}-panel" data-fm-critique-panel>{"".join(panel_options)}</select>'
|
|
951
|
+
"</div>"
|
|
952
|
+
'<div class="fm-field">'
|
|
953
|
+
f'<label for="{root_id}-action">Action</label>'
|
|
954
|
+
f'<select id="{root_id}-action" data-fm-critique-action>{action_options}</select>'
|
|
955
|
+
"</div>"
|
|
956
|
+
"</div>"
|
|
957
|
+
'<div class="fm-field">'
|
|
958
|
+
f'<label for="{root_id}-note">Note / instruction for agent</label>'
|
|
959
|
+
f'<textarea id="{root_id}-note" data-fm-critique-note '
|
|
960
|
+
'placeholder="e.g., Highlight checkout vs search and annotate the v2.3 deploy"></textarea>'
|
|
961
|
+
"</div>"
|
|
962
|
+
'<pre class="fm-preview" data-fm-critique-preview></pre>'
|
|
963
|
+
'<div class="fm-toolbar-group">'
|
|
964
|
+
'<button type="button" class="fm-btn fm-btn-accent" data-fm-copy-edit>Copy mint.edit(...)</button>'
|
|
965
|
+
'<button type="button" class="fm-btn" data-fm-copy-feedback>Copy Feedback JSON</button>'
|
|
966
|
+
"</div>"
|
|
967
|
+
"</section>"
|
|
968
|
+
)
|
|
969
|
+
|
|
970
|
+
toolbar = (
|
|
971
|
+
'<div class="fm-toolbar">'
|
|
972
|
+
'<div class="fm-toolbar-group">'
|
|
973
|
+
'<button type="button" class="fm-btn" data-fm-toggle-facts aria-expanded="false">Facts & Data</button>'
|
|
974
|
+
'<button type="button" class="fm-btn" data-fm-toggle-critique aria-expanded="false">Critique / Ask Agent</button>'
|
|
975
|
+
"</div>"
|
|
976
|
+
'<div class="fm-toolbar-group">'
|
|
977
|
+
'<button type="button" class="fm-btn" data-fm-download-svg>Download SVG</button>'
|
|
978
|
+
'<button type="button" class="fm-btn" data-fm-copy-spec>Copy Spec JSON</button>'
|
|
979
|
+
'<span class="fm-status" data-fm-status role="status" aria-live="polite"></span>'
|
|
980
|
+
"</div>"
|
|
981
|
+
"</div>"
|
|
982
|
+
)
|
|
983
|
+
|
|
984
|
+
js = _js_block(
|
|
985
|
+
root_id,
|
|
986
|
+
_safe_json_for_script(spec_dict),
|
|
987
|
+
_safe_json_for_script(exp.takeaway),
|
|
988
|
+
)
|
|
989
|
+
|
|
990
|
+
return (
|
|
991
|
+
f"{css}\n"
|
|
992
|
+
f'<figure id="{root_id}" class="fm-root" data-fm-theme="{html.escape(exp.theme.name, quote=True)}" '
|
|
993
|
+
f'data-fm-mode="{tokens["mode"]}">'
|
|
994
|
+
f"{figure_section}"
|
|
995
|
+
f"{toolbar}"
|
|
996
|
+
f"{facts_drawer}"
|
|
997
|
+
f"{critique_drawer}"
|
|
998
|
+
"</figure>\n"
|
|
999
|
+
f"{js}"
|
|
1000
|
+
)
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
def render_html(
|
|
1004
|
+
exp_or_spec: Explanation | Mapping[str, Any],
|
|
1005
|
+
*,
|
|
1006
|
+
interactive: bool = True,
|
|
1007
|
+
) -> str:
|
|
1008
|
+
"""Render a standalone, self-contained HTML5 document for an ``Explanation`` or spec dict."""
|
|
1009
|
+
exp = _ensure_explanation(exp_or_spec)
|
|
1010
|
+
fragment = render_html_fragment(exp, interactive=interactive)
|
|
1011
|
+
tokens = _theme_tokens(exp.theme)
|
|
1012
|
+
page_title = html.escape(exp.takeaway, quote=True)
|
|
1013
|
+
return (
|
|
1014
|
+
"<!DOCTYPE html>\n"
|
|
1015
|
+
'<html lang="en">\n'
|
|
1016
|
+
"<head>\n"
|
|
1017
|
+
'<meta charset="utf-8">\n'
|
|
1018
|
+
'<meta name="viewport" content="width=device-width, initial-scale=1">\n'
|
|
1019
|
+
f"<title>{page_title}</title>\n"
|
|
1020
|
+
"<style>\n"
|
|
1021
|
+
f"html, body {{ margin: 0; padding: 16px; background: {tokens['bg']}; color: {tokens['ink']}; }}\n"
|
|
1022
|
+
"</style>\n"
|
|
1023
|
+
"</head>\n"
|
|
1024
|
+
"<body>\n"
|
|
1025
|
+
f"{fragment}\n"
|
|
1026
|
+
"</body>\n"
|
|
1027
|
+
"</html>\n"
|
|
1028
|
+
)
|