#!/usr/bin/env node /** * Write quarto/_extensions/pplus/pplus-views.css: the app's own rules for what the static views draw, so a Quarto * page shows the flowchart, the table of values, the proof and the rest exactly as the app does. * * pixi run quarto-css (build first; `pixi run test` fails while the file is out of date) * * It renders every static view of a few catalog problems (src/quarto/render.ts, as `quarto render` would), collects * the classes they use, and copies from styles.css every rule whose selectors use only those classes, each selector * scoped under `.pplus-static`. The app's color tokens come along: light by default, dark when the Quarto page is * dark (`body.quarto-dark`, or Bootstrap's `data-bs-theme="dark"`); the paper and ink follow the page's own. * * It also copies the course's stylesheets for the machine views (course/*.css) and writes pplus-hw.css from * styles/course/bridge.css. * * node scripts/quarto-css.mjs --check exit 1 if a file is not what this would write */ import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath, pathToFileURL } from 'node:url'; const ROOT = fileURLToPath(new URL('..', import.meta.url)); const OUT = path.join(ROOT, 'quarto/_extensions/pplus/pplus-views.css'); const dist = (p) => pathToFileURL(path.join(ROOT, 'dist', p)).href; if (!fs.existsSync(path.join(ROOT, 'dist/quarto/render.js'))) { console.error('quarto-css: dist/ is missing; run `pixi run build` first'); process.exit(1); } const { installDocument } = await import(dist('quarto/dom.js')); installDocument(); const { renderStatic, STATIC_VIEWS } = await import(dist('quarto/render.js')); const { problemById } = await import(dist('core/catalog.js')); /* ---------- the classes the views use ---------- */ const samples = []; for (const id of ['count-base', 'count-base-proved', 'match-off-by-one', 'five-bugs', 'binary-search', 'asm-two-pointers', 'demo']) { const p = problemById(id); const files = Object.fromEntries(Object.entries(p.sources).filter(([, v]) => typeof v === 'string' && v.trim())); for (const lang of Object.keys(files)) samples.push({ files, lang, call: p.call ?? null, setup: p.setup, machine: p.machine }); } samples.push({ files: { mojo: fs.readFileSync(path.join(ROOT, 'mojo/stress/lifecycle-moves.mojo'), 'utf8') }, lang: 'mojo' }); const used = new Set(); for (const s of samples) for (const view of STATIC_VIEWS.filter((v) => v !== 'hw')) { let html = ''; try { html = renderStatic({ ...s, view }).html; } catch { continue; } for (const m of html.matchAll(/class="([^"]*)"/g)) for (const c of m[1].split(/\s+/)) if (c) used.add(c); } // the editor's token colors and the step colors, whichever a sample happened to show for (const c of ['tok-keyword', 'tok-builtin', 'tok-string', 'tok-number', 'tok-comment', 'tok-label', 'tok-op', 'tok-error', 'tok-punct', 'tok-convention', 'tok-transfer', 'tok-name']) used.add(c); /* ---------- styles.css as rules ---------- */ /** Top-level rules and @media blocks: { selector, body } or { media, rules }. Comments are dropped. */ function parse(css) { css = css.replace(/\/\*[\s\S]*?\*\//g, ''); const out = []; let i = 0; const block = (from) => { let depth = 0; for (let k = from; k < css.length; k++) { if (css[k] === '{') depth++; else if (css[k] === '}' && --depth === 0) return k; } return css.length; }; while (i < css.length) { const open = css.indexOf('{', i); if (open < 0) break; const prelude = css.slice(i, open).trim(); const close = block(open); const body = css.slice(open + 1, close); if (prelude.startsWith('@media')) out.push({ media: prelude, rules: parse(body) }); else if (!prelude.startsWith('@')) out.push({ selector: prelude, body: body.trim() }); i = close + 1; } return out; } const tokens = { light: new Map(), dark: new Map() }; const LIGHT = /^:root$/, DARK = /^:root\[data-theme="dark"\]$/; const SKIP_TOKENS = new Set(['--paper', '--paper-2', '--paper-3', '--ink', '--ink-2', '--ink-3', '--line', '--line-2', '--mono', '--sans', 'color-scheme']); /** A selector the static views can use: every class in it is one they emit, and nothing in it names the app's page. */ function keep(sel) { if (/(^|[\s>+~(,])(html|body|:root)\b/.test(sel) || /\[data-theme|\.is-embed|\.shell|\.home|::?-webkit|:hover|:focus|:active/.test(sel)) return false; const classes = [...sel.matchAll(/\.([\w-]+)/g)].map((m) => m[1]); if (!classes.length) return false; return classes.every((c) => used.has(c)); } function scoped(rules, indent = '') { const lines = []; for (const r of rules) { if (r.media) { // the app's narrow-screen rearrangements are for its workspace; a page keeps the view's own layout continue; } const sels = r.selector.split(',').map((s) => s.trim()); if (sels.length === 1 && LIGHT.test(sels[0])) { collect(r.body, tokens.light); continue; } if (sels.length === 1 && DARK.test(sels[0])) { collect(r.body, tokens.dark); continue; } const kept = sels.filter(keep); if (!kept.length || !r.body) continue; lines.push(`${indent}${kept.map((s) => `.pplus-static ${s}`).join(',\n' + indent)} {\n${r.body.split('\n').map((l) => `${indent} ${l.trim()}`).filter((l) => l.trim()).join('\n')}\n${indent}}`); } return lines; } function collect(body, into) { for (const decl of body.split(';')) { const k = decl.slice(0, decl.indexOf(':')).trim(); const v = decl.slice(decl.indexOf(':') + 1).trim(); if (k.startsWith('--') && v && !SKIP_TOKENS.has(k)) into.set(k, v); } } const rules = scoped(parse(fs.readFileSync(path.join(ROOT, 'styles.css'), 'utf8'))); const decls = (m) => [...m].map(([k, v]) => ` ${k}: ${v};`).join('\n'); const text = `/* pplus-views.css: GENERATED by \`pixi run quarto-css\` (scripts/quarto-css.mjs) from styles.css. Do not edit. The app's own rules for what the static views draw, scoped under .pplus-static, with the app's color tokens; the paper and ink follow the Quarto page (Bootstrap's variables). */ .pplus-static { --paper: var(--bs-body-bg, #ffffff); --paper-2: color-mix(in srgb, var(--bs-body-bg, #ffffff) 94%, var(--bs-body-color, #16191f)); --paper-3: color-mix(in srgb, var(--bs-body-bg, #ffffff) 88%, var(--bs-body-color, #16191f)); --ink: var(--bs-body-color, #16191f); --ink-2: color-mix(in srgb, var(--bs-body-color, #16191f) 68%, var(--bs-body-bg, #ffffff)); --ink-3: color-mix(in srgb, var(--bs-body-color, #16191f) 48%, var(--bs-body-bg, #ffffff)); --line: color-mix(in srgb, var(--bs-body-color, #16191f) 14%, var(--bs-body-bg, #ffffff)); --line-2: color-mix(in srgb, var(--bs-body-color, #16191f) 24%, var(--bs-body-bg, #ffffff)); --mono: var(--bs-font-monospace, "IBM Plex Mono", ui-monospace, Menlo, Consolas, monospace); --sans: inherit; --bg: var(--paper); --bg-2: var(--paper-2); --bg-3: var(--paper-3); --fg: var(--ink); --fg-2: var(--ink-2); --note: var(--ink-3); --current: var(--marker-bg); --last: var(--last-bg); --radius: var(--r-lg); ${decls(tokens.light)} } body.quarto-dark .pplus-static, [data-bs-theme="dark"] .pplus-static { ${decls(tokens.dark)} } ${rules.join('\n\n')} `; /* ---------- the machine views: the course's stylesheets, as the board uses them ---------- */ // tokens.css, kit.css and asm86.css are the course site's own, written for Quarto pages: they go in unchanged // (styles/course/README.md). bridge.css's :root block maps the app's tokens onto the ones a Quarto page already // has, so a page gets the rest of it: the board's adjustments to the course views. const EXT = path.join(ROOT, 'quarto/_extensions/pplus'); const outputs = [[OUT, text]]; for (const f of ['tokens.css', 'kit.css', 'asm86.css']) outputs.push([path.join(EXT, 'course', f), fs.readFileSync(path.join(ROOT, 'styles/course', f), 'utf8')]); const bridge = fs.readFileSync(path.join(ROOT, 'styles/course/bridge.css'), 'utf8'); const afterRoot = bridge.slice(bridge.indexOf('}', bridge.indexOf(':root {')) + 1).replace(/^\s+/, ''); outputs.push([path.join(EXT, 'pplus-hw.css'), `/* pplus-hw.css: GENERATED by \`pixi run quarto-css\` (scripts/quarto-css.mjs) from styles/course/bridge.css. Do not edit. The Hardware board's adjustments to the course's machine views (course/*.css), for the pplus-hw shortcodes. A Quarto page already has the colors and fonts those files read (--bs-body-bg, --bs-body-color, body.quarto-dark). */ ${afterRoot}`]); if (process.argv.includes('--check')) { const stale = outputs.filter(([file, want]) => !fs.existsSync(file) || fs.readFileSync(file, 'utf8') !== want).map(([file]) => path.relative(ROOT, file)); if (stale.length) { console.error(`quarto-css: out of date: ${stale.join(', ')}; run \`pixi run quarto-css\``); process.exit(1); } console.log('quarto-css: up to date'); } else { for (const [file, want] of outputs) { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, want); } console.log(`quarto-css: wrote ${outputs.map(([f]) => path.relative(ROOT, f)).join(', ')} (${rules.length} rules, ${used.size} classes)`); } process.exit(0);