@allons-y/course-kit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +373 -0
  2. package/README.md +90 -2
  3. package/assets/fonts/instrument-sans-italic-var.woff2 +0 -0
  4. package/assets/fonts/instrument-sans-var.woff2 +0 -0
  5. package/assets/fonts/pt-mono.woff2 +0 -0
  6. package/assets/scripts/copy.js +99 -0
  7. package/assets/scripts/deck.js +161 -0
  8. package/assets/scripts/email.js +17 -0
  9. package/assets/scripts/practice.js +545 -0
  10. package/assets/scripts/theme-panel.js +647 -0
  11. package/assets/scripts/theme-restore.js +17 -0
  12. package/assets/styles/base.css +2090 -0
  13. package/assets/styles/deck.css +968 -0
  14. package/assets/styles/font.css +36 -0
  15. package/assets/styles/notes.css +137 -0
  16. package/assets/styles/print.css +428 -0
  17. package/assets/styles/semantics.css +101 -0
  18. package/components/practice/check-controls.webc +50 -0
  19. package/components/practice/choice-list.webc +86 -0
  20. package/components/practice/cite-panel.webc +108 -0
  21. package/components/practice/practice-figure.webc +47 -0
  22. package/components/practice/practice-fill.webc +154 -0
  23. package/components/practice/practice-grid.webc +82 -0
  24. package/components/practice/practice-judge.webc +165 -0
  25. package/components/practice/practice-match.webc +178 -0
  26. package/components/practice/practice-question.webc +141 -0
  27. package/components/practice/practice-selfcheck.webc +40 -0
  28. package/components/practice/practice-terms.webc +95 -0
  29. package/components/practice/practice-tree.webc +91 -0
  30. package/components/practice/practice-worksheet.webc +369 -0
  31. package/components/site/copyright.webc +13 -0
  32. package/components/site/course-documents.webc +27 -0
  33. package/components/site/course-now.webc +393 -0
  34. package/components/site/course-summary.webc +136 -0
  35. package/components/site/demo-weeks.webc +91 -0
  36. package/components/site/glossary-entry.webc +31 -0
  37. package/components/site/glossary-panel.webc +1482 -0
  38. package/components/site/glossary.webc +45 -0
  39. package/components/site/grading.webc +50 -0
  40. package/components/site/instructor.webc +269 -0
  41. package/components/site/masthead.webc +147 -0
  42. package/components/site/nav-links.webc +174 -0
  43. package/components/site/policies.webc +17 -0
  44. package/components/site/practice-index.webc +31 -0
  45. package/components/site/schedule-overview.webc +145 -0
  46. package/components/site/schedule-weeks.webc +589 -0
  47. package/components/site/site-footer.webc +119 -0
  48. package/components/site/slide-timetable.webc +152 -0
  49. package/components/site/syllabus.webc +217 -0
  50. package/components/ui/arrow-link.webc +19 -0
  51. package/components/ui/assigned-list.webc +101 -0
  52. package/components/ui/callout.webc +11 -0
  53. package/components/ui/card-list.webc +124 -0
  54. package/components/ui/codepen-embed.webc +123 -0
  55. package/components/ui/download-button.webc +49 -0
  56. package/components/ui/eyebrow.webc +18 -0
  57. package/components/ui/icons/github.webc +6 -0
  58. package/components/ui/icons/google.webc +9 -0
  59. package/components/ui/link-list.webc +130 -0
  60. package/components/ui/link-section.webc +40 -0
  61. package/components/ui/meeting-card.webc +73 -0
  62. package/components/ui/meeting-decks.webc +38 -0
  63. package/components/ui/table-rubric.webc +251 -0
  64. package/components/ui/today-link.webc +43 -0
  65. package/components/ui/today-marker.webc +149 -0
  66. package/components/ui/week-block.webc +53 -0
  67. package/examples/starter/_data/course.json +20 -0
  68. package/examples/starter/_data/dates.json +16 -0
  69. package/examples/starter/_data/grading.json +6 -0
  70. package/examples/starter/_data/instructor.json +7 -0
  71. package/examples/starter/_data/policies.json +9 -0
  72. package/examples/starter/_data/scale.json +8 -0
  73. package/examples/starter/_data/schedule.json +22 -0
  74. package/examples/starter/_data/theme.json +17 -0
  75. package/examples/starter/content/index.webc +12 -0
  76. package/examples/starter/content/schedule.webc +12 -0
  77. package/examples/starter/content/slides/index.11tydata.js +5 -0
  78. package/examples/starter/content/slides/index.webc +12 -0
  79. package/examples/starter/content/slides/week-1-day-1.md +40 -0
  80. package/examples/starter/eleventy.config.js +8 -0
  81. package/glue/deck-notes.data.js +41 -0
  82. package/glue/deck-notes.webc +32 -0
  83. package/glue/lesson-day.data.js +17 -0
  84. package/glue/lesson-day.webc +0 -0
  85. package/glue/lesson-plans.data.js +13 -0
  86. package/glue/lesson-plans.webc +2 -0
  87. package/index.js +6 -0
  88. package/layouts/base.webc +79 -0
  89. package/layouts/deck.webc +46 -0
  90. package/layouts/demo.webc +16 -0
  91. package/layouts/document.webc +10 -0
  92. package/layouts/lesson-detail.webc +109 -0
  93. package/layouts/lesson.webc +71 -0
  94. package/layouts/notes.webc +23 -0
  95. package/layouts/worksheet.webc +52 -0
  96. package/lib/assets.js +42 -0
  97. package/lib/bundles.js +79 -0
  98. package/lib/check.js +110 -0
  99. package/lib/components.js +19 -0
  100. package/lib/copy.js +653 -0
  101. package/lib/data/build.js +22 -0
  102. package/lib/data/fonts.js +16 -0
  103. package/lib/data/glossary.js +304 -0
  104. package/lib/data/index.js +8 -0
  105. package/lib/data/lessons.js +173 -0
  106. package/lib/data/project.js +22 -0
  107. package/lib/data/read.js +46 -0
  108. package/lib/data/site.js +70 -0
  109. package/lib/data/term.js +80 -0
  110. package/lib/extensions.js +70 -0
  111. package/lib/files.js +14 -0
  112. package/lib/filters.js +584 -0
  113. package/lib/fit.js +106 -0
  114. package/lib/glue.js +26 -0
  115. package/lib/lesson-materials.js +66 -0
  116. package/lib/markdown.js +568 -0
  117. package/lib/minify.js +53 -0
  118. package/lib/paths.js +5 -0
  119. package/lib/pdf.js +134 -0
  120. package/lib/plugin.js +228 -0
  121. package/lib/plugins.js +34 -0
  122. package/lib/postcss.js +93 -0
  123. package/lib/theme-server.js +88 -0
  124. package/lib/theme.js +185 -0
  125. package/lib/worksheet-dialect.js +415 -0
  126. package/lib/worksheets.js +276 -0
  127. package/package.json +118 -4
  128. package/schemas/course.schema.json +156 -0
  129. package/schemas/dates.schema.json +165 -0
  130. package/schemas/grading.schema.json +59 -0
  131. package/schemas/instructor.schema.json +68 -0
  132. package/schemas/policies.schema.json +90 -0
  133. package/schemas/project.schema.json +209 -0
  134. package/schemas/scale.schema.json +68 -0
  135. package/schemas/schedule.schema.json +260 -0
  136. package/schemas/theme.schema.json +704 -0
  137. package/schemas/worksheet.schema.json +449 -0
package/lib/glue.js ADDED
@@ -0,0 +1,26 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+
4
+ import deckNotes from "../glue/deck-notes.data.js";
5
+ import lessonDay from "../glue/lesson-day.data.js";
6
+ import lessonPlans from "../glue/lesson-plans.data.js";
7
+ import { packageRoot } from "./paths.js";
8
+
9
+ const root = path.join(packageRoot, "glue");
10
+
11
+ /** Data for each glue page, by name. */
12
+ const DATA = { "deck-notes": deckNotes, "lesson-day": lessonDay, "lesson-plans": lessonPlans };
13
+
14
+ /**
15
+ * Publish glue pages (pagination and permalink templates) as virtual
16
+ * templates. A page the course repo also defines is skipped.
17
+ * @param {import('@11ty/eleventy').UserConfig} config
18
+ * @param {{ inputDir?: string, pages: Record<string, string> }} options `pages` maps a glue name to its virtual path, e.g. { "lesson-day": "lessons/lesson-day.webc" }
19
+ */
20
+ export function registerGlue(config, { inputDir = "content", pages }) {
21
+ for (const [name, virtualPath] of Object.entries(pages)) {
22
+ if (fs.existsSync(path.join(inputDir, virtualPath))) continue;
23
+ if (!DATA[name]) throw new Error(`course-kit: no glue page named "${name}"`);
24
+ config.addTemplate(virtualPath, fs.readFileSync(path.join(root, `${name}.webc`), "utf8"), DATA[name]);
25
+ }
26
+ }
@@ -0,0 +1,66 @@
1
+ import { fill, resolveCopy } from "./copy.js";
2
+ import { assignmentsDue, decksFor, dueLabel } from "./filters.js";
3
+
4
+ /**
5
+ * @typedef {object} LinkItem
6
+ * @property {string} title
7
+ * @property {string} [href] the item is plain text without one
8
+ * @property {string} [note] muted text after the title
9
+ * @property {{ text: string, href: string, after?: string }} [extra] a second link after the title
10
+ */
11
+
12
+ /**
13
+ * The speaker-notes decks for a lesson-day page's meeting.
14
+ * @param {{ lesson: { week: number, day: number }, collections?: { deck?: object[] } }} data
15
+ * @returns {{ title: string, url: string, notesUrl: string }[]}
16
+ */
17
+ export const lessonDecks = (data) => decksFor(data.collections?.deck, data.lesson.week, data.lesson.day);
18
+
19
+ /**
20
+ * The "Materials & links" sections of a lesson-day page, in order, each ready
21
+ * for `<link-section>`. A section with nothing to list is left out, except
22
+ * the resources one, which says so.
23
+ * @param {object} data a lesson-day page's data: `lesson`, `lessons`, `lessonDemos`, `collections`
24
+ * @returns {{ title: string, items: LinkItem[], empty?: string }[]}
25
+ */
26
+ export function lessonMaterials(data) {
27
+ const { lesson } = data;
28
+ const copy = (data.copy ?? resolveCopy()).lessonMaterials;
29
+ const note = (...parts) => parts.filter(Boolean).join(", ");
30
+ const sections = [
31
+ {
32
+ title: copy.slidesForThisMeeting,
33
+ items: lessonDecks(data).map((deck) => ({ title: deck.title, href: deck.url, extra: { text: copy.speakerNotes, href: deck.notesUrl, after: copy.printable } })),
34
+ },
35
+ {
36
+ title: copy.demosFromThisMeeting,
37
+ items: (data.lessonDemos ?? []).map((demo) => ({ title: demo.title, href: `/demo/${demo.slug}/`, note: demo.description })),
38
+ },
39
+ {
40
+ title: copy.exercisesDue,
41
+ items: assignmentsDue(data.collections?.assignment, lesson, data.lessons).map((item) => ({ title: item.title, href: item.url, note: item.dueLabel })),
42
+ },
43
+ {
44
+ title: copy.readingForThisMeeting,
45
+ items: (lesson.meetingReadings ?? []).map((reading) => ({
46
+ title: reading.title,
47
+ href: reading.href,
48
+ note: note(reading.check, reading.due && fill(copy.due, { when: dueLabel(reading) })),
49
+ })),
50
+ },
51
+ {
52
+ title: copy.deadlinesToAnnounce,
53
+ items: (lesson.due ?? []).map((item) => ({ title: item.title, href: item.href, note: item.due ? fill(copy.due, { when: dueLabel(item) }) : "" })),
54
+ },
55
+ {
56
+ title: copy.assignedBeforeThisWeek,
57
+ items: (lesson.readings ?? []).map((reading) => ({ title: reading.title, href: reading.href })),
58
+ },
59
+ {
60
+ title: lesson.readings?.length ? copy.postedForTheClass : "",
61
+ items: (lesson.resources ?? []).map((resource) => ({ title: resource.title, href: resource.href })),
62
+ empty: copy.nothingPostedForThis,
63
+ },
64
+ ];
65
+ return sections.filter((section) => section.items.length || section.empty);
66
+ }
@@ -0,0 +1,568 @@
1
+ import { createRequire } from "node:module";
2
+
3
+ import markdownIt from "markdown-it";
4
+ import markdownItAnchor from "markdown-it-anchor";
5
+ import markdownItFootnote from "markdown-it-footnote";
6
+
7
+ import { resolveCopy } from "./copy.js";
8
+
9
+ const slugify = (str) =>
10
+ encodeURIComponent(
11
+ String(str)
12
+ .toLowerCase()
13
+ ?.replace(/[.)([\]?!\s]/g, "-")
14
+ ?.replace(/[^a-z0-9]+/g, "-")
15
+ ?.replace(/-+/g, "-")
16
+ ?.replace(/^-+|-+$/g, "")
17
+ ?.replace(/-+/g, "-"),
18
+ );
19
+
20
+ const { escapeHtml } = markdownIt().utils;
21
+
22
+ /** Prism highlighter. `createRequire`, never ESM import: Prism's component loader is CommonJS. */
23
+ const prismHighlight = createRequire(import.meta.url)("@11ty/eleventy-plugin-syntaxhighlight/src/markdownSyntaxHighlightOptions.js")({
24
+ alwaysWrapLineHighlights: true,
25
+ preAttributes: { tabindex: 0 },
26
+ });
27
+
28
+ /**
29
+ * Escapes ```text fences, which the plugin passes through as raw HTML.
30
+ * @param {string} str
31
+ * @param {string} language
32
+ * @returns {string}
33
+ */
34
+ const highlight = (str, language) => prismHighlight(language.split("/")[0] === "text" ? escapeHtml(str) : str, language);
35
+
36
+ const SLIDE_KINDS = new Set(["title", "section", "checkpoint", "vocab", "api"]);
37
+ const SLIDE_MARKER = ">";
38
+ const CONTAINER_MARKER = ":";
39
+ const MIN_MARKERS = 3;
40
+ const CONTAINER_CLASS = /^[a-z][a-z0-9-]*$/;
41
+
42
+ /**
43
+ * Where a markdown-it StateCore is in a file, for an error message. Eleventy
44
+ * stamps `env.file`/`env.page.inputPath` on the render env; fall back to
45
+ * "deck" so this still works when called outside that (e.g. tests).
46
+ */
47
+ const fileOf = (env) => env?.file ?? env?.page?.inputPath ?? "deck";
48
+
49
+ class DeckError extends Error {}
50
+
51
+ const fail = (env, line, message) => {
52
+ throw new DeckError(`${fileOf(env)}:${line + 1}: ${message}`);
53
+ };
54
+
55
+ /**
56
+ * A single-line-per-marker block rule: a line of `markerChar` repeated
57
+ * `>= 3` times plus info text opens a container of `tokenType`; the bare
58
+ * marker closes the most recently opened one. Deliberately not
59
+ * markdown-it-container's forward-scan approach: that closes the outer
60
+ * container when same-marker containers nest.
61
+ * @param {string} markerChar
62
+ * @param {string} tokenType
63
+ * @param {(info: string, env: object, line: number) => string} [validateOpen] validates the open line's info text, returning the value to store on the token (throws on an invalid open)
64
+ */
65
+ const markerContainerRule =
66
+ (markerChar, tokenType, validateOpen) =>
67
+ (state, startLine, _endLine, silent) => {
68
+ if (state.sCount[startLine] - state.blkIndent >= 4) return false;
69
+ const start = state.bMarks[startLine] + state.tShift[startLine];
70
+ const max = state.eMarks[startLine];
71
+ const src = state.src.slice(start, max);
72
+
73
+ let pos = 0;
74
+ while (pos < src.length && src[pos] === markerChar) pos += 1;
75
+ if (pos < MIN_MARKERS) return false;
76
+ const info = src.slice(pos).trim();
77
+ if (silent) return true;
78
+
79
+ const normalized = info && validateOpen ? validateOpen(info, state.env, startLine) : info;
80
+ const token = state.push(info ? `${tokenType}_open` : `${tokenType}_close`, "div", info ? 1 : -1);
81
+ token.markup = markerChar.repeat(MIN_MARKERS);
82
+ token.info = normalized;
83
+ token.map = [startLine, startLine + 1];
84
+ token.attrSet("data-line", String(startLine + 1));
85
+ state.line = startLine + 1;
86
+ return true;
87
+ };
88
+
89
+ /**
90
+ * After parsing, confirm every `openType`/`closeType` pair is balanced —
91
+ * fails the build naming the file and line rather than silently autoclosing
92
+ * (markdown-it-container's behavior) and losing a slide.
93
+ */
94
+ const checkBalanced = (openType, closeType, label) => (state) => {
95
+ let depth = 0;
96
+ let openedAt = null;
97
+ for (const token of state.tokens) {
98
+ if (token.type === openType) {
99
+ if (depth === 0) openedAt = token;
100
+ depth += 1;
101
+ } else if (token.type === closeType) {
102
+ depth -= 1;
103
+ if (depth < 0) fail(state.env, Number(token.attrGet("data-line") ?? 1) - 1, `a bare marker closes ${label} that was never opened`);
104
+ }
105
+ }
106
+ if (depth > 0) fail(state.env, Number(openedAt.attrGet("data-line") ?? 1) - 1, `${label} is never closed`);
107
+ };
108
+
109
+ /** Class list for a generic `::: name` container. `cols-2`/`cols-3` imply `cols`. */
110
+ const containerClasses = (info, env, line) => {
111
+ const names = info.split(/\s+/).filter(Boolean);
112
+ for (const name of names) {
113
+ if (!CONTAINER_CLASS.test(name)) fail(env, line, `"${name}" is not a valid container name in \`::: ${info}\``);
114
+ }
115
+ if (names.some((name) => /^cols-\d$/.test(name)) && !names.includes("cols")) names.unshift("cols");
116
+ return names.join(" ");
117
+ };
118
+
119
+ /** `notes Label (0:00–0:05)` split into its label and timing, if present. */
120
+ const noteInfo = (info) => {
121
+ const [, label = "", timing = ""] = /^(.*?)(?:\(([^)]*)\))?$/.exec(info.trim().replace(/^notes\b/, "").trim());
122
+ return { label: label.trim(), timing: timing.trim() };
123
+ };
124
+
125
+ const baseOptions = { html: true, xhtmlOut: true, typographer: true, breaks: false, linkify: true, slugify, highlight };
126
+
127
+ /**
128
+ * markdown-it-anchor's permalink option, skipped inside a slide. Scans
129
+ * backward for an unclosed `container_slide_open` rather than an env flag:
130
+ * this plugin's own core rule runs after the per-render env is reset.
131
+ */
132
+ const insideSlide = (state, idx) => {
133
+ let depth = 0;
134
+ for (let i = idx - 1; i >= 0; i -= 1) {
135
+ if (state.tokens[i].type === "container_slide_close") depth += 1;
136
+ else if (state.tokens[i].type === "container_slide_open") {
137
+ if (depth === 0) return true;
138
+ depth -= 1;
139
+ }
140
+ }
141
+ return false;
142
+ };
143
+
144
+ /** The permalink link, built per call so its label follows the course's copy. */
145
+ const anchorPermalink = (...args) =>
146
+ markdownItAnchor.permalink.linkInsideHeader({
147
+ placement: "before",
148
+ space: " ",
149
+ symbol: "#",
150
+ ariaLabel: resolveCopy().markdown.permalinkToThisHeading,
151
+ })(...args);
152
+
153
+ const anchorOptions = {
154
+ level: [2],
155
+ permalink: (slug, opts, state, idx) => {
156
+ if (insideSlide(state, idx)) return;
157
+ anchorPermalink(slug, opts, state, idx);
158
+ },
159
+ };
160
+
161
+ /*
162
+ * Speaker notes and slide typography — the deck-specific pass, run once
163
+ * after parsing (a core rule). Removes every `::: notes` block from the
164
+ * deck in both flavors; when `env.notesSheet` is set, collects them per
165
+ * slide for the instructor notes sheet instead (see `deckNotes`). Drops
166
+ * `::: tags` (glossary overrides) the same way. Collapses
167
+ * `::: eyebrow` into dot-separated `<span>`s; every other `::: name`
168
+ * becomes `<div class="name">`. See docs/writing-content.md.
169
+ */
170
+ const deckContainerRule = (state) => {
171
+ const tokens = state.tokens;
172
+ const notesOut = [];
173
+
174
+ for (let i = tokens.length - 1; i >= 0; i -= 1) {
175
+ const open = tokens[i];
176
+ if (open.type !== "container_container_open") continue;
177
+
178
+ let depth = 1;
179
+ let end = i + 1;
180
+ while (end < tokens.length && depth > 0) {
181
+ if (tokens[end].type === "container_container_open") depth += 1;
182
+ else if (tokens[end].type === "container_container_close") depth -= 1;
183
+ end += 1;
184
+ }
185
+ const line = Number(open.attrGet("data-line") ?? 1) - 1;
186
+ const isNotes = /^notes\b/.test(open.info);
187
+ const isEyebrow = /^eyebrow\s*$/.test(open.info);
188
+ const isTags = /^tags\s*$/.test(open.info);
189
+
190
+ // Glossary tag overrides: read from the source by the glossary data, never rendered.
191
+ if (isTags) {
192
+ tokens.splice(i, end - i);
193
+ continue;
194
+ }
195
+
196
+ if (isNotes) {
197
+ const children = tokens.slice(i + 1, end - 1);
198
+ tokens.splice(i, end - i);
199
+ if (!state.env.notesSheet) continue;
200
+ // The owning slide is the next `container_slide_close`, matched by
201
+ // object reference: later splices only touch positions after `i`.
202
+ const closeToken = tokens.slice(i).find((token) => token.type === "container_slide_close");
203
+ notesOut.push({ closeToken, ...noteInfo(open.info), html: state.md.renderer.render(children, state.md.options, {}) });
204
+ continue;
205
+ }
206
+
207
+ if (isEyebrow) {
208
+ const items = tokens
209
+ .slice(i + 1, end - 1)
210
+ .filter((t) => t.type === "inline")
211
+ .map((t) => `<span>${state.md.renderer.renderInline(t.children, state.md.options, state.env)}</span>`)
212
+ .join("");
213
+ const html = new state.Token("html_block", "", 0);
214
+ html.content = `<div class="eyebrow separators">${items}</div>\n`;
215
+ html.block = true;
216
+ tokens.splice(i, end - i, html);
217
+ continue;
218
+ }
219
+
220
+ const openHtml = new state.Token("html_block", "", 0);
221
+ openHtml.block = true;
222
+ openHtml.content = `<div class="${containerClasses(open.info, state.env, line)}">\n`;
223
+ const closeHtml = new state.Token("html_block", "", 0);
224
+ closeHtml.block = true;
225
+ closeHtml.content = "</div>\n";
226
+ tokens[i] = openHtml;
227
+ tokens[end - 1] = closeHtml;
228
+ }
229
+
230
+ if (state.env.notesSheet) state.env.notesSheet.slides = sheetSlides(state, notesOut.reverse());
231
+ };
232
+
233
+ /**
234
+ * One entry per slide for the notes sheet: its number (matching the deck's
235
+ * `#sN`), kind, first heading, and notes in source order.
236
+ * @returns {{ number: number, kind: string, title: string, notes: { label: string, timing: string, html: string }[] }[]}
237
+ */
238
+ const sheetSlides = (state, notes) => {
239
+ const slides = [];
240
+ let current = null;
241
+ state.tokens.forEach((token, index) => {
242
+ if (token.type === "container_slide_open") {
243
+ current = { number: slides.length + 1, kind: token.info, title: "", notes: [] };
244
+ slides.push(current);
245
+ } else if (token.type === "container_slide_close" && current) {
246
+ current.notes = notes.filter((note) => note.closeToken === token).map(({ label, timing, html }) => ({ label, timing, html }));
247
+ current = null;
248
+ } else if (current && !current.title && token.type === "heading_open") {
249
+ current.title = state.md.renderer.renderInline(state.tokens[index + 1].children, state.md.options, {});
250
+ }
251
+ });
252
+ return slides;
253
+ };
254
+
255
+ /**
256
+ * Parse a deck's markdown (front matter already stripped) for its speaker
257
+ * notes, without rendering the deck. Feeds the notes sheet.
258
+ * @param {string} source
259
+ * @param {string} [file] for build errors
260
+ */
261
+ export const deckNotes = (source, file) => {
262
+ const env = { file, notesSheet: {} };
263
+ markdown.parse(source ?? "", env);
264
+ return env.notesSheet.slides ?? [];
265
+ };
266
+
267
+ /*
268
+ * Slide typography (blockquote -> `.lede`, top-level prose -> `.tight`,
269
+ * `-`/`1.` lists -> `.bullets`/`.steps`, right-aligned table cells -> `.num`)
270
+ * is gated on `env.slideDepth` because these classes are wrong or inert
271
+ * outside a slide.
272
+ */
273
+ const inSlideProse = (env) => env.slideDepth > 0;
274
+
275
+ const installSlideTypography = (md) => {
276
+ md.renderer.rules.container_slide_open = (tokens, idx, _options, env) => {
277
+ env.slideDepth = (env.slideDepth ?? 0) + 1;
278
+ env.slideBaseLevel = tokens[idx].level;
279
+ const kind = tokens[idx].info.trim();
280
+ const number = (env.slideNumber = (env.slideNumber ?? 0) + 1);
281
+ return `<section class="slide" id="s${number}"${kind ? ` data-kind="${kind}"` : ""} aria-label="Slide ${number}"><div class="slide-body">\n`;
282
+ };
283
+ md.renderer.rules.container_slide_close = (_tokens, _idx, _options, env) => {
284
+ env.slideDepth = Math.max(0, (env.slideDepth ?? 1) - 1);
285
+ return "</div></section>\n";
286
+ };
287
+
288
+ md.renderer.rules.blockquote_open = (tokens, idx, options, env, self) => {
289
+ if (!inSlideProse(env)) return self.renderToken(tokens, idx, options);
290
+ env.quoteDepth = (env.quoteDepth ?? 0) + 1;
291
+ return "";
292
+ };
293
+ md.renderer.rules.blockquote_close = (tokens, idx, options, env, self) => {
294
+ if (!inSlideProse(env)) return self.renderToken(tokens, idx, options);
295
+ env.quoteDepth = Math.max(0, (env.quoteDepth ?? 1) - 1);
296
+ return "";
297
+ };
298
+ md.renderer.rules.paragraph_open = (tokens, idx, options, env, self) => {
299
+ if (inSlideProse(env)) {
300
+ if (env.quoteDepth > 0) tokens[idx].attrJoin("class", "lede");
301
+ else if (tokens[idx].level === (env.slideBaseLevel ?? 0) + 1) tokens[idx].attrJoin("class", "tight");
302
+ }
303
+ return self.renderToken(tokens, idx, options);
304
+ };
305
+ md.renderer.rules.bullet_list_open = (tokens, idx, options, env, self) => {
306
+ if (inSlideProse(env)) tokens[idx].attrJoin("class", "bullets");
307
+ return self.renderToken(tokens, idx, options);
308
+ };
309
+ md.renderer.rules.ordered_list_open = (tokens, idx, options, env, self) => {
310
+ if (inSlideProse(env)) tokens[idx].attrJoin("class", "steps");
311
+ return self.renderToken(tokens, idx, options);
312
+ };
313
+ const numericCell = (tokens, idx, options, env, self) => {
314
+ const token = tokens[idx];
315
+ /* An empty header cell is announced as an empty header; write it as a plain cell. */
316
+ if (token.type === "th_open" && !tokens[idx + 1]?.content?.trim()) {
317
+ token.tag = "td";
318
+ if (tokens[idx + 2]?.type === "th_close") tokens[idx + 2].tag = "td";
319
+ }
320
+ if (inSlideProse(env) && /text-align:\s*right/.test(token.attrGet("style") ?? "")) {
321
+ token.attrs = token.attrs.filter(([name]) => name !== "style");
322
+ token.attrJoin("class", "num");
323
+ }
324
+ return self.renderToken(tokens, idx, options);
325
+ };
326
+ md.renderer.rules.th_open = numericCell;
327
+ md.renderer.rules.td_open = numericCell;
328
+ };
329
+
330
+ /**
331
+ * Slide line budget — the cheap, Chromium-free overflow warning, estimating
332
+ * each slide's rendered line count and warning (never failing) past this
333
+ * value. A heuristic that under-counts dense code; `CHECK_FIT` (lib/fit.js)
334
+ * is the real measurement.
335
+ */
336
+ export const SLIDE_LINE_BUDGET = 17.5;
337
+
338
+ // Characters of slide-size prose per line across the full slide width.
339
+ const CHARS_PER_LINE = 88;
340
+ // Rendered line height as a share of one prose line, per block kind.
341
+ const COST = { h1: 3, h2: 2.2, h3: 1.2, lede: 1.5, code: 0.9, row: 1.15, gap: 0.35, item: 0.2, step: 0.45, card: 1.6, callout: 1.2 };
342
+ // Prose inside a card is set smaller than slide prose: more characters per
343
+ // line, less height per line.
344
+ const CARD_SCALE = 0.8;
345
+
346
+ const plainText = (inline) => inline.replace(/[`*_]/g, "");
347
+ const wrapped = (text, width) => Math.max(1, Math.ceil(plainText(text).length / width));
348
+
349
+ /** Lines an `html_block` renders to: an SVG scales to the column width. */
350
+ const htmlLines = (content, width) => {
351
+ const viewBox = /viewBox="\s*[-\d.]+\s+[-\d.]+\s+([\d.]+)\s+([\d.]+)/.exec(content);
352
+ if (viewBox) {
353
+ const pixels = (width / CHARS_PER_LINE) * 1160 * (Number(viewBox[2]) / Number(viewBox[1]));
354
+ return pixels / 36;
355
+ }
356
+ return content.split("\n").filter(Boolean).length / 2;
357
+ };
358
+
359
+ /** Index just past the block that opens at `tokens[i]` (a container or a nested block pair). */
360
+ const blockEnd = (tokens, i, to) => {
361
+ if (tokens[i].nesting !== 1) return i + 1;
362
+ const open = tokens[i].type;
363
+ const close = open.replace(/_open$/, "_close");
364
+ let depth = 0;
365
+ let end = i;
366
+ do {
367
+ if (tokens[end].type === open) depth += 1;
368
+ else if (tokens[end].type === close) depth -= 1;
369
+ end += 1;
370
+ } while (end < to && depth > 0);
371
+ return end;
372
+ };
373
+
374
+ /** Lines for one `::: name` container, `tokens[i]` being its open token. */
375
+ const measureContainer = (tokens, i, end, width) => {
376
+ const names = tokens[i].info.split(/\s+/);
377
+ const cols = /^cols-(\d)$/.exec(names[0])?.[1];
378
+ if (names[0] === "notes") return 0;
379
+ if (names[0] === "eyebrow") return 1 + COST.gap;
380
+ if (cols) return measureColumns(tokens, i + 1, end - 1, width / Number(cols) - 3, Number(cols)) + COST.gap;
381
+ const card = names.includes("card");
382
+ const scale = (names.includes("big") ? 1.4 : 1) * (card ? CARD_SCALE : 1);
383
+ const inner = measureSpan(tokens, i + 1, end - 1, card ? (width - 6) / CARD_SCALE : width) * scale;
384
+ return inner + (card ? COST.card : names.includes("callout") ? COST.callout : 0) + COST.gap;
385
+ };
386
+
387
+ /** Lines for the table row opening at `tokens[i]`: its longest cell, wrapped at half the width. */
388
+ const measureRow = (tokens, i, end, width) => {
389
+ let tallest = 1;
390
+ for (let j = i; j < end; j += 1) {
391
+ if (tokens[j].type === "inline") tallest = Math.max(tallest, wrapped(tokens[j].content, width * 0.5));
392
+ }
393
+ return tallest * COST.row;
394
+ };
395
+
396
+ /**
397
+ * Lines for `tokens[from, to)`, one nesting level: containers recurse with
398
+ * the column width they impose.
399
+ */
400
+ const measureSpan = (tokens, from, to, width) => {
401
+ let lines = 0;
402
+ let i = from;
403
+ while (i < to) {
404
+ const token = tokens[i];
405
+ if (token.type === "container_container_open") {
406
+ const end = blockEnd(tokens, i, to);
407
+ lines += measureContainer(tokens, i, end, width);
408
+ i = end;
409
+ } else if (token.type === "heading_open") {
410
+ lines += (COST[token.tag] ?? 1) * wrapped(tokens[i + 1].content, width * (token.tag === "h3" ? 1 : 0.6)) + COST.gap;
411
+ i += 3;
412
+ } else if (token.type === "paragraph_open") {
413
+ const lede = tokens[i - 1]?.type === "blockquote_open";
414
+ const item = token.hidden ? (tokens[i - 1]?.info ? COST.step : COST.item) : COST.gap;
415
+ lines += (lede ? COST.lede : 1) * wrapped(tokens[i + 1].content, lede ? width * 0.65 : token.hidden ? width - 4 : width) + item;
416
+ i += 3;
417
+ } else if (token.type === "fence") {
418
+ lines += token.content.trimEnd().split("\n").length * COST.code + 1 + COST.gap;
419
+ i += 1;
420
+ } else if (token.type === "html_block") {
421
+ lines += htmlLines(token.content, width) + COST.gap;
422
+ i += 1;
423
+ } else if (token.type === "tr_open") {
424
+ const end = blockEnd(tokens, i, to);
425
+ lines += measureRow(tokens, i, end, width);
426
+ i = end;
427
+ } else {
428
+ i += 1;
429
+ }
430
+ }
431
+ return lines;
432
+ };
433
+
434
+ /**
435
+ * `cols-N`: every direct child (a `::: card`, or a loose block) is one grid
436
+ * cell, N cells per row, so the height is the sum over rows of each row's
437
+ * tallest cell.
438
+ */
439
+ const measureColumns = (tokens, from, to, width, columns) => {
440
+ const cells = [];
441
+ let i = from;
442
+ while (i < to) {
443
+ const end = blockEnd(tokens, i, to);
444
+ cells.push(measureSpan(tokens, i, end, width));
445
+ i = end;
446
+ }
447
+ let lines = 0;
448
+ for (let row = 0; row < cells.length; row += columns) lines += Math.max(...cells.slice(row, row + columns));
449
+ return lines;
450
+ };
451
+
452
+ const slideBudgetRule = (state) => {
453
+ if (state.env.notesSheet) return;
454
+ const tokens = state.tokens;
455
+ const estimates = (state.env.slideEstimates = []);
456
+ let number = 0;
457
+ for (let i = 0; i < tokens.length; i += 1) {
458
+ if (tokens[i].type !== "container_slide_open") continue;
459
+ number += 1;
460
+ let end = i + 1;
461
+ while (end < tokens.length && tokens[end].type !== "container_slide_close") end += 1;
462
+ const lines = Math.round(measureSpan(tokens, i + 1, end, CHARS_PER_LINE) * 10) / 10;
463
+ const line = Number(tokens[i].attrGet("data-line") ?? 1);
464
+ estimates.push({ slide: number, line, lines });
465
+ if (lines > SLIDE_LINE_BUDGET) {
466
+ process.stderr.write(`[slide-budget] ${fileOf(state.env)}:${line}: slide #s${number} estimates ${lines} lines against a budget of ${SLIDE_LINE_BUDGET} — likely to overflow at 1280×720\n`);
467
+ }
468
+ i = end;
469
+ }
470
+ };
471
+
472
+ /**
473
+ * The one markdown-it instance every page, decks included, renders through.
474
+ * @type {import("markdown-it").MarkdownIt}
475
+ */
476
+ export const markdown = markdownIt(baseOptions).use(markdownItAnchor, anchorOptions).use(markdownItFootnote);
477
+
478
+ markdown.block.ruler.before(
479
+ "fence",
480
+ "deck_slide",
481
+ markerContainerRule(SLIDE_MARKER, "container_slide", (info, env, line) => {
482
+ const match = /^slide(?:\s+(\S+))?$/.exec(info);
483
+ if (!match) fail(env, line, `\`>>> ${info}\` doesn't open a slide — expected \`>>> slide\` or \`>>> slide <kind>\``);
484
+ const [, kind = ""] = match;
485
+ if (kind && !SLIDE_KINDS.has(kind)) {
486
+ fail(env, line, `slide kind "${kind}" is not one of ${[...SLIDE_KINDS].join(", ")}`);
487
+ }
488
+ return kind;
489
+ }),
490
+ { alt: ["paragraph", "reference", "blockquote", "list"] },
491
+ );
492
+
493
+ markdown.block.ruler.before("fence", "deck_container", markerContainerRule(CONTAINER_MARKER, "container_container"), {
494
+ alt: ["paragraph", "reference", "blockquote", "list"],
495
+ });
496
+
497
+ markdown.core.ruler.push("deck_slide_balance", checkBalanced("container_slide_open", "container_slide_close", "a slide"));
498
+ markdown.core.ruler.push("deck_container_balance", checkBalanced("container_container_open", "container_container_close", "a `:::` container"));
499
+ markdown.core.ruler.push("deck_slide_budget", slideBudgetRule);
500
+ markdown.core.ruler.push("deck_containers", deckContainerRule);
501
+
502
+ installSlideTypography(markdown);
503
+
504
+
505
+ /* ```prompt fences render as prose figures, not code; ```prompt-avoid is the
506
+ same but without the copy control. See docs/writing-content.md. */
507
+ const defaultFence = markdown.renderer.rules.fence;
508
+
509
+ /** The colored edge for each language family; anything else gets a neutral edge. */
510
+ const LANGUAGE_EDGES = {
511
+ css: "css", scss: "css",
512
+ js: "js", javascript: "js", jsx: "js", ts: "js", typescript: "js",
513
+ html: "html", markup: "html", webc: "html", njk: "html", xml: "html", svg: "html", php: "html",
514
+ bash: "shell", sh: "shell", shell: "shell", zsh: "shell", console: "shell", shellsession: "shell",
515
+ };
516
+
517
+ /** Whether the fence at `idx` sits inside a `>>> slide`: slides keep the bare `<pre>`. */
518
+ const fenceInSlide = (tokens, idx) => {
519
+ let depth = 0;
520
+ for (let i = idx - 1; i >= 0; i -= 1) {
521
+ if (tokens[i].type === "container_slide_close") depth += 1;
522
+ else if (tokens[i].type === "container_slide_open") {
523
+ if (depth === 0) return true;
524
+ depth -= 1;
525
+ }
526
+ }
527
+ return false;
528
+ };
529
+
530
+ /**
531
+ * A fenced sample as a `figure.code-block`: language label, optional file name
532
+ * (`title="path/file.ext"` on the fence) and the highlighted lines. The copy
533
+ * button is added by /js/copy.js.
534
+ * The bare `<pre>` stays for anything that is not a page's own prose: a fence
535
+ * in a slide or a deck, a notes sheet, and anything rendered outside a page.
536
+ * @returns {string}
537
+ */
538
+ const codeBlock = (tokens, idx, options, env, self) => {
539
+ const pre = defaultFence(tokens, idx, options, env, self);
540
+ const inputPath = env?.page?.inputPath ?? "";
541
+ if (!inputPath || inputPath.includes("/slides/") || env?.layout === "deck" || env?.notesSheet || fenceInSlide(tokens, idx)) return pre;
542
+ const info = (tokens[idx].info || "").trim();
543
+ const first = info.split(/\s+/)[0];
544
+ const language = first.includes("=") ? "" : first.split("/")[0].toLowerCase();
545
+ const title = /\btitle="([^"]+)"/.exec(info)?.[1];
546
+ const edge = LANGUAGE_EDGES[language] ?? "neutral";
547
+ const lines = tokens[idx].content.replace(/\n$/, "").split("\n").length;
548
+ const numbered = lines > 1 && edge !== "shell" && language !== "text" && language !== "";
549
+ const { escapeHtml: esc } = markdown.utils;
550
+ const copy = resolveCopy().code;
551
+ const label = copy.languages[language] ?? (language ? language.toUpperCase() : copy.plain);
552
+ const file = title ? `<span class="code-block-file">${esc(title)}</span>` : "";
553
+ return `<figure class="code-block" data-edge="${edge}"${numbered ? " data-line-numbers" : ""}>\n<figcaption class="code-block-head"><span class="code-block-lang">${esc(label)}</span>${file}</figcaption>\n${pre}</figure>\n`;
554
+ };
555
+
556
+ markdown.renderer.rules.fence = (tokens, idx, options, env, self) => {
557
+ const info = (tokens[idx].info || "").trim();
558
+ if (info !== "prompt" && info !== "prompt-avoid") {
559
+ return codeBlock(tokens, idx, options, env, self);
560
+ }
561
+ const paragraphs = tokens[idx].content
562
+ .trim()
563
+ .split(/\n{2,}/)
564
+ .map((part) => `<p>${markdown.utils.escapeHtml(part.replace(/\n/g, " "))}</p>`)
565
+ .join("\n");
566
+ const avoid = info === "prompt-avoid";
567
+ return `<figure class="prompt${avoid ? " prompt-avoid" : ""}"${avoid ? "" : " data-copyable"}>\n${paragraphs}\n</figure>\n`;
568
+ };