-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbuild-html.js
More file actions
2124 lines (1851 loc) · 60.2 KB
/
build-html.js
File metadata and controls
2124 lines (1851 loc) · 60.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 node
const fs = require('fs');
const path = require('path');
const { marked, Renderer } = require('marked');
const hljs = require('highlight.js');
const chokidar = require('chokidar');
const PODCAST_INDEX_URL = 'https://lp.csedesigns.com/ggg/PODCASTS.html';
const PODCAST_FEED_URL = 'https://lp.csedesigns.com/ggg/feed.xml';
const PODCAST_AUDIO_BASE_URL = 'https://lp.csedesigns.com/ggg/media';
const REPO_BLOB_BASE_URL = 'https://github.com/Community-Access/git-going-with-github/blob/main';
// Accumulates page data for search index
const searchPages = [];
// Configure marked with syntax highlighting via custom renderer (marked v11+)
const renderer = new Renderer();
renderer.code = function (code, infostring, escaped) {
const lang = (infostring || '').match(/^\S*/)?.[0] || null;
const language = lang && hljs.getLanguage(lang) ? lang : null;
let highlighted;
try {
highlighted = language
? hljs.highlight(code, { language }).value
: hljs.highlightAuto(code).value;
} catch (err) {
highlighted = code;
}
const cls = language ? ` class="hljs language-${language}"` : ' class="hljs"';
return `<pre><code${cls}>${highlighted}</code></pre>\n`;
};
// Generate heading IDs matching GitHub's anchor algorithm so TOC links work
function headingAnchor(text) {
// Strip inline HTML tags (e.g. <code>, <strong>)
const plain = text.replace(/<[^>]+>/g, '');
return plain
.toLowerCase()
.replace(/[^\w\s-]/g, '') // remove punctuation except hyphens
.replace(/ /g, '-'); // spaces → hyphens (preserve consecutive hyphens)
}
renderer.heading = function (text, level) {
const id = headingAnchor(text);
return `<h${level} id="${id}">${text}</h${level}>\n`;
};
// Unwrap single <p> from list items so screen readers don't announce a
// separate paragraph element before reading the bullet text (loose list fix)
renderer.listitem = function (text, task, checked) {
const unwrapped = text.replace(/^<p>([\s\S]*?)<\/p>\n?$/, '$1');
if (task) {
if (/<input\b[^>]*type="checkbox"/.test(unwrapped)) {
return `<li>${unwrapped}</li>\n`;
}
const checkbox = `<input type="checkbox"${checked ? ' checked' : ''} disabled> `;
return `<li>${checkbox}${unwrapped}</li>\n`;
}
return `<li>${unwrapped}</li>\n`;
};
// Add scope="col" to all <th> elements for WCAG 1.3.1
renderer.tablecell = function (content, flags) {
const tag = flags.header ? 'th' : 'td';
const align = flags.align ? ` style="text-align:${flags.align}"` : '';
const scope = flags.header ? ' scope="col"' : '';
return `<${tag}${align}${scope}>${content}</${tag}>\n`;
};
marked.setOptions({
breaks: false,
gfm: true,
renderer
});
function normalizeGeneratedText(text) {
return text
.replace(/\r\n/g, '\n')
.replace(/\r/g, '\n')
.replace(/^(={7,})(.*)$/gm, '<span aria-hidden="true"></span>$1$2')
.replace(/[ \t]+$/gm, '')
.trimEnd() + '\n';
}
function writeGeneratedFile(filePath, content) {
fs.writeFileSync(filePath, normalizeGeneratedText(content), 'utf-8');
}
function writeRedirectPage(filePath, targetHref) {
const redirectHtml = `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="refresh" content="0; url=${targetHref}">
<link rel="canonical" href="${targetHref}">
<title>Redirecting...</title>
</head>
<body>
<p>Redirecting to <a href="${targetHref}">${targetHref}</a>...</p>
</body>
</html>`;
ensureDir(path.dirname(filePath));
writeGeneratedFile(filePath, redirectHtml);
}
function normalizePodcastEndpoints(text) {
return text
.replace(/href="(?:\.\.\/)?admin\/PODCASTS\.(?:md|html)(#[^"]*)?"/gi, `href="${PODCAST_INDEX_URL}$1"`)
.replace(/href="(?:https?:\/\/community-access\.org\/git-going-with-github)?\/?podcasts\/feed\.xml"/gi, `href="${PODCAST_FEED_URL}"`);
}
let docsCatalogCache = null;
let podcastCompanionCache = null;
function escapeHtmlText(value) {
return String(value)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function readMarkdownTitle(filePath, fallbackTitle) {
try {
const content = fs.readFileSync(filePath, 'utf-8');
const heading = content.match(/^#\s+(.+)$/m);
if (heading && heading[1]) {
return heading[1].trim();
}
} catch (err) {
// Ignore title extraction failures and use fallback.
}
return fallbackTitle;
}
function getDocsCatalog() {
if (docsCatalogCache) {
return docsCatalogCache;
}
const docsDir = path.join(process.cwd(), 'docs');
if (!fs.existsSync(docsDir)) {
docsCatalogCache = {
essentials: [],
chapters: [],
day1: [],
day2: [],
appendices: []
};
return docsCatalogCache;
}
const files = fs.readdirSync(docsDir)
.filter((name) => name.toLowerCase().endsWith('.md'))
.sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
const toItem = (name) => {
const sourcePath = path.join(docsDir, name);
const fallback = name
.replace(/\.md$/i, '')
.replace(/-/g, ' ')
.replace(/\b\w/g, (m) => m.toUpperCase());
return {
href: `docs/${name.replace(/\.md$/i, '.html')}`,
title: readMarkdownTitle(sourcePath, fallback),
source: name
};
};
const essentialsOrder = ['course-guide.md', 'get-going.md', 'CHALLENGES.md'];
const essentials = essentialsOrder
.filter((name) => files.includes(name))
.map(toItem);
const chapters = files
.filter((name) => /^\d{2}-.*\.md$/i.test(name))
.map(toItem);
const day1 = chapters.filter((item) => {
const num = Number(item.source.slice(0, 2));
return !Number.isNaN(num) && num <= 10;
});
const day2 = chapters.filter((item) => {
const num = Number(item.source.slice(0, 2));
return !Number.isNaN(num) && num >= 11;
});
const appendices = files
.filter((name) => /^appendix-[a-z0-9-]+\.md$/i.test(name))
.map(toItem)
.sort((a, b) => {
const getAppendixKey = (source) => {
const match = source.match(/^appendix-([a-z0-9]+)-?/i);
const key = (match && match[1] ? match[1] : '').toLowerCase();
const isExtended = ['aa', 'ab', 'ac'].includes(key);
return { key, isExtended };
};
const aKey = getAppendixKey(a.source);
const bKey = getAppendixKey(b.source);
// Keep AA/AB/AC at the bottom of appendix navigation.
if (aKey.isExtended && !bKey.isExtended) return 1;
if (!aKey.isExtended && bKey.isExtended) return -1;
return a.source.localeCompare(b.source, undefined, { numeric: true });
});
docsCatalogCache = { essentials, chapters, day1, day2, appendices };
return docsCatalogCache;
}
function listFilesRecursive(dirPath, predicate, acc = []) {
if (!fs.existsSync(dirPath)) return acc;
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(dirPath, entry.name);
if (entry.isDirectory()) {
listFilesRecursive(full, predicate, acc);
} else if (entry.isFile() && predicate(entry.name, full)) {
acc.push(full);
}
}
return acc;
}
function parseTranscriptSegments(scriptText) {
const segments = [];
let currentSpeaker = null;
let currentLines = [];
for (const line of scriptText.split('\n')) {
const trimmed = line.trim();
if (!trimmed) continue;
if (trimmed === '[PAUSE]') {
if (currentSpeaker && currentLines.length) {
segments.push({ speaker: currentSpeaker, text: currentLines.join(' ').trim() });
currentLines = [];
}
continue;
}
const speakerMatch = trimmed.match(/^\[(ALEX|JAMIE)\]$/);
if (speakerMatch) {
if (currentSpeaker && currentLines.length) {
segments.push({ speaker: currentSpeaker, text: currentLines.join(' ').trim() });
currentLines = [];
}
currentSpeaker = speakerMatch[1];
continue;
}
const inlineMatch = trimmed.match(/^\[(ALEX|JAMIE)\]\s+(.*)/);
if (inlineMatch) {
if (currentSpeaker && currentLines.length) {
segments.push({ speaker: currentSpeaker, text: currentLines.join(' ').trim() });
currentLines = [];
}
currentSpeaker = inlineMatch[1];
if (inlineMatch[2]) currentLines.push(inlineMatch[2]);
continue;
}
if (currentSpeaker) {
currentLines.push(trimmed);
}
}
if (currentSpeaker && currentLines.length) {
segments.push({ speaker: currentSpeaker, text: currentLines.join(' ').trim() });
}
return segments;
}
function getPodcastCompanionsForPage(normalizedRelativePath) {
if (!normalizedRelativePath.startsWith('docs/')) {
return [];
}
if (!podcastCompanionCache) {
const manifestPath = path.join(process.cwd(), 'podcasts', 'manifest.json');
const scriptsDir = path.join(process.cwd(), 'podcasts', 'scripts');
const manifest = fs.existsSync(manifestPath)
? JSON.parse(fs.readFileSync(manifestPath, 'utf-8'))
: [];
const scripts = listFilesRecursive(
scriptsDir,
(name) => name.toLowerCase().endsWith('.txt')
);
const scriptMap = new Map();
for (const scriptPath of scripts) {
scriptMap.set(path.basename(scriptPath).toLowerCase(), scriptPath);
}
const bySource = new Map();
for (const ep of manifest) {
if (!ep.audio) {
throw new Error(`manifest entry missing required 'audio' field (number=${ep.number}, slug=${ep.slug}); regenerate manifest before building HTML`);
}
const audioFile = ep.audio;
const canonicalBase = audioFile.replace(/\.mp3$/i, '');
const scriptName = `${canonicalBase}.txt`.toLowerCase();
const scriptPath = scriptMap.get(scriptName) || null;
const transcriptUrl = scriptPath
? `${REPO_BLOB_BASE_URL}/${path.relative(process.cwd(), scriptPath).replace(/\\/g, '/')}`
: `${REPO_BLOB_BASE_URL}/podcasts/scripts`;
const previewSegments = (() => {
if (!scriptPath) return [];
try {
const raw = fs.readFileSync(scriptPath, 'utf-8');
return parseTranscriptSegments(raw).slice(0, 4);
} catch {
return [];
}
})();
const item = {
title: ep.title || ep.slug,
audioUrl: `${PODCAST_AUDIO_BASE_URL}/${audioFile}`,
transcriptUrl,
previewSegments
};
const sources = Array.isArray(ep.sources) ? ep.sources : [];
for (const src of sources) {
const key = String(src || '').toLowerCase();
if (!key) continue;
if (!bySource.has(key)) bySource.set(key, []);
bySource.get(key).push(item);
}
}
podcastCompanionCache = { bySource };
}
const sourceMd = path.basename(normalizedRelativePath).replace(/\.html$/i, '.md').toLowerCase();
return podcastCompanionCache.bySource.get(sourceMd) || [];
}
function renderCompanionMedia(normalizedRelativePath) {
const companions = getPodcastCompanionsForPage(normalizedRelativePath);
if (!companions.length) {
return '';
}
const cards = companions.map((c) => {
const preview = c.previewSegments.length
? `<details class="companion-preview"><summary>Transcript preview</summary>${c.previewSegments.map((s) => `<p><strong>${s.speaker === 'ALEX' ? 'Alex' : 'Jamie'}:</strong> ${escapeHtmlText(s.text)}</p>`).join('')}</details>`
: '';
return `<article class="companion-card">
<h3>${escapeHtmlText(c.title)}</h3>
<p class="companion-note">Companion audio: this episode reinforces key ideas and may not be a word-for-word reading of this page.</p>
<audio controls preload="none" class="companion-player" src="${c.audioUrl}">
Your browser does not support the audio element.
</audio>
<p class="companion-links">
<a href="${c.audioUrl}" target="_blank" rel="noopener noreferrer">Open audio file (external)</a>
<span aria-hidden="true"> · </span>
<a href="${c.transcriptUrl}" target="_blank" rel="noopener noreferrer">Full transcript source (external)</a>
</p>
${preview}
</article>`;
}).join('');
return `<section id="companion-media" class="companion-media" aria-label="Companion podcast content">
<h2 class="companion-title">Companion Podcast and Transcript</h2>
<p class="companion-intro">Use audio and transcript companions to review concepts in a conversational format.</p>
${cards}
</section>`;
}
function renderQuickJumps(prefix, hasCompanionMedia, hasOnPageToc) {
const links = [
'<a href="#course-content">Jump to course content</a>',
'<a href="#main-content">Jump to main content top</a>'
];
if (hasOnPageToc) {
links.push('<a href="#on-this-page">Jump to on-page sections</a>');
}
if (hasCompanionMedia) {
links.push('<a href="#companion-media">Jump to companion audio</a>');
}
links.push(`<a href="${prefix}docs/CHALLENGES.html">Open challenge hub</a>`);
links.push(`<a href="${prefix}work.html">Open issue-style challenge walkthrough</a>`);
return `<nav class="quick-jumps" aria-label="Quick jumps">
<h2 class="quick-jumps-title">Quick Jumps</h2>
<ul class="quick-jumps-list">
${links.map((link) => `<li>${link}</li>`).join('')}
</ul>
</nav>`;
}
function renderGuidedSidebar(normalizedRelativePath, prefix) {
const catalog = getDocsCatalog();
const sequenceState = getLearningSequenceState(normalizedRelativePath);
const renderLinks = (items) => {
if (!items.length) {
return '<li><span class="guided-empty">No entries yet.</span></li>';
}
return items.map((item) => {
const isCurrent = normalizedRelativePath === item.href;
const href = item.href.startsWith('http') ? item.href : `${prefix}${item.href}`;
const external = item.href.startsWith('http') ? ' <span class="guided-external">(external)</span>' : '';
return `<li><a href="${href}"${isCurrent ? ' aria-current="page" class="guided-active"' : ''}>${escapeHtmlText(item.title)}${external}</a></li>`;
}).join('\n');
};
const externalResources = [
{ href: PODCAST_INDEX_URL, title: 'Podcast Episodes' },
{ href: PODCAST_FEED_URL, title: 'RSS Feed' }
];
const getHelpItems = [
{ href: 'https://github.com/Community-Access/support', title: 'Support Hub' }
];
const challengeLabItems = [
{ href: 'docs/CHALLENGES.html', title: 'Challenge Hub' },
{ href: 'docs/17-issue-templates.html', title: 'Issue Template Deep Dive' }
];
if (fs.existsSync(path.join(process.cwd(), 'work.md'))) {
challengeLabItems.splice(1, 0, {
href: 'work.html',
title: 'Issue-Style Challenge Walkthrough'
});
}
const progressCard = sequenceState.index === -1
? ''
: `<section class="guided-progress" aria-label="Learning progress">
<h3>Learning Progress</h3>
<p class="guided-progress-copy">${sequenceState.index + 1} of ${sequenceState.total} pages in the guided sequence</p>
<div class="guided-progress-track" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${sequenceState.percent}" aria-label="Guided sequence progress">
<span class="guided-progress-fill" style="width:${sequenceState.percent}%;"></span>
</div>
<p class="guided-progress-percent">${sequenceState.percent}% complete</p>
</section>`;
return `<aside class="guided-sidebar" aria-label="Guided reference">
<h2 class="guided-title">Guided Reference</h2>
<p class="guided-intro">Follow the learning order, then jump into challenge issue views, appendices, and support resources.</p>
${progressCard}
<section class="guided-resume" aria-label="Resume learning">
<a id="resume-link" class="guided-resume-link" href="${prefix}index.html" hidden>Resume where you left off</a>
</section>
<nav class="guided-nav" aria-label="Workshop navigation">
<section class="guided-section">
<h3>Start Here</h3>
<ul>
<li><a href="${prefix}index.html"${normalizedRelativePath === 'index.html' ? ' aria-current="page" class="guided-active"' : ''}>Workshop Home</a></li>
${renderLinks(catalog.essentials)}
</ul>
</section>
<section class="guided-section">
<h3>Learning Order</h3>
<details${normalizedRelativePath.startsWith('docs/') ? ' open' : ''}>
<summary>Day 1 chapters</summary>
<ul>
${renderLinks(catalog.day1)}
</ul>
</details>
<details${normalizedRelativePath.startsWith('docs/') ? ' open' : ''}>
<summary>Day 2 chapters</summary>
<ul>
${renderLinks(catalog.day2)}
</ul>
</details>
</section>
<section class="guided-section">
<h3>Appendices</h3>
<details${normalizedRelativePath.startsWith('docs/appendix-') ? ' open' : ''}>
<summary>Reference library</summary>
<ul>
${renderLinks(catalog.appendices)}
</ul>
</details>
</section>
<section class="guided-section">
<h3>Challenge Lab</h3>
<ul>
${renderLinks(challengeLabItems)}
</ul>
</section>
<section class="guided-section">
<h3>External Resources</h3>
<ul>
${renderLinks(externalResources)}
</ul>
</section>
<section class="guided-section">
<h3>Get Help</h3>
<ul>
${renderLinks(getHelpItems)}
</ul>
</section>
</nav>
</aside>`;
}
function getLearningSequence() {
const catalog = getDocsCatalog();
return [
...catalog.essentials,
...catalog.chapters,
...catalog.appendices
];
}
function getLearningSequenceState(normalizedRelativePath) {
const ordered = getLearningSequence();
const index = ordered.findIndex((item) => item.href === normalizedRelativePath);
const total = ordered.length;
const percent = index >= 0 && total > 0
? Math.round(((index + 1) / total) * 100)
: 0;
return { ordered, index, total, percent };
}
function renderOnPageToc(content) {
const headings = [];
const re = /<h([2-3]) id="([^"]+)">([\s\S]*?)<\/h\1>/gi;
let match;
while ((match = re.exec(content)) !== null) {
const level = Number(match[1]);
const id = match[2];
const text = match[3]
.replace(/<[^>]+>/g, '')
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.trim();
if (id && text) {
headings.push({ level, id, text });
}
}
if (!headings.length) {
return '';
}
const links = headings.map((h) => {
const cls = h.level === 3 ? ' onpage-sub' : '';
return `<li class="onpage-item${cls}"><a href="#${escapeHtmlText(h.id)}">${escapeHtmlText(h.text)}</a></li>`;
}).join('\n');
return `<nav id="on-this-page" class="onpage-nav" aria-label="On this page">
<h2 class="onpage-title">On This Page</h2>
<ul class="onpage-list">
${links}
</ul>
</nav>`;
}
function renderProgressionNav(normalizedRelativePath, prefix) {
const state = getLearningSequenceState(normalizedRelativePath);
if (state.index === -1) {
return '';
}
const prev = state.index > 0 ? state.ordered[state.index - 1] : null;
const next = state.index < state.ordered.length - 1 ? state.ordered[state.index + 1] : null;
const prevHtml = prev
? `<a class="progression-link progression-prev" href="${prefix}${prev.href}" rel="prev"><span class="progression-label">Previous</span><span class="progression-title">${escapeHtmlText(prev.title)}</span></a>`
: '<span class="progression-link progression-disabled" aria-disabled="true"><span class="progression-label">Previous</span><span class="progression-title">Start of sequence</span></span>';
const nextHtml = next
? `<a class="progression-link progression-next" href="${prefix}${next.href}" rel="next"><span class="progression-label">Next</span><span class="progression-title">${escapeHtmlText(next.title)}</span></a>`
: '<span class="progression-link progression-disabled" aria-disabled="true"><span class="progression-label">Next</span><span class="progression-title">End of sequence</span></span>';
return `<nav class="progression-nav" aria-label="Page progression">
${prevHtml}
${nextHtml}
</nav>`;
}
// HTML template with accessibility features
const htmlTemplate = (content, title, relativePath) => {
const normalizedRelativePath = relativePath.replace(/\\/g, '/');
const depth = normalizedRelativePath.split('/').length - 1;
const prefix = depth > 0 ? '../'.repeat(depth) : './';
const guidedSidebar = renderGuidedSidebar(normalizedRelativePath, prefix);
const companionMedia = renderCompanionMedia(normalizedRelativePath);
const onPageToc = renderOnPageToc(content);
const quickJumps = renderQuickJumps(prefix, !!companionMedia, !!onPageToc);
const progressionNav = renderProgressionNav(normalizedRelativePath, prefix);
const isHome = normalizedRelativePath === 'index.html';
const isRegister = normalizedRelativePath === 'REGISTER.html';
const siteName = 'GIT Going with GitHub';
const titleContainsSiteName = title === siteName || title.includes(siteName);
const pageTitle = isHome || titleContainsSiteName ? title : `${title} - ${siteName}`;
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="GIT Going with GitHub - A two-day accessible open source workshop by Community Access">
<title>${pageTitle}</title>
<link rel="stylesheet" href="${prefix}styles/github-markdown.css">
<link rel="stylesheet" href="${prefix}styles/highlight.css">
<link rel="stylesheet" href="${prefix}styles/custom.css">
<style>
.markdown-body {
box-sizing: border-box;
min-width: 0;
max-width: 980px;
margin: 0;
padding: 45px;
}
.page-layout {
max-width: 1320px;
margin: 0 auto;
padding: 1rem 1rem 2rem;
display: grid;
grid-template-columns: minmax(240px, 300px) minmax(0, 1fr);
gap: 1.25rem;
align-items: start;
}
@media (max-width: 767px) {
.page-layout {
grid-template-columns: 1fr;
padding: 0.5rem 0.5rem 1rem;
}
.markdown-body {
padding: 15px;
}
}
</style>
</head>
<body>
<a class="skip-link" href="#main-content">Skip to main content</a>
<header class="site-header" role="banner">
<div class="site-header-inner">
<nav aria-label="Breadcrumb" class="breadcrumb">
${isHome
? '<span aria-current="page">Home</span>'
: `<a href="${prefix}index.html">Home</a> <span aria-hidden="true">›</span> <span aria-current="page">${title}</span>`
}
</nav>
<div class="header-actions">
<a href="https://github.com/Community-Access/git-going-with-github/wiki" class="wiki-link" target="_blank" rel="noopener noreferrer">
<svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
<path d="M1.75 1h8.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 10.25 10H7.06l-2.573 2.573A1.458 1.458 0 0 1 2 11.543V10h-.25A1.75 1.75 0 0 1 0 8.25v-5.5C0 1.784.784 1 1.75 1ZM1.5 2.75v5.5c0 .138.112.25.25.25h1a.75.75 0 0 1 .75.75v2.19l2.72-2.72a.749.749 0 0 1 .53-.22h3.5a.25.25 0 0 0 .25-.25v-5.5a.25.25 0 0 0-.25-.25h-8.5a.25.25 0 0 0-.25.25Zm13 2a.25.25 0 0 0-.25-.25h-.5a.75.75 0 0 1 0-1.5h.5c.966 0 1.75.784 1.75 1.75v5.5A1.75 1.75 0 0 1 14.25 12H14v1.543a1.457 1.457 0 0 1-2.487 1.03L9.22 12.28a.749.749 0 1 1 1.06-1.06l2.22 2.22v-2.19a.75.75 0 0 1 .75-.75h.25a.25.25 0 0 0 .25-.25v-5.5Z"/>
</svg>
Wiki
</a>
<form role="search" class="search-form" action="${prefix}search.html" method="get">
<label for="site-search" class="search-label">Search docs</label>
<input
type="search"
id="site-search"
class="search-input"
name="q"
placeholder="Search docs…"
autocomplete="off"
aria-label="Search documentation"
>
<button type="submit" class="search-button" aria-label="Submit search">
<svg aria-hidden="true" focusable="false" width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
<path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z"/>
</svg>
</button>
</form>
</div>
</div>
</header>
<div class="page-layout">
${guidedSidebar}
<main id="main-content" class="markdown-body page-main">
${quickJumps}
${companionMedia}
${onPageToc}
<div id="course-content">${content}</div>
${progressionNav}
</main>
</div>
<footer role="contentinfo" class="site-footer">
<p><strong>GIT Going with GitHub</strong> - A workshop by <a href="https://community-access.org">Community Access</a></p>
<p><a href="https://github.com/community-access/git-going-with-github">View on GitHub</a> · <a href="https://community-access.org">community-access.org</a></p>
</footer>
${isRegister ? `<script>
(function() {
// Lightweight gate for temporary cohort control on the public opt-in page.
var accessKey = 'gggStudentOptInAccess';
var failCountKey = 'gggStudentOptInFailCount';
var lockUntilKey = 'gggStudentOptInLockUntil';
var maxAttempts = 3;
var lockMinutes = 15;
var expected = atob('R0dHMjAyNiE=');
function renderRestricted(message) {
document.body.innerHTML = [
'<main class="markdown-body" id="main-content">',
'<h1>Access restricted</h1>',
'<p>This student opt-in page is temporarily password protected.</p>',
'<p>' + message + '</p>',
'<p>If you need access, contact the workshop facilitators in the discussion forum.</p>',
'<p><a href="https://github.com/community-access/git-going-with-github/discussions">Open Discussion Forum</a></p>',
'</main>'
].join('');
}
if (sessionStorage.getItem(accessKey) === 'granted') {
return;
}
var now = Date.now();
var lockUntil = parseInt(localStorage.getItem(lockUntilKey) || '0', 10);
if (lockUntil > now) {
var minutesRemaining = Math.ceil((lockUntil - now) / 60000);
renderRestricted('For security, this page is temporarily locked due to multiple incorrect password attempts. Please try again in about ' + minutesRemaining + ' minute(s).');
return;
}
if (lockUntil > 0 && lockUntil <= now) {
localStorage.removeItem(lockUntilKey);
localStorage.setItem(failCountKey, '0');
}
var failCount = parseInt(localStorage.getItem(failCountKey) || '0', 10);
if (isNaN(failCount) || failCount < 0) {
failCount = 0;
}
var allowed = false;
while (failCount < maxAttempts) {
var attemptsRemaining = maxAttempts - failCount;
var entered = window.prompt('Welcome. This page is protected for current students.\n\nEnter the student opt-in password (' + attemptsRemaining + ' attempt(s) remaining):');
if (entered === null) {
break;
}
if (entered === expected) {
sessionStorage.setItem(accessKey, 'granted');
localStorage.setItem(failCountKey, '0');
localStorage.removeItem(lockUntilKey);
allowed = true;
break;
}
failCount += 1;
localStorage.setItem(failCountKey, String(failCount));
if (failCount < maxAttempts) {
var remaining = maxAttempts - failCount;
window.alert('That password was not correct. Please try again. Remaining attempts: ' + remaining + '.');
}
}
if (!allowed) {
if (failCount >= maxAttempts) {
var lockUntilTs = Date.now() + (lockMinutes * 60000);
localStorage.setItem(lockUntilKey, String(lockUntilTs));
renderRestricted('For security, this page is now locked for ' + lockMinutes + ' minutes because too many incorrect passwords were entered.');
} else {
renderRestricted('No password was entered, so access could not be granted.');
}
}
})();
</script>` : ''}
<script>
(function() {
var key = 'gggLastVisitedPath';
var currentPath = window.location.pathname || '';
try {
if (currentPath) {
localStorage.setItem(key, currentPath);
}
} catch (e) {}
var resumeLink = document.getElementById('resume-link');
if (!resumeLink) return;
try {
var savedPath = localStorage.getItem(key);
if (savedPath && savedPath !== currentPath) {
resumeLink.hidden = false;
resumeLink.setAttribute('href', savedPath);
}
} catch (e) {}
})();
</script>
${(isHome || isRegister) ? `<script>
(function() {
var url = 'https://api.github.com/search/issues?q=repo:community-access/git-going-with-github+label:enrolled+is:issue';
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.setRequestHeader('Accept', 'application/vnd.github+json');
xhr.onload = function() {
if (xhr.status === 200) {
try {
var count = JSON.parse(xhr.responseText).total_count;
var els = document.querySelectorAll('[id^="registration-count"]');
for (var i = 0; i < els.length; i++) {
els[i].textContent = count;
}
} catch (e) {}
}
};
xhr.onerror = function() {};
xhr.send();
})();
</script>` : ''}</body>
</html>`;
};
// Create output directory structure
function ensureDir(dirPath) {
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
}
// Convert markdown file to HTML
function convertMarkdownFile(mdPath, outputDir) {
try {
const content = fs.readFileSync(mdPath, 'utf-8');
let htmlContent = marked.parse(content);
// Rewrite internal .md links to .html (href="...md" and href="...md#anchor")
htmlContent = htmlContent.replace(
/href="(?!https?:\/\/|mailto:)([^"]*?)\.md(#[^"]*)?"/g,
(match, filePart, anchor) => {
// ANNOUNCEMENT.md at root level becomes index.html
const rewritten = filePart.replace(/(?:^|\/)ANNOUNCEMENT$/, (m) =>
m.startsWith('/') ? '/index' : 'index'
);
return `href="${rewritten}.html${anchor || ''}"`;
}
);
// Always route podcast landing/feed links to the LP-hosted distribution endpoints.
htmlContent = normalizePodcastEndpoints(htmlContent);
// Add aria-label to GFM task list checkboxes (WCAG 1.3.1 / 4.1.2)
htmlContent = htmlContent.replace(
/<input disabled="" type="checkbox"(?: checked="")?>\s*([^<]+)/g,
(match, label) => {
const trimmed = label.trim();
return match.replace('<input ', `<input aria-label="${trimmed.replace(/"/g, '"')}" `);
}
);
// Determine output path
const relativePath = path.relative(process.cwd(), mdPath);
let outputPath = path.join(outputDir, relativePath.replace(/\.md$/, '.html'));
const isRootRegisterPage = path.basename(mdPath) === 'REGISTER.md' && path.dirname(relativePath) === '.';
const isSubfolderReadme = path.basename(mdPath) === 'README.md' && path.dirname(relativePath) !== '.';
// ANNOUNCEMENT.md becomes the site front page (index.html)
// README.md at the root becomes README.html (repo documentation)
if (path.basename(mdPath) === 'ANNOUNCEMENT.md' && path.dirname(relativePath) === '.') {
outputPath = path.join(outputDir, 'index.html');
} else if (isSubfolderReadme) {
// Sub-folder READMEs still become index.html in their directory
const dir = path.dirname(outputPath);
outputPath = path.join(dir, 'index.html');
}
// Extract title from first heading or filename
const titleMatch = content.match(/^#\s+(.+)$/m);
const title = titleMatch ? titleMatch[1] : path.basename(mdPath, '.md');
// Get relative path for template
const relativeFromOutput = path.relative(outputDir, outputPath);
// Collect page data for search index (strip HTML tags for plain text)
const plainText = htmlContent
.replace(/<[^>]+>/g, ' ')
.replace(/\s+/g, ' ')
.trim();
searchPages.push({
id: relativeFromOutput.replace(/\\/g, '/'),
title,
url: relativeFromOutput.replace(/\\/g, '/'),
body: plainText.slice(0, 5000)
});
// Create full HTML
const html = htmlTemplate(htmlContent, title, relativeFromOutput);
// Ensure output directory exists
ensureDir(path.dirname(outputPath));
// Write HTML file
writeGeneratedFile(outputPath, html);
console.log(`✓ Converted: ${relativePath} → ${path.relative(process.cwd(), outputPath)}`);
// Subfolder READMEs render at /<dir>/index.html. Also write a /<dir>/README.html
// alias so explicit links to `<dir>/README.html` (a common, natural form) don't 404.
if (isSubfolderReadme) {
const readmeAlias = path.join(path.dirname(outputPath), 'README.html');
writeGeneratedFile(readmeAlias, html);
console.log(`✓ Alias: ${path.relative(process.cwd(), readmeAlias)}`);
}
// Keep lowercase registration URLs working on case-sensitive hosts.
if (isRootRegisterPage) {
const lowerFileAlias = path.join(outputDir, 'register.html');
const lowerDirAlias = path.join(outputDir, 'register', 'index.html');
writeRedirectPage(lowerFileAlias, './REGISTER.html');
writeRedirectPage(lowerDirAlias, '../REGISTER.html');
console.log('✓ Added aliases: register.html, register/index.html');
}
return outputPath;
} catch (error) {
console.error(`✗ Error converting ${mdPath}:`, error.message);
return null;
}
}
// Find all markdown files
function findMarkdownFiles(dir, fileList = []) {
const files = fs.readdirSync(dir);
files.forEach(file => {
const filePath = path.join(dir, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
// Skip generated, private, and editor-history directories.
const relativeDir = path.relative(process.cwd(), filePath).replace(/\\/g, '/');
const generatedPodcastDir = relativeDir === 'podcasts/bundles' || relativeDir === 'podcasts/challenge-bundles';
if (!generatedPodcastDir && !['node_modules', '.git', '.github', '.history', 'html'].includes(file)) {
findMarkdownFiles(filePath, fileList);
}
} else if (file.endsWith('.md')) {
fileList.push(filePath);
}
});
return fileList;
}
// Add Quick Jumps/TOC styles to custom CSS
function setupStyles(outputDir) {
const stylesDir = path.join(outputDir, 'styles');
ensureDir(stylesDir);
// Copy github-markdown-css
const githubCss = require.resolve('github-markdown-css');
fs.copyFileSync(githubCss, path.join(stylesDir, 'github-markdown.css'));
// Copy highlight.js CSS (GitHub theme)
const highlightCss = path.join(require.resolve('highlight.js'), '../../styles/github.css');
fs.copyFileSync(highlightCss, path.join(stylesDir, 'highlight.css'));
// Create custom CSS for additional accessibility and styling
const customCss = `
/* Quick Jumps/TOC navigation */
.quick-jumps {
margin: 1.5em 0 2em 0;
padding: 0.75em 1.2em;
background: #f6f8fa;
border: 1px solid #d0d7de;
border-radius: 6px;
font-size: 1rem;
box-shadow: 0 1px 2px rgba(27,31,35,0.03);
}
.quick-jumps-label {
font-weight: 600;
font-size: 1.05em;
margin-right: 0.7em;
}
.quick-jumps-list {
list-style: none;
margin: 0.5em 0 0 0;
padding: 0;
}
.quick-jumps-list li {
margin: 0.15em 0;