-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.py
More file actions
1379 lines (1134 loc) · 40.2 KB
/
build.py
File metadata and controls
1379 lines (1134 loc) · 40.2 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
import re
import sys
import shutil
import html
import time
import json
from pathlib import Path
from datetime import datetime, date
from email.utils import formatdate
import markdown # pip install markdown
import yaml # pip install pyyaml
from bs4 import BeautifulSoup # pip install beautifulsoup4
BASE_DIR = Path(__file__).parent # build-scripts directory
# Filenames that live inside build-scripts/
CSS_FILENAME = "style.css"
LUNR_JS_FILENAME = "lunr.js"
SEARCH_JS_FILENAME = "search.js"
# Generated into output_dir
THEME_JS_FILENAME = "theme.js"
SEARCH_INDEX_FILENAME = "search_index.json"
# Matches headings like "## 2025-01-02"
ENTRY_HEADING_RE = re.compile(r"^(#{2,6})\s+(\d{4}-\d{2}-\d{2})\s*$")
# -----------------------
# Config
# -----------------------
def get_config_path_from_args() -> Path:
"""
Determine which config file to use.
- If a path is passed as first argument, use that.
- Otherwise, assume ../config.yml relative to build-scripts.
"""
if len(sys.argv) > 1:
return Path(sys.argv[1]).resolve()
return (BASE_DIR.parent / "config.yml").resolve()
def load_config(config_path: Path) -> dict:
if not config_path.exists():
print(f"Config file not found: {config_path}", file=sys.stderr)
sys.exit(1)
data = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {}
# extra_head can be string or list
extra_head = data.get("extra_head", [])
if isinstance(extra_head, str):
extra_head_list = [extra_head]
elif isinstance(extra_head, list):
extra_head_list = [str(x) for x in extra_head]
else:
extra_head_list = []
# extra_footer can be string or list
extra_footer = data.get("extra_footer", [])
if isinstance(extra_footer, str):
extra_footer_list = [extra_footer]
elif isinstance(extra_footer, list):
extra_footer_list = [extra_footer]
else:
extra_footer_list = []
extra_footer_items = data.get("extra_footer", [])
if isinstance(extra_footer_items, str):
extra_footer_list = [extra_footer_items]
elif isinstance(extra_footer_items, list):
extra_footer_list = [str(x) for x in extra_footer_items]
else:
extra_footer_list = []
# NEW: resources – list of files/paths to copy to output
resources_cfg = data.get("resources", [])
if isinstance(resources_cfg, str):
resources_list = [resources_cfg]
elif isinstance(resources_cfg, list):
resources_list = [str(x) for x in resources_cfg]
else:
resources_list = []
cfg = {
"site_title": data.get("site_title", "Journal"),
"site_tagline": data.get("site_tagline", ""),
"site_url": data.get("site_url", ""),
"content_root": data.get("content_root", "content"),
"output_dir": data.get("output_dir", "_site"),
"order": data.get("order", "reverse"), # "reverse" or "chronological"
"latest_as_index": bool(data.get("latest_as_index", True)),
"extra_head": extra_head_list,
"extra_footer": extra_footer_list,
"enable_search": bool(data.get("enable_search", True)),
"include_drafts": bool(data.get("include_drafts", False)),
# NEW
"resources": resources_list,
}
return cfg
# -----------------------
# Parsing markdown entries
# -----------------------
def parse_month_file(path: Path):
"""
Parse a monthly markdown file into a list of entries:
{ "date": "YYYY-MM-DD", "heading_level": 2, "content_md": "..." }
"""
text = path.read_text(encoding="utf-8")
lines = text.splitlines()
entries = []
current_date = None
current_level = None
current_lines = []
for line in lines:
m = ENTRY_HEADING_RE.match(line)
if m:
# flush previous
if current_date is not None:
entries.append(
{
"date": current_date,
"heading_level": current_level or 2,
"content_md": "\n".join(current_lines).strip(),
}
)
current_lines = []
hashes = m.group(1)
current_level = len(hashes)
current_date = m.group(2)
else:
# allow top-level month heading like "# December 2025"
if line.startswith("# ") and current_date is None:
continue
current_lines.append(line)
if current_date is not None:
entries.append(
{
"date": current_date,
"heading_level": current_level or 2,
"content_md": "\n".join(current_lines).strip(),
}
)
return entries
def extract_meta(entry: dict):
"""
Extracts metadata from the top of entry["content_md"]:
tags: outdoors, family
draft: true
tags: list[str]
draft: bool
"""
lines = entry["content_md"].splitlines()
tags = []
draft = False
body_start = 0
for i, line in enumerate(lines):
stripped = line.strip()
if not stripped:
body_start = i + 1
break
lower = stripped.lower()
if lower.startswith("tags:"):
tag_str = stripped[5:].strip()
tags = [t.strip() for t in tag_str.split(",") if t.strip()]
elif lower.startswith("draft:"):
val = stripped[6:].strip().lower()
draft = val in ("true", "yes", "1", "y", "on")
else:
body_start = i
break
body = "\n".join(lines[body_start:]).strip()
entry["content_md"] = body
entry["tags"] = tags
entry["draft"] = draft
def collect_entries_by_year(
content_root: Path,
order: str = "reverse",
include_drafts: bool = False,
):
"""
Returns { "2024": [entries...], "2025": [entries...] }
Entries sorted within each year by date.
"""
entries_by_year = {}
for year_dir in sorted(content_root.iterdir()):
if not year_dir.is_dir():
continue
if not year_dir.name.isdigit():
continue
year = year_dir.name
year_entries = []
for md_file in sorted(year_dir.glob("*.md")):
for e in parse_month_file(md_file):
extract_meta(e)
if e.get("draft") and not include_drafts:
continue
e["_dt"] = datetime.strptime(e["date"], "%Y-%m-%d")
e["source_file"] = md_file
e["year"] = year
year_entries.append(e)
if not year_entries:
continue
reverse = (order == "reverse")
year_entries.sort(key=lambda x: x["_dt"], reverse=reverse)
entries_by_year[year] = year_entries
return entries_by_year
# -----------------------
# Tags
# -----------------------
def slugify_tag(tag: str) -> str:
s = tag.strip().lower()
s = re.sub(r"[\s_]+", "-", s)
s = re.sub(r"[^a-z0-9-]", "", s)
s = re.sub(r"-{2,}", "-", s).strip("-")
return s or "tag"
def build_tag_index(entries_by_year: dict):
"""
Returns:
{
"outdoors": {"name": "outdoors", "entries": [...]},
...
}
where keys are slugs.
"""
tag_map = {}
for year, entries in entries_by_year.items():
for e in entries:
for tag in e.get("tags") or []:
slug = slugify_tag(tag)
if slug not in tag_map:
tag_map[slug] = {"name": tag, "entries": []}
tag_map[slug]["entries"].append(e)
for slug, data in tag_map.items():
data["entries"].sort(key=lambda x: x["_dt"], reverse=True)
return tag_map
# -----------------------
# HTML helpers
# -----------------------
def wrap_images_with_figures(html_fragment: str, gallery_id=None) -> str:
soup = BeautifulSoup(html_fragment, "html.parser")
for img in list(soup.find_all("img")):
alt = (img.get("alt") or "").strip()
src = (img.get("src") or "").strip()
if not src:
continue
# Skip if already inside a figure
if img.find_parent("figure"):
continue
clean = src.split("?", 1)[0].split("#", 1)[0]
ext = clean.rsplit(".", 1)[-1].lower() if "." in clean else ""
parent_p = img.find_parent("p")
# Determine whether we should replace the whole paragraph
replace_p = False
if parent_p:
non_ws = []
for c in parent_p.contents:
# include tags, and non-empty text nodes
if getattr(c, "name", None) is not None:
non_ws.append(c)
else:
if str(c).strip():
non_ws.append(c)
replace_p = (len(non_ws) == 1 and non_ws[0] == img)
# IMPORTANT: detach the img from the tree before doing replacements
# This prevents "replace a tag with its parent" / ancestry conflicts.
img.extract()
figure = soup.new_tag("figure")
figure["class"] = "entry-figure"
if ext in ("mp4", "webm", "ogg"):
video = soup.new_tag("video")
video["class"] = "entry-video"
video["controls"] = True
video["playsinline"] = True
video["preload"] = "metadata"
source = soup.new_tag("source")
source["src"] = src
if ext == "mp4":
source["type"] = "video/mp4"
elif ext == "webm":
source["type"] = "video/webm"
elif ext == "ogg":
source["type"] = "video/ogg"
video.append(source)
figure.append(video)
elif ext == "gif":
# optional: treat GIF link as looping muted video (better performance than <img>)
video = soup.new_tag("video")
video["class"] = "entry-video"
video["autoplay"] = True
video["loop"] = True
video["muted"] = True
video["playsinline"] = True
video["preload"] = "metadata"
source = soup.new_tag("source")
source["src"] = src
video.append(source)
figure.append(video)
else:
# Put the original image back into the figure
figure.append(img)
if alt:
cap = soup.new_tag("figcaption")
cap.string = alt
figure.append(cap)
# Replace either the <p> wrapper or (if not in a simple <p>) insert figure where img was.
if replace_p and parent_p:
parent_p.replace_with(figure)
else:
# If we extracted img, we no longer have its old position.
# Best fallback: append figure at the end (rare case in your journal)
# OR insert at parent_p position if it existed.
if parent_p:
parent_p.insert_after(figure)
else:
soup.append(figure)
return str(soup)
#def render_entry(entry, *, link_tags: bool = True, permalink_href: str | None = None):
def render_entry(entry, *, link_tags: bool = True, permalink_href=None):
"""
Render a single <article> with date, permalink, and tag pills.
permalink_href:
- None => use "#YYYY-MM-DD" (default, like year pages)
- string => used as-is for the permalink href
"""
date_str = entry["date"]
level = max(2, min(6, entry.get("heading_level", 2)))
heading_tag = f"h{level}"
raw_html = markdown.markdown(entry["content_md"])
content_html = wrap_images_with_figures(raw_html, gallery_id=date_str)
if permalink_href is None:
permalink = f"#{date_str}"
else:
permalink = permalink_href
# tags
tags = entry.get("tags") or []
tag_html = ""
if tags:
pills = []
for tag in tags:
slug = slugify_tag(tag)
label = html.escape(tag)
if link_tags:
href = f"tag/{slug}.html"
pill = f'<li><a href="{href}" class="entry-tag">{label}</a></li>'
else:
pill = f'<li><span class="entry-tag">{label}</span></li>'
pills.append(pill)
tag_html = f'<ul class="entry-tags">{"".join(pills)}</ul>'
return f"""<article id="{date_str}" class="entry">
<header class="entry-header">
<{heading_tag} class="entry-date">
<time datetime="{date_str}">{date_str}</time>
</{heading_tag}>
<a class="entry-permalink"
href="{permalink}"
title="Copy link to this entry"
aria-label="Copy link to this entry">
🔗
</a>
{tag_html}
</header>
<div class="entry-body">
{content_html}
</div>
</article>
"""
def sidebar_extra_links(prefix: str = "", active_on_this_day: bool = False) -> str:
"""
Left sidebar helper: 'On this day' and 'Tags' links.
prefix: "" for root pages, "../" for tag pages.
"""
on_this_classes = "sidebar-link"
if active_on_this_day:
on_this_classes += " active"
return f"""
<div class="sidebar-extra-links">
<a href="{prefix}on-this-day.html" class="{on_this_classes}">On this day</a>
<a href="{prefix}tags.html" class="sidebar-link">Tags</a>
</div>"""
def copy_toast_html() -> str:
"""
Small toast element shown when a permalink is copied.
"""
return """
<div id="copy-toast" class="copy-toast" role="status" aria-live="polite">
Link copied to clipboard
</div>"""
def build_common_head_and_footer(cfg: dict):
extra_head_items = cfg.get("extra_head") or []
extra_head_html = ""
if extra_head_items:
extra_head_html = "\n " + "\n ".join(extra_head_items)
extra_footer_items = cfg.get("extra_footer") or []
extra_footer_html = ""
if extra_footer_items:
extra_footer_html = "\n " + "\n ".join(extra_footer_items)
return extra_head_html, extra_footer_html
def search_ui_html(cfg: dict) -> str:
"""
Only year pages / index get the search box.
"""
if not cfg.get("enable_search", True):
return ""
return """
<section class="search-section">
<form class="search-form" role="search" onsubmit="return false;">
<label for="search-input" class="search-label">Search entries</label>
<input id="search-input" class="search-input" type="search" placeholder="Search this journal">
</form>
<div id="search-results" class="search-results" aria-live="polite"></div>
</section>
"""
def search_scripts_html(cfg: dict, prefix: str = "") -> str:
"""
Scripts for search; prefix is "" on root pages, "../" on tag pages if ever needed.
"""
if not cfg.get("enable_search", True):
return ""
return (
f'\n<script src="{prefix}{LUNR_JS_FILENAME}"></script>'
f'\n<script src="{prefix}{SEARCH_JS_FILENAME}"></script>'
)
def theme_script_html(prefix: str = "") -> str:
"""
Script tag for theme persistence (theme.js). prefix is "" or "../".
"""
return f'\n<script src="{prefix}{THEME_JS_FILENAME}"></script>'
# -----------------------
# Page renderers
# -----------------------
def render_year_page(year: str, years: list, entries: list, cfg: dict, *, is_index: bool = False) -> str:
articles_html = "\n\n".join(render_entry(e, link_tags=True) for e in entries)
site_title = cfg["site_title"]
site_tagline = cfg["site_tagline"]
if is_index:
page_title = site_title
main_heading = f'<h2 class="year-title">Latest entries – {year}</h2>'
else:
page_title = f"{site_title} – {year}"
main_heading = f'<h2 class="year-title">{year}</h2>'
# Sidebar year links
year_links = []
for y in sorted(years, reverse=True):
href = f"{y}.html"
css_class = "year-link"
if (is_index and y == year) or (not is_index and y == year):
css_class += " active"
year_links.append(f'<li><a href="{href}" class="{css_class}">{y}</a></li>')
years_nav_html = "\n ".join(year_links)
extra_head_html, extra_footer_html = build_common_head_and_footer(cfg)
order_text = "reverse chronological" if cfg.get("order", "reverse") == "reverse" else "chronological"
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{page_title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<link rel="alternate" type="application/rss+xml" title="{site_title} – RSS" href="rss.xml">{extra_head_html}
</head>
<body>
<input type="checkbox" id="theme-toggle" class="theme-toggle-checkbox" aria-label="Toggle dark mode">
<div class="layout">
<aside class="sidebar">
<header class="site-header">
<h1 class="site-title"><a href="index.html">{site_title}</a></h1>
<p class="site-tagline">{site_tagline}</p>
</header>
<div class="theme-toggle-control">
<label for="theme-toggle" class="theme-toggle-label">
<span class="theme-toggle-icon theme-toggle-light" aria-hidden="true">☀️</span>
<span class="theme-toggle-icon theme-toggle-dark" aria-hidden="true">🌙</span>
<span class="theme-toggle-text">Theme</span>
</label>
</div>
{sidebar_extra_links(prefix="", active_on_this_day=False)}
<input type="checkbox"
id="year-toggle"
class="year-toggle-checkbox"
aria-label="Toggle year navigation">
<label for="year-toggle" class="year-toggle-label">
<span class="year-toggle-burger" aria-hidden="true">
<span></span>
<span></span>
<span></span>
</span>
<span class="year-toggle-text">Browse years</span>
</label>
<nav class="year-nav">
<h2 class="year-nav-title">Years</h2>
<ul class="year-nav-list">
{years_nav_html}
</ul>
</nav>
</aside>
<main class="content">
<div class="content-inner">
<header class="content-header">
{main_heading}
<p class="content-subtitle">Entries are shown in {order_text} order.</p>
</header>
{search_ui_html(cfg)}
{articles_html}
</div>
</main>
</div>
<footer class="site-footer">
{extra_footer_html}
</footer>
{copy_toast_html()}{search_scripts_html(cfg, prefix="")}{theme_script_html(prefix="")}
</body>
</html>
"""
def render_on_this_day_page(years, cfg):
"""
Render the *shell* for the On This Day page.
The actual date and entries are filled in by on-this-day.js
using on_this_day_index.json.
"""
site_title = cfg["site_title"]
site_tagline = cfg["site_tagline"]
page_title = f"{site_title} – On this day"
# Sidebar years
year_links = []
for y in sorted(years, reverse=True):
href = f"{y}.html"
css_class = "year-link"
year_links.append(f'<li><a href="{href}" class="{css_class}">{y}</a></li>')
years_nav_html = "\n ".join(year_links)
extra_head_html, extra_footer_html = build_common_head_and_footer(cfg)
# Heading and containers that JS will fill
main_heading = '<h2 id="on-this-day-heading" class="year-title">On this day</h2>'
subtitle = '<p id="on-this-day-subtitle" class="content-subtitle">Loading entries for today…</p>'
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{page_title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<link rel="alternate" type="application/rss+xml" title="{site_title} – RSS" href="rss.xml">{extra_head_html}
</head>
<body>
<input type="checkbox" id="theme-toggle" class="theme-toggle-checkbox" aria-label="Toggle dark mode">
<div class="layout">
<aside class="sidebar">
<header class="site-header">
<h1 class="site-title"><a href="index.html">{site_title}</a></h1>
<p class="site-tagline">{site_tagline}</p>
</header>
<div class="theme-toggle-control">
<label for="theme-toggle" class="theme-toggle-label">
<span class="theme-toggle-icon theme-toggle-light" aria-hidden="true">☀️</span>
<span class="theme-toggle-icon theme-toggle-dark" aria-hidden="true">🌙</span>
<span class="theme-toggle-text">Theme</span>
</label>
</div>
{sidebar_extra_links(prefix="", active_on_this_day=True)}
<input type="checkbox"
id="year-toggle"
class="year-toggle-checkbox"
aria-label="Toggle year navigation">
<label for="year-toggle" class="year-toggle-label">
<span class="year-toggle-burger" aria-hidden="true">
<span></span>
<span></span>
<span></span>
</span>
<span class="year-toggle-text">Browse years</span>
</label>
<nav class="year-nav">
<h2 class="year-nav-title">Years</h2>
<ul class="year-nav-list">
{years_nav_html}
</ul>
</nav>
</aside>
<main class="content">
<div class="content-inner">
<header class="content-header">
{main_heading}
{subtitle}
</header>
<div id="on-this-day-entries">
<p>Loading…</p>
</div>
</div>
</main>
</div>
<footer class="site-footer">
{extra_footer_html}
</footer>
{copy_toast_html()}
<script src="on-this-day.js"></script>{theme_script_html(prefix="")}
</body>
</html>
"""
def render_tag_page(tag_name: str, tag_slug: str, years: list, entries: list, cfg: dict) -> str:
"""
Tag page: no search UI.
"""
site_title = cfg["site_title"]
site_tagline = cfg["site_tagline"]
page_title = f"{site_title} – Tag: {tag_name}"
main_heading = f'<h2 class="year-title">Tag: {html.escape(tag_name)}</h2>'
# Sidebar years
year_links = []
for y in sorted(years, reverse=True):
href = f"../{y}.html"
css_class = "year-link"
year_links.append(f'<li><a href="{href}" class="{css_class}">{y}</a></li>')
years_nav_html = "\n ".join(year_links)
extra_head_html, extra_footer_html = build_common_head_and_footer(cfg)
if entries:
articles_html = "\n\n".join(render_entry(e, link_tags=False) for e in entries)
subtitle = "Entries across all years with this tag."
else:
articles_html = "<p>No entries yet for this tag.</p>"
subtitle = "No entries found for this tag."
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{page_title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../style.css">
<link rel="alternate" type="application/rss+xml" title="{site_title} – RSS" href="../rss.xml">{extra_head_html}
</head>
<body>
<input type="checkbox" id="theme-toggle" class="theme-toggle-checkbox" aria-label="Toggle dark mode">
<div class="layout">
<aside class="sidebar">
<header class="site-header">
<h1 class="site-title"><a href="../index.html">{site_title}</a></h1>
<p class="site-tagline">{site_tagline}</p>
</header>
<div class="theme-toggle-control">
<label for="theme-toggle" class="theme-toggle-label">
<span class="theme-toggle-icon theme-toggle-light" aria-hidden="true">☀️</span>
<span class="theme-toggle-icon theme-toggle-dark" aria-hidden="true">🌙</span>
<span class="theme-toggle-text">Theme</span>
</label>
</div>
{sidebar_extra_links(prefix="../", active_on_this_day=False)}
<input type="checkbox"
id="year-toggle"
class="year-toggle-checkbox"
aria-label="Toggle year navigation">
<label for="year-toggle" class="year-toggle-label">
<span class="year-toggle-burger" aria-hidden="true">
<span></span>
<span></span>
<span></span>
</span>
<span class="year-toggle-text">Browse years</span>
</label>
<nav class="year-nav">
<h2 class="year-nav-title">Years</h2>
<ul class="year-nav-list">
{years_nav_html}
</ul>
</nav>
</aside>
<main class="content">
<div class="content-inner">
<header class="content-header">
{main_heading}
<p class="content-subtitle">{subtitle}</p>
</header>
{articles_html}
</div>
</main>
</div>
<footer class="site-footer">
{extra_footer_html}
</footer>
{copy_toast_html()}{theme_script_html(prefix="../")}
</body>
</html>
"""
def render_tag_index_page(tag_index: dict, years: list, cfg: dict) -> str:
"""
Root-level tags.html: tag name + count + link to tag/<slug>.html
"""
site_title = cfg["site_title"]
site_tagline = cfg["site_tagline"]
page_title = f"{site_title} – Tags"
main_heading = '<h2 class="year-title">Tags</h2>'
# Sidebar years
year_links = []
for y in sorted(years, reverse=True):
href = f"{y}.html"
css_class = "year-link"
year_links.append(f'<li><a href="{href}" class="{css_class}">{y}</a></li>')
years_nav_html = "\n ".join(year_links)
extra_head_html, extra_footer_html = build_common_head_and_footer(cfg)
if tag_index:
items = []
for slug, data in sorted(tag_index.items(), key=lambda kv: kv[1]["name"].lower()):
name = data["name"]
count = len(data["entries"])
items.append(
f'<li class="tag-index-item">'
f'<a href="tag/{slug}.html" class="tag-index-link">{html.escape(name)}</a> '
f'<span class="tag-index-count">({count})</span>'
f'</li>'
)
tags_html = '<ul class="tag-index-list">' + "".join(items) + "</ul>"
subtitle = "All tags used in this journal."
else:
tags_html = "<p>No tags yet.</p>"
subtitle = "No tags found."
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{page_title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="style.css">
<link rel="alternate" type="application/rss+xml" title="{site_title} – RSS" href="rss.xml">{extra_head_html}
</head>
<body>
<input type="checkbox" id="theme-toggle" class="theme-toggle-checkbox" aria-label="Toggle dark mode">
<div class="layout">
<aside class="sidebar">
<header class="site-header">
<h1 class="site-title"><a href="index.html">{site_title}</a></h1>
<p class="site-tagline">{site_tagline}</p>
</header>
<div class="theme-toggle-control">
<label for="theme-toggle" class="theme-toggle-label">
<span class="theme-toggle-icon theme-toggle-light" aria-hidden="true">☀️</span>
<span class="theme-toggle-icon theme-toggle-dark" aria-hidden="true">🌙</span>
<span class="theme-toggle-text">Theme</span>
</label>
</div>
{sidebar_extra_links(prefix="", active_on_this_day=False)}
<input type="checkbox"
id="year-toggle"
class="year-toggle-checkbox"
aria-label="Toggle year navigation">
<label for="year-toggle" class="year-toggle-label">
<span class="year-toggle-burger" aria-hidden="true">
<span></span>
<span></span>
<span></span>
</span>
<span class="year-toggle-text">Browse years</span>
</label>
<nav class="year-nav">
<h2 class="year-nav-title">Years</h2>
<ul class="year-nav-list">
{years_nav_html}
</ul>
</nav>
</aside>
<main class="content">
<div class="content-inner">
<header class="content-header">
{main_heading}
<p class="content-subtitle">{subtitle}</p>
</header>
{tags_html}
</div>
</main>
</div>
<footer class="site-footer">
{extra_footer_html}
</footer>
{copy_toast_html()}{search_scripts_html(cfg, prefix="")}{theme_script_html(prefix="")}
</body>
</html>
"""
# -----------------------
# Static assets / RSS / search index
# -----------------------
def copy_css(output_dir: Path):
src = BASE_DIR / CSS_FILENAME
if not src.exists():
print(f"WARNING: CSS file not found at {src}", file=sys.stderr)
return
dest = output_dir / CSS_FILENAME
shutil.copy2(src, dest)
print(f"Copied CSS to {dest}")
def copy_search_js(cfg: dict, output_dir: Path):
if not cfg.get("enable_search", True):
return
for filename in (LUNR_JS_FILENAME, SEARCH_JS_FILENAME):
src = BASE_DIR / filename
if not src.exists():
print(f"WARNING: Search JS file not found at {src}", file=sys.stderr)
continue
dest = output_dir / filename
shutil.copy2(src, dest)
print(f"Copied {filename} to {dest}")
def copy_on_this_day_js(output_dir: Path):
src = BASE_DIR / "on-this-day.js"
if not src.exists():
print(f"WARNING: on-this-day.js not found at {src}", file=sys.stderr)
return
dest = output_dir / "on-this-day.js"
shutil.copy2(src, dest)
print(f"Copied on-this-day.js to {dest}")
def copy_resources(cfg: dict, project_root: Path, content_root: Path, output_dir: Path):
"""
Copy arbitrary resource files listed in config['resources'] into the output dir.
Each entry is treated as a *relative path*.
Search order for each resource:
1) project_root / resource
2) content_root / resource
If found, it is copied to output_dir / resource (creating parent dirs).
"""
resources = cfg.get("resources") or []
if not resources:
return
for rel in resources:
rel_path = Path(rel)
# Try project root first (same dir as config.yml)
candidates = [
project_root / rel_path,
content_root / rel_path,
]
src = None
for cand in candidates:
if cand.exists():
src = cand
break
if src is None:
print(f"WARNING: resource not found: {rel}", file=sys.stderr)
continue
dest = output_dir / rel_path
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(src, dest)
print(f"Copied resource {src} -> {dest}")
def write_theme_js(output_dir: Path):
"""
Write theme.js (persistent dark mode + permalink share/copy) into the output dir.
"""
js = r"""