decklight 0.8.1 → 0.9.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 (133) hide show
  1. package/PLATFORM.md +666 -0
  2. package/README.md +224 -150
  3. package/SPEC.md +732 -886
  4. package/cli/agent-review.mjs +245 -0
  5. package/cli/agents.mjs +25 -5
  6. package/cli/associate.mjs +12 -12
  7. package/cli/audit.mjs +42 -10
  8. package/cli/banner.mjs +41 -17
  9. package/cli/bundle-audio.mjs +183 -0
  10. package/cli/bundle.mjs +383 -31
  11. package/cli/cast.mjs +7 -7
  12. package/cli/check.mjs +961 -0
  13. package/cli/clone-deck.mjs +179 -0
  14. package/cli/commands.mjs +345 -0
  15. package/cli/comments.mjs +64 -18
  16. package/cli/commit-flow.mjs +44 -19
  17. package/cli/commit-message.mjs +51 -74
  18. package/cli/commit-split.mjs +601 -0
  19. package/cli/deck-refs.mjs +59 -0
  20. package/cli/deck-routes.mjs +67 -0
  21. package/cli/deckfile.mjs +3 -5
  22. package/cli/decklight.mjs +68 -289
  23. package/cli/design-system-deps.mjs +209 -0
  24. package/cli/design-system-edit.mjs +194 -0
  25. package/cli/design-system-refs.mjs +409 -0
  26. package/cli/design-system.mjs +429 -0
  27. package/cli/doctor.mjs +115 -0
  28. package/cli/edit-git.mjs +353 -0
  29. package/cli/edit-handover.mjs +445 -0
  30. package/cli/edit-look.mjs +388 -0
  31. package/cli/edit-slides.mjs +683 -0
  32. package/cli/edit.mjs +2126 -842
  33. package/cli/enhance.mjs +483 -0
  34. package/cli/extension.mjs +10 -10
  35. package/cli/font-refs.mjs +273 -0
  36. package/cli/font.mjs +246 -0
  37. package/cli/git-tree.mjs +1 -1
  38. package/cli/git.mjs +65 -11
  39. package/cli/import.mjs +56 -10
  40. package/cli/init.mjs +400 -234
  41. package/cli/library.mjs +127 -0
  42. package/cli/loader.mjs +3 -1
  43. package/cli/marketplace.mjs +215 -21
  44. package/cli/narrate.mjs +176 -0
  45. package/cli/open-browser.mjs +63 -0
  46. package/cli/open.mjs +943 -0
  47. package/cli/pdf.mjs +41 -13
  48. package/cli/pkg.mjs +44 -2
  49. package/cli/plugin.mjs +43 -41
  50. package/cli/port-conflict.mjs +53 -23
  51. package/cli/pptx-export.mjs +57 -24
  52. package/cli/publish.mjs +8 -4
  53. package/cli/qr.mjs +1 -1
  54. package/cli/record.mjs +14 -12
  55. package/cli/remote.mjs +11 -11
  56. package/cli/restore.mjs +11 -4
  57. package/cli/review-ref.mjs +125 -0
  58. package/cli/review-remote.mjs +92 -48
  59. package/cli/review-routes.mjs +254 -0
  60. package/cli/review-store.mjs +47 -7
  61. package/cli/review-submit.mjs +47 -57
  62. package/cli/runtime-link.mjs +560 -0
  63. package/cli/serve.mjs +235 -44
  64. package/cli/setup.mjs +112 -0
  65. package/cli/sign.mjs +1 -1
  66. package/cli/skill-content.mjs +190 -33
  67. package/cli/skills.mjs +107 -24
  68. package/cli/start.mjs +110 -0
  69. package/cli/supervise.mjs +6 -6
  70. package/cli/theme-refs.mjs +515 -0
  71. package/cli/theme.mjs +181 -137
  72. package/cli/trust.mjs +83 -0
  73. package/cli/units.mjs +39 -42
  74. package/cli/update-check.mjs +1 -5
  75. package/cli/upgrade.mjs +194 -28
  76. package/cli/upstream.mjs +4 -3
  77. package/cli/util.mjs +4 -4
  78. package/cli/wizard.mjs +6 -6
  79. package/dist/build-info.json +1 -1
  80. package/dist/decklight.css +1126 -49
  81. package/dist/decklight.js +212 -115
  82. package/dist/decklight.js.map +4 -4
  83. package/docs/GLOSSARY.md +141 -0
  84. package/docs/architecture.svg +17 -17
  85. package/package.json +4 -2
  86. package/themes/README.md +9 -8
  87. package/themes/reveal-solarized.css +10 -0
  88. package/tools/args.mjs +20 -0
  89. package/tools/atomic-write.mjs +48 -0
  90. package/tools/brand-palette.mjs +717 -0
  91. package/tools/bridge.mjs +1 -1
  92. package/tools/build-groups.mjs +42 -0
  93. package/tools/color.mjs +48 -0
  94. package/tools/deck-html.mjs +396 -11
  95. package/tools/design-system-format.mjs +753 -0
  96. package/tools/elevenlabs-tts.mjs +110 -17
  97. package/tools/exec.mjs +1 -1
  98. package/tools/extension-check.mjs +31 -7
  99. package/tools/font-format.mjs +190 -0
  100. package/tools/font-stacks.mjs +24 -0
  101. package/tools/gemini-tts.mjs +3 -0
  102. package/tools/lipsync-config.mjs +103 -0
  103. package/tools/lipsync-engines.mjs +205 -2
  104. package/tools/lipsync-server.mjs +264 -41
  105. package/tools/lipsync.mjs +37 -18
  106. package/tools/local-voice.mjs +32 -42
  107. package/tools/narration-manifest.mjs +196 -0
  108. package/tools/narration-synth.mjs +416 -0
  109. package/tools/pptx.mjs +776 -19
  110. package/tools/publish-targets.mjs +1 -1
  111. package/tools/publish-voices.mjs +3 -3
  112. package/tools/recording-impact.mjs +7 -3
  113. package/tools/render-theme.mjs +33 -0
  114. package/tools/review-anchor.mjs +28 -12
  115. package/tools/semver.mjs +40 -0
  116. package/tools/sentences.mjs +180 -0
  117. package/tools/shot.mjs +14 -7
  118. package/tools/site-voices.mjs +232 -0
  119. package/tools/template-theme.mjs +1 -1
  120. package/tools/test-impact.mjs +17 -10
  121. package/tools/theme-check.mjs +30 -3
  122. package/tools/tts-cache.mjs +4 -3
  123. package/tools/tts-engines.mjs +38 -20
  124. package/tools/tts-setup.mjs +7 -7
  125. package/tools/video-options.mjs +34 -0
  126. package/tools/video.mjs +461 -48
  127. package/tools/voiceover-server.mjs +185 -104
  128. package/tools/voiceover.mjs +119 -261
  129. package/tools/zip.mjs +1 -1
  130. package/cli/dev.mjs +0 -623
  131. package/cli/present.mjs +0 -853
  132. package/cli/review.mjs +0 -361
  133. package/tools/publish-site-voices.mjs +0 -75
package/tools/bridge.mjs CHANGED
@@ -28,7 +28,7 @@ export const corsHeaders = (expose = '') => ({
28
28
  *
29
29
  * `max` is opt-in, and which callers set it is the design. The lipsync bridge
30
30
  * receives a slide's WAV here and the TTS bridge a sentence; neither has a
31
- * size a cap could sensibly name. The phone remote in cli/present.mjs does:
31
+ * size a cap could sensibly name. The phone remote in cli/edit.mjs does:
32
32
  * it is the one route reachable from OFF this machine under --remote, its
33
33
  * payloads are a few dozen bytes of "go to slide 7", and a body past 4 KB is
34
34
  * not a bigger request, it is someone probing. So that caller passes `max`,
@@ -0,0 +1,42 @@
1
+ // Copyright 2026 Gilles Philippart
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * How build steps become clicks (SPEC BUILD_SEMANTICS): every step on a slide
6
+ * sorts by its order key — the explicit `data-build-order`, or its document
7
+ * position — and only EXPLICIT steps sharing a key advance together.
8
+ *
9
+ * Pure, and here rather than in src/core/builds.js so `decklight check` can
10
+ * count a slide's clicks from the file by the same rule the runtime applies
11
+ * to the DOM (#526): cli/ and tools/ never import src/, which the package
12
+ * does not ship, while src/ may import a tool.
13
+ *
14
+ * `items` = [{ key, explicit }] in document/emission order; returns groups of
15
+ * item indices, one group per click.
16
+ */
17
+ export function computeGroups(items) {
18
+ const indexed = items.map((it, i) => ({ ...it, i }));
19
+ indexed.sort((a, b) => a.key - b.key || a.i - b.i);
20
+ const groups = [];
21
+ let cur = null;
22
+ let curKey = null;
23
+ let curExplicit = false;
24
+ for (const it of indexed) {
25
+ if (cur && it.explicit && curExplicit && it.key === curKey) {
26
+ cur.push(it.i);
27
+ continue;
28
+ }
29
+ cur = [it.i];
30
+ curKey = it.key;
31
+ curExplicit = it.explicit;
32
+ groups.push(cur);
33
+ }
34
+ return groups;
35
+ }
36
+
37
+ /** The order item for a step: `orderAttr` explicit when present, else the auto position `auto`. */
38
+ export function orderItem(orderAttr, auto) {
39
+ const explicit = orderAttr != null && orderAttr !== '';
40
+ const key = explicit ? parseInt(orderAttr, 10) : auto;
41
+ return { key: Number.isFinite(key) ? key : auto, explicit };
42
+ }
package/tools/color.mjs CHANGED
@@ -108,3 +108,51 @@ export function parseTheme(css) {
108
108
  }
109
109
  return { tokens, exceptions };
110
110
  }
111
+
112
+ // ── OKLab, for the nested diagram tones (SPEC SVG_DIAGRAMS, #541) ───────────
113
+ // A box drawn inside a panel is painted one lightness step of the panel's
114
+ // colour toward the ink — `color-mix(in oklab, <fill> 82%, <ink>)` in the
115
+ // runtime's stylesheet. The gate below needs the same mix in Node, so the
116
+ // conversion lives here, next to the WCAG math it shares a parser with.
117
+
118
+ const srgbToLinear = (v) => { v /= 255; return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
119
+ const linearToSrgb = (v) => { const c = v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055; return Math.round(Math.max(0, Math.min(1, c)) * 255); };
120
+
121
+ /** sRGB [r, g, b] (0–255) → OKLab [L, a, b] (Björn Ottosson's matrices). */
122
+ export function toOklab([r, g, b]) {
123
+ const [lr, lg, lb] = [r, g, b].map(srgbToLinear);
124
+ const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb);
125
+ const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb);
126
+ const s = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb);
127
+ return [
128
+ 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * s,
129
+ 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * s,
130
+ 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * s,
131
+ ];
132
+ }
133
+
134
+ /** OKLab [L, a, b] → sRGB [r, g, b] (0–255), clamped into gamut the simple way. */
135
+ export function fromOklab([L, a, b]) {
136
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;
137
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;
138
+ const s = (L - 0.0894841775 * a - 1.2914855480 * b) ** 3;
139
+ return [
140
+ linearToSrgb(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),
141
+ linearToSrgb(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),
142
+ linearToSrgb(-0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s),
143
+ ];
144
+ }
145
+
146
+ /** `color-mix(in oklab, c1 <w1>, c2)` — w1 as a fraction; the CSS default is the runtime's. */
147
+ export function mixOklab(c1, c2, w1) {
148
+ const [A, B] = [toOklab(c1), toOklab(c2)];
149
+ return fromOklab(A.map((v, i) => v * w1 + B[i] * (1 - w1)));
150
+ }
151
+
152
+ /** The share of the panel in a nested tone — `color-mix(in oklab, var(--d-fill-N) 82%, var(--d-text))`. */
153
+ export const NESTED_MIX = 0.82;
154
+
155
+ /** The nested tone of a panel colour toward the ink, as [r, g, b]. */
156
+ export const nestedTone = (fill, ink) => mixOklab(fill, ink, NESTED_MIX);
157
+
158
+ export const rgbToHex = ([r, g, b]) => '#' + [r, g, b].map((v) => v.toString(16).padStart(2, '0')).join('');
@@ -8,6 +8,9 @@
8
8
  // never drift apart. Lives under tools/ because tools/shot.mjs is a consumer
9
9
  // and the dependency only ever flows cli/ → tools/.
10
10
 
11
+ import { escapeHtml } from './escape.mjs';
12
+ import { PAUSE_MARK, CLICK_MARK, hasWords, notesMarks } from './sentences.mjs';
13
+
11
14
  /**
12
15
  * A section's `<aside class="notes">`. Capture group [1] is the inner HTML (what
13
16
  * voiceover pulls); the whole match is what edit tests for and replaces.
@@ -44,10 +47,31 @@ export const sectionInner = (body) => {
44
47
  const s = String(body ?? '');
45
48
  const open = s.indexOf('>');
46
49
  const inner = open === -1 ? s : s.slice(open + 1);
47
- const close = inner.toLowerCase().lastIndexOf('</section>');
50
+ const close = lastIndexOfCI(inner, '</section>');
48
51
  return close === -1 ? inner : inner.slice(0, close);
49
52
  };
50
53
 
54
+ /**
55
+ * `indexOf` / `lastIndexOf`, case-insensitively, WITHOUT lower-casing the
56
+ * haystack first. `s.toLowerCase().indexOf(x)` looks equivalent and is not:
57
+ * lower-casing can change a string's length (U+0130 İ becomes two code units),
58
+ * after which every index it returns is off by one per such character, and a
59
+ * slice of the original at that index lands inside the tag it was aiming at.
60
+ * The needles here are ASCII tag names, so a case-insensitive regex is exact.
61
+ */
62
+ const literal = (needle) => new RegExp(needle.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&'), 'gi');
63
+ export function indexOfCI(s, needle, from = 0) {
64
+ const re = literal(needle);
65
+ re.lastIndex = from;
66
+ const m = re.exec(s);
67
+ return m ? m.index : -1;
68
+ }
69
+ export function lastIndexOfCI(s, needle) {
70
+ let at = -1;
71
+ for (const m of s.matchAll(literal(needle))) at = m.index;
72
+ return at;
73
+ }
74
+
51
75
  /**
52
76
  * A slide's own text, as the fingerprint that anchors review comments sees it
53
77
  * (SPEC REVIEW) — the file-reading twin of `slideBody` in src/core/finder.js.
@@ -85,15 +109,63 @@ export const slideHeading = (sectionBody, i) => {
85
109
  *
86
110
  * The runtime gets this for free from `textContent`; a tool reading the FILE
87
111
  * has to do it, and has to do it the same way or the two disagree about what a
88
- * segment says.
112
+ * segment says — an `&mdash;` the deck shows as a dash was once spoken, and
113
+ * hashed, as the letters of its name.
114
+ *
115
+ * ⟨PAUSE⟩ (#560) goes too, by default — this is the text that is SPOKEN and
116
+ * SHOWN. `{ marks: true }` keeps it, spaced as a word of its own, for the
117
+ * callers to whom it is part of the take: the hash that decides a slide is
118
+ * stale (a moved pause is a re-record, since a recording bakes it), the
119
+ * synthesis core, and the `.txt` script written beside the audio.
89
120
  */
90
- export const cleanNotes = (s) => String(s ?? '')
91
- .replace(/⟨CLICK⟩/g, ' ')
92
- .replace(/<[^>]+>/g, ' ')
93
- .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
121
+ export const cleanNotes = (s, { marks = false } = {}) => decodeNoteEntities(readNotes(s)
122
+ .replaceAll(CLICK_MARK, ' ')
123
+ .replaceAll(PAUSE_MARK, marks ? ` ${PAUSE_MARK} ` : ' ')
124
+ .replace(/<[^>]+>/g, ' '))
94
125
  .replace(/\s+/g, ' ')
95
126
  .trim();
96
127
 
128
+ /**
129
+ * A slide's notes markup with every marker in its one canonical form, the way
130
+ * the runtime reads them: brackets written as entities are brackets, and
131
+ * `[pause]`, `<click>`, `<slow>…</slow>` and the rest are `⟨PAUSE⟩`,
132
+ * `⟨CLICK⟩`, `⟨SLOW⟩…⟨/SLOW⟩` (tools/sentences.mjs `notesMarks`). Everything
133
+ * that splits the raw file on a marker reads it through this first.
134
+ */
135
+ export const readNotes = (s) => notesMarks(markBrackets(s));
136
+
137
+ /**
138
+ * A marker's angle brackets written as entities — `&#10216;CLICK&#10217;`,
139
+ * `&lang;PAUSE&rang;` — as the brackets themselves. The browser reads them that
140
+ * way (`textContent` decodes), so a tool splitting the raw FILE on ⟨CLICK⟩ has
141
+ * to as well, before it splits, or the two count different beats.
142
+ */
143
+ export const markBrackets = (s) => String(s ?? '')
144
+ .replace(/&(?:#10216|#x27e8|lang);/gi, '⟨')
145
+ .replace(/&(?:#10217|#x27e9|rang);/gi, '⟩');
146
+
147
+ // The named entities prose in a note actually uses. A browser knows ~2,000;
148
+ // these are the ones an author (or an agent writing HTML) reaches for, and one
149
+ // not listed is left as written rather than guessed at.
150
+ const NAMED = {
151
+ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: '\u00a0',
152
+ mdash: '—', ndash: '–', hellip: '…', lsquo: '‘', rsquo: '’', ldquo: '“', rdquo: '”',
153
+ laquo: '«', raquo: '»', lang: '⟨', rang: '⟩', larr: '←', rarr: '→', uarr: '↑',
154
+ darr: '↓', harr: '↔', crarr: '↵', times: '×', middot: '·', bull: '•', deg: '°',
155
+ copy: '©', reg: '®', trade: '™', eacute: 'é', egrave: 'è', agrave: 'à', ccedil: 'ç',
156
+ };
157
+
158
+ /**
159
+ * Entities in note text decoded as a browser decodes them: numeric refs and
160
+ * the named set above, in ONE pass — so `&amp;lt;` is `&lt;`, exactly like a
161
+ * parser. Runs after tags are stripped, so escaped markup survives as text.
162
+ */
163
+ export const decodeNoteEntities = (s) => String(s ?? '').replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, body) => {
164
+ if (body[0] !== '#') return NAMED[body] ?? m;
165
+ const code = body[1] === 'x' || body[1] === 'X' ? parseInt(body.slice(2), 16) : parseInt(body.slice(1), 10);
166
+ return Number.isInteger(code) && code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m;
167
+ });
168
+
97
169
  /**
98
170
  * A slide's notes split into the ⟨CLICK⟩ segments that become FILES, or null
99
171
  * when there are not enough to be worth segmenting.
@@ -107,10 +179,14 @@ export const cleanNotes = (s) => String(s ?? '')
107
179
  * every filename by one.
108
180
  *
109
181
  * An empty segment is dropped rather than recorded as silence — a ⟨CLICK⟩ at
110
- * the very start or end of a note is punctuation, not a beat.
182
+ * the very start or end of a note is punctuation, not a beat. So is one that
183
+ * is nothing but ⟨PAUSE⟩ or audio tags: a hold, or direction, with no words
184
+ * has no take to be baked into (`hasWords`).
111
185
  */
112
- export const notesSegments = (notes) => {
113
- const parts = String(notes ?? '').split('⟨CLICK⟩').map(cleanNotes).filter(Boolean);
186
+ export const notesSegments = (notes, { marks = false } = {}) => {
187
+ const parts = readNotes(notes).split(CLICK_MARK)
188
+ .map((part) => cleanNotes(part, { marks }))
189
+ .filter((part) => hasWords(part));
114
190
  return parts.length > 1 ? parts : null;
115
191
  };
116
192
 
@@ -127,6 +203,89 @@ export function locateSlide(html, n) {
127
203
  return { parts, idx };
128
204
  }
129
205
 
206
+ /**
207
+ * Where a section body's OWN `</section>` starts, or -1.
208
+ *
209
+ * `sectionBodies` cuts at the next `<section`, so for every slide but the last
210
+ * one the closing tag is simply the last thing in the piece. The last slide's
211
+ * piece carries the whole tail of the document — `</div>`, the inlined runtime,
212
+ * `</body>` — and a deck that SHOWS markup in a code block carries `</section>`
213
+ * as text. So neither end is reliable on its own: scan from the front with
214
+ * script, style and comment bodies blanked out, and take the first real one.
215
+ *
216
+ * Blanking preserves offsets (same length, spaces), so the index found in the
217
+ * blanked copy is the index in the original.
218
+ */
219
+ export function sectionCloseIndex(body) {
220
+ const blanked = String(body ?? '').replace(
221
+ /<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>|<!--[\s\S]*?-->/gi,
222
+ (m) => ' '.repeat(m.length),
223
+ );
224
+ return indexOfCI(blanked, '</section>');
225
+ }
226
+
227
+ /**
228
+ * One section's markup, re-indented to sit at `indent` in its new deck.
229
+ *
230
+ * A slide arrives with the indentation of the file it came from, and a deck is
231
+ * a text file people read and diff — a block that lands four spaces out of
232
+ * step is a diff nobody can review. Every line is shifted by the same amount,
233
+ * so the section's own inner structure is preserved exactly.
234
+ */
235
+ export function reindentSection(section, indent) {
236
+ const lines = String(section).replace(/\s+$/, '').split('\n');
237
+ // The section's own base indentation is NOT the first line's: a section read
238
+ // out of a deck starts at `<section`, its leading whitespace having been the
239
+ // previous line's. The closing tag sits at the base, and where there is none
240
+ // to read, the shallowest line does.
241
+ const closing = /^([ \t]*)<\/section>/.exec(lines[lines.length - 1])?.[1];
242
+ const inner = lines.slice(1).filter((l) => l.trim());
243
+ const own = closing ?? (inner.length
244
+ ? inner.reduce((m, l) => {
245
+ const w = /^[ \t]*/.exec(l)[0];
246
+ return w.length < m.length ? w : m;
247
+ }, /^[ \t]*/.exec(inner[0])[0])
248
+ : '');
249
+ return lines.map((l, i) => {
250
+ if (i === 0) return indent + l.trimStart();
251
+ return l.startsWith(own) ? indent + l.slice(own.length) : l;
252
+ }).join('\n');
253
+ }
254
+
255
+ /**
256
+ * A deck with `sections` inserted after slide `n` (0 puts them first).
257
+ *
258
+ * The sections are written as they arrive, only re-indented — a slide is
259
+ * self-contained markup, which is what makes taking one from another deck a
260
+ * paste rather than a merge.
261
+ */
262
+ export function insertSectionsAfter(html, n, sections) {
263
+ const list = sections.filter((x) => String(x ?? '').trim());
264
+ if (!list.length) return html;
265
+ const parts = String(html).split(/(<section\b)/);
266
+ if (parts.length < 3) throw new Error('this deck has no slides to insert beside');
267
+ // the whitespace the anchor slide's own <section> sits at: the run after the
268
+ // last newline of whatever precedes that token
269
+ const before = parts[Math.max(0, 2 * n - 2)];
270
+ const indent = /\n([ \t]*)$/.exec(before)?.[1] ?? '';
271
+ const block = list.map((sec) => reindentSection(sec, indent)).join('\n');
272
+
273
+ if (n === 0) {
274
+ // Before the first slide: the deck's preamble ends where slide 1 opens, so
275
+ // this is the one insertion that never looks for a closing tag.
276
+ parts[0] = parts[0].replace(/\s*$/, '') + '\n' + block + '\n' + indent;
277
+ return parts.join('');
278
+ }
279
+
280
+ const { parts: p2, idx } = locateSlide(html, n);
281
+ const seg = p2[idx];
282
+ const close = sectionCloseIndex(seg);
283
+ if (close === -1) throw new Error(`slide ${n}: no </section> to insert after`);
284
+ const end = close + '</section>'.length;
285
+ p2[idx] = seg.slice(0, end) + '\n' + block + seg.slice(end);
286
+ return p2.join('');
287
+ }
288
+
130
289
  /**
131
290
  * Insert `fragment` right before the deck's LAST `</body>`. A bundled deck
132
291
  * inlines decklight.js, whose speaker-view popup template carries a literal
@@ -135,7 +294,7 @@ export function locateSlide(html, n) {
135
294
  * own fallback (bundle fails; shot appends).
136
295
  */
137
296
  export function injectBeforeBodyEnd(html, fragment) {
138
- const at = html.toLowerCase().lastIndexOf('</body>');
297
+ const at = lastIndexOfCI(html, '</body>');
139
298
  return at === -1 ? null : html.slice(0, at) + fragment + html.slice(at);
140
299
  }
141
300
 
@@ -190,7 +349,7 @@ function consumeElement(html, start) {
190
349
  }
191
350
  if (OPAQUE_ELEMENTS.has(name)) {
192
351
  const marker = `</${name}`;
193
- const at = html.toLowerCase().indexOf(marker, tagEnd + 1);
352
+ const at = indexOfCI(html, marker, tagEnd + 1);
194
353
  const end = at === -1 ? html.length : findTagEnd(html, at) + 1;
195
354
  return { tag: name, start, end };
196
355
  }
@@ -229,3 +388,229 @@ export function sectionChildRanges(seg) {
229
388
  }
230
389
  return ranges;
231
390
  }
391
+
392
+ /**
393
+ * The element children of ONE element's raw html (`<g …>…</g>`), by raw
394
+ * position — `sectionChildRanges` one level further down, so an edit can
395
+ * reach a shape inside a diagram by its path from the slide's top-level
396
+ * child. Offsets are into `el` itself. A void or self-closed element has none.
397
+ */
398
+ export function elementChildRanges(el) {
399
+ const src = String(el ?? '');
400
+ const open = findTagEnd(src, 0);
401
+ if (src[0] !== '<' || open < 0 || src[open - 1] === '/') return [];
402
+ const name = readTagName(src, 1);
403
+ if (VOID_ELEMENTS.has(name) || OPAQUE_ELEMENTS.has(name)) return [];
404
+ const ranges = [];
405
+ let i = open + 1;
406
+ while (i < src.length) {
407
+ if (src[i] !== '<') { i++; continue; }
408
+ if (src.startsWith('<!--', i)) { i = skipComment(src, i); continue; }
409
+ if (src[i + 1] === '/') break; // the element's own closing tag
410
+ const child = consumeElement(src, i);
411
+ ranges.push({ tag: child.tag, start: child.start, end: child.end });
412
+ i = child.end;
413
+ }
414
+ return ranges;
415
+ }
416
+
417
+ /** A section body split into its open tag's attributes and everything after. */
418
+ export function splitOpenTag(body) {
419
+ const src = String(body ?? '');
420
+ let quote = '';
421
+ for (let i = 0; i < src.length; i++) {
422
+ const c = src[i];
423
+ if (quote) { if (c === quote) quote = ''; continue; }
424
+ if (c === '"' || c === "'") { quote = c; continue; }
425
+ if (c === '>') {
426
+ const attrs = src.slice(0, i).replace(/\/$/, '');
427
+ return { attrs, close: src.slice(i - (src[i - 1] === '/' ? 1 : 0), i + 1), rest: src.slice(i + 1) };
428
+ }
429
+ }
430
+ return { attrs: '', close: '>', rest: src };
431
+ }
432
+
433
+ /** `class="a" data-layout="split"` → `{ class: 'a', 'data-layout': 'split' }`. */
434
+ export function readAttrs(text) {
435
+ const out = {};
436
+ const re = /([:@\w-]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;
437
+ for (const m of String(text ?? '').matchAll(re)) {
438
+ out[m[1].toLowerCase()] = m[2] ?? m[3] ?? m[4] ?? '';
439
+ }
440
+ return out;
441
+ }
442
+
443
+ export const writeAttrs = (attrs) => Object.entries(attrs)
444
+ .map(([k, v]) => (v === '' ? ` ${k}` : ` ${k}="${String(v).replace(/"/g, '&quot;')}"`))
445
+ .join('');
446
+
447
+ /**
448
+ * Rewrite slide `n`'s opening tag: every name in `clear` dropped, then `set`
449
+ * written on. The slide's CONTENT is not touched — this is the tag only.
450
+ *
451
+ * Returns `{ html, replaced }`, where `replaced` is what the cleared names held
452
+ * before, so the caller can say what it took away rather than only what it put.
453
+ */
454
+ export function setSectionAttrs(html, n, { clear = [], clearIf = null, set = {} } = {}) {
455
+ const { parts, idx } = locateSlide(String(html ?? ''), n);
456
+ const { attrs, rest } = splitOpenTag(parts[idx]);
457
+ const had = readAttrs(attrs);
458
+ const replaced = {};
459
+ for (const k of Object.keys(had)) {
460
+ if (!clear.includes(k) && !clearIf?.(k)) continue;
461
+ replaced[k] = had[k];
462
+ delete had[k];
463
+ }
464
+ for (const [k, v] of Object.entries(set)) had[k] = v;
465
+ parts[idx] = `${writeAttrs(had)}>${rest}`;
466
+ return { html: parts.join(''), replaced };
467
+ }
468
+
469
+ // ── whole-slide operations: new · duplicate · delete · reorder ─────────────
470
+ // The slide bar's five verbs, as string transforms over the deck FILE rather
471
+ // than over a parsed DOM — the same reason every other file-side edit here is
472
+ // (SPEC DECK_ANATOMY): the file is what an author reads and diffs, so moving a
473
+ // slide has to hand back the bytes they typed, not a re-serialisation of them.
474
+ //
475
+ // Numbering is by SOURCE ORDER throughout. A hidden slide is a slide here,
476
+ // exactly as it is for comments, review anchors and history — `isHiddenSection`
477
+ // is for tools that produce one THING per slide, and none of these do.
478
+
479
+ /**
480
+ * Slide `n`'s source range in the deck: `[start, end)`, spanning its
481
+ * `<section` through its own `</section>`, plus the indentation the line it
482
+ * opens on sits at.
483
+ *
484
+ * The two offsets are what makes a move a MOVE — the section's bytes are cut
485
+ * and pasted rather than rebuilt, so duplicating a slide or swapping two of
486
+ * them changes nothing whatever about the slides themselves.
487
+ */
488
+ export function slideRange(html, n) {
489
+ const src = String(html ?? '');
490
+ const { parts, idx } = locateSlide(src, n);
491
+ let start = 0;
492
+ for (let i = 0; i < idx - 1; i++) start += parts[i].length; // up to, not including, the `<section` token
493
+ const close = sectionCloseIndex(parts[idx]);
494
+ if (close === -1) throw new Error(`slide ${n}: no </section> to work with`);
495
+ const end = start + parts[idx - 1].length + close + '</section>'.length;
496
+ return { start, end, indent: /\n([ \t]*)$/.exec(src.slice(0, start))?.[1] ?? '' };
497
+ }
498
+
499
+ /**
500
+ * The section a `new` slide inserts. Written at zero indentation and moved
501
+ * into place by `reindentSection`, so it lands level with its neighbours in a
502
+ * deck whose sections sit inside `<div class="decklight">` and in one whose
503
+ * sections sit at the left margin alike.
504
+ */
505
+ export const BLANK_SLIDE = `<section>
506
+ <h2>New slide</h2>
507
+ <p>Say something here.</p>
508
+ <aside class="notes"></aside>
509
+ </section>`;
510
+
511
+ /** A deck with a blank slide inserted after slide `after`. */
512
+ export const insertBlankSlide = (html, after) =>
513
+ insertSectionsAfter(String(html ?? ''), after, [BLANK_SLIDE]);
514
+
515
+ /**
516
+ * A deck with slide `n` copied to sit right after itself.
517
+ *
518
+ * The copy is BYTE-IDENTICAL, not reindented: it is going in at the same
519
+ * indentation it came out of, and a duplicate that differs from its original
520
+ * by a space is a diff that says something happened when nothing did.
521
+ */
522
+ export function duplicateSlide(html, n) {
523
+ const src = String(html ?? '');
524
+ const { start, end, indent } = slideRange(src, n);
525
+ const copy = src.slice(start, end);
526
+ return src.slice(0, end) + '\n' + indent + copy + src.slice(end);
527
+ }
528
+
529
+ /**
530
+ * A deck with slide `n` removed — and with the line it sat on removed too.
531
+ *
532
+ * Cutting the section alone would leave its newline and its indentation
533
+ * behind as a blank line that nobody typed, and the next `git diff` would
534
+ * carry it. The newline taken is the one BEFORE the slide, so the newline
535
+ * that ends the slide goes on ending whatever now follows it.
536
+ */
537
+ export function deleteSlide(html, n) {
538
+ const src = String(html ?? '');
539
+ const { start, end } = slideRange(src, n);
540
+ const before = /\n[ \t]*$/.exec(src.slice(0, start));
541
+ if (before) return src.slice(0, before.index) + src.slice(end);
542
+ // slide 1 of a deck that opens on it (no line above to take): drop the
543
+ // break that followed it instead, so the next slide moves up to the top.
544
+ const after = /^[ \t]*\n/.exec(src.slice(end));
545
+ return src.slice(0, start) + src.slice(end + (after ? after[0].length : 0));
546
+ }
547
+
548
+ /**
549
+ * A deck with slides `a` and `b` swapped, each landing at the OTHER'S
550
+ * indentation (`reindentSection`) rather than carrying its own along.
551
+ *
552
+ * In the ordinary deck, where both sit at the same depth, that is a no-op and
553
+ * the two sections are exchanged byte for byte. It matters for the deck it is
554
+ * not: a slide pasted in at the wrong depth must not drag that depth up the
555
+ * file with it every time somebody presses the reorder key.
556
+ */
557
+ export function swapSlides(html, a, b) {
558
+ const src = String(html ?? '');
559
+ const [lo, hi] = a < b ? [a, b] : [b, a];
560
+ if (lo === hi) return src;
561
+ const first = slideRange(src, lo);
562
+ const second = slideRange(src, hi);
563
+ // The destination's own leading whitespace is already in the deck — it sits
564
+ // before `start` — so the moved section is reindented and then has its FIRST
565
+ // line's indentation taken off again, or every swap would push the pair one
566
+ // level deeper than the one before it.
567
+ const moved = (text, indent) => reindentSection(text, indent).replace(/^[ \t]*/, '');
568
+ return src.slice(0, first.start)
569
+ + moved(src.slice(second.start, second.end), first.indent)
570
+ + src.slice(first.end, second.start)
571
+ + moved(src.slice(first.start, first.end), second.indent)
572
+ + src.slice(second.end);
573
+ }
574
+
575
+ /**
576
+ * A deck with `<img src alt>` inserted into slide `slide`, after top-level
577
+ * child `index` — the same addressing the element-edit routes use
578
+ * (`sectionChildRanges`).
579
+ *
580
+ * `index === null` means "on the slide": the image goes after the last content
581
+ * child and BEFORE the asides, so a picture dropped on a slide that has
582
+ * speaker notes lands on the slide and not inside the notes, where the
583
+ * audience would never see it (DECK_ANATOMY — notes, sources and rehearse are
584
+ * all `<aside>` siblings at the end of a section).
585
+ *
586
+ * Returns `{ html, index }`: the caller has to be able to tell the browser
587
+ * which child the new element IS, since every element route addresses by
588
+ * position and everything after the insertion has just shifted.
589
+ */
590
+ export function insertImage(html, slide, index, { src = '', alt = '' } = {}) {
591
+ const deck = String(html ?? '');
592
+ const { parts, idx } = locateSlide(deck, slide);
593
+ const seg = parts[idx];
594
+ const ranges = sectionChildRanges(seg);
595
+ // the whitespace a child's own line begins at, or null when it does not
596
+ // begin a line (a slide written on one line stays on one line)
597
+ const indentOf = (r) => (r ? /\n([ \t]*)$/.exec(seg.slice(0, r.start))?.[1] ?? null : null);
598
+
599
+ let at; // offset in `seg` to insert at
600
+ let position; // the new element's child index once it is in
601
+ if (index === null || index === undefined) {
602
+ let k = ranges.length;
603
+ while (k > 0 && ranges[k - 1].tag === 'aside') k--;
604
+ position = k;
605
+ at = k > 0 ? ranges[k - 1].end : seg.indexOf('>') + 1;
606
+ } else {
607
+ const r = ranges[index];
608
+ if (!r) throw new Error(`slide ${slide}: no element at index ${index} (has ${ranges.length})`);
609
+ position = index + 1;
610
+ at = r.end;
611
+ }
612
+ const tag = `<img src="${escapeHtml(src)}" alt="${escapeHtml(alt)}">`;
613
+ const indent = indentOf(ranges[Math.max(0, position - 1)]) ?? indentOf(ranges[0]);
614
+ parts[idx] = seg.slice(0, at) + (indent === null ? tag : `\n${indent}${tag}`) + seg.slice(at);
615
+ return { html: parts.join(''), index: position };
616
+ }