forked from w3c/csswg-drafts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild-index.py
More file actions
719 lines (638 loc) · 25.1 KB
/
build-index.py
File metadata and controls
719 lines (638 loc) · 25.1 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
"""
All the drafts are built by the build-specs workflow itself.
This handles the rest of the work:
* creates an index page listing all specs
* creates symlinks for unlevelled urls, linking to the appropriate levelled folder
* builds timestamps.json, which provides metadata about the specs
"""
import glob
import json
import os
import os.path
import re
import subprocess
from collections import defaultdict
from datetime import datetime, timezone
import bikeshed
from html.parser import HTMLParser
def title_from_html(file):
class HTMLTitleParser(HTMLParser):
def __init__(self):
super().__init__()
self.in_title = False
self.title = ""
self.done = False
def handle_starttag(self, tag, attrs):
if tag == "title":
self.in_title = True
def handle_data(self, data):
if self.in_title:
self.title += data
def handle_endtag(self, tag):
if tag == "title" and self.in_title:
self.in_title = False
self.done = True
self.reset()
parser = HTMLTitleParser()
with open(file, encoding="UTF-8") as f:
for line in f:
parser.feed(line)
if parser.done:
break
if not parser.done:
parser.close()
return parser.title if parser.done else None
def get_date_authored_timestamp_from_git(path):
source = os.path.realpath(path)
proc = subprocess.run(["git", "log", "-1", "--format=%at", source],
capture_output = True, encoding = "utf_8")
return int(proc.stdout.splitlines()[-1])
def get_bs_spec_metadata(folder_name, path):
spec = bikeshed.Spec(path)
spec.assembleDocument()
level = int(spec.md.level) if spec.md.level else 0
if spec.md.shortname == "css-animations-2":
shortname = "css-animations"
elif spec.md.shortname == "css-gcpm-4":
shortname = "css-gcpm"
elif spec.md.shortname == "css-transitions-2":
shortname = "css-transitions"
elif spec.md.shortname == "scroll-animations-1":
shortname = "scroll-animations"
else:
# Fix CSS snapshots (e.g. "css-2022")
snapshot_match = re.match(
"^css-(20[0-9]{2})$", spec.md.shortname)
if snapshot_match:
shortname = "css-snapshot"
level = int(snapshot_match.group(1))
else:
shortname = spec.md.shortname
return {
"timestamp": get_date_authored_timestamp_from_git(path),
"shortname": shortname,
"level": level,
"title": spec.md.title,
"workStatus": spec.md.workStatus
}
def get_html_spec_metadata(folder_name, path):
match = re.match("^([a-z0-9-]+)-([0-9]+)$", folder_name)
if match and match.group(1) == "css":
shortname = "css-snapshot"
title = f"CSS Snapshot {match.group(2)}"
else:
shortname = match.group(1) if match else folder_name
title = title_from_html(path)
return {
"shortname": shortname,
"level": int(match.group(2)) if match else 0,
"title": title,
"workStatus": "completed" # It's a good heuristic
}
def create_symlink(shortname, spec_folder):
"""Creates a <shortname> symlink pointing to the given <spec_folder>.
"""
if spec_folder in timestamps:
timestamps[shortname] = timestamps[spec_folder]
try:
os.symlink(spec_folder, shortname)
except OSError:
pass
def format_timestamp(ts):
"""Format a Unix timestamp as a human-readable date string."""
dt = datetime.fromtimestamp(ts, tz=timezone.utc)
return dt.strftime("%Y-%m-%d")
def escape_html(text):
"""Escape HTML special characters."""
return (text
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """))
CURRENT_WORK_EXCEPTIONS = {
"compositing": 2,
"css-conditional": 5,
"css-easing": 2,
"css-grid": 2,
"css-snapshot": None, # always choose the last spec
"css-values": 4,
"css-writing-modes": 4,
"web-animations": 2
}
# ------------------------------------------------------------------------------
bikeshed.messages.state.dieOn = "nothing"
specgroups = defaultdict(list)
timestamps = defaultdict(list)
for entry in os.scandir("."):
if entry.is_dir(follow_symlinks=False):
# Not actual specs, just examples.
if entry.name in ["css-module"]:
continue
bs_file = os.path.join(entry.path, "Overview.bs")
html_file = os.path.join(entry.path, "Overview.html")
if os.path.exists(bs_file):
metadata = get_bs_spec_metadata(entry.name, bs_file)
timestamps[entry.name] = metadata["timestamp"]
elif os.path.exists(html_file):
metadata = get_html_spec_metadata(entry.name, html_file)
else:
# Not a spec
continue
metadata["dir"] = entry.name
metadata["currentWork"] = False
issues_files = sorted(f for f in glob.glob(os.path.join(entry.path, "issues-*.html"))
if not f.endswith(".bsi.html"))
metadata["issues"] = [os.path.basename(f) for f in issues_files]
specgroups[metadata["shortname"]].append(metadata)
# Reorder the specs with common shortname based on their level (or year, for
# CSS snapshots), and determine which spec is the current work.
for shortname, specgroup in specgroups.items():
if len(specgroup) == 1:
if shortname != specgroup[0]["dir"]:
create_symlink(shortname, specgroup[0]["dir"])
else:
specgroup.sort(key=lambda spec: spec["level"])
# TODO: This algorithm for determining which spec is the current work
# is wrong in a number of cases. Try and come up with a better
# algorithm, rather than maintaining a list of exceptions.
for spec in specgroup:
if shortname in CURRENT_WORK_EXCEPTIONS:
if CURRENT_WORK_EXCEPTIONS[shortname] == spec["level"]:
spec["currentWork"] = True
currentWorkDir = spec["dir"]
break
elif spec["workStatus"] != "completed":
spec["currentWork"] = True
currentWorkDir = spec["dir"]
break
else:
specgroup[-1]["currentWork"] = True
currentWorkDir = specgroup[-1]["dir"]
if shortname != currentWorkDir:
create_symlink(shortname, currentWorkDir)
if shortname == "css-snapshot":
create_symlink("css", currentWorkDir)
with open('./timestamps.json', 'w') as f:
json.dump(timestamps, f, indent = 2, sort_keys=True)
# Legacy path redirects
# These handle old URLs that were previously served by Apache RewriteRule redirects.
# For local targets, we use symlinks. For cross-origin targets (css-houdini.org),
# we create HTML files with meta refresh.
LEGACY_REDIRECTS = {
# Old name -> new name (local redirects via symlink)
"css-anchor-1": "css-anchor-position-1",
"css3-grid-align": "css-grid-1",
"css3-text-layout": "css-writing-modes-3",
"css3-2d-transforms": "css-transforms",
"css3-3d-transforms": "css-transforms",
"mediaqueries3": "mediaqueries-3",
"mediaqueries4": "mediaqueries-4",
"css-namespaces-1": "css-namespaces",
"css-snappoints-1": "css-scroll-snap-1",
"css-snappoints": "css-scroll-snap",
"css-snap-size-1": "css-rhythm-1",
"css-snap-size": "css-rhythm",
"css-step-sizing": "css-rhythm",
"css-containment": "css-contain",
"css-logical-props": "css-logical",
"css-device-adapt-1": "css-viewport-1",
"css-device-adapt": "css-viewport",
"css-overscroll-behavior-1": "css-overscroll-1",
"css-overscroll-behavior": "css-overscroll",
"css-shared-element-transitions-1": "css-view-transitions-1",
"css-shared-element-transitions": "css-view-transitions",
"css-timing-1": "css-easing-1",
"css-timing": "css-easing",
"css-scoping-2": "css-cascade-6",
}
# Cross-origin redirects need HTML meta refresh files
CROSS_ORIGIN_REDIRECTS = {
"cssom-values-1": "https://drafts.css-houdini.org/css-typed-om-1/",
"cssom-values": "https://drafts.css-houdini.org/css-typed-om/",
}
REDIRECT_HTML_TEMPLATE = """<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Redirecting…</title>
<meta http-equiv="refresh" content="0; url={url}">
<link rel="canonical" href="{url}">
</head>
<body>
<p>This page has moved to <a href="{url}">{url}</a>.</p>
</body>
</html>
"""
for old_path, new_path in LEGACY_REDIRECTS.items():
if os.path.exists(new_path) and not os.path.exists(old_path):
try:
os.symlink(new_path, old_path)
except OSError:
pass
for old_path, url in CROSS_ORIGIN_REDIRECTS.items():
if not os.path.exists(old_path):
os.makedirs(old_path, exist_ok=True)
index_file = os.path.join(old_path, "index.html")
if not os.path.exists(index_file):
with open(index_file, "w", encoding="utf-8") as f:
f.write(REDIRECT_HTML_TEMPLATE.format(url=url))
# css2 subpage redirects: old CSS 2.1 chapter URLs redirect to the spec root
CSS2_SUBPAGES = [
"about.html", "aural.html", "box.html", "cascade.html", "changes.html",
"colors.html", "conform.html", "cover.html", "fonts.html", "generate.html",
"grammar.html", "indexlist.html", "intro.html", "leftblank.html", "media.html",
"page.html", "propidx.html", "refs.html", "sample.html", "selector.html",
"syndata.html", "tables.html", "text.html", "ui.html", "visudet.html",
"visufx.html", "visuren.html", "zindex.html",
]
for subpage in CSS2_SUBPAGES:
subpage_path = os.path.join("css2", subpage)
if not os.path.exists(subpage_path):
with open(subpage_path, "w", encoding="utf-8") as f:
f.write(REDIRECT_HTML_TEMPLATE.format(url="./"))
# Build the index page
# Flatten all specs into a single list with full metadata
all_specs = []
for shortname, specgroup in specgroups.items():
group_size = len(specgroup)
for spec in specgroup:
dir_name = spec["dir"]
ts = timestamps.get(dir_name, 0)
title = spec["title"] or dir_name
doc_links = []
for fname in spec.get("issues", []):
label = fname.replace("issues-", "").replace(".html", "")
doc_links.append((f"./{dir_name}/{fname}", label))
all_specs.append({
"shortname": shortname,
"dir": dir_name,
"title": title,
"ts": ts if isinstance(ts, int) else 0,
"currentWork": spec["currentWork"],
"level": spec["level"],
"group_size": group_size,
"doc_links": doc_links,
})
# Sort by timestamp descending (most recent first) for default view
all_specs.sort(key=lambda s: s["ts"], reverse=True)
# Generate HTML for each spec
REPO = "https://github.com/w3c/csswg-drafts"
spec_items = []
for spec in all_specs:
t = escape_html(spec["title"]).replace("Level ", "Level\u00a0")
d = spec["dir"]
sn = spec["shortname"]
ts = spec["ts"]
lv = spec["level"]
gs = spec["group_size"]
date_str = format_timestamp(ts) if ts else ""
iso_date = datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") if ts else ""
cw = ' <span class="badge current-work">Current Work</span>' if spec["currentWork"] else ""
links = [
f'<a href="{REPO}/issues?q=is%3Aissue+is%3Aopen+label%3A{d}">Issues</a>',
f'<a href="{REPO}/pulls?q=is%3Apr+is%3Aopen+label%3A{d}">PRs</a>',
f'<a href="{REPO}/commits/main/{d}/">History</a>',
]
for url, label in spec["doc_links"]:
links.append(f'<a href="{url}">DoC: {escape_html(label)}</a>')
links_html = ' <span class="sep">\u00b7</span> '.join(links)
spec_items.append(
f' <div class="spec" data-ts="{ts}" data-shortname="{escape_html(sn)}"'
f' data-dir="{escape_html(d)}" data-level="{lv}" data-group-size="{gs}">\n'
f' <div class="spec-header">\n'
f' <span class="activity-dot" data-ts="{ts}"></span>\n'
f' <a class="spec-title" href="./{d}/">{t}</a>{cw}\n'
f' <code class="spec-shortname">{escape_html(d)}</code>\n'
f' <time class="spec-date" datetime="{iso_date}" data-ts="{ts}">{date_str}</time>\n'
f' <span class="chevron" aria-hidden="true">›</span>\n'
f' </div>\n'
f' <div class="spec-details">\n'
f' <div class="spec-links">{links_html}</div>\n'
f' </div>\n'
f' </div>'
)
specs_html = "\n".join(spec_items)
HTML_START = """\
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>CSS Working Group Editor Drafts</title>
<style>
*, *::before, *::after { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; text-size-adjust: 100%; }
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
max-width: 960px; margin: 0 auto; padding: 1.5em 1em;
color: #1f2328; background: #fff; line-height: 1.5;
}
h1 { font-size: 1.5em; font-weight: 600; margin: 0 0 0.75em; }
a { color: #0366d6; text-decoration: none; }
a:hover { text-decoration: underline; }
.search-bar {
position: sticky; top: 0; background: #fff;
padding: 0.5em 0 0.75em; z-index: 10;
}
.search-bar input {
width: 100%; padding: 0.6em 1em; font-size: 1em;
border: 1px solid #d1d5db; border-radius: 6px;
outline: none; background: #f6f8fa; color: inherit;
}
.search-bar input:focus {
background: #fff; border-color: #0366d6;
box-shadow: 0 0 0 3px rgba(3,102,214,0.15);
}
.controls {
display: flex; gap: 0.5em; align-items: center;
margin-bottom: 0.75em; font-size: 0.85em; color: #666;
}
.controls button {
background: none; border: 1px solid #d1d5db;
padding: 0.25em 0.75em; border-radius: 4px;
cursor: pointer; font-size: inherit; color: #444;
}
.controls button:hover { background: #f6f8fa; }
.controls button:focus-visible { outline: 2px solid #0366d6; outline-offset: 1px; }
.controls button.active { background: #0366d6; color: #fff; border-color: #0366d6; }
.spec-count { margin-left: auto; }
#spec-list { margin-top: 0.25em; }
.spec { padding: 0.6em 0; border-bottom: 1px solid #eee; }
.spec:last-child { border-bottom: none; }
.spec.hidden { display: none; }
.spec-header {
display: flex; align-items: baseline; gap: 0.5em; flex-wrap: wrap;
}
.activity-dot {
display: inline-block; width: 8px; height: 8px;
border-radius: 50%; flex-shrink: 0; position: relative; top: -1px;
}
.activity-dot.recent { background: #1a7f37; }
.activity-dot.moderate { background: #bf8700; }
.activity-dot.stale { background: #ccc; }
.spec-title { color: #0366d6; text-decoration: none; font-weight: 500; }
.spec-title:hover { text-decoration: underline; }
.badge {
font-size: 0.75em; padding: 0.15em 0.5em; border-radius: 3px;
font-weight: 500; white-space: nowrap;
}
.current-work { background: #dafbe1; color: #1a7f37; }
.spec-shortname {
font-size: 0.8em; color: #656d76; background: #f6f8fa;
padding: 0.1em 0.4em; border-radius: 3px;
}
.spec-date {
margin-left: auto; font-size: 0.85em; color: #656d76; white-space: nowrap;
}
.chevron { display: none; }
.spec-links { margin-top: 0.2em; padding-left: 1.5em; font-size: 0.8em; }
.spec-links a { color: #656d76; text-decoration: none; }
.spec-links a:hover { color: #0366d6; text-decoration: underline; }
.sep { color: #ccc; margin: 0 0.15em; }
.group-header {
font-weight: 600; font-size: 0.9em; padding: 1em 0 0.3em;
color: #1f2328; border-bottom: 1px solid #d1d5db;
}
.grouped-spec { padding-left: 1.5em; }
.no-results { padding: 2em; text-align: center; color: #666; display: none; }
/* ---- Mobile ---- */
@media (max-width: 640px) {
body { padding: 1em 0.75em; }
h1 { font-size: 1.25em; }
.search-bar input { font-size: 16px; }
.spec {
padding: 0.75em 0;
-webkit-tap-highlight-color: transparent;
}
.spec-header {
display: grid;
grid-template-columns: auto 1fr auto auto;
gap: 0.15em 0.4em;
align-items: baseline;
cursor: pointer;
}
.activity-dot { grid-row: 1; grid-column: 1; }
.spec-title { grid-row: 1; grid-column: 2; }
.spec-date { grid-row: 1; grid-column: 3; margin-left: 0; }
.chevron {
grid-row: 1; grid-column: 4;
display: inline-block; color: #8b949e; font-size: 0.75em;
transition: transform 0.2s ease; user-select: none;
}
.spec.expanded .chevron { transform: rotate(90deg); }
.badge { grid-row: 2; grid-column: 2 / -1; justify-self: start; }
.spec-shortname { display: none; }
.spec-details { display: none; }
.spec.expanded .spec-details { display: block; }
.spec-links {
display: flex; flex-wrap: wrap; gap: 0.4em;
padding: 0.4em 0 0.1em 1.25em; margin-top: 0;
}
.spec-links .sep { display: none; }
.spec-links a {
display: inline-flex; align-items: center;
background: #f6f8fa; color: #444;
padding: 0.35em 0.7em; border-radius: 999px;
font-size: 0.85em; min-height: 28px;
}
.spec-links a:hover { text-decoration: none; background: #e8ecf0; }
.controls button { padding: 0.4em 0.85em; }
.grouped-spec { padding-left: 0.75em; }
}
/* ---- Dark mode ---- */
@media (prefers-color-scheme: dark) {
body { background: #0d1117; color: #e6edf3; }
.search-bar { background: #0d1117; }
.search-bar input {
background: #161b22; border-color: #30363d; color: #e6edf3;
}
.search-bar input::placeholder { color: #484f58; }
.search-bar input:focus {
background: #0d1117; border-color: #58a6ff;
box-shadow: 0 0 0 3px rgba(88,166,255,0.15);
}
.spec { border-bottom-color: #21262d; }
.spec-title { color: #58a6ff; }
.spec-shortname { background: #161b22; color: #8b949e; }
.spec-date { color: #8b949e; }
.spec-links a { color: #8b949e; }
.spec-links a:hover { color: #58a6ff; }
.sep { color: #484f58; }
.controls { color: #8b949e; }
.controls button { color: #8b949e; border-color: #30363d; }
.controls button:hover { background: #161b22; }
.controls button.active {
background: #1f6feb; color: #fff; border-color: #1f6feb;
}
.current-work { background: #0d2818; color: #3fb950; }
.activity-dot.recent { background: #3fb950; }
.activity-dot.moderate { background: #d29922; }
.activity-dot.stale { background: #484f58; }
.group-header { color: #e6edf3; border-bottom-color: #30363d; }
.no-results { color: #8b949e; }
.chevron { color: #484f58; }
a { color: #58a6ff; }
}
@media (max-width: 640px) and (prefers-color-scheme: dark) {
.spec-links a { background: #21262d; color: #8b949e; }
.spec-links a:hover { background: #30363d; color: #58a6ff; }
}
</style>
</head>
<body>
<h1>CSS Working Group Editor Drafts</h1>
<div class="search-bar">
<input type="text" id="search" placeholder="Filter specifications\u2026" autofocus>
</div>
<div class="controls">
<button id="sort-recent" class="active">Recent</button>
<button id="sort-grouped">Grouped</button>
<span class="spec-count" id="spec-count"></span>
</div>
<div id="spec-list">
"""
HTML_END = """\
</div>
<div class="no-results" id="no-results">No matching specifications.</div>
<script>
(function() {
var searchInput = document.getElementById('search');
var specList = document.getElementById('spec-list');
var specs = Array.from(specList.querySelectorAll('.spec'));
var btnRecent = document.getElementById('sort-recent');
var btnGrouped = document.getElementById('sort-grouped');
var countEl = document.getElementById('spec-count');
var noResults = document.getElementById('no-results');
var totalCount = specs.length;
var mobileQuery = window.matchMedia('(max-width: 640px)');
var now = Date.now() / 1000;
var DAY = 86400;
specs.forEach(function(el) {
var ts = parseInt(el.dataset.ts);
if (!ts) return;
var age = now - ts;
var dot = el.querySelector('.activity-dot');
var timeEl = el.querySelector('.spec-date');
if (age < 30 * DAY) {
dot.className = 'activity-dot recent';
dot.title = 'Updated recently';
} else if (age < 180 * DAY) {
dot.className = 'activity-dot moderate';
dot.title = 'Updated in the last 6 months';
} else {
dot.className = 'activity-dot stale';
dot.title = 'Not updated in 6+ months';
}
var rel;
if (age < DAY) rel = 'today';
else if (age < 2 * DAY) rel = 'yesterday';
else if (age < 7 * DAY) rel = Math.floor(age / DAY) + ' days ago';
else if (age < 30 * DAY) {
var w = Math.floor(age / (7 * DAY));
rel = w === 1 ? 'last week' : w + ' weeks ago';
} else if (age < 365 * DAY) {
var m = Math.floor(age / (30 * DAY));
rel = m === 1 ? 'last month' : m + ' months ago';
} else {
var y = Math.floor(age / (365 * DAY));
rel = y === 1 ? 'last year' : y + ' years ago';
}
timeEl.title = timeEl.textContent;
timeEl.textContent = rel;
});
function updateCount() {
var visible = specs.filter(function(s) {
return !s.classList.contains('hidden');
}).length;
countEl.textContent = visible === totalCount
? totalCount + ' specs' : visible + ' of ' + totalCount;
noResults.style.display = visible === 0 ? 'block' : 'none';
}
updateCount();
searchInput.addEventListener('input', function() {
var q = searchInput.value.toLowerCase();
specs.forEach(function(el) {
var text = el.dataset.dir + ' ' + el.dataset.shortname + ' ' +
el.querySelector('.spec-title').textContent.toLowerCase();
if (text.indexOf(q) >= 0) el.classList.remove('hidden');
else el.classList.add('hidden');
});
specList.querySelectorAll('.group-header').forEach(function(h) {
var sn = h.dataset.shortname;
var any = specs.some(function(s) {
return s.dataset.shortname === sn && !s.classList.contains('hidden');
});
h.style.display = any ? '' : 'none';
});
specs.forEach(function(s) { s.classList.remove('expanded'); });
updateCount();
});
function sortRecent() {
window.localStorage.setItem('index-sort', 'recent');
specList.querySelectorAll('.group-header').forEach(function(h) { h.remove(); });
specs.sort(function(a, b) {
return parseInt(b.dataset.ts) - parseInt(a.dataset.ts);
});
specs.forEach(function(el) {
el.classList.remove('grouped-spec');
specList.appendChild(el);
});
btnRecent.classList.add('active');
btnGrouped.classList.remove('active');
}
function sortGrouped() {
window.localStorage.setItem('index-sort', 'grouped');
specList.querySelectorAll('.group-header').forEach(function(h) { h.remove(); });
specs.sort(function(a, b) {
var c = a.dataset.shortname.localeCompare(b.dataset.shortname);
if (c !== 0) return c;
return parseInt(a.dataset.level) - parseInt(b.dataset.level);
});
var lastSn = null;
specs.forEach(function(el) {
var sn = el.dataset.shortname;
var gs = parseInt(el.dataset.groupSize);
if (sn !== lastSn && gs > 1) {
var header = document.createElement('div');
header.className = 'group-header';
header.dataset.shortname = sn;
header.textContent = sn;
specList.appendChild(header);
}
if (gs > 1) el.classList.add('grouped-spec');
else el.classList.remove('grouped-spec');
specList.appendChild(el);
lastSn = sn;
});
btnGrouped.classList.add('active');
btnRecent.classList.remove('active');
}
btnRecent.addEventListener('click', sortRecent);
btnGrouped.addEventListener('click', sortGrouped);
if (window.localStorage.getItem('index-sort') === 'grouped') {
sortGrouped();
}
// Mobile: tap spec header to expand/collapse (accordion)
specs.forEach(function(el) {
var header = el.querySelector('.spec-header');
header.addEventListener('click', function(e) {
if (e.target.closest('a')) return;
if (!mobileQuery.matches) return;
var wasExpanded = el.classList.contains('expanded');
specs.forEach(function(s) { s.classList.remove('expanded'); });
if (!wasExpanded) el.classList.add('expanded');
});
});
// Auto-expand first spec on mobile to demonstrate the pattern
if (mobileQuery.matches && specs.length > 0) {
specs[0].classList.add('expanded');
}
})();
</script>
</body>
</html>
"""
with open("./index.html", mode='w', encoding="UTF-8") as f:
f.write(HTML_START)
f.write(specs_html)
f.write(HTML_END)