-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwrap-reports.js
More file actions
574 lines (498 loc) · 16.1 KB
/
wrap-reports.js
File metadata and controls
574 lines (498 loc) · 16.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
#!/usr/bin/env node
/**
* wrap-reports.js - Wraps standalone HTML reports with site navigation
*
* PURPOSE:
* This script enables a zero-config workflow for publishing standalone HTML reports.
* Drop an HTML file into data/static_reports_html/, run npm run wrap-reports,
* and the report appears on the site with full navigation.
*
* HOW IT WORKS:
* 1. Scans data/static_reports_html/ for HTML files
* 2. Extracts <title>, <style>, <body>, and external scripts from each
* 3. Wraps content in site template with nav/header/footer
* 4. Scopes CSS to prevent conflicts (body{} -> .report-slug{})
* 5. Outputs wrapped reports to reports/{slug}.html
* 6. Generates reports/index.html with a grid of all reports
*
* CSS ISOLATION:
* Reports often have global styles targeting body, *, etc.
* To prevent conflicts with the site styles, we:
* - Wrap report content in a div with class .report-{slug}
* - Transform CSS selectors: body {} -> .report-{slug} {}
* - Site styles load first, then scoped report styles
*
* WORKFLOW:
* 1. Drop HTML file into data/static_reports_html/
* 2. Run: npm run wrap-reports
* 3. Commit: git add reports/ && git commit -m "Add reports" && git push
*/
const fs = require('fs').promises;
const path = require('path');
const SOURCE_DIR = 'data/static_reports_html';
const OUTPUT_DIR = 'reports';
/**
* Convert filename to URL slug
* Examples:
* bubble_watch.html -> bubble_watch
* team_comparison_2026-02-01.html -> team_comparison_2026-02-01
*/
function fileToSlug(filename) {
return path.basename(filename, '.html');
}
/**
* Convert slug to human-readable title
* Examples:
* bubble_watch -> Bubble Watch
* team_comparison_2026-02-01 -> Team Comparison 2026 02 01
*/
function slugToTitle(slug) {
return slug
.replace(/_/g, ' ')
.replace(/-/g, ' ')
.replace(/\b\w/g, c => c.toUpperCase());
}
/**
* Extract content between tags using regex
* Returns the first match or null
*/
function extractBetween(html, startTag, endTag) {
const regex = new RegExp(`${startTag}([\\s\\S]*?)${endTag}`, 'i');
const match = html.match(regex);
return match ? match[1].trim() : null;
}
/**
* Extract the <title> from HTML
*/
function extractTitle(html) {
const match = html.match(/<title>([^<]*)<\/title>/i);
return match ? match[1].trim() : null;
}
/**
* Extract all <style> blocks from HTML
*/
function extractStyles(html) {
const styles = [];
const regex = /<style[^>]*>([\s\S]*?)<\/style>/gi;
let match;
while ((match = regex.exec(html)) !== null) {
styles.push(match[1].trim());
}
return styles.join('\n\n');
}
/**
* Extract external script URLs (src attributes)
*/
function extractExternalScripts(html) {
const scripts = [];
const regex = /<script[^>]+src=["']([^"']+)["'][^>]*>/gi;
let match;
while ((match = regex.exec(html)) !== null) {
scripts.push(match[1]);
}
return scripts;
}
/**
* Extract inline script content
*/
function extractInlineScripts(html) {
const scripts = [];
// Match script tags without src attribute that have content
const regex = /<script(?![^>]*\ssrc=)[^>]*>([\s\S]*?)<\/script>/gi;
let match;
while ((match = regex.exec(html)) !== null) {
const content = match[1].trim();
if (content) {
scripts.push(content);
}
}
return scripts;
}
/**
* Extract body content (everything between <body> and </body>)
* Strips out script tags since we handle those separately
*/
function extractBody(html) {
let body = extractBetween(html, '<body[^>]*>', '</body>') || '';
// Remove all script tags (both with src and inline) since we handle them separately
body = body.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');
return body.trim();
}
/**
* Scope CSS selectors to prevent conflicts with site styles
*
* Transforms:
* body { ... } -> .report-slug { ... }
* * { ... } -> .report-slug * { ... }
* .class { ... } -> .report-slug .class { ... }
*
* This keeps report styles isolated to their wrapper div
*/
function scopeCSS(css, slug) {
const scopeClass = `.report-${slug}`;
// Split CSS into rules (handling nested braces for @media etc.)
let result = '';
let depth = 0;
let currentRule = '';
const inMedia = false;
const mediaQuery = '';
for (let i = 0; i < css.length; i++) {
const char = css[i];
if (char === '{') {
depth++;
currentRule += char;
} else if (char === '}') {
depth--;
currentRule += char;
if (depth === 0) {
// Process completed rule
if (currentRule.trim().startsWith('@media')) {
// Handle @media blocks
result += scopeMediaBlock(currentRule, scopeClass);
} else if (
currentRule.trim().startsWith('@keyframes') ||
currentRule.trim().startsWith('@-webkit-keyframes')
) {
// Keep keyframes as-is
result += currentRule;
} else {
// Regular rule
result += scopeRule(currentRule, scopeClass);
}
currentRule = '';
}
} else {
currentRule += char;
}
}
return result;
}
/**
* Scope a single CSS rule
*/
function scopeRule(rule, scopeClass) {
// Match selector and body
const match = rule.match(/^([^{]+)\{([\s\S]*)\}$/);
if (!match) {
return rule;
}
const selector = match[1].trim();
const body = match[2];
// Transform selector
const scopedSelector = scopeSelector(selector, scopeClass);
return `${scopedSelector} {\n${body}}\n`;
}
/**
* Scope a @media block
*/
function scopeMediaBlock(block, scopeClass) {
// Extract media query and inner rules
const mediaMatch = block.match(/@media([^{]+)\{([\s\S]*)\}$/);
if (!mediaMatch) {
return block;
}
const mediaQuery = mediaMatch[1].trim();
const innerCSS = mediaMatch[2];
// Scope inner rules
const scopedInner = scopeCSS(innerCSS, scopeClass.replace('.report-', ''));
return `@media ${mediaQuery} {\n${scopedInner}}\n`;
}
/**
* Scope a single selector
*/
function scopeSelector(selector, scopeClass) {
// Handle multiple selectors (comma-separated)
return selector
.split(',')
.map(s => {
s = s.trim();
// body -> .report-slug
if (s === 'body') {
return scopeClass;
}
// html -> .report-slug (treat similarly)
if (s === 'html') {
return scopeClass;
}
// * -> .report-slug *
if (s === '*') {
return `${scopeClass} *`;
}
// body.class or body .class -> .report-slug.class or .report-slug .class
if (s.startsWith('body')) {
return s.replace(/^body/, scopeClass);
}
// Regular selectors -> .report-slug .selector
return `${scopeClass} ${s}`;
})
.join(', ');
}
/**
* Generate navigation HTML with Reports dropdown
* Mirrors the full site navigation from build.js
*/
function generateNav(reports, currentSlug = null) {
// Build Reports dropdown items
const dropdownItems = reports
.map(r => {
const isActive = r.slug === currentSlug ? ' class="active"' : '';
return ` <li><a href="${r.slug}.html"${isActive}>${r.title}</a></li>`;
})
.join('\n');
// Navigation with Reports dropdown - matches full site nav from build.js
return `
<nav class="main-nav">
<div class="nav-container">
<div class="logo"><a href="/">The D3 Stat Lab</a></div>
<!-- Hamburger Menu Toggle (only appears on mobile) -->
<div class="menu-toggle" id="menuToggle">
<span></span>
<span></span>
<span></span>
</div>
<!-- Navigation Links -->
<ul class="nav-links" id="navMenu">
<!-- Close button placed separately at the top of the menu -->
<div class="menu-close" id="menuClose"></div>
<li><a href="/">Home</a></li>
<li><a href="/npi.html">NPI</a></li>
<li><a href="/season_simulations.html">Season Simulations</a></li>
<li><a href="/current_season_rankings.html">Current Season Rankings</a></li>
<li><a href="/conference_rankings.html">Conference Rankings</a></li>
<li><a href="/composite_rankings.html">Composite Rankings</a></li>
<li><a href="/distances.html">Distances</a></li>
<li><a href="/preseason_rankings.html">26-27 Preseason Rankings</a></li>
<li><a href="/returners.html">Returning and Non-Returning</a></li>
<li><a href="/publishing_tracker.html">Publishing Tracker</a></li>
<li class="nav-dropdown">
<a href="/reports/" class="dropdown-trigger${currentSlug ? ' active' : ''}">Reports <span class="dropdown-arrow">▾</span></a>
<ul class="dropdown-menu">
<li><a href="/reports/">All Reports</a></li>
<li class="dropdown-divider"></li>
${dropdownItems}
</ul>
</li>
<li><a href="/premium.html">Premium</a></li>
<li><a href="/contact.html">Contact</a></li>
</ul>
</div>
<!-- Overlay for mobile -->
<div class="nav-overlay" id="navOverlay"></div>
</nav>`;
}
/**
* Generate the wrapped HTML for a single report
*/
function generateWrappedReport(report, allReports) {
const { slug, title, styles, body, externalScripts, inlineScripts } = report;
const nav = generateNav(allReports, slug);
// Generate external script tags
const externalScriptTags = externalScripts
.map(src => ` <script src="${src}"></script>`)
.join('\n');
// Generate inline script tags
const inlineScriptTags = inlineScripts
.map(content => ` <script>\n${content}\n </script>`)
.join('\n');
return `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>${title} - The D3 Stat Lab</title>
<!-- Block AI/LLM crawlers from using content for training -->
<meta name="robots" content="noai, noimageai" />
<meta name="googlebot" content="noai, noimageai" />
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="stylesheet" href="/styles.css" />
<link rel="stylesheet" href="/css/reports.css" />
<!-- Scoped report styles -->
<style>
${styles}
</style>
<!-- GoatCounter Analytics -->
<script
data-goatcounter="https://thed3statlab.goatcounter.com/count"
async
src="https://gc.zgo.at/count.js"
></script>
</head>
<body>
${nav}
<div class="report-wrapper">
<div class="report-back-link">
<a href="/reports/">← Back to Reports</a>
</div>
<div class="report-${slug}">
${body}
</div>
</div>
<footer>
<p>© <span id="currentYear">2026</span> D3 Stat Lab. All rights reserved.</p>
</footer>
<script>document.getElementById('currentYear').textContent = new Date().getFullYear();</script>
<!-- JavaScript for navigation -->
<script src="/js/navigation.js"></script>
<script src="/js/reports-nav.js"></script>
${externalScriptTags}
${inlineScriptTags}
</body>
</html>`;
}
/**
* Generate the reports index page
*/
function generateIndexPage(reports) {
const nav = generateNav(reports);
// Sort reports alphabetically by title
const sortedReports = [...reports].sort((a, b) =>
a.title.localeCompare(b.title)
);
// Generate report cards
const cards = sortedReports
.map(r => {
return ` <a href="${r.slug}.html" class="report-card">
<h3>${r.title}</h3>
<span class="report-card-arrow">→</span>
</a>`;
})
.join('\n');
return `<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Reports - The D3 Stat Lab</title>
<!-- Block AI/LLM crawlers from using content for training -->
<meta name="robots" content="noai, noimageai" />
<meta name="googlebot" content="noai, noimageai" />
<link rel="icon" type="image/png" href="/favicon.png" />
<link rel="stylesheet" href="/styles.css" />
<link rel="stylesheet" href="/css/reports.css" />
<!-- GoatCounter Analytics -->
<script
data-goatcounter="https://thed3statlab.goatcounter.com/count"
async
src="https://gc.zgo.at/count.js"
></script>
</head>
<body>
${nav}
<main>
<header>
<h1>Reports</h1>
<p>Interactive reports and visualizations for D3 Women's Basketball</p>
</header>
<div class="reports-grid">
${cards}
</div>
</main>
<footer>
<p>© <span id="currentYear">2026</span> D3 Stat Lab. All rights reserved.</p>
</footer>
<script>document.getElementById('currentYear').textContent = new Date().getFullYear();</script>
<!-- JavaScript for navigation -->
<script src="/js/navigation.js"></script>
<script src="/js/reports-nav.js"></script>
</body>
</html>`;
}
/**
* Process a single HTML report file
*/
async function processReport(filename) {
const filepath = path.join(SOURCE_DIR, filename);
const html = await fs.readFile(filepath, 'utf8');
const slug = fileToSlug(filename);
const extractedTitle = extractTitle(html);
const title = extractedTitle || slugToTitle(slug);
const rawStyles = extractStyles(html);
const styles = scopeCSS(rawStyles, slug);
const body = extractBody(html);
const externalScripts = extractExternalScripts(html);
const inlineScripts = extractInlineScripts(html);
return {
slug,
title,
styles,
body,
externalScripts,
inlineScripts,
filename,
};
}
/**
* Main entry point
*/
async function main() {
console.log('📦 Wrapping static reports...\n');
try {
// Ensure output directory exists
await fs.mkdir(OUTPUT_DIR, { recursive: true });
// Find all HTML files in source directory
let files;
try {
files = await fs.readdir(SOURCE_DIR);
} catch (e) {
console.log(`ℹ️ No source directory found at ${SOURCE_DIR}`);
console.log(' Create the directory and add HTML reports to wrap.\n');
return;
}
const htmlFiles = files.filter(f => f.endsWith('.html'));
if (htmlFiles.length === 0) {
console.log(`ℹ️ No HTML files found in ${SOURCE_DIR}\n`);
return;
}
console.log(`📄 Found ${htmlFiles.length} reports to process...\n`);
// Clean up stale reports in output dir that no longer have a source file.
// Without this, old files linger in reports/ and get picked up by build.js
// for the nav dropdown, creating broken links.
const sourceBasenames = new Set(htmlFiles.map(f => path.basename(f)));
try {
const existingOutputFiles = await fs.readdir(OUTPUT_DIR);
const staleFiles = existingOutputFiles.filter(
f =>
f.endsWith('.html') && f !== 'index.html' && !sourceBasenames.has(f)
);
for (const stale of staleFiles) {
await fs.unlink(path.join(OUTPUT_DIR, stale));
console.log(` 🗑 Removed stale report: ${stale}`);
}
if (staleFiles.length > 0) {
console.log('');
}
} catch (e) {
// Output dir may not exist yet — that's fine, nothing to clean
}
// Process all reports
const reports = [];
for (const file of htmlFiles) {
const report = await processReport(file);
reports.push(report);
console.log(` ✓ Processed ${file} → ${report.slug}.html`);
}
// Generate wrapped reports
console.log('\n📝 Generating wrapped reports...\n');
for (const report of reports) {
const html = generateWrappedReport(report, reports);
const outputPath = path.join(OUTPUT_DIR, `${report.slug}.html`);
await fs.writeFile(outputPath, html, 'utf8');
console.log(` ✓ Generated ${outputPath}`);
}
// Generate index page
const indexHtml = generateIndexPage(reports);
const indexPath = path.join(OUTPUT_DIR, 'index.html');
await fs.writeFile(indexPath, indexHtml, 'utf8');
console.log(` ✓ Generated ${indexPath}`);
console.log(`\n✅ Successfully wrapped ${reports.length} reports!`);
console.log(' View at: http://localhost:8000/reports/\n');
} catch (error) {
console.error('\n❌ Error:', error.message);
process.exit(1);
}
}
// Run if called directly
if (require.main === module) {
main();
}
module.exports = { main, processReport, scopeCSS };