@allons-y/course-kit 0.0.0-stage → 0.2.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 +19 -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 +2091 -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 +432 -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 +370 -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 +656 -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 +61 -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 +231 -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 +119 -4
  128. package/schemas/course.schema.json +161 -0
  129. package/schemas/dates.schema.json +165 -0
  130. package/schemas/grading.schema.json +59 -0
  131. package/schemas/instructor.schema.json +76 -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/theme.js ADDED
@@ -0,0 +1,185 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ /**
5
+ * Every color token, by role. The CSS name is `--color-<key>`.
6
+ * `site` and `deck` are the defaults in base.css and deck.css; a token with no
7
+ * default for a stylesheet is not written to it.
8
+ */
9
+ export const TOKENS = [
10
+ { key: "page", role: "Page background", site: { light: "#FBF9F3", dark: "#1C1613" }, deck: { light: "#FBF9F3", dark: "#1C1613" } },
11
+ { key: "surface", role: "Raised or alternate surface: cards, table headers, code", site: { light: "#F8F6F0", dark: "#2A211C" }, deck: { light: "#fff", dark: "#2A211C" } },
12
+ { key: "surface-subtle", role: "Faint surface tint", site: { light: "color-mix(in oklab, #EFEBDF 22%, transparent)", dark: "hsl(22deg 20% 17% / 30%)" } },
13
+ { key: "surface-overlay", role: "Popovers and menus", site: { light: "#FBF9F3", dark: "#2B2019" } },
14
+ { key: "surface-accent", role: "Accent-tinted wash, light enough for muted and accent text to stay at 7:1", site: { light: "color-mix(in oklab, var(--color-accent) 7%, var(--color-page))", dark: "color-mix(in oklab, var(--color-accent) 9%, var(--color-page))" }, deck: "color-mix(in oklab, var(--color-accent-strong) 14%, light-dark(white, black))" },
15
+ { key: "surface-accent-secondary", role: "Wayfinding wash: today, the current week", site: { light: "color-mix(in oklab, var(--color-accent-secondary) 5%, var(--color-page))", dark: "color-mix(in oklab, var(--color-accent-secondary) 9%, var(--color-page))" } },
16
+ { key: "table-header", role: "Table header cells", site: "var(--color-surface)" },
17
+ { key: "surface-warning", role: "Warning panel background", deck: { light: "#fff2e6", dark: "#3a2314" } },
18
+ { key: "text", role: "Body text", site: { light: "#33394E", dark: "#FBF9F3" }, deck: { light: "#33394E", dark: "#FBF9F3" } },
19
+ { key: "text-muted", role: "Secondary text", site: { light: "#414C75", dark: "#B6AFAB" }, deck: { light: "#414C75", dark: "#B6AFAB" } },
20
+ { key: "border", role: "Lines, rules and borders", site: { light: "#B6AFAB", dark: "#5A4A40" }, deck: { light: "#EFEBDF", dark: "#3A2E27" } },
21
+ { key: "border-accent", role: "Accent-tinted line", deck: "color-mix(in oklab, var(--color-accent-strong) 40%, light-dark(white, black))" },
22
+ { key: "accent", role: "Brand color: fills, buttons, rules, the masthead wash", site: { light: "#8B1E5E", dark: "#F07DB7" }, deck: { light: "#8B1E5E", dark: "#F07DB7" } },
23
+ { key: "accent-text", role: "Brand color for type, dark enough to read", site: { light: "#8B1E5E", dark: "#FC88C2" }, deck: { light: "#8B1E5E", dark: "#FC88C2" } },
24
+ { key: "accent-strong", role: "Brand color for decorative marks: the text tone in light mode, the fill in dark", deck: "light-dark(var(--color-accent-text), var(--color-accent))" },
25
+ { key: "on-accent", role: "Text on a brand-color fill", site: { light: "#FBF9F3", dark: "#1C1613" } },
26
+ { key: "accent-fill-hover", role: "Solid brand fill, hovered, under on-accent text", site: { light: "#6F1849", dark: "#EE93C2" } },
27
+ { key: "accent-hover", role: "Brand fill, hovered", site: "color-mix(in oklch, var(--color-accent) 40%, transparent)" },
28
+ { key: "accent-active", role: "Brand fill, pressed", site: "color-mix(in oklch, var(--color-accent) 40%, transparent)" },
29
+ { key: "accent-secondary", role: "Wayfinding color: progress, section bars, the current location, highlighted code", site: { light: "#1F4E9C", dark: "#84B0F7" }, deck: { light: "#1F4E9C", dark: "#84B0F7" } },
30
+ { key: "on-accent-secondary", role: "Text on a wayfinding-color fill", site: { light: "#FBF9F3", dark: "#1C1613" } },
31
+ { key: "link", role: "Links", site: "var(--color-accent-text)" },
32
+ { key: "link-hover", role: "Links, hovered", site: "color-mix(in oklch, var(--color-link) 90%, var(--color-text))" },
33
+ { key: "link-focus", role: "Links, focused", site: "color-mix(in oklch, var(--color-link) 90%, var(--color-text))" },
34
+ { key: "link-active", role: "Links, pressed", site: "color-mix(in oklch, var(--color-link) 90%, var(--color-text))" },
35
+ { key: "success", role: "Success: correct answers, confirmations", site: { light: "#0E5F40", dark: "#53C696" }, deck: { light: "#1A6034", dark: "#7fd8a0" } },
36
+ { key: "on-success", role: "Text on a success fill", site: { light: "#FBF9F3", dark: "#1C1613" } },
37
+ { key: "error", role: "Error: wrong answers, failures", site: { light: "#A90916", dark: "#FF8D88" }, deck: { light: "#A02317", dark: "#ff9d8f" } },
38
+ { key: "on-error", role: "Text on an error fill", site: { light: "#FBF9F3", dark: "#1C1613" } },
39
+ { key: "warning", role: "Warnings and cautions", site: { light: "#FFC143", dark: "#D59719" }, deck: { light: "#8a3500", dark: "#ffb37a" } },
40
+ { key: "warning-edge", role: "The edge and mark of a warning: dark enough to read as a line on the page and on a warning wash", site: { light: "#8A5A00", dark: "#D59719" } },
41
+ { key: "on-warning", role: "Text on a warning fill", site: { light: "#33394E", dark: "#1C1613" } },
42
+ { key: "highlight", role: "Highlighted (marked) text", site: { light: "#FFD36C", dark: "#FFC233" } },
43
+ { key: "on-highlight", role: "Text on a highlight fill", site: "#33394E" },
44
+ { key: "focus-ring", role: "Focus outline (solid, 2.4.13)", site: { light: "#33394E", dark: "#FFC233" } },
45
+ { key: "border-strong", role: "Edges of anything operable (at least 3:1)", site: { light: "#414C75", dark: "#B6AFAB" } },
46
+ { key: "tag-test", role: "Glossary tag hue for tests; its tints derive from it", site: { light: "#b37019", dark: "#e7a855" } },
47
+ { key: "tag-reading", role: "Glossary tag hue for readings; its tints derive from it", site: { light: "#1938b3", dark: "#5572e7" } },
48
+ { key: "tag-meeting", role: "Glossary tag hue for class meetings; its tints derive from it", site: { light: "#13863d", dark: "#55e78b" } },
49
+ { key: "code", role: "Preformatted code text and its border", site: "var(--color-text)" },
50
+ { key: "code-surface", role: "Code block ground", site: { light: "#FFFDF8", dark: "#241C18" } },
51
+ { key: "code-text", role: "Code text", site: "var(--color-text)" },
52
+ { key: "code-keyword", role: "Code keywords, and the copy button", site: { light: "#824306", dark: "#E9A35C" } },
53
+ { key: "code-string", role: "Code strings", site: { light: "#635200", dark: "#FFD36C" } },
54
+ { key: "code-function", role: "Code functions", site: { light: "#195A6E", dark: "#7BD1E6" } },
55
+ { key: "code-number", role: "Code numbers", site: { light: "#992D15", dark: "#FF9F80" } },
56
+ { key: "code-comment", role: "Code comments", site: { light: "#414C75", dark: "#B6AFAB" } },
57
+ { key: "code-edge-css", role: "Decorative language bar: CSS", site: "#7BD1E6" },
58
+ { key: "code-edge-js", role: "Decorative language bar: JavaScript", site: "#FFC233" },
59
+ { key: "code-edge-html", role: "Decorative language bar: HTML", site: "#B0651E" },
60
+ { key: "code-edge-shell", role: "Decorative language bar: terminal", site: "#D6A86A" },
61
+ { key: "code-edge-neutral", role: "Decorative language bar: anything else", site: "var(--color-border)" },
62
+ { key: "highlight-line", role: "Highlighted code line wash", site: { light: "color-mix(in oklab, var(--color-accent-secondary) 3%, var(--color-code-surface))", dark: "color-mix(in oklab, var(--color-accent-secondary) 6%, var(--color-code-surface))" } },
63
+ ];
64
+
65
+ /** Default gradient stops. A theme may list one to four. */
66
+ export const GRADIENT = [{ light: "#8B1E5E", dark: "#E573AD" }, "#7BD1E6", { light: "#FFD36C", dark: "#FFC233" }, "#FF9A56"];
67
+
68
+ const KEYS = new Set(TOKENS.map((token) => token.key));
69
+ const UNSAFE = /[;{}<>]/;
70
+
71
+ /**
72
+ * @param {unknown} value a color, or `{ light, dark }`
73
+ * @returns {string} the CSS value
74
+ */
75
+ const css = (value) => (typeof value === "string" ? value : `light-dark(${value.light}, ${value.dark})`);
76
+
77
+ /**
78
+ * @param {unknown} value
79
+ * @param {string} where a path for the error message
80
+ */
81
+ const checkColor = (value, where) => {
82
+ const ok = (v) => typeof v === "string" && v.trim() !== "" && !UNSAFE.test(v);
83
+ if (ok(value)) return;
84
+ if (value && typeof value === "object" && ok(value.light) && ok(value.dark) && Object.keys(value).length === 2) return;
85
+ throw new Error(`theme: ${where} must be a color, or { "light": color, "dark": color }`);
86
+ };
87
+
88
+ /**
89
+ * @param {Record<string, unknown>} overrides
90
+ * @param {string} where
91
+ */
92
+ const checkOverrides = (overrides, where) => {
93
+ for (const [key, value] of Object.entries(overrides)) {
94
+ if (key === "$schema") continue;
95
+ if (key === "gradient" && where === "theme") {
96
+ if (!Array.isArray(value) || value.length < 1 || value.length > 4) throw new Error("theme: gradient must list one to four colors");
97
+ value.forEach((stop, index) => checkColor(stop, `gradient[${index}]`));
98
+ continue;
99
+ }
100
+ if ((key === "site" || key === "deck") && where === "theme") {
101
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`theme: ${key} must be an object of color overrides`);
102
+ checkOverrides(value, `theme.${key}`);
103
+ continue;
104
+ }
105
+ if (!KEYS.has(key)) throw new Error(`${where}: "${key}" is not a color token. Use one of: ${[...KEYS].join(", ")}`);
106
+ checkColor(value, `${where}.${key}`);
107
+ }
108
+ };
109
+
110
+ /**
111
+ * Throw a plain-language error unless `theme` is a valid theme.json object.
112
+ * @param {unknown} theme
113
+ */
114
+ export function validateTheme(theme) {
115
+ if (!theme || typeof theme !== "object" || Array.isArray(theme)) throw new Error("theme: must be an object");
116
+ checkOverrides(theme, "theme");
117
+ }
118
+
119
+ /**
120
+ * The course's theme: `_data/theme.json` over the config option over the defaults.
121
+ * Top-level keys apply to the site and the decks; `site` and `deck` hold overrides for one only.
122
+ * @param {{ dataDir?: string, theme?: object }} [options]
123
+ * @returns {{ overrides: Record<string, unknown>, site: Record<string, unknown>, deck: Record<string, unknown>, gradient: unknown[] }}
124
+ */
125
+ export function resolveTheme({ dataDir, theme = {} } = {}) {
126
+ let file = {};
127
+ if (dataDir) {
128
+ try {
129
+ file = JSON.parse(readFileSync(join(dataDir, "theme.json"), "utf8"));
130
+ } catch (error) {
131
+ if (error.code !== "ENOENT") throw new Error(`theme: ${join(dataDir, "theme.json")} is not valid JSON (${error.message})`, { cause: error });
132
+ }
133
+ }
134
+ checkOverrides(theme, "theme");
135
+ checkOverrides(file, "theme");
136
+ const { site: optionSite = {}, deck: optionDeck = {}, gradient: optionGradient, ...optionTokens } = theme;
137
+ const { site: fileSite = {}, deck: fileDeck = {}, gradient: fileGradient, ...fileTokens } = file;
138
+ delete optionTokens.$schema;
139
+ delete fileTokens.$schema;
140
+ return {
141
+ overrides: { ...optionTokens, ...fileTokens },
142
+ site: { ...optionSite, ...fileSite },
143
+ deck: { ...optionDeck, ...fileDeck },
144
+ gradient: fileGradient ?? optionGradient ?? GRADIENT,
145
+ };
146
+ }
147
+
148
+ /**
149
+ * The `--color-*` declarations for one stylesheet.
150
+ * @param {"site" | "deck"} context
151
+ * @param {ReturnType<typeof resolveTheme>} theme
152
+ * @returns {string}
153
+ */
154
+ export function renderColors(context, theme) {
155
+ const lines = [];
156
+ for (const token of TOKENS) {
157
+ const fallback = token[context];
158
+ if (fallback === undefined) continue;
159
+ const value = theme[context][token.key] ?? theme.overrides[token.key] ?? fallback;
160
+ lines.push(`--color-${token.key}: ${css(value)};`);
161
+ }
162
+ if (context === "site") {
163
+ const stops = theme.gradient.map((stop, index) => `--color-gradient-${index + 1}: ${css(stop)};`);
164
+ const names = theme.gradient.map((_, index) => `var(--color-gradient-${index + 1})`);
165
+ // A gradient needs two stops; one color repeats.
166
+ if (names.length === 1) names.push(names[0]);
167
+ lines.push(...stops, `--gradient-stops: ${names.join(", ")};`);
168
+ }
169
+ return lines.join("\n");
170
+ }
171
+
172
+ const MARKER = /\/\*\s*tokens:([a-z-]+)\s*\*\//g;
173
+
174
+ /**
175
+ * Replace each `/* tokens:site *\/` or `/* tokens:deck *\/` marker in a stylesheet.
176
+ * @param {string} source
177
+ * @param {ReturnType<typeof resolveTheme>} theme
178
+ * @returns {string}
179
+ */
180
+ export function applyTokens(source, theme) {
181
+ return source.replace(MARKER, (_, name) => {
182
+ if (name !== "site" && name !== "deck") throw new Error(`course-kit: unknown theme token block "${name}"`);
183
+ return renderColors(name, theme);
184
+ });
185
+ }
@@ -0,0 +1,415 @@
1
+ /*
2
+ * The worksheet markdown dialect: `content/practice/<name>.worksheet.md` in,
3
+ * the object `prepareWorksheet` takes out.
4
+ *
5
+ * Worksheets are mostly prose — prompts, explanations, definitions, code
6
+ * snippets — and prose does not belong in JSON. This is the same trade the
7
+ * slide decks make: author in markdown with `:::` containers, and fail the
8
+ * build naming the file and line when the shape is wrong, rather than
9
+ * validate in the editor and render something quietly wrong.
10
+ *
11
+ * It is a block reader, not a markdown-it plugin, because what it produces is
12
+ * data rather than HTML. Fences are consumed whole, so a `:::` or a `|` inside
13
+ * one is content; containers nest by counting opens and closes, so a `::: bank`
14
+ * inside a `::: match` closes the bank.
15
+ *
16
+ * `schemas/worksheet.schema.json` still describes the object this produces.
17
+ */
18
+ import matter from "gray-matter";
19
+
20
+ const MARKER = /^:{3,}\s*(.*)$/;
21
+ const FENCE = /^(`{3,})\s*([\w-]*)\s*$/;
22
+ const HEADING = /^(#{1,6})\s+(.*)$/;
23
+ const SECTION = /^(\d+)\.\s+(.+)$/;
24
+ /** `[label](target)`, the only link shape the dialect reads. */
25
+ const LINK = /^\[([^\]]+)\]\(([^)]+)\)$/;
26
+ /** `1/2#s7` — week 1, day 2, slide 7. Anything else is used as an href. */
27
+ const SLIDE_REF = /^(\d+)\/(\d+)(?:#s(\d+))?$/;
28
+ const TASK = /^[-*]\s+\[([ xX])\]\s+(.*)$/;
29
+ const BULLET = /^[-*]\s+(.*)$/;
30
+ const ORDERED = /^\d+[.)]\s+(.*)$/;
31
+ const FIELD = /^(why|source|hint|verdict)\s*:\s*(.*)$/;
32
+ /** A blank's answers: `` `shown` / `also accepted` ``. */
33
+ const ANSWERS = /`([^`]+)`/g;
34
+ const KINDS = ["choice", "match", "fill", "tree", "grid", "judge", "selfcheck"];
35
+
36
+ class WorksheetError extends Error {}
37
+
38
+ const fail = (file, line, message) => {
39
+ throw new WorksheetError(`${file}:${line}: ${message}`);
40
+ };
41
+
42
+ /** Trim one level of list indentation so a nested block reads as its own. */
43
+ const dedent = (lines) => {
44
+ const indents = lines.filter((l) => l.text.trim()).map((l) => l.text.match(/^\s*/)[0].length);
45
+ const least = Math.min(...indents, Infinity);
46
+ return Number.isFinite(least) ? lines.map((l) => ({ ...l, text: l.text.slice(least) })) : lines;
47
+ };
48
+
49
+ /**
50
+ * Split lines into blocks: fences and containers whole, everything else as
51
+ * paragraphs. Blocks carry their first line number so errors can point at it.
52
+ * @param {{text: string, line: number}[]} lines
53
+ * @param {string} file
54
+ * @returns {object[]}
55
+ */
56
+ function readBlocks(lines, file) {
57
+ const blocks = [];
58
+ let i = 0;
59
+ while (i < lines.length) {
60
+ const { text, line } = lines[i];
61
+ if (!text.trim()) {
62
+ i += 1;
63
+ continue;
64
+ }
65
+
66
+ const fence = text.trim().match(FENCE);
67
+ if (fence) {
68
+ const close = lines.findIndex((l, j) => j > i && l.text.trim().startsWith(fence[1]));
69
+ if (close === -1) fail(file, line, "a code fence is never closed");
70
+ blocks.push({ type: "fence", lang: fence[2], code: lines.slice(i + 1, close).map((l) => l.text), line });
71
+ i = close + 1;
72
+ continue;
73
+ }
74
+
75
+ const marker = text.trim().match(MARKER);
76
+ if (marker) {
77
+ if (!marker[1]) fail(file, line, "a bare ::: closes a container that was never opened");
78
+ let depth = 1;
79
+ let j = i + 1;
80
+ for (; j < lines.length && depth > 0; j += 1) {
81
+ const inner = lines[j].text.trim();
82
+ const innerFence = inner.match(FENCE);
83
+ if (innerFence) {
84
+ const end = lines.findIndex((l, k) => k > j && l.text.trim().startsWith(innerFence[1]));
85
+ if (end === -1) fail(file, lines[j].line, "a code fence is never closed");
86
+ j = end;
87
+ continue;
88
+ }
89
+ const innerMarker = inner.match(MARKER);
90
+ if (innerMarker) depth += innerMarker[1] ? 1 : -1;
91
+ }
92
+ if (depth > 0) fail(file, line, `::: ${marker[1]} is never closed`);
93
+ const [name, ...rest] = marker[1].split(/\s+/);
94
+ blocks.push({ type: "container", name, info: rest, body: dedent(lines.slice(i + 1, j - 1)), line });
95
+ i = j;
96
+ continue;
97
+ }
98
+
99
+ const heading = text.trim().match(HEADING);
100
+ if (heading) {
101
+ blocks.push({ type: "heading", depth: heading[1].length, text: heading[2].trim(), line });
102
+ i += 1;
103
+ continue;
104
+ }
105
+
106
+ let end = i;
107
+ while (end < lines.length && lines[end].text.trim() && !lines[end].text.trim().match(MARKER) && !lines[end].text.trim().match(FENCE) && !lines[end].text.trim().match(HEADING)) end += 1;
108
+ blocks.push({ type: "paragraph", lines: lines.slice(i, end), line });
109
+ i = end;
110
+ }
111
+ return blocks;
112
+ }
113
+
114
+ /** `[label](1/2#s7)` or `[label](/a/path/)` -> a source object. */
115
+ function parseSource(text, file, line) {
116
+ const link = text.trim().match(LINK);
117
+ if (!link) fail(file, line, `a source must read [label](week/day#sN): ${text.trim()}`);
118
+ const [, label, target] = link;
119
+ const slide = target.match(SLIDE_REF);
120
+ if (!slide) return { label, href: target };
121
+ const source = { label, week: Number(slide[1]), day: Number(slide[2]) };
122
+ if (slide[3]) source.slide = Number(slide[3]);
123
+ return source;
124
+ }
125
+
126
+ /** Group a paragraph's lines into `key: value` fields and plain prose. */
127
+ function readParagraph(block) {
128
+ const fields = [];
129
+ const prose = [];
130
+ for (const { text, line } of block.lines) {
131
+ const trimmed = text.trim();
132
+ const field = trimmed.match(FIELD);
133
+ if (field) {
134
+ fields.push({ key: field[1], value: field[2].trim(), quote: [], line });
135
+ } else if (trimmed.startsWith(">") && fields.length) {
136
+ fields.at(-1).quote.push(trimmed.replace(/^>\s?/, ""));
137
+ } else if (fields.length) {
138
+ fields.at(-1).value = `${fields.at(-1).value} ${trimmed}`.trim();
139
+ } else {
140
+ prose.push(trimmed);
141
+ }
142
+ }
143
+ return { fields, prose: prose.join(" ") };
144
+ }
145
+
146
+ /** Bullet list items, each with any indented continuation lines. */
147
+ function listItems(lines, pattern = BULLET) {
148
+ const items = [];
149
+ for (const { text, line } of lines) {
150
+ if (!text.trim()) continue;
151
+ const match = text.trim().match(pattern);
152
+ const indent = text.match(/^\s*/)[0].length;
153
+ if (match && (items.length === 0 || indent <= items.at(-1).indent)) {
154
+ items.push({ text: match[match.length - 1], extra: [], indent, line });
155
+ } else if (items.length) {
156
+ items.at(-1).extra.push({ text: text.trim(), line });
157
+ }
158
+ }
159
+ return items;
160
+ }
161
+
162
+ /** The one container a question kind may nest, e.g. `bank` inside `match`. */
163
+ const nested = (blocks, name) => blocks.find((b) => b.type === "container" && b.name === name);
164
+
165
+ /**
166
+ * Parse one `::: <kind> <id>` container into an authored question.
167
+ * @param {object} block
168
+ * @param {string} file
169
+ * @returns {object}
170
+ */
171
+ function parseQuestion(block, file) {
172
+ const kind = block.name;
173
+ const id = block.info[0];
174
+ if (!id) fail(file, block.line, `::: ${kind} needs a question id, e.g. \`::: ${kind} 1.2\``);
175
+ const question = { id, kind };
176
+ const blocks = readBlocks(block.body, file);
177
+
178
+ for (const child of blocks) {
179
+ if (child.type !== "paragraph") continue;
180
+ const { fields, prose } = readParagraph(child);
181
+ if (prose && question.prompt === undefined) question.prompt = prose;
182
+ else if (prose && !fields.length && !question.body) question.body = prose;
183
+ for (const field of fields) {
184
+ if (field.key === "why") question.why = field.value;
185
+ else if (field.key === "hint") question.dragHint = field.value;
186
+ else if (field.key === "verdict") question.verdict = field.value;
187
+ else if (field.key === "source") {
188
+ const source = parseSource(field.value, file, field.line);
189
+ if (field.quote.length) source.quote = field.quote.join(" ");
190
+ question.sources = [...(question.sources ?? []), source];
191
+ }
192
+ }
193
+ }
194
+
195
+ // An ```svg fence is the question's figure, whatever its kind; any other
196
+ // fence is the snippet the kind below reads.
197
+ const figure = blocks.find((b) => b.type === "fence" && b.lang === "svg");
198
+ if (figure) question.figure = figure.code.join("\n");
199
+ const fence = blocks.find((b) => b.type === "fence" && b.lang !== "svg");
200
+ if (fence?.lang) question.lang = fence.lang;
201
+ const lists = blocks.filter((b) => b.type === "paragraph" && b.lines.some((l) => l.text.trim().match(BULLET) || l.text.trim().match(ORDERED)));
202
+
203
+ if (kind === "choice") {
204
+ if (fence) question.code = fence.code.join("\n");
205
+ const options = listItems(lists[0]?.lines ?? [], TASK);
206
+ if (!options.length) fail(file, block.line, "a choice question needs a `- [ ]` list of options");
207
+ question.options = options.map((o) => o.text);
208
+ question.answer = options.findIndex((o, index) => lists[0].lines.filter((l) => l.text.trim().match(TASK))[index].text.trim().match(TASK)[1].toLowerCase() === "x");
209
+ if (question.answer === -1) fail(file, block.line, "no option is marked `- [x]`");
210
+ }
211
+
212
+ if (kind === "match") {
213
+ if (fence) question.code = fence.code.join("\n");
214
+ const bank = nested(blocks, "bank");
215
+ if (!bank) fail(file, block.line, "a match question needs a `::: bank` of lettered options");
216
+ question.bank = listItems(bank.body).map((entry) => {
217
+ const lettered = entry.text.match(/^([A-Z])[.)]\s+(.*)$/);
218
+ if (!lettered) fail(file, entry.line, `a bank entry must read "A. text": ${entry.text}`);
219
+ return { letter: lettered[1], text: lettered[2] };
220
+ });
221
+ if (bank.info.includes("drag")) question.dragDrop = true;
222
+ const items = listItems(lists.find((l) => l.lines.some((x) => x.text.trim().match(ORDERED)))?.lines ?? [], ORDERED);
223
+ if (!items.length) fail(file, block.line, "a match question needs a numbered list of items");
224
+ question.items = items.map((item) => {
225
+ const paired = item.text.match(/^(.*?)\s+—\s+([A-Z])$/);
226
+ if (!paired) fail(file, item.line, `a match item must read "text — A": ${item.text}`);
227
+ const parsed = { text: paired[1], answer: paired[2] };
228
+ const source = item.extra.find((e) => e.text.startsWith("["));
229
+ if (source) parsed.source = parseSource(source.text, file, source.line);
230
+ return parsed;
231
+ });
232
+ }
233
+
234
+ if (kind === "fill") {
235
+ if (fence) question.code = fence.code.join("\n");
236
+ const bank = nested(blocks, "bank");
237
+ if (bank) {
238
+ const words = bank.body.map((l) => l.text.trim()).filter(Boolean).join(" ");
239
+ question.bank = words.split("·").map((w) => w.trim()).filter(Boolean);
240
+ if (bank.info.includes("drag")) question.dragDrop = true;
241
+ }
242
+ question.blanks = listItems(lists.find((l) => l.lines.some((x) => x.text.trim().match(ORDERED)))?.lines ?? [], ORDERED).map((item) => parseBlank(item, file));
243
+ if (!question.blanks.length) fail(file, block.line, "a fill question needs a numbered list of blanks");
244
+ }
245
+
246
+ if (kind === "tree") {
247
+ if (fence) question.code = fence.code.join("\n");
248
+ const tree = lists.find((l) => l.lines.some((x) => x.text.trim().match(BULLET)));
249
+ if (!tree) fail(file, block.line, "a tree question needs a nested list of nodes");
250
+ const { nodes, blanks } = parseTree(tree.lines, file);
251
+ question.nodes = nodes;
252
+ question.blanks = blanks;
253
+ }
254
+
255
+ if (kind === "grid") {
256
+ if (fence) question.code = fence.code.join("\n");
257
+ const table = blocks.find((b) => b.type === "paragraph" && b.lines[0].text.trim().startsWith("|"));
258
+ if (!table) fail(file, block.line, "a grid question needs a table");
259
+ const rows = table.lines.map((l) => ({ cells: l.text.trim().replace(/^\||\|$/g, "").split("|").map((c) => c.trim()), line: l.line }));
260
+ question.rowHeader = rows[0].cells[0];
261
+ question.columns = rows[0].cells.slice(1);
262
+ question.rows = rows.slice(2).map((row) => {
263
+ const answer = row.cells.slice(1).findIndex((c) => c.toLowerCase() === "x");
264
+ if (answer === -1) fail(file, row.line, `no column is marked x: ${row.cells[0]}`);
265
+ return { text: row.cells[0], answer };
266
+ });
267
+ }
268
+
269
+ if (kind === "judge") {
270
+ if (!fence) fail(file, block.line, "a judge question needs a fenced snippet");
271
+ // Every line carries a two-column gutter so the snippet keeps its own
272
+ // indentation: " " normally, "! " on the line that causes the problem.
273
+ for (const [index, text] of fence.code.entries()) {
274
+ if (text.trim() && !/^(\s\s|! )/.test(text)) fail(file, fence.line + index + 1, `a judge snippet's lines need a two-space gutter, "! " on the offending one: ${text}`);
275
+ }
276
+ question.lines = fence.code.map((l) => l.slice(2));
277
+ question.lineAnswers = fence.code.map((l, index) => (l.startsWith("!") ? index : -1)).filter((index) => index !== -1);
278
+ if (!question.verdict) fail(file, block.line, "a judge question needs a `verdict:` letter from the section legend");
279
+ question.verdictLetter = question.verdict;
280
+ delete question.verdict;
281
+ }
282
+
283
+ if (kind === "selfcheck") {
284
+ if (fence) question.code = fence.code.join("\n");
285
+ const reveal = nested(blocks, "reveal");
286
+ const check = nested(blocks, "check");
287
+ if (!reveal) fail(file, block.line, "a selfcheck question needs a `::: reveal` list");
288
+ question.reveal = listItems(reveal.body).map((i) => i.text);
289
+ if (check) question.checkYourself = listItems(check.body).map((i) => i.text);
290
+ }
291
+
292
+ delete question.body;
293
+ return question;
294
+ }
295
+
296
+ /** `Label _(hint)_ — `shown` / `also accepted`` -> a blank. */
297
+ function parseBlank(item, file) {
298
+ const split = item.text.match(/^(.*?)\s+—\s+(.*)$/);
299
+ if (!split) fail(file, item.line, `a blank must read "label — \`answer\`": ${item.text}`);
300
+ const answers = split[2];
301
+ let label = split[1];
302
+ const blank = {};
303
+ const hint = label.match(/\s*_\(([^)]+)\)_\s*$/);
304
+ if (hint) {
305
+ blank.hint = hint[1];
306
+ label = label.slice(0, hint.index);
307
+ }
308
+ const accept = [...answers.matchAll(ANSWERS)].map((m) => m[1]);
309
+ if (!accept.length) fail(file, item.line, `a blank's answers must be in backticks: ${item.text}`);
310
+ return { label: label.trim(), ...blank, accept, display: accept[0] };
311
+ }
312
+
313
+ /** A nested list of element names; `?name` is a blank the student fills. */
314
+ function parseTree(lines, file) {
315
+ const nodes = [];
316
+ const blanks = [];
317
+ const indents = [];
318
+ for (const { text, line } of lines) {
319
+ if (!text.trim()) continue;
320
+ const bullet = text.trim().match(BULLET);
321
+ if (!bullet) fail(file, line, `a tree node must be a list item: ${text.trim()}`);
322
+ const indent = text.match(/^\s*/)[0].length;
323
+ while (indents.length && indents.at(-1) >= indent) indents.pop();
324
+ indents.push(indent);
325
+ const depth = indents.length - 1;
326
+ const [name, label] = bullet[1].split(/\s+—\s+/);
327
+ if (!name.startsWith("?")) {
328
+ nodes.push({ depth, label: name.trim() });
329
+ continue;
330
+ }
331
+ const accept = [...name.matchAll(ANSWERS)].map((m) => m[1]);
332
+ const display = accept.length ? accept[0] : name.slice(1).trim();
333
+ nodes.push({ blank: blanks.length, depth });
334
+ blanks.push({
335
+ label: `Blank ${blanks.length + 1}${label ? ` — ${label.trim()}` : ""}`,
336
+ accept: accept.length ? accept : [display],
337
+ display,
338
+ });
339
+ }
340
+ return { nodes, blanks };
341
+ }
342
+
343
+ /**
344
+ * Parse a worksheet markdown file into the object `prepareWorksheet` takes.
345
+ * @param {string} source the file's contents
346
+ * @param {string} [file] path, for error messages
347
+ * @returns {object} `{title, description, eyebrow, heading, lede, intro, terms, sections}`
348
+ */
349
+ export function parseWorksheet(source, file = "worksheet") {
350
+ const { data, content } = matter(source);
351
+ const offset = source.slice(0, source.length - content.length).split("\n").length;
352
+ const lines = content.split("\n").map((text, index) => ({ text, line: index + offset }));
353
+ const blocks = readBlocks(lines, file);
354
+
355
+ const worksheet = { ...data, intro: [], terms: [], sections: [] };
356
+ let section = null;
357
+
358
+ for (const block of blocks) {
359
+ if (block.type === "heading") {
360
+ const match = block.text.match(SECTION);
361
+ if (block.depth !== 2 || !match) fail(file, block.line, `a section heading must read "## 1. Title": ${block.text}`);
362
+ section = { n: Number(match[1]), title: match[2], questions: [] };
363
+ worksheet.sections.push(section);
364
+ continue;
365
+ }
366
+
367
+ if (block.type === "container" && block.name === "terms") {
368
+ worksheet.terms = listItems(block.body).map((item) => {
369
+ const parsed = item.text.match(/^\*\*(.+?)\*\*\s+—\s+(.*?)(\s*\[[^\]]+\]\([^)]+\))?$/);
370
+ if (!parsed) fail(file, item.line, `a term must read "**term** — definition [label](week/day#sN)": ${item.text}`);
371
+ const term = { term: parsed[1], definition: parsed[2].trim() };
372
+ if (parsed[3]) term.source = parseSource(parsed[3].trim(), file, item.line);
373
+ return term;
374
+ });
375
+ continue;
376
+ }
377
+
378
+ if (block.type === "container" && block.name === "legend") {
379
+ if (!section) fail(file, block.line, "a legend belongs to a section, after its heading");
380
+ section.legend = listItems(block.body).map((item) => {
381
+ const lettered = item.text.match(/^([A-Z])[.)]\s+(.*)$/);
382
+ if (!lettered) fail(file, item.line, `a legend entry must read "A. text": ${item.text}`);
383
+ return { letter: lettered[1], text: lettered[2] };
384
+ });
385
+ continue;
386
+ }
387
+
388
+ if (block.type === "container" && KINDS.includes(block.name)) {
389
+ if (!section) fail(file, block.line, `${block.name} ${block.info[0] ?? ""} comes before any "## 1. Title" section heading`);
390
+ const question = parseQuestion(block, file);
391
+ if (question.kind === "judge") {
392
+ const letter = question.verdictLetter;
393
+ question.answer = (section.legend ?? []).findIndex((entry) => entry.letter === letter);
394
+ if (question.answer === -1) fail(file, block.line, `verdict: ${letter} is not a letter in this section's legend`);
395
+ delete question.verdictLetter;
396
+ }
397
+ section.questions.push(question);
398
+ continue;
399
+ }
400
+
401
+ if (block.type === "container") fail(file, block.line, `"${block.name}" is not a worksheet container`);
402
+
403
+ if (block.type === "paragraph") {
404
+ const { prose } = readParagraph(block);
405
+ if (!prose) continue;
406
+ if (section && section.questions.length === 0 && section.blurb === undefined) section.blurb = prose;
407
+ else if (!section) worksheet.intro.push(prose);
408
+ }
409
+ }
410
+
411
+ if (!worksheet.sections.length) fail(file, offset, "a worksheet needs at least one `## 1. Title` section");
412
+ return worksheet;
413
+ }
414
+
415
+ export default parseWorksheet;