-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrosspresent.py
More file actions
1863 lines (1615 loc) · 67.9 KB
/
Copy pathcrosspresent.py
File metadata and controls
1863 lines (1615 loc) · 67.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""crossPresent — turn one Markdown file into a self-contained HTML presentation.
No dependencies. No build chain. No JS in the output (unless you opt into
mermaid diagrams). Charts are rendered to inline SVG at build time, so the
result is a single file that works offline, adapts to dark/light mode, and
prints one slide per page.
Usage (after `pip install .` — or run `python3 crosspresent.py` uninstalled):
crosspresent new mydeck # scaffold mydeck.md
crosspresent build mydeck.md # -> mydeck.html
crosspresent build mydeck.md -t deck -o out/deck.html --open
crosspresent serve mydeck.md # live preview, reload on save
Templates: sidebar (TOC + scrolling sections, the default), deck
(full-screen snap-scrolling slides), doc (single-column report).
Palettes: default, ocean, forest, mono, crimson — `palette:` in frontmatter.
Charts can pull labels/values from CSV or JSON files via "data": "file.csv".
Speaker notes (```notes blocks) are stripped unless you pass --notes.
"""
import argparse
import base64
import csv
import glob
import html
import http.server
import json
import math
import mimetypes
import re
import sys
import tempfile
import threading
import time
import unicodedata
import webbrowser
from pathlib import Path
VERSION = "1.1.0"
# --------------------------------------------------------------------------
# Frontmatter
# --------------------------------------------------------------------------
def parse_frontmatter(text):
"""Parse a leading `--- key: value ... ---` block. Returns (meta, body)."""
lines = text.split("\n")
if not lines or lines[0].strip() != "---":
return {}, text
meta = {}
for i in range(1, len(lines)):
stripped = lines[i].strip()
if stripped == "---":
return meta, "\n".join(lines[i + 1:])
if not stripped or stripped.startswith("#"):
continue
key, sep, value = lines[i].partition(":")
if sep:
meta[key.strip().lower()] = value.strip().strip('"').strip("'")
return {}, text # opening --- with no closing --- : treat as content
# --------------------------------------------------------------------------
# Inline markdown
# --------------------------------------------------------------------------
BADGE_ALIASES = {
"good": "good", "green": "good", "pass": "good",
"warn": "warn", "amber": "warn", "yellow": "warn",
"bad": "bad", "red": "bad", "fail": "bad",
"info": "info", "blue": "info",
"accent": "accent", "orange": "accent",
"purple": "purple", "teal": "teal",
"dim": "dim", "gray": "dim", "grey": "dim",
}
_CODE_SPAN = re.compile(r"`([^`]+)`")
def render_inline(text):
"""Render inline markdown to HTML. Everything is escaped; the only HTML
in the result is what this function generates."""
spans = []
def stash(match):
spans.append("<code>%s</code>" % html.escape(match.group(1)))
return "\x00%d\x00" % (len(spans) - 1)
text = _CODE_SPAN.sub(stash, text)
text = html.escape(text)
# images: 
text = re.sub(
r"!\[([^\]]*)\]\(([^)\s]+)\)",
r'<img src="\2" alt="\1">', text)
# badges: [[TEXT]] or [[TEXT|class]]
def badge(match):
label, _, cls = match.group(1).partition("|")
cls = BADGE_ALIASES.get(cls.strip().lower(),
re.sub(r"[^a-z0-9_-]", "", cls.strip().lower()))
cls_attr = (" " + cls) if cls else ""
return '<span class="badge%s">%s</span>' % (cls_attr, label.strip())
text = re.sub(r"\[\[([^\]\[|]+(?:\|[^\]\[]*)?)\]\]", badge, text)
# links: [text](href) — script-ish URL schemes degrade to plain text
def link(match):
text_part, href = match.group(1), match.group(2)
if re.match(r"(?i)^\s*(javascript|vbscript|data)\s*:", href):
return text_part
return '<a href="%s">%s</a>' % (href, text_part)
text = re.sub(r"\[([^\]]+)\]\(([^)\s]+)\)", link, text)
# bold / italic
text = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", text)
text = re.sub(r"(?<!\*)\*([^*\n]+)\*(?!\*)", r"<em>\1</em>", text)
return re.sub(r"\x00(\d+)\x00", lambda m: spans[int(m.group(1))], text)
def strip_markup(text):
"""Plain text version of an inline-markdown string (for TOC labels)."""
text = re.sub(r"`([^`]+)`", r"\1", text)
text = re.sub(r"\[\[([^\]\[|]+)(?:\|[^\]\[]*)?\]\]", r"\1", text)
text = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", text)
text = re.sub(r"\*\*?([^*]+)\*\*?", r"\1", text)
return text.strip()
def slugify(text):
text = strip_markup(text)
text = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode()
text = re.sub(r"[^a-zA-Z0-9]+", "-", text).strip("-").lower()
return text or "slide"
# --------------------------------------------------------------------------
# Charts (inline SVG)
# --------------------------------------------------------------------------
PALETTE = ["var(--c1)", "var(--c2)", "var(--c3)", "var(--c4)",
"var(--c5)", "var(--c6)", "var(--c7)"]
def fmt_num(value):
if value == 0:
return "0"
# compact notation keeps axis and bar labels inside the chart margins
for div, suffix in ((1e12, "T"), (1e9, "B"), (1e6, "M"), (1e3, "k")):
if abs(value) >= (div if div > 1e3 else 1e5):
scaled = value / div
text = "%.1f" % scaled if abs(scaled) < 10 else "%.0f" % scaled
if "." in text:
text = text.rstrip("0").rstrip(".")
return text + suffix
if abs(value - round(value)) < 1e-9:
return str(int(round(value)))
return "%.6g" % value
def nice_ticks(vmax, count=4):
"""Round tick values from 0 up to (at least) vmax."""
if vmax <= 0:
return [0, 1]
raw_step = vmax / count
magnitude = 10 ** math.floor(math.log10(raw_step))
step = 10 * magnitude
for mult in (1, 2, 2.5, 5, 10):
if mult * magnitude * count >= vmax:
step = mult * magnitude
break
ticks = max(1, math.ceil(vmax / step - 1e-9))
return [i * step for i in range(ticks + 1)]
class ChartError(Exception):
pass
def _number(value):
try:
number = float(value)
except (TypeError, ValueError):
raise ChartError("chart value %r is not a number" % (value,)) from None
if not math.isfinite(number):
raise ChartError("chart value %r is not finite" % (value,))
return number
def _chart_height(spec, default=280):
try:
height = int(spec.get("height", default))
except (TypeError, ValueError):
raise ChartError(
'"height" must be a number, got %r' % (spec.get("height"),)) from None
if height < 80:
raise ChartError('"height" must be at least 80')
return height
def _series_of(spec):
"""Normalize a chart spec to (labels, [{name, values}])."""
if "series" in spec:
series = []
for entry in spec["series"]:
series.append({"name": str(entry.get("name", "")),
"values": [_number(v) for v in entry.get("values", [])]})
elif "values" in spec:
series = [{"name": str(spec.get("name", "")),
"values": [_number(v) for v in spec["values"]]}]
else:
raise ChartError('chart needs "values" or "series"')
if not series or not any(s["values"] for s in series):
raise ChartError("chart has no data points")
count = max(len(s["values"]) for s in series)
if any(s["values"] and len(s["values"]) != count for s in series):
print("warning: chart series have unequal lengths — short ones "
"padded with 0", file=sys.stderr)
for s in series:
s["values"] += [0.0] * (count - len(s["values"]))
raw_labels = [str(x) for x in spec.get("labels", [])]
if raw_labels and len(raw_labels) != count:
print("warning: chart has %d labels but %d values per series"
% (len(raw_labels), count), file=sys.stderr)
labels = raw_labels[:count] + [""] * (count - len(raw_labels))
return labels, series
def _legend(entries):
"""entries: [(label, color)] -> HTML legend."""
keys = "".join(
'<span class="key"><i style="background:%s"></i>%s</span>'
% (color, html.escape(label)) for label, color in entries)
return '<div class="legend">%s</div>' % keys
def _axis_grid(ticks, x0, x1, y_of):
parts = []
for tick in ticks:
y = y_of(tick)
parts.append('<line class="grid" x1="%g" y1="%g" x2="%g" y2="%g"/>'
% (x0, y, x1, y))
parts.append('<text class="tick" x="%g" y="%g" text-anchor="end">%s</text>'
% (x0 - 6, y + 3.5, fmt_num(tick)))
return parts
def _x_label_step(count, max_labels=14):
return max(1, math.ceil(count / max_labels))
def chart_bar(spec, labels, series):
width, height = 640, _chart_height(spec)
ml, mr, mt, mb = 46, 12, 18, 26 # top margin leaves room for value labels
plot_w, plot_h = width - ml - mr, height - mt - mb
vmax = max(max(s["values"]) for s in series)
ticks = nice_ticks(vmax)
top = ticks[-1]
def y_of(v):
return mt + plot_h * (1 - v / top)
parts = _axis_grid(ticks, ml, width - mr, y_of)
n = len(labels)
group_w = plot_w / n
band = group_w * 0.66
bar_w = band / len(series)
show_values = len(series) == 1 and n <= 14
step = _x_label_step(n)
for i in range(n):
gx = ml + i * group_w + (group_w - band) / 2
for k, s in enumerate(series):
value = s["values"][i]
bx, by = gx + k * bar_w, y_of(value)
parts.append(
'<rect x="%g" y="%g" width="%g" height="%g" rx="2" fill="%s"/>'
% (bx, by, max(bar_w - 2, 1), y_of(0) - by, PALETTE[k % len(PALETTE)]))
if show_values and value > 0:
parts.append(
'<text class="val" x="%g" y="%g" text-anchor="middle">%s</text>'
% (bx + bar_w / 2, by - 4, fmt_num(value)))
if labels[i] and i % step == 0:
parts.append(
'<text class="tick" x="%g" y="%g" text-anchor="middle">%s</text>'
% (ml + i * group_w + group_w / 2, height - 8, html.escape(labels[i])))
svg = ('<svg viewBox="0 0 %d %d" role="img">%s</svg>'
% (width, height, "".join(parts)))
legend = _legend([(s["name"], PALETTE[k % len(PALETTE)])
for k, s in enumerate(series)]) if len(series) > 1 else ""
return svg, legend
_HBAR_LABEL_CHARS = 30
def chart_hbar(spec, labels, series):
if len(series) > 1:
raise ChartError('hbar charts take a single series — '
'use "values", or type "bar" for grouped series')
values = series[0]["values"]
n = len(values)
shown = [label if len(label) <= _HBAR_LABEL_CHARS
else label[:_HBAR_LABEL_CHARS - 1] + "…" for label in labels]
longest = max((len(s) for s in shown), default=0)
ml = min(16 + _HBAR_LABEL_CHARS * 7, 16 + longest * 7)
row_h = 30
width, height = 640, n * row_h + 14
mr, mt = 46, 6
plot_w = width - ml - mr
vmax = max(values)
top = nice_ticks(vmax)[-1]
parts = []
for i, value in enumerate(values):
y = mt + i * row_h
bar_len = plot_w * value / top
parts.append('<rect x="%g" y="%g" width="%g" height="%g" rx="3" fill="%s"/>'
% (ml, y + 5, max(bar_len, 1), row_h - 12,
PALETTE[i % len(PALETTE)] if spec.get("colorful")
else PALETTE[0]))
parts.append('<text class="tick" x="%g" y="%g" text-anchor="end">%s</text>'
% (ml - 8, y + row_h / 2 + 3, html.escape(shown[i])))
parts.append('<text class="val" x="%g" y="%g">%s</text>'
% (ml + bar_len + 6, y + row_h / 2 + 3, fmt_num(value)))
svg = ('<svg viewBox="0 0 %d %d" role="img">%s</svg>'
% (width, height, "".join(parts)))
return svg, ""
def chart_line(spec, labels, series, area=False):
width, height = 640, _chart_height(spec)
ml, mr, mt, mb = 46, 14, 10, 26
plot_w, plot_h = width - ml - mr, height - mt - mb
vmax = max(max(s["values"]) for s in series)
ticks = nice_ticks(vmax)
top = ticks[-1]
n = len(labels)
def x_of(i):
return ml + (plot_w / 2 if n == 1 else plot_w * i / (n - 1))
def y_of(v):
return mt + plot_h * (1 - v / top)
parts = _axis_grid(ticks, ml, width - mr, y_of)
step = _x_label_step(n)
for i in range(0, n, step):
if labels[i]:
parts.append(
'<text class="tick" x="%g" y="%g" text-anchor="middle">%s</text>'
% (x_of(i), height - 8, html.escape(labels[i])))
for k, s in enumerate(series):
color = PALETTE[k % len(PALETTE)]
points = " ".join("%g,%g" % (x_of(i), y_of(v))
for i, v in enumerate(s["values"]))
if area:
parts.append(
'<path d="M%g,%g L%s L%g,%g Z" fill="%s" opacity="0.16"/>'
% (x_of(0), y_of(0), points, x_of(n - 1), y_of(0), color))
parts.append('<polyline points="%s" fill="none" stroke="%s" '
'stroke-width="2.5" stroke-linejoin="round"/>' % (points, color))
if n <= 30:
for i, v in enumerate(s["values"]):
parts.append('<circle cx="%g" cy="%g" r="3" fill="%s"/>'
% (x_of(i), y_of(v), color))
svg = ('<svg viewBox="0 0 %d %d" role="img">%s</svg>'
% (width, height, "".join(parts)))
legend = _legend([(s["name"], PALETTE[k % len(PALETTE)])
for k, s in enumerate(series)]) if len(series) > 1 else ""
return svg, legend
def chart_pie(spec, labels, series, donut=False):
values = series[0]["values"]
total = sum(values)
if total <= 0:
raise ChartError("pie chart values sum to zero")
size = 220
cx = cy = size / 2
r_outer = size / 2 - 4
r_inner = r_outer * 0.62 if donut else 0
parts = []
nonzero = [(i, v) for i, v in enumerate(values) if v > 0]
if len(nonzero) == 1:
i = nonzero[0][0]
color = PALETTE[i % len(PALETTE)]
if donut:
parts.append('<circle cx="%g" cy="%g" r="%g" fill="none" stroke="%s" '
'stroke-width="%g"/>'
% (cx, cy, (r_outer + r_inner) / 2, color, r_outer - r_inner))
else:
parts.append('<circle cx="%g" cy="%g" r="%g" fill="%s"/>'
% (cx, cy, r_outer, color))
else:
angle = -math.pi / 2
for i, value in enumerate(values):
if value <= 0:
continue
sweep = 2 * math.pi * value / total
a0, a1 = angle, angle + sweep
angle = a1
large = 1 if sweep > math.pi else 0
x0o, y0o = cx + r_outer * math.cos(a0), cy + r_outer * math.sin(a0)
x1o, y1o = cx + r_outer * math.cos(a1), cy + r_outer * math.sin(a1)
color = PALETTE[i % len(PALETTE)]
if donut:
x0i, y0i = cx + r_inner * math.cos(a1), cy + r_inner * math.sin(a1)
x1i, y1i = cx + r_inner * math.cos(a0), cy + r_inner * math.sin(a0)
path = ("M%g,%g A%g,%g 0 %d 1 %g,%g L%g,%g A%g,%g 0 %d 0 %g,%g Z"
% (x0o, y0o, r_outer, r_outer, large, x1o, y1o,
x0i, y0i, r_inner, r_inner, large, x1i, y1i))
else:
path = ("M%g,%g L%g,%g A%g,%g 0 %d 1 %g,%g Z"
% (cx, cy, x0o, y0o, r_outer, r_outer, large, x1o, y1o))
parts.append('<path d="%s" fill="%s" stroke="var(--panel)" '
'stroke-width="1.5"/>' % (path, color))
svg = ('<svg viewBox="0 0 %d %d" role="img" class="pie">%s</svg>'
% (size, size, "".join(parts)))
legend = _legend([
("%s — %s (%s%%)" % (labels[i] or "·", fmt_num(v),
fmt_num(round(100 * v / total, 1))),
PALETTE[i % len(PALETTE)])
for i, v in enumerate(values)])
return svg, legend
CHART_TYPES = {
"bar": chart_bar,
"hbar": chart_hbar,
"line": chart_line,
"area": lambda spec, labels, series: chart_line(spec, labels, series, area=True),
"pie": chart_pie,
"donut": lambda spec, labels, series: chart_pie(spec, labels, series, donut=True),
}
def _load_chart_data(spec, ctx):
"""Fill labels/values/series from the CSV or JSON file named in "data"."""
rel = str(spec["data"])
if any(key in spec for key in ("labels", "values", "series")):
raise ChartError('chart uses "data" — remove the inline '
'labels/values/series keys')
path = Path(ctx.get("base_dir", ".")) / rel
if not path.is_file():
raise ChartError('data file "%s" not found' % rel)
if path.suffix.lower() == ".json":
try:
loaded = json.loads(path.read_text(encoding="utf-8"))
except json.JSONDecodeError as exc:
raise ChartError('data file "%s": %s' % (rel, exc)) from exc
if not isinstance(loaded, dict):
raise ChartError('data file "%s" must be a JSON object with '
'labels and values/series' % rel)
for key in ("labels", "values", "series", "name"):
if key in loaded:
spec[key] = loaded[key]
return
# CSV: header row, first column = labels, every other column = a series
with path.open(newline="", encoding="utf-8-sig") as handle:
rows = [row for row in csv.reader(handle)
if any(cell.strip() for cell in row)]
if len(rows) < 2 or len(rows[0]) < 2:
raise ChartError('data file "%s" needs a header row plus data rows, '
'first column = labels' % rel)
header = [cell.strip() for cell in rows[0]]
spec["labels"] = [row[0].strip() for row in rows[1:]]
columns = []
for col in range(1, len(header)):
values = []
for row_no, row in enumerate(rows[1:], start=2):
cell = row[col].strip() if col < len(row) else ""
try:
values.append(float(cell) if cell else 0.0)
except ValueError:
raise ChartError('data file "%s": %r (row %d, column "%s") '
'is not a number' % (rel, cell, row_no,
header[col])) from None
columns.append({"name": header[col], "values": values})
if len(columns) == 1:
spec["values"] = columns[0]["values"]
spec.setdefault("name", columns[0]["name"])
else:
spec["series"] = columns
def render_chart(body, ctx):
try:
spec = json.loads("\n".join(body))
except json.JSONDecodeError as exc:
raise ChartError("invalid JSON in chart block: %s" % exc) from exc
if not isinstance(spec, dict):
raise ChartError("chart block must be a JSON object")
if "data" in spec:
_load_chart_data(spec, ctx)
kind = str(spec.get("type", "bar")).lower()
if kind not in CHART_TYPES:
raise ChartError('unknown chart type "%s" (use %s)'
% (kind, ", ".join(sorted(CHART_TYPES))))
labels, series = _series_of(spec)
svg, legend = CHART_TYPES[kind](spec, labels, series)
caption = ('<figcaption>%s</figcaption>' % render_inline(str(spec["title"]))
if spec.get("title") else "")
return ('<figure class="chart chart-%s">%s'
'<div class="chart-body">%s%s</div></figure>'
% (kind, caption, svg, legend))
# --------------------------------------------------------------------------
# Block-level markdown
# --------------------------------------------------------------------------
STAT_COLOR_ALIASES = {
"green": "green", "good": "green", "pass": "green",
"amber": "amber", "warn": "amber", "yellow": "amber",
"red": "red", "bad": "red", "fail": "red",
"blue": "blue", "info": "blue",
"gray": "gray", "grey": "gray", "dim": "gray",
}
def render_stats(body):
cells = []
for line in body:
if not line.strip():
continue
parts = [p.strip() for p in line.split("|")]
num = parts[0]
label = parts[1] if len(parts) > 1 else ""
color = STAT_COLOR_ALIASES.get(parts[2].lower(), "") \
if len(parts) > 2 and parts[2] else ""
cells.append('<div class="stat%s"><div class="num">%s</div>'
'<div class="lab">%s</div></div>'
% ((" " + color) if color else "",
render_inline(num), render_inline(label)))
return '<div class="stat-row">%s</div>' % "".join(cells)
def render_note(label, body_lines, extra_class=""):
label_html = ('<div class="note-label">%s</div>' % render_inline(label)
if label else "")
paragraphs = []
current = []
for line in body_lines + [""]:
if line.strip():
current.append(line.strip())
elif current:
paragraphs.append("<p>%s</p>" % render_inline(" ".join(current)))
current = []
return ('<div class="note%s">%s%s</div>'
% (extra_class, label_html, "".join(paragraphs)))
def render_pills(body):
pills = []
for line in body:
if not line.strip():
continue
text, _, href = (p.strip() for p in line.partition("|"))
if href:
pills.append('<a class="pill" href="%s">%s</a>'
% (html.escape(href, quote=True), render_inline(text)))
else:
pills.append('<span class="pill">%s</span>' % render_inline(text))
return '<div class="row">%s</div>' % "".join(pills)
def render_cards(arg, body, ctx):
cards = []
title, content = None, []
for line in body + ["### "]:
if line.startswith("### "):
if title is not None or content:
cards.append((title, content))
title, content = line[4:].strip(), []
else:
content.append(line)
rendered = []
for card_title, card_body in cards:
title_html = "<h3>%s</h3>" % render_inline(card_title) if card_title else ""
rendered.append('<div class="card">%s%s</div>'
% (title_html, render_blocks(card_body, ctx)))
if arg and arg.strip() in ("2", "3"):
cols = int(arg.strip())
else:
count = len(rendered)
cols = 3 if count in (3, 6, 9) else 2
return '<div class="grid cols-%d">%s</div>' % (cols, "".join(rendered))
def render_table(rows):
def cells(row):
row = row.strip()
if row.startswith("|"):
row = row[1:]
if row.endswith("|"):
row = row[:-1]
return [c.strip() for c in row.split("|")]
aligns = []
for cell in cells(rows[1]):
left, right = cell.startswith(":"), cell.endswith(":")
aligns.append("center" if left and right else
"right" if right else "left")
def render_row(row, tag):
out = []
for i, cell in enumerate(cells(row)):
align = aligns[i] if i < len(aligns) else "left"
style = ' style="text-align:%s"' % align if align != "left" else ""
out.append("<%s%s>%s</%s>" % (tag, style, render_inline(cell), tag))
return "<tr>%s</tr>" % "".join(out)
head = render_row(rows[0], "th")
body = "".join(render_row(r, "td") for r in rows[2:])
return ("<table><thead>%s</thead><tbody>%s</tbody></table>" % (head, body))
def render_list(lines, start):
ordered = bool(re.match(r"^\s*\d+[.)]\s", lines[start]))
items = [] # (text, [subitems])
i = start
while i < len(lines):
match = re.match(r"^(\s*)([-*+]|\d+[.)])\s+(.*)$", lines[i])
if not match or not lines[i].strip():
break
indent, text = len(match.group(1)), match.group(3)
if indent >= 2 and items:
items[-1][1].append(text)
else:
items.append((text, []))
i += 1
tag = "ol" if ordered else "ul"
out = []
for text, children in items:
if children:
sub = "".join("<li>%s</li>" % render_inline(c) for c in children)
out.append("<li>%s<ul>%s</ul></li>" % (render_inline(text), sub))
else:
out.append("<li>%s</li>" % render_inline(text))
return "<%s>%s</%s>" % (tag, "".join(out), tag), i
_FENCE_RE = re.compile(r"^```(\S*)\s*(.*?)\s*$")
_LIST_RE = re.compile(r"^\s*([-*+]|\d+[.)])\s+")
_TABLE_SEP_RE = re.compile(r"^\|?[\s:|-]+\|[\s:|-]*$")
def _is_block_start(line):
stripped = line.strip()
return (not stripped
or stripped.startswith("```")
or stripped.startswith("#")
or stripped.startswith(">")
or stripped.startswith("|")
or stripped.startswith("<")
or bool(_LIST_RE.match(line))
or bool(re.fullmatch(r"-{3,}", stripped)))
def render_fence(lang, arg, body, ctx):
if lang == "chart":
return render_chart(body, ctx)
if lang == "stats":
return render_stats(body)
if lang == "note":
return render_note(arg, body)
if lang == "notes":
if not ctx.get("show_notes"):
return ""
return render_note(arg or "Speaker notes", body, extra_class=" speaker")
if lang == "cards":
return render_cards(arg, body, ctx)
if lang == "pills":
return render_pills(body)
if lang == "mermaid":
ctx["mermaid"] = True
return '<pre class="mermaid">%s</pre>' % html.escape("\n".join(body))
css_class = ' class="language-%s"' % html.escape(lang) if lang else ""
return "<pre><code%s>%s</code></pre>" % (css_class,
html.escape("\n".join(body)))
def render_blocks(lines, ctx, intro_first=False):
out = []
i = 0
saw_paragraph = False
while i < len(lines):
stripped = lines[i].strip()
if not stripped:
i += 1
continue
fence = _FENCE_RE.match(stripped)
if fence:
lang, arg = fence.group(1).lower(), fence.group(2)
body = []
depth = 0 # nested fences (with info strings) inside cards/notes
i += 1
while i < len(lines):
inner = lines[i].strip()
if inner.startswith("```"):
if inner == "```":
if depth == 0:
break
depth -= 1
else:
depth += 1
body.append(lines[i])
i += 1
i += 1 # closing fence
try:
out.append(render_fence(lang, arg, body, ctx))
except ChartError as exc:
raise SystemExit("error: %s (in slide “%s”)"
% (exc, ctx.get("slide", "?"))) from exc
continue
if stripped.startswith("### "):
out.append("<h3>%s</h3>" % render_inline(stripped[4:]))
i += 1
continue
if re.fullmatch(r"-{3,}", stripped):
out.append("<hr>")
i += 1
continue
if stripped.startswith(">"):
quote = []
while i < len(lines) and lines[i].strip().startswith(">"):
quote.append(lines[i].strip().lstrip(">").strip())
i += 1
label = None
if quote and re.fullmatch(r"\*\*[^*]+\*\*", quote[0]):
label, quote = quote[0].strip("*"), quote[1:]
out.append(render_note(label, quote))
continue
if (stripped.startswith("|") and i + 1 < len(lines)
and _TABLE_SEP_RE.match(lines[i + 1].strip())):
rows = []
while i < len(lines) and lines[i].strip().startswith("|"):
rows.append(lines[i].strip())
i += 1
out.append(render_table(rows))
continue
if _LIST_RE.match(lines[i]):
block, i = render_list(lines, i)
out.append(block)
continue
if stripped.startswith("<"):
raw = []
while i < len(lines) and lines[i].strip():
raw.append(lines[i])
i += 1
out.append("\n".join(raw))
continue
# paragraph
para = []
while i < len(lines) and lines[i].strip() and not _is_block_start(lines[i]):
para.append(lines[i].strip())
i += 1
css = ' class="intro"' if intro_first and not saw_paragraph else ""
saw_paragraph = True
out.append("<p%s>%s</p>" % (css, render_inline(" ".join(para))))
return "\n".join(out)
# --------------------------------------------------------------------------
# Slides
# --------------------------------------------------------------------------
def split_slides(body):
slides = []
current = None
fence_depth = 0
for line in body.split("\n"):
stripped = line.strip()
if stripped.startswith("```"):
if stripped == "```" and fence_depth > 0:
fence_depth -= 1
else:
fence_depth += 1
heading = None if fence_depth else re.match(r"^(#{1,2})\s+(.*)$", line)
if heading:
title = heading.group(2).strip()
slide_id = None
id_match = re.search(r"\{#([a-zA-Z0-9_-]+)\}\s*$", title)
if id_match:
slide_id = id_match.group(1)
title = title[:id_match.start()].strip()
current = {"level": len(heading.group(1)), "title": title,
"id": slide_id, "lines": []}
slides.append(current)
else:
if current is None:
if not stripped:
continue
current = {"level": 2, "title": "", "id": None, "lines": []}
slides.append(current)
current["lines"].append(line)
# assign unique ids
used = set()
for slide in slides:
base = slide["id"] or slugify(slide["title"])
candidate, n = base, 2
while candidate in used:
candidate = "%s-%d" % (base, n)
n += 1
slide["id"] = candidate
used.add(candidate)
return slides
# --------------------------------------------------------------------------
# Page template
# --------------------------------------------------------------------------
PAGE_CSS = """
:root {
--bg: %(bg)s;
--panel: #161a22;
--panel-2: #1d2230;
--ink: #e8ecf1;
--ink-dim: #aab2c0;
--rule: #2a3142;
--accent: %(accent)s;
--accent-2: #6aa9ff;
--good: #6fcf97;
--warn: #ffd166;
--bad: #ff7676;
%(chart_dark)s
--mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
}
@media (prefers-color-scheme: light) {
:root {
--bg: %(bg_light)s;
--panel: #ffffff;
--panel-2: #f3f4f8;
--ink: #1c2024;
--ink-dim: #5b6470;
--rule: #e3e6ec;
--accent: %(accent_light)s;
--accent-2: #1f5fcb;
--good: #1e9e5a;
--warn: #b88600;
--bad: #d64545;
%(chart_light)s
}
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; background: var(--bg); color: var(--ink); }
body {
font: 16px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
-webkit-font-smoothing: antialiased;
}
.layout { display: grid; grid-template-columns: 240px 1fr; min-height: 100vh; }
nav.toc {
position: sticky; top: 0; align-self: start; max-height: 100vh; overflow: auto;
border-right: 1px solid var(--rule); padding: 28px 20px 40px;
background: var(--panel);
}
nav.toc h2 {
font-size: 11px; letter-spacing: 0.12em; text-transform: uppercase;
color: var(--ink-dim); margin: 0 0 14px;
}
nav.toc ol { list-style: none; margin: 0; padding: 0; counter-reset: step; }
nav.toc ol li { counter-increment: step; margin: 4px 0; }
nav.toc ol li a {
display: block; padding: 6px 8px; border-radius: 6px;
text-decoration: none; color: var(--ink); font-size: 13.5px;
}
nav.toc ol li a::before {
content: counter(step, decimal-leading-zero);
color: var(--ink-dim); font-family: var(--mono); font-size: 11px;
margin-right: 10px;
}
nav.toc ol li a:hover { background: var(--panel-2); }
main { padding: 0; min-width: 0; }
section.slide {
padding: 64px 72px;
border-bottom: 1px solid var(--rule);
min-height: 100vh;
}
section.slide.title {
background: linear-gradient(135deg, var(--panel) 0%%, var(--panel-2) 100%%);
}
.eyebrow {
font-size: 11px; letter-spacing: 0.18em; text-transform: uppercase;
color: var(--accent); margin-bottom: 18px;
}
h1 { font-size: 42px; line-height: 1.15; margin: 0 0 16px; letter-spacing: -0.01em; }
h1.hero { font-size: 56px; max-width: 18ch; }
h2.slide-h { font-size: 30px; margin: 0 0 28px; letter-spacing: -0.01em; }
h3 { font-size: 18px; margin: 28px 0 10px; color: var(--ink); }
p, li { color: var(--ink); font-size: 16.5px; }
p.intro { font-size: 17px; color: var(--ink); max-width: 70ch; }
a { color: var(--accent-2); }
hr { border: none; border-top: 1px solid var(--rule); margin: 26px 0; }
img { max-width: 100%%; border-radius: 8px; }
.grid { display: grid; gap: 20px; margin: 18px 0; }
.grid.cols-2 { grid-template-columns: 1fr 1fr; }
.grid.cols-3 { grid-template-columns: repeat(3, 1fr); }
.card {
background: var(--panel); border: 1px solid var(--rule); border-radius: 10px;
padding: 20px 22px;
}
.card h3 { margin-top: 0; }
table { width: 100%%; border-collapse: collapse; margin: 12px 0; font-size: 14.5px; }
th, td {
text-align: left; padding: 10px 12px;
border-bottom: 1px solid var(--rule); vertical-align: top;
}
th { font-weight: 600; color: var(--ink-dim); font-size: 12.5px;
text-transform: uppercase; letter-spacing: 0.06em; }
code, kbd { font-family: var(--mono); font-size: 13.5px;
background: var(--panel-2); padding: 1px 6px; border-radius: 4px; }
pre {
background: var(--panel-2); border: 1px solid var(--rule); border-radius: 8px;
padding: 14px 16px; overflow: auto; font-family: var(--mono); font-size: 13px;
line-height: 1.55;
}
pre code { background: none; padding: 0; font-size: inherit; }
.badge {
display: inline-block; font-family: var(--mono); font-size: 11.5px;
padding: 2px 8px; border-radius: 999px; border: 1px solid var(--rule);
background: var(--panel-2); color: var(--ink-dim);
letter-spacing: 0.04em;
}
.badge.good { color: var(--good); border-color: color-mix(in srgb, var(--good) 35%%, transparent); }
.badge.warn { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 40%%, transparent); }
.badge.bad { color: var(--bad); border-color: color-mix(in srgb, var(--bad) 35%%, transparent); }
.badge.info { color: var(--accent-2); border-color: color-mix(in srgb, var(--accent-2) 35%%, transparent); }
.badge.accent { color: var(--accent); border-color: color-mix(in srgb, var(--accent) 35%%, transparent); }
.badge.purple { color: var(--c4); border-color: color-mix(in srgb, var(--c4) 35%%, transparent); }
.badge.teal { color: var(--c7); border-color: color-mix(in srgb, var(--c7) 35%%, transparent); }
.badge.dim { color: var(--ink-dim); }
.pill {
display: inline-flex; align-items: center; gap: 6px;
background: var(--panel-2); border: 1px solid var(--rule);
border-radius: 999px; padding: 4px 10px; font-size: 12.5px;
font-family: var(--mono); color: var(--ink-dim); text-decoration: none;
}
a.pill:hover { color: var(--ink); border-color: var(--accent); }
.note {
border-left: 3px solid var(--accent); padding: 14px 18px;
background: var(--panel-2); border-radius: 0 8px 8px 0;
margin: 18px 0; font-size: 15.5px;
}
.note p { margin: 6px 0; font-size: 15.5px; }
.note .note-label {
font-weight: 600; color: var(--accent);
text-transform: uppercase; letter-spacing: 0.08em; font-size: 11.5px;
margin-bottom: 6px;
}
.note.speaker {
background: transparent; border: 1px dashed var(--rule);
border-left: 3px solid var(--c4); border-radius: 0 8px 8px 0;
color: var(--ink-dim);
}
.note.speaker .note-label { color: var(--c4); }
.stat-row { display: flex; gap: 28px; flex-wrap: wrap; margin: 20px 0 6px; }
.stat { background: var(--panel); border: 1px solid var(--rule);
border-radius: 10px; padding: 14px 22px; min-width: 120px; }
.stat .num { font-size: 32px; font-weight: 700; line-height: 1; }
.stat .lab { font-size: 12px; color: var(--ink-dim);
text-transform: uppercase; letter-spacing: 0.08em; margin-top: 6px; }
.stat.green .num { color: var(--good); }
.stat.amber .num { color: var(--warn); }
.stat.red .num { color: var(--bad); }
.stat.blue .num { color: var(--accent-2); }
.stat.gray .num { color: var(--ink-dim); }
.row { display: flex; flex-wrap: wrap; gap: 8px; margin: 14px 0; }
figure.chart { margin: 22px 0; }
figure.chart figcaption {
font-size: 13px; color: var(--ink-dim); font-family: var(--mono);
text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 10px;
}
.chart-body { display: flex; align-items: center; gap: 26px; flex-wrap: wrap; }
.chart svg { max-width: 100%%; height: auto; flex: 1 1 360px; min-width: 280px; }
.chart svg.pie { flex: 0 0 200px; min-width: 180px; max-width: 220px; }
.chart text { font-family: var(--mono); font-size: 11px; fill: var(--ink-dim); }
.chart text.val { fill: var(--ink); font-size: 11.5px; }
.chart line.grid { stroke: var(--rule); stroke-width: 1; }
.legend { display: flex; flex-direction: column; gap: 8px; font-size: 13.5px; }
.legend .key { display: inline-flex; align-items: center; gap: 8px; color: var(--ink); }
.legend .key i { width: 12px; height: 12px; border-radius: 3px; flex: none; }
.chart-bar .legend, .chart-line .legend, .chart-area .legend {
flex-direction: row; gap: 18px; flex-basis: 100%%;
}
.footer {
padding: 28px 72px; color: var(--ink-dim); font-size: 13px;