decklight 0.10.0 → 0.11.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 (117) hide show
  1. package/NOTICE +2 -0
  2. package/PLATFORM.md +17 -0
  3. package/README.md +53 -25
  4. package/SPEC.md +1239 -67
  5. package/cli/agents.mjs +139 -15
  6. package/cli/bundle.mjs +68 -2
  7. package/cli/cast.mjs +45 -14
  8. package/cli/check-fixes.mjs +12 -4
  9. package/cli/check-watch.mjs +151 -0
  10. package/cli/check.mjs +460 -71
  11. package/cli/code-editor.mjs +287 -0
  12. package/cli/commands.mjs +13 -2
  13. package/cli/commit-message.mjs +34 -7
  14. package/cli/commit-split.mjs +123 -23
  15. package/cli/decklight.mjs +11 -1
  16. package/cli/design-system-edit.mjs +37 -1
  17. package/cli/edit-address.mjs +184 -0
  18. package/cli/edit-git.mjs +21 -4
  19. package/cli/edit-handover.mjs +136 -25
  20. package/cli/edit-look.mjs +45 -1
  21. package/cli/edit-open.mjs +143 -0
  22. package/cli/edit-slides.mjs +1043 -67
  23. package/cli/edit-translate.mjs +243 -0
  24. package/cli/edit.mjs +3182 -267
  25. package/cli/editor-support.mjs +286 -0
  26. package/cli/enhance.mjs +148 -20
  27. package/cli/find-replace.mjs +142 -0
  28. package/cli/fix-review.mjs +368 -0
  29. package/cli/init.mjs +93 -19
  30. package/cli/keep-awake.mjs +68 -0
  31. package/cli/migrate-writing.mjs +214 -0
  32. package/cli/narrate.mjs +51 -10
  33. package/cli/open.mjs +29 -9
  34. package/cli/outside-edit.mjs +257 -0
  35. package/cli/paste.mjs +92 -0
  36. package/cli/pdf.mjs +61 -2
  37. package/cli/pptx-export.mjs +3 -1
  38. package/cli/publish.mjs +24 -3
  39. package/cli/record.mjs +19 -8
  40. package/cli/rewrite.mjs +265 -0
  41. package/cli/runtime-link.mjs +218 -17
  42. package/cli/serve.mjs +7 -4
  43. package/cli/setup.mjs +2 -2
  44. package/cli/skill-content.mjs +212 -8
  45. package/cli/skills/slide-writing.md +333 -0
  46. package/cli/skills/voiceover.md +423 -0
  47. package/cli/skills.mjs +36 -13
  48. package/cli/starter-full.mjs +353 -0
  49. package/cli/supervise.mjs +14 -0
  50. package/cli/theme.mjs +3 -2
  51. package/cli/translate-core.mjs +466 -0
  52. package/cli/translate-files.mjs +149 -0
  53. package/cli/translate.mjs +458 -0
  54. package/cli/util.mjs +25 -0
  55. package/cli/vocabulary-docs.mjs +138 -0
  56. package/dist/decklight.css +2087 -91
  57. package/dist/decklight.js +367 -203
  58. package/dist/decklight.js.map +4 -4
  59. package/docs/GLOSSARY.md +9 -2
  60. package/docs/WRITING_RESEARCH.md +327 -0
  61. package/package.json +5 -3
  62. package/themes/coastal.css +3 -0
  63. package/themes/metropolis.css +2 -0
  64. package/themes/reveal-blood.css +3 -0
  65. package/themes/reveal-league.css +2 -0
  66. package/themes/reveal-moon.css +2 -0
  67. package/themes/reveal-serif.css +1 -0
  68. package/themes/reveal-sky.css +1 -0
  69. package/themes/reveal-solarized.css +4 -0
  70. package/tools/brand-palette.mjs +6 -1
  71. package/tools/build-groups.mjs +28 -8
  72. package/tools/cdp.mjs +176 -0
  73. package/tools/chart-spec.mjs +242 -0
  74. package/tools/click-match.mjs +70 -0
  75. package/tools/code-options.mjs +174 -0
  76. package/tools/conversation.mjs +49 -0
  77. package/tools/deck-family.mjs +101 -0
  78. package/tools/deck-html.mjs +212 -15
  79. package/tools/design-system-format.mjs +15 -1
  80. package/tools/diagram-shapes.mjs +221 -0
  81. package/tools/elevenlabs-tts.mjs +62 -53
  82. package/tools/face-clip.mjs +96 -0
  83. package/tools/face-layout.mjs +94 -0
  84. package/tools/gemini-tts.mjs +1 -1
  85. package/tools/invisible-in-print.mjs +27 -0
  86. package/tools/lipsync-auto.mjs +197 -0
  87. package/tools/lipsync-config.mjs +16 -0
  88. package/tools/lipsync-engines.mjs +22 -4
  89. package/tools/lipsync-server.mjs +8 -5
  90. package/tools/lipsync.mjs +122 -30
  91. package/tools/local-voice.mjs +1 -1
  92. package/tools/mouth-file.mjs +26 -0
  93. package/tools/mouth.mjs +320 -0
  94. package/tools/narration-manifest.mjs +24 -4
  95. package/tools/narration-synth.mjs +96 -76
  96. package/tools/recording-impact.mjs +16 -1
  97. package/tools/sentences.mjs +7 -1
  98. package/tools/starters.mjs +402 -0
  99. package/tools/steps.mjs +118 -0
  100. package/tools/take-check.mjs +146 -0
  101. package/tools/template-theme.mjs +3 -1
  102. package/tools/test-impact.mjs +36 -12
  103. package/tools/theme-check.mjs +196 -1
  104. package/tools/tone-cue.mjs +108 -0
  105. package/tools/tts-cache.mjs +9 -3
  106. package/tools/tts-engines.mjs +100 -11
  107. package/tools/video-cache.mjs +93 -0
  108. package/tools/video-live.mjs +349 -0
  109. package/tools/video-options.mjs +11 -0
  110. package/tools/video.mjs +772 -127
  111. package/tools/viseme-fit.mjs +27 -0
  112. package/tools/viseme-match.mjs +77 -0
  113. package/tools/vocabulary.mjs +397 -0
  114. package/tools/voice-renumber.mjs +605 -0
  115. package/tools/voiceover-server.mjs +42 -11
  116. package/tools/voiceover.mjs +48 -20
  117. package/dist/build-info.json +0 -1
@@ -31,27 +31,61 @@
31
31
  // both sides is a hoisted function declaration, and nothing is read until a
32
32
  // request arrives.
33
33
 
34
- import { mkdirSync, writeFileSync } from 'node:fs';
35
- import { basename, resolve, sep } from 'node:path';
34
+ import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync, createWriteStream, linkSync, rmSync } from 'node:fs';
35
+ import { basename, dirname, relative, resolve, sep } from 'node:path';
36
36
 
37
37
  import {
38
38
  notesTextToAside, setSlideNotes,
39
39
  sourcesToAside, setSlideSources,
40
- setSlideTiming, setSlideLayout, setSlideHidden,
41
- upsertNarrationTrack,
42
- locateElement, removeSlideElement, setSlideElementHtml, setSlideElementBuild, setElementStyles, setElementAttr, setElementText, removeNestedElement } from './edit.mjs';
40
+ setSlideTiming, setSlideLayout, LAYOUTS, setSlideHidden, setSlideFace,
41
+ upsertNarrationTrack, configuredTrackDirs,
42
+ removeSlideElement, setSlideElementHtml, setSlideElementBuild, setElementBuildAttrs, setSlideBuildOrder, setDiagramOrder, groupDiagramNodes, setElementStyles, editedNodes, setElementAttr, setElementText, setElementLines, removeNestedElement, removeNestedElements, moveSlideElement,
43
+ duplicateSlideElement, removeSlideElements, duplicateSlideElements, moveSlideElements, joinSlideElements } from './edit.mjs';
44
+ import { locateElement, openElement } from './edit-address.mjs';
45
+ import { setElementPicture, setElementOptions, setConversationTurn, setSlideBackground, pictureToBackground, setSlideAttrs, pasteSlideElement, withoutPageIds } from './edit.mjs';
46
+ import { relativeAssets, pasteSection } from './paste.mjs';
47
+ import { findInDeck, replaceInDeck } from './find-replace.mjs';
48
+ import { setElementGeometry, setDiagramCanvas, addDiagramShape, duplicateDiagramNode, duplicateDiagramNodes, editConnector, CONNECTOR_OPS, GROUP_OPS } from './edit.mjs';
43
49
  import { oneline } from './git.mjs';
44
- import { slotWriteProblem, applySlideTemplate, insertSlideTemplateSlide, describeTemplateChange } from './design-system-edit.mjs';
50
+ import { slotWriteProblem, slotMoveProblem, applySlideTemplate, insertSlideTemplateSlide, describeTemplateChange, slideSlots } from './design-system-edit.mjs';
45
51
  import { designSystemRefs, resolveDesignSystemRef, packageVerdict } from './design-system-refs.mjs';
46
52
  import { markedSources } from './theme-refs.mjs';
47
53
  import { parseTemplateRef } from '../tools/design-system-format.mjs';
54
+ import { parseFaceLayout } from '../tools/face-layout.mjs';
48
55
  import { setDeckConcepts } from './runtime-link.mjs';
49
56
  // The whole-slide and image transforms are NOT in edit.mjs with the rest: they
50
57
  // are string surgery on a deck's sections, which is what tools/deck-html.mjs
51
58
  // is, and nothing about them wants the server.
52
59
  import {
53
- sectionBodies, insertBlankSlide, duplicateSlide, deleteSlide, swapSlides, insertImage,
60
+ sectionBodies, insertBlankSlide, duplicateSlide, deleteSlide, swapSlides, insertSectionsAfter, slideRange,
54
61
  } from '../tools/deck-html.mjs';
62
+ // A slide op moves the deck's recordings with their slides (#916): Node-only
63
+ // file moves, which is what tools/ is for.
64
+ import {
65
+ voiceFolders, planSteps, applyPlans,
66
+ } from '../tools/voice-renumber.mjs';
67
+ // What Add and the New slide kinds put in: the server's own closed set
68
+ import { insertStarter, insertBlock, insertSlideOfKind, SLIDE_KINDS } from '../tools/starters.mjs';
69
+ import { escapeHtml } from '../tools/escape.mjs';
70
+
71
+ /**
72
+ * Is `src` a path this deck can carry? Relative, and only relative.
73
+ *
74
+ * A scheme is somebody else's server (or, for `javascript:` and `data:`,
75
+ * somebody else's code); a leading slash is the serving root rather than the
76
+ * folder the deck lives in, so it breaks the moment the deck is opened over
77
+ * `file://` or published under a path; and `..` points outside what travels
78
+ * with the file. A deck is one HTML file and what sits beside it
79
+ * (DECK_ANATOMY), and an `<img>` the author cannot send anybody is worse
80
+ * than a refusal. A declaration, not a const: edit.mjs's picture transforms
81
+ * call it across the deliberate static cycle between the two modules.
82
+ */
83
+ export function relativeSrc(s) {
84
+ return typeof s === 'string' && !!s.trim()
85
+ && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(s)
86
+ && !/^[/\\]/.test(s)
87
+ && !s.split(/[/\\]/).includes('..');
88
+ }
55
89
 
56
90
  /**
57
91
  * Put the slide-mutation routes into `routes`, the table cli/edit.mjs
@@ -161,10 +195,16 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
161
195
  * { slide, layout: "acme/divider" } convert or switch slide N
162
196
  * { slide, layout: null } remove: back to a plain slide
163
197
  * { slide, layout: "acme/divider", insert: true } a new slide after slide N
198
+ * { slide, template: null, layout: "split" } leave the template for a built-in
199
+ * layout: both in ONE edit, so one
200
+ * undo, and never a moment with neither
164
201
  */
165
202
  function slideTemplateRoute({ body, json }) {
166
- const { slide, template, insert } = JSON.parse(body || '{}');
203
+ const { slide, template, insert, layout } = JSON.parse(body || '{}');
167
204
  if (!Number.isInteger(slide) || slide < 1 || !(template === null || typeof template === 'string')) throw new Error('bad payload');
205
+ if (layout !== undefined && (template !== null || insert || !LAYOUTS.includes(layout))) {
206
+ return json(400, { ok: false, error: `a layout goes only with leaving a template (template: null), and is one of ${LAYOUTS.join(', ')}` });
207
+ }
168
208
  const html = readDeck();
169
209
  let def = null;
170
210
  if (template !== null) {
@@ -173,14 +213,20 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
173
213
  def = r.layout;
174
214
  } else if (insert) return json(400, { ok: false, error: 'insert needs a template' });
175
215
  let report = null;
216
+ // a slide inserted is every later recording one slide on (#916)
217
+ const voices = insert ? voicePlans(html, 'insert', slide) : { plans: [] };
218
+ if (voices.error) return json(409, { ok: false, error: voices.error });
176
219
  try {
177
- const changed = applyEdit((deck) => {
220
+ const done = editWithVoices((deck) => {
178
221
  if (insert) return insertSlideTemplateSlide(deck, slide, def);
179
222
  const out = applySlideTemplate(deck, slide, def);
180
223
  report = out;
181
- return out.html;
182
- });
183
- const said = insert ? `a new ${def.ref} slide after slide ${slide}` : describeTemplateChange(report, def?.ref ?? '');
224
+ return layout === undefined ? out.html : setSlideLayout(out.html, slide, layout);
225
+ }, html, voices.plans);
226
+ if (done.error) return json(409, { ok: false, error: done.error });
227
+ const { changed } = done;
228
+ const said = insert ? `a new ${def.ref} slide after slide ${slide}`
229
+ : describeTemplateChange(report, def?.ref ?? '') + (layout === undefined ? '' : ` · layout ${layout}`);
184
230
  if (changed) console.log(` slide template: slide ${slide} — ${said}`);
185
231
  return json(200, {
186
232
  ok: true, changed, said, ...(insert ? { inserted: slide + 1 } : { mode: report.mode, moved: report.moved, lacking: report.lacking }),
@@ -191,6 +237,37 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
191
237
  }
192
238
  }
193
239
 
240
+ /**
241
+ * What putting slide N into a template would do, WITHOUT writing it: the
242
+ * layout picker draws each template's thumbnail from this, so what a cell
243
+ * shows is what choosing it writes (the same applySlideTemplate, on the
244
+ * file). `template` empty is the plain slide, out of any template.
245
+ * GET ?slide=N&template=acme/divider → { mode, moved, lacking, said, slots }
246
+ * `slots` is every child of the slide, in file order, and the slot it would
247
+ * name (null for none).
248
+ */
249
+ function slideTemplatePreviewRoute({ url, json }) {
250
+ const slide = Number(url.searchParams.get('slide'));
251
+ const value = url.searchParams.get('template') ?? '';
252
+ if (!Number.isInteger(slide) || slide < 1) return json(400, { ok: false, error: 'bad payload' });
253
+ try {
254
+ const html = readDeck();
255
+ let def = null;
256
+ if (value) {
257
+ const r = deckTemplate(html, value);
258
+ if (r.error) return json(409, { ok: false, error: r.error });
259
+ def = r.layout;
260
+ }
261
+ const out = applySlideTemplate(html, slide, def);
262
+ return json(200, {
263
+ ok: true, mode: out.mode, moved: out.moved, lacking: out.lacking,
264
+ said: describeTemplateChange(out, def?.ref ?? ''), slots: slideSlots(out.html, slide),
265
+ });
266
+ } catch (e) {
267
+ return json(404, { ok: false, error: oneline(e) });
268
+ }
269
+ }
270
+
194
271
  function hiddenRoute({ body, json }) {
195
272
  const { slide, hidden } = JSON.parse(body);
196
273
  if (!Number.isInteger(slide) || slide < 1 || typeof hidden !== 'boolean') throw new Error('bad payload');
@@ -199,6 +276,30 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
199
276
  return json(200, { ok: true, changed, ...history.counts() });
200
277
  }
201
278
 
279
+ // Where the filmed face shows (FACE_LAYOUT), for one slide or several at
280
+ // once: Where…'s "this slide", "every filmed slide" and "every slide". The value is
281
+ // read back through the one reader the deck and the video share, so the
282
+ // file never holds a placement that reader would not understand.
283
+ function faceRoute({ body, json }) {
284
+ const { slides, face } = JSON.parse(body);
285
+ if (!Array.isArray(slides) || !slides.length || !slides.every((n) => Number.isInteger(n) && n >= 1)
286
+ || typeof face !== 'string' || (face && parseFaceLayout(face).bad.length)) throw new Error('bad payload');
287
+ const changed = applyEdit((html) => slides.reduce((h, n) => setSlideFace(h, n, face), html));
288
+ if (changed) console.log(` face ${face || 'corner'} on slide${slides.length === 1 ? '' : 's'} ${slides.join(', ')}`);
289
+ return json(200, { ok: true, changed, ...history.counts() });
290
+ }
291
+
292
+ // Whether a track folder plays by beats is a fact about the FOLDER, not
293
+ // about the take that just finished (#926): one slide re-recorded with no
294
+ // ⟨CLICK⟩ writes only its whole-slide file, and the client's per-take guess
295
+ // then read as "this track has no segments". Any `slide-NN-KK` file says it
296
+ // does — the same test the tracks route reports.
297
+ const beatsIn = (dir) => {
298
+ try {
299
+ return readdirSync(resolve(dirname(deckPath), dir)).some((f) => /^slide-\d+-\d+\.(wav|m4a|mp3)$/.test(f));
300
+ } catch { return false; }
301
+ };
302
+
202
303
  function narrationRoute({ body, json }) {
203
304
  const { files, ext, segments } = JSON.parse(body || '{}');
204
305
  // The same three shapes /deck/edit/narration/record refuses for a folder, refused
@@ -228,7 +329,8 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
228
329
  label: label || files.trim(),
229
330
  dir: files.trim(),
230
331
  ...(ext === undefined ? {} : { ext }),
231
- ...(segments === undefined ? {} : { segments }),
332
+ // an explicit `false` still turns a track's beats off; silence never does
333
+ ...(segments !== undefined ? { segments } : beatsIn(files.trim()) ? { segments: true } : {}),
232
334
  });
233
335
  if (next === null) {
234
336
  // Not a failure of this server — a deck whose config is built
@@ -250,15 +352,48 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
250
352
  function elementSourceRoute({ url, json }) {
251
353
  const slide = Number(url.searchParams.get('slide'));
252
354
  const index = Number(url.searchParams.get('index'));
253
- if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) {
355
+ // `path=0.2` and `tag=li`: the node there below the element, as a copy of it takes it
356
+ const rawPath = url.searchParams.get('path');
357
+ const path = rawPath ? rawPath.split('.').map(Number) : null;
358
+ const tag = url.searchParams.get('tag');
359
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || !pathShape(path)) {
254
360
  return json(400, { ok: false, error: 'bad payload' });
255
361
  }
256
362
  try {
363
+ if (path?.length) {
364
+ const e = openElement(readDeck(), slide, index);
365
+ return json(200, { ok: true, html: e.src(e.at(path, tag || null)) });
366
+ }
257
367
  const { parts, idx, r } = locateElement(readDeck(), slide, index);
258
368
  return json(200, { ok: true, html: parts[idx].slice(r.start, r.end) });
259
369
  } catch (e) {
260
- return json(404, { ok: false, error: oneline(e) });
370
+ return json(e.code === 'STALE' ? 409 : 404, { ok: false, error: oneline(e) });
371
+ }
372
+ }
373
+
374
+ /**
375
+ * A change to several selected elements of one slide (PRESENTING_EDITING,
376
+ * selecting several): `write` is the batch's pure transform, run through
377
+ * ONE applyEdit, so one undo takes all of it back. A stale page is a 409
378
+ * and a refused move says why. Asked for in place, the write is quiet here
379
+ * and every other page is told (`event`). `answer` adds what the page needs
380
+ * to show it (where the copies or the moved ones are).
381
+ */
382
+ function batchRoute(json, slide, said, write, items, { inPlace = false, from = null, event = 'content', answer = () => ({}) } = {}) {
383
+ if (!Number.isInteger(slide) || slide < 1 || !Array.isArray(items)) return json(400, { ok: false, error: 'bad payload' });
384
+ let changed;
385
+ try {
386
+ changed = applyEdit(write);
387
+ } catch (e) {
388
+ if (e.code === 'STALE' || e.code === 'REFUSED') return json(409, { ok: false, error: oneline(e), ...(e.code === 'STALE' ? { stale: true } : {}) });
389
+ return json(400, { ok: false, error: oneline(e) });
390
+ }
391
+ if (changed) console.log(` ${items.length} elements ${said}: slide ${slide} #${items.map((it) => it.index).join(', #')}`);
392
+ if (changed && inPlace === true) {
393
+ quiet(readDeck());
394
+ broadcast(event, { slide, from: typeof from === 'string' ? from.slice(0, 64) : null });
261
395
  }
396
+ return json(200, { ok: true, changed, ...(changed ? answer() : {}), inPlace: !!changed && inPlace === true, ...history.counts() });
262
397
  }
263
398
 
264
399
  // The three that WRITE an element. Same door as layout and notes: a pure
@@ -267,16 +402,39 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
267
402
  // place: the page that saved already shows it, so the watcher skips its
268
403
  // reload and every other page is sent a `content` event instead.
269
404
  // `path` (a node inside the element, the selection inside a diagram) removes
270
- // that node alone; without it the whole element goes
405
+ // that node alone; without it the whole element goes. Asked `quiet` (a block
406
+ // inside a column, which the page takes off itself), the write is in place:
407
+ // no reload there, and every other page is sent `content`.
271
408
  function elementRemoveRoute({ body, json }) {
272
- const { slide, index, path = null, tag = null } = JSON.parse(body);
273
- if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) throw new Error('bad payload');
409
+ const { slide, index, path = null, tag = null, quiet: inPlace = false, from = null, items = null, paths = null } = JSON.parse(body);
410
+ // several selected (`items: [{ index, tag? }]`): all of them, one edit, one undo
411
+ if (items !== null) return batchRoute(json, slide, 'removed', (html) => removeSlideElements(html, slide, items), items, { inPlace, from });
412
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || (paths !== null && !Array.isArray(paths))) throw new Error('bad payload');
274
413
  let changed;
275
414
  try {
276
- changed = applyEdit((html) => (path ? removeNestedElement(html, slide, index, { path, tag }) : removeSlideElement(html, slide, index)));
415
+ // several shapes of one diagram (`paths: [{ path, tag }]`): all of them, one undo
416
+ changed = applyEdit((html) => (paths ? removeNestedElements(html, slide, index, paths)
417
+ : path ? removeNestedElement(html, slide, index, { path, tag }) : removeSlideElement(html, slide, index)));
277
418
  } catch (e) { if (e.code !== 'STALE') throw e; return json(409, { ok: false, error: oneline(e) }); }
278
419
  if (changed) console.log(` element removed: slide ${slide} #${index}${path ? ` › ${path.join('.')}` : ''}`);
279
- return json(200, { ok: true, changed, ...history.counts() });
420
+ if (changed && inPlace === true) {
421
+ quiet(readDeck());
422
+ broadcast('content', { slide, index, from: typeof from === 'string' ? from.slice(0, 64) : null });
423
+ }
424
+ return json(200, { ok: true, changed, inPlace: !!changed && inPlace === true, ...history.counts() });
425
+ }
426
+
427
+ /**
428
+ * `POST /deck/edit/element/join` — `{ slide, items, html }` (Turn into ▸
429
+ * with several selected): the joined block the page made from their
430
+ * sources put where the first of them stands, the others taken out, in one
431
+ * edit (joinSlideElements). Not quiet: the page that asked reloads onto it.
432
+ */
433
+ function elementJoinRoute({ body, json }) {
434
+ const { slide, items = null, html } = JSON.parse(body || '{}');
435
+ let done = null;
436
+ return batchRoute(json, slide, 'joined into one', (deck) => { done = joinSlideElements(deck, slide, items, html); return done.html; }, items,
437
+ { answer: () => ({ index: done.index }) });
280
438
  }
281
439
 
282
440
  function elementContentRoute({ body, json }) {
@@ -297,17 +455,225 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
297
455
  return json(200, { ok: true, changed, ...history.counts() });
298
456
  }
299
457
 
458
+ /**
459
+ * `POST /deck/edit/element/move` — `{ slide, index, to, tag?, path?, quiet?, from? }`
460
+ * (PRESENTING_EDITING, Moving): element `index` to content position `to`
461
+ * on its slide, or, with `path`, the node there to place `to` among its own
462
+ * siblings (a list item). One applyEdit, one undo entry. The answer names
463
+ * where the element is now (`index`, `path`), since everything after it
464
+ * has shifted. On a design-system slide an element moves only within its
465
+ * slot. Asked for in place, the write is quiet and every other page is told.
466
+ */
467
+ function elementMoveRoute({ body, json }) {
468
+ const { slide, index, to, tag = null, path = null, quiet: inPlace = false, from = null, items = null, dir = null } = JSON.parse(body || '{}');
469
+ // several selected: one place up (`dir` -1) or down (1) together, one edit; the answer says where each is now
470
+ if (items !== null) {
471
+ let moved = null;
472
+ return batchRoute(json, slide, `moved ${dir === -1 ? 'up' : 'down'}`, (html) => { moved = moveSlideElements(html, slide, items, dir); return moved.html; }, items,
473
+ { inPlace, from, answer: () => ({ indices: moved.indices }) });
474
+ }
475
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || !Number.isInteger(to) || to < 0
476
+ || (path !== null && !Array.isArray(path)) || (tag !== null && typeof tag !== 'string')) {
477
+ return json(400, { ok: false, error: 'bad payload' });
478
+ }
479
+ if (!path?.length) {
480
+ const problem = slotMoveProblem(readDeck(), slide, index, to);
481
+ if (problem) return json(409, { ok: false, error: problem });
482
+ }
483
+ let moved = null;
484
+ let changed;
485
+ try {
486
+ changed = applyEdit((html) => { moved = moveSlideElement(html, slide, index, { to, path, tag }); return moved.html; });
487
+ } catch (e) {
488
+ if (e.code !== 'STALE' && e.code !== 'REFUSED') throw e;
489
+ return json(409, { ok: false, error: oneline(e), ...(e.code === 'STALE' ? { stale: true } : {}) });
490
+ }
491
+ if (changed) console.log(` element moved: slide ${slide} #${index}${path?.length ? ` › ${path.join('.')}` : ''} → ${to}`);
492
+ if (changed && inPlace === true) {
493
+ quiet(readDeck());
494
+ broadcast('content', { slide, index: moved.index, from: typeof from === 'string' ? from.slice(0, 64) : null });
495
+ }
496
+ return json(200, { ok: true, changed, index: moved.index, path: moved.path, inPlace: !!changed && inPlace === true, ...history.counts() });
497
+ }
498
+
499
+ /**
500
+ * `POST /deck/edit/element/order` — `{ slide, index, path, tag, to, groups?,
501
+ * quiet?, from? }` (SVG_DIAGRAMS, front and back): a node of a diagram
502
+ * brought to the front, forward, backward or sent to the back
503
+ * (setDiagramOrder). What covers what is the order the nodes are written
504
+ * in, and so, unless a key says otherwise, is the order they build in: so
505
+ * `groups`, the slide's clicks as they play now (the Builds tab's shape),
506
+ * are stamped first, every step frozen where it plays (setSlideBuildOrder
507
+ * with `freeze`), and the narration's beats stay with their clicks. One
508
+ * applyEdit, one undo. Answers the node's path now and each stamped order.
509
+ */
510
+ /**
511
+ * `POST /deck/edit/element/group` — `{ slide, index, op, paths? | path, tag,
512
+ * groups?, quiet?, from? }` (SVG_DIAGRAMS, groups): `op: 'group'` wraps the nodes at
513
+ * `paths` in one `<g data-group>`, `'ungroup'` puts the members of the `<g>`
514
+ * at `path` back where it stood, `'mark'` gives that `<g>` `data-group`
515
+ * (groupDiagramNodes). When the diagram builds, `groups` (the slide's clicks
516
+ * as they play) are stamped first, every step frozen where it plays, as
517
+ * front and back does. One applyEdit, one undo; a refusal or a stale path
518
+ * is a 409. Answers the group's `path` and `markup`, or the `members` and
519
+ * the `wires` joined to them now.
520
+ */
521
+ function elementGroupRoute({ body, json }) {
522
+ const { slide, index, op, paths = null, path = null, tag = null, groups = null, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
523
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || !GROUP_OPS.includes(op)
524
+ || (op === 'group' ? !Array.isArray(paths) : !Array.isArray(path)) || (groups !== null && !Array.isArray(groups))) {
525
+ return json(400, { ok: false, error: 'bad payload' });
526
+ }
527
+ let done = null; let orders = [];
528
+ let changed;
529
+ try {
530
+ changed = applyEdit((html) => {
531
+ // the diagram builds: the slide's clicks as they play, frozen first, so grouping changes none of them
532
+ let out = html;
533
+ if (groups?.length) { const st = setSlideBuildOrder(out, slide, groups, { freeze: true }); out = st.html; orders = st.orders; }
534
+ done = groupDiagramNodes(out, slide, index, { op, paths, path, tag, frozen: !!groups?.length });
535
+ return done.html;
536
+ });
537
+ } catch (e) {
538
+ if (e.code !== 'STALE' && e.code !== 'REFUSED') throw e;
539
+ return json(409, { ok: false, error: oneline(e), ...(e.code === 'STALE' ? { stale: true } : {}) });
540
+ }
541
+ if (changed) console.log(` diagram ${op === 'group' ? `${paths.length} nodes grouped` : op === 'mark' ? 'group marked' : 'group taken apart'}: slide ${slide} #${index}`);
542
+ if (changed && inPlace === true) {
543
+ quiet(readDeck());
544
+ broadcast('content', { slide, index, from: typeof from === 'string' ? from.slice(0, 64) : null });
545
+ }
546
+ const { html: _, ...answer } = done;
547
+ return json(200, { ok: true, changed, ...answer, orders, inPlace: !!changed && inPlace === true, ...history.counts() });
548
+ }
549
+
550
+ function elementOrderRoute({ body, json }) {
551
+ const { slide, index, path, tag = null, to, groups = null, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
552
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || !Array.isArray(path) || (groups !== null && !Array.isArray(groups))) {
553
+ return json(400, { ok: false, error: 'bad payload' });
554
+ }
555
+ let done = null; let orders = [];
556
+ let changed;
557
+ try {
558
+ changed = applyEdit((html) => {
559
+ let out = html;
560
+ if (groups?.length) { const st = setSlideBuildOrder(out, slide, groups, { freeze: true }); out = st.html; orders = st.orders; }
561
+ done = setDiagramOrder(out, slide, index, { path, tag, to });
562
+ return done.html;
563
+ });
564
+ } catch (e) {
565
+ if (e.code !== 'STALE' && e.code !== 'REFUSED') throw e;
566
+ return json(409, { ok: false, error: oneline(e), ...(e.code === 'STALE' ? { stale: true } : {}) });
567
+ }
568
+ if (changed) console.log(` diagram order: slide ${slide} #${index} › ${path.join('.')} → ${to}${orders.length ? ` (${orders.length} steps frozen)` : ''}`);
569
+ if (changed && inPlace === true) {
570
+ quiet(readDeck());
571
+ broadcast('content', { slide, index, from: typeof from === 'string' ? from.slice(0, 64) : null });
572
+ }
573
+ return json(200, { ok: true, changed, path: done.path, orders, inPlace: !!changed && inPlace === true, ...history.counts() });
574
+ }
575
+
576
+ /**
577
+ * `POST /deck/edit/element/duplicate` — `{ slide, index, tag?, path?, quiet?,
578
+ * from? }` (PRESENTING_EDITING, Duplicate): element `index`, or the node at
579
+ * `path` below it, copied right after itself (duplicateSlideElement). One
580
+ * applyEdit, one undo entry. The answer is the copy's markup and where it
581
+ * is (`index`, `path`), so the page puts the very same thing on the slide.
582
+ * Asked for in place, the write is quiet and every other page is told.
583
+ */
584
+ function elementDuplicateRoute({ body, json }) {
585
+ const { slide, index, tag = null, path = null, quiet: inPlace = false, from = null, items = null } = JSON.parse(body || '{}');
586
+ // several selected: each copied right after itself, one edit; the answer is each copy's markup and where it is
587
+ if (items !== null) {
588
+ let done = null;
589
+ return batchRoute(json, slide, 'duplicated', (html) => { done = duplicateSlideElements(html, slide, items); return done.html; }, items,
590
+ { inPlace, from, answer: () => ({ copies: done.copies.map((c) => ({ index: c.index, html: c.markup })) }) });
591
+ }
592
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0
593
+ || (path !== null && !Array.isArray(path)) || (tag !== null && typeof tag !== 'string')) {
594
+ return json(400, { ok: false, error: 'bad payload' });
595
+ }
596
+ let done = null;
597
+ try {
598
+ applyEdit((html) => { done = duplicateSlideElement(html, slide, index, { path, tag }); return done.html; });
599
+ } catch (e) {
600
+ if (e.code === 'STALE' || e.code === 'REFUSED') return json(409, { ok: false, error: oneline(e), ...(e.code === 'STALE' ? { stale: true } : {}) });
601
+ if (/^no slide \d|no element at index/.test(e.message)) return json(404, { ok: false, error: oneline(e) });
602
+ return json(400, { ok: false, error: oneline(e) });
603
+ }
604
+ console.log(` element duplicated: slide ${slide} #${index}${path?.length ? ` › ${path.join('.')}` : ''} → #${done.index}${done.path.length ? ` › ${done.path.join('.')}` : ''}`);
605
+ if (inPlace === true) {
606
+ quiet(readDeck());
607
+ broadcast('content', { slide, index: done.index, from: typeof from === 'string' ? from.slice(0, 64) : null });
608
+ }
609
+ return json(200, { ok: true, changed: true, index: done.index, path: done.path, html: done.markup, inPlace: inPlace === true, ...history.counts() });
610
+ }
611
+
300
612
  function elementEffectRoute({ body, json }) {
301
- const { slide, index, effect } = JSON.parse(body);
613
+ const { slide, index, effect, path = [], tag = null } = JSON.parse(body);
302
614
  if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0
303
- || (effect !== null && typeof effect !== 'string')) {
615
+ || (effect !== null && typeof effect !== 'string') || (tag !== null && typeof tag !== 'string')) {
304
616
  throw new Error('bad payload');
305
617
  }
306
- const changed = applyEdit((html) => setSlideElementBuild(html, slide, index, effect));
307
- if (changed) console.log(` element effect saved: slide ${slide} #${index} → ${effect ?? '(removed)'}`);
618
+ let changed;
619
+ try {
620
+ changed = applyEdit((html) => setSlideElementBuild(html, slide, index, effect, { path, tag }));
621
+ } catch (e) { if (e.code !== 'STALE') throw e; return json(409, { ok: false, error: oneline(e) }); }
622
+ if (changed) console.log(` element effect saved: slide ${slide} #${index}${path.length ? ` › ${path.join('.')}` : ''} → ${effect ?? '(removed)'}`);
308
623
  return json(200, { ok: true, changed, ...history.counts() });
309
624
  }
310
625
 
626
+ /**
627
+ * `POST /deck/edit/element/build` — `{ slide, index, path?, tag?, effect?,
628
+ * stay?, self?, animate?, drawStops?, drawSpeed?, travelMs?, arrive?, repeat?, quiet?, from? }`: a node's build settings
629
+ * (setElementBuildAttrs), one applyEdit so one undo. Asked for in place (the
630
+ * Builds tab, Build ▸, Animate ▸ shown on the page already), the write is
631
+ * quiet here and every other page is told, and reloads.
632
+ */
633
+ function elementBuildRoute({ body, json }) {
634
+ const { slide, index, path = [], tag = null, effect, stay, self, animate, drawStops, drawSpeed, travelMs, arrive, repeat, quiet: inPlace, from } = JSON.parse(body);
635
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || (tag !== null && typeof tag !== 'string')) throw new Error('bad payload');
636
+ let changed;
637
+ try {
638
+ changed = applyEdit((html) => setElementBuildAttrs(html, slide, index, { path, tag, effect, stay, self, animate, drawStops, drawSpeed, travelMs, arrive, repeat }));
639
+ } catch (e) { if (e.code !== 'STALE') throw e; return json(409, { ok: false, error: oneline(e) }); }
640
+ if (changed && inPlace === true) {
641
+ quiet(readDeck());
642
+ broadcast('builds', { slide, index, from: typeof from === 'string' ? from.slice(0, 64) : null });
643
+ }
644
+ if (changed) {
645
+ const said = [effect !== undefined && `effect ${effect === null ? '(removed)' : effect || 'default'}`, stay !== undefined && `stay ${stay}`,
646
+ self !== undefined && `one step ${self}`, animate !== undefined && `animate ${animate ?? '(none)'}`,
647
+ drawStops !== undefined && `stages ${drawStops ?? '(none)'}`, drawSpeed !== undefined && `pace ${drawSpeed ?? 'default'}`,
648
+ travelMs !== undefined && `trip ${travelMs ?? 'default'}`, arrive !== undefined && `arrives ${arrive ?? 'fade'}`, repeat !== undefined && `repeats ${repeat}`].filter(Boolean).join(', ');
649
+ console.log(` build saved: slide ${slide} #${index}${path.length ? ` › ${path.join('.')}` : ''} → ${said}`);
650
+ }
651
+ return json(200, { ok: true, changed, inPlace: inPlace === true, ...history.counts() });
652
+ }
653
+
654
+ /**
655
+ * `POST /deck/edit/slide/builds` — `{ slide, groups, quiet?, from? }`: the
656
+ * slide's build order as the Builds tab arranged it (setSlideBuildOrder),
657
+ * every step stamped in one applyEdit, so one undo. Answers each node's
658
+ * order as written, for the page to show without a reload; asked for in
659
+ * place, every other page is told, and reloads.
660
+ */
661
+ function slideBuildsRoute({ body, json }) {
662
+ const { slide, groups, quiet: inPlace, from } = JSON.parse(body);
663
+ if (!Number.isInteger(slide) || slide < 1) throw new Error('bad payload');
664
+ let orders = [];
665
+ let changed;
666
+ try {
667
+ changed = applyEdit((html) => { const done = setSlideBuildOrder(html, slide, groups); orders = done.orders; return done.html; });
668
+ } catch (e) { if (e.code !== 'STALE') throw e; return json(409, { ok: false, error: oneline(e) }); }
669
+ if (changed && inPlace === true) {
670
+ quiet(readDeck());
671
+ broadcast('builds', { slide, from: typeof from === 'string' ? from.slice(0, 64) : null });
672
+ }
673
+ if (changed) console.log(` build order saved: slide ${slide} → ${groups.length} click${groups.length === 1 ? '' : 's'}${orders.every((o) => o.order === null) ? ' (as written)' : ''}`);
674
+ return json(200, { ok: true, changed, orders, inPlace: inPlace === true, ...history.counts() });
675
+ }
676
+
311
677
  /**
312
678
  * `POST /deck/edit/element/style` — `{ slide, index, edits, concept? }`: the
313
679
  * colour picker's save (element edit mode → Colors…). One applyEdit for a
@@ -315,18 +681,31 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
315
681
  * press. A pasted style (Paste style) can carry the shape's concept too,
316
682
  * `concept: { path, tag, value }` (value null takes it off), written in the
317
683
  * same edit: a style that is a concept is that concept, not its colour.
684
+ * Asked to `echo`, the answer carries the markup of each node it styled
685
+ * (`nodes: [{ path, html }]`): a line restyled to dashes is put back on the
686
+ * page as the file has it, since a drawn stroke is the engine's to rebuild.
318
687
  */
319
688
  function elementStyleRoute({ body, json }) {
320
- const { slide, index, edits = [], concept = null, quiet: inPlace, from } = JSON.parse(body);
689
+ const { slide, index, edits = [], concept = null, quiet: inPlace, from, echo = false, items = null } = JSON.parse(body);
690
+ // several selected (`items: [{ index, edits }]`, Paste style or a pick on all of them): one edit, one undo
691
+ if (items !== null) {
692
+ if (!Array.isArray(items) || !items.length || items.length > 64 || items.some((it) => !Number.isInteger(it?.index) || it.index < 0 || !Array.isArray(it.edits) || !it.edits.length)) {
693
+ throw new Error('bad items');
694
+ }
695
+ return batchRoute(json, slide, 'restyled', (html) => items.reduce((out, it) => setElementStyles(out, slide, it.index, it.edits), html), items,
696
+ { inPlace, from, event: 'styles' });
697
+ }
321
698
  if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) throw new Error('bad payload');
322
699
  if (concept !== null && (typeof concept !== 'object' || !(concept.value === null || typeof concept.value === 'string'))) throw new Error('bad payload');
323
700
  if (!concept && (!Array.isArray(edits) || !edits.length)) throw new Error('bad edits');
324
- let changed;
701
+ let changed; let nodes = null;
325
702
  try {
326
703
  changed = applyEdit((html) => {
327
704
  const styled = Array.isArray(edits) && edits.length ? setElementStyles(html, slide, index, edits) : html;
328
- return concept ? setElementAttr(styled, slide, index,
705
+ const out = concept ? setElementAttr(styled, slide, index,
329
706
  { path: concept.path ?? [], tag: concept.tag ?? null, name: 'data-concept', value: concept.value }) : styled;
707
+ if (echo === true) nodes = editedNodes(out, slide, index, edits);
708
+ return out;
330
709
  });
331
710
  } catch (e) { if (e.code !== 'STALE') throw e; return json(409, { ok: false, error: oneline(e) }); }
332
711
  // Asked for IN PLACE (the inspector's Colors and Type tabs), the write is
@@ -340,22 +719,68 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
340
719
  const said = [...(edits ?? []).map((e) => `${e.prop} ${e.value}`), ...(concept ? [`concept ${concept.value ?? '(detached)'}`] : [])];
341
720
  console.log(` element colours saved: slide ${slide} #${index} → ${said.join(', ')}`);
342
721
  }
343
- return json(200, { ok: true, changed, ...history.counts() });
722
+ return json(200, { ok: true, changed, ...(nodes ? { nodes } : {}), ...history.counts() });
344
723
  }
345
724
 
346
725
  /**
347
726
  * `POST /deck/edit/element/text` — `{ slide, index, path, tag, was, text }`:
348
727
  * a diagram label edited in place (SVG_DIAGRAMS). The words between one
349
728
  * `<text>`/`<tspan>`'s tags change and nothing else in the diagram does; a
350
- * label the file no longer says is a 409.
729
+ * label the file no longer says is a 409. With `lines` instead of `text`
730
+ * (a label that wraps), the `<text>` is written as those lines.
351
731
  */
352
732
  function elementTextRoute({ body, json }) {
353
- const { slide, index, path = [], tag = null, was, text, quiet: inPlace = false, from = null } = JSON.parse(body);
733
+ const { slide, index, path = [], tag = null, was, text, lines = null, quiet: inPlace = false, from = null } = JSON.parse(body);
734
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) throw new Error('bad payload');
735
+ let changed;
736
+ // `lines`: a label that wraps, as the page broke it (setElementLines); `text`: one line's words
737
+ try { changed = applyEdit((html) => (lines ? setElementLines(html, slide, index, { path, tag: tag ?? 'text', was, lines }) : setElementText(html, slide, index, { path, tag, was, text }))); }
738
+ catch (e) { if (e.code !== 'STALE') throw e; return json(409, { ok: false, error: oneline(e) }); }
739
+ if (changed) console.log(` diagram label saved: slide ${slide} #${index} → ${JSON.stringify(lines ?? text).slice(0, 60)}`);
740
+ if (changed && inPlace === true) {
741
+ quiet(readDeck());
742
+ broadcast('content', { slide, index, from: typeof from === 'string' ? from.slice(0, 64) : null });
743
+ }
744
+ return json(200, { ok: true, changed, ...history.counts() });
745
+ }
746
+
747
+ /**
748
+ * `POST /deck/edit/element/canvas` — `{ slide, index, path, tag, viewBox,
749
+ * width?, height?, quiet?, from? }`: a diagram's canvas given more room or
750
+ * less, or its size on the slide with it (SVG_DIAGRAMS, setDiagramCanvas).
751
+ * One undo entry; asked in place, quiet here and every other page told.
752
+ */
753
+ function elementCanvasRoute({ body, json }) {
754
+ const { slide, index, path = [], tag = 'svg', viewBox, width = null, height = null, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
755
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || !Array.isArray(path)) return json(400, { ok: false, error: 'bad payload' });
756
+ let changed;
757
+ try { changed = applyEdit((html) => setDiagramCanvas(html, slide, index, { path, tag, viewBox, width, height })); }
758
+ catch (e) { if (e.code !== 'STALE') throw e; return json(409, { ok: false, error: oneline(e) }); }
759
+ if (changed) console.log(` diagram canvas: slide ${slide} #${index} → ${['x', 'y', 'w', 'h'].map((k) => viewBox?.[k]).join(' ')}${width ? ` · ${width} wide` : ''}`);
760
+ if (changed && inPlace === true) {
761
+ quiet(readDeck());
762
+ broadcast('content', { slide, index, from: typeof from === 'string' ? from.slice(0, 64) : null });
763
+ }
764
+ return json(200, { ok: true, changed, ...history.counts() });
765
+ }
766
+
767
+ /**
768
+ * `POST /deck/edit/element/geometry` — `{ slide, index, edits: [{ path, tag,
769
+ * attr, value }], quiet?, from? }`: nodes of a diagram moved or resized in
770
+ * write mode (SVG_DIAGRAMS), every edit of one drag in ONE applyEdit, so `Z`
771
+ * takes a box and the label that moved with it back in one press. The
772
+ * attributes are a closed set and a move is `transform: translate(x y)`,
773
+ * merged with what the transform says (setElementGeometry). A path the file
774
+ * no longer has is a 409. Asked in place, the page that dragged already
775
+ * shows it: quiet here, every other page sent `content` (it reloads).
776
+ */
777
+ function elementGeometryRoute({ body, json }) {
778
+ const { slide, index, edits, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
354
779
  if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0) throw new Error('bad payload');
355
780
  let changed;
356
- try { changed = applyEdit((html) => setElementText(html, slide, index, { path, tag, was, text })); }
781
+ try { changed = applyEdit((html) => setElementGeometry(html, slide, index, edits)); }
357
782
  catch (e) { if (e.code !== 'STALE') throw e; return json(409, { ok: false, error: oneline(e) }); }
358
- if (changed) console.log(` diagram label saved: slide ${slide} #${index} → ${JSON.stringify(text).slice(0, 60)}`);
783
+ if (changed) console.log(` diagram moved: slide ${slide} #${index} → ${edits.map((e) => `${e.attr} ${e.value}`).join(', ').slice(0, 120)}`);
359
784
  if (changed && inPlace === true) {
360
785
  quiet(readDeck());
361
786
  broadcast('content', { slide, index, from: typeof from === 'string' ? from.slice(0, 64) : null });
@@ -363,6 +788,68 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
363
788
  return json(200, { ok: true, changed, ...history.counts() });
364
789
  }
365
790
 
791
+ /**
792
+ * `POST /deck/edit/element/shape` — `{ slide, index, path, tag, op, kind?,
793
+ * at?, by?, quiet?, from? }`: a shape added to a diagram (`op: 'add'`, `path`
794
+ * the `<svg>`, `kind` box | ellipse | label | line, `at` where in the svg's
795
+ * coordinates) or a node duplicated (`op: 'duplicate'`, `path` the node).
796
+ * The server owns the markup (addDiagramShape, duplicateDiagramNode) and
797
+ * answers with it, `added: { path, html }` (and `defs` when an arrowhead
798
+ * had to be defined), so the page puts the very node the file got on the
799
+ * slide. One undo entry; a stale path is a 409.
800
+ */
801
+ function elementShapeRoute({ body, json }) {
802
+ const { slide, index, path, tag = null, op, kind = null, at = null, by = null, paths = null, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
803
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || !['add', 'duplicate'].includes(op) || (paths !== null && !Array.isArray(paths))) throw new Error('bad payload');
804
+ let out = null;
805
+ let changed;
806
+ try {
807
+ changed = applyEdit((html) => {
808
+ // several shapes duplicated together (`paths: [{ path, tag }]`): one write, `added` a list
809
+ out = op === 'add' ? addDiagramShape(html, slide, index, { path, tag: tag ?? 'svg', kind, at })
810
+ : paths ? duplicateDiagramNodes(html, slide, index, paths, { by }) : duplicateDiagramNode(html, slide, index, { path, tag, by });
811
+ return out.html;
812
+ });
813
+ } catch (e) { if (e.code !== 'STALE') throw e; return json(409, { ok: false, error: oneline(e) }); }
814
+ if (changed) console.log(` diagram ${op === 'add' ? `${kind} added` : paths ? `${paths.length} nodes duplicated` : 'node duplicated'}: slide ${slide} #${index}`);
815
+ if (changed && inPlace === true) {
816
+ quiet(readDeck());
817
+ broadcast('content', { slide, index, from: typeof from === 'string' ? from.slice(0, 64) : null });
818
+ }
819
+ return json(200, { ok: true, changed, added: out.added, defs: out.defs ?? null, ...history.counts() });
820
+ }
821
+
822
+ /**
823
+ * `POST /deck/edit/element/connector` — `{ slide, index, op, …, quiet?,
824
+ * from? }`: a connector added between two nodes of a diagram, an end
825
+ * reconnected or let go, its route, its arrowheads, its direction
826
+ * (SVG_DIAGRAMS; editConnector says each op's fields). The page sends the
827
+ * geometry it routed, since only it can measure a label; the server checks
828
+ * every value and writes the markup: the nodes' `data-node` names, the
829
+ * wire, an arrowhead's definition. It answers with what it wrote (`wire`,
830
+ * `added`, `defs`, `named`), so the page puts the very same markup on the
831
+ * slide. One undo entry; a stale path is a 409.
832
+ */
833
+ function elementConnectorRoute({ body, json }) {
834
+ const req = JSON.parse(body || '{}');
835
+ const { slide, index, op, quiet: inPlace = false, from = null } = req;
836
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || !CONNECTOR_OPS.includes(op)) throw new Error('bad payload');
837
+ let out = null;
838
+ let changed;
839
+ try {
840
+ changed = applyEdit((html) => {
841
+ out = editConnector(html, slide, index, req);
842
+ return out.html;
843
+ });
844
+ } catch (e) { if (e.code !== 'STALE') throw e; return json(409, { ok: false, error: oneline(e) }); }
845
+ if (changed) console.log(` connector ${op}: slide ${slide} #${index} › ${out.wire.path.join('.')}`);
846
+ if (changed && inPlace === true) {
847
+ quiet(readDeck());
848
+ broadcast('content', { slide, index, from: typeof from === 'string' ? from.slice(0, 64) : null });
849
+ }
850
+ return json(200, { ok: true, changed, wire: out.wire, added: out.added ?? null, defs: out.defs, named: out.named, ...history.counts() });
851
+ }
852
+
366
853
  /**
367
854
  * `POST /deck/edit/element/concept` — `{ slide, index, path, tag, concept }`:
368
855
  * the shape's `data-concept` (SVG_DIAGRAMS, #718), set from the right-click
@@ -433,7 +920,47 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
433
920
 
434
921
  // ── whole slides: the slide bar's new · duplicate · delete · reorder ──────
435
922
 
436
- const SLIDE_OPS = new Set(['new', 'duplicate', 'delete', 'up', 'down', 'move']);
923
+ /**
924
+ * The deck's voice folders, each planned for one slide op (#916): manifest
925
+ * entry n is slide n and its files are slide-NN…, so a slide inserted at 30
926
+ * would otherwise leave every later recording one slide off — out of step
927
+ * though not a word of it changed. `{ plans }` to carry out with the deck,
928
+ * or `{ error }` when a rename would overwrite a file outside the plan, in
929
+ * which case NOTHING is done: not the folders, not the deck.
930
+ */
931
+ function voicePlans(html, op, slide, to) {
932
+ const steps = voiceFolders(deckPath, configuredTrackDirs(html))
933
+ .map((dir) => ({ dir, op, slide, ...(to === undefined ? {} : { to }) }));
934
+ const r = planSteps(dirname(deckPath), steps);
935
+ return r.error ? { error: `${r.error} — nothing was changed` } : r;
936
+ }
937
+
938
+ /**
939
+ * Write the deck and move its recordings as ONE undo entry: the steps that
940
+ * undo the moves ride into the history beside the deck, so Z puts both
941
+ * back. The folders move FIRST — a folder that cannot is put back as it was
942
+ * and the op refused before the deck is touched — and are put back again if
943
+ * the deck then cannot be written. `{ changed }` or `{ error }`.
944
+ */
945
+ function editWithVoices(change, before, plans) {
946
+ const next = typeof change === 'function' ? change(before) : change;
947
+ if (next === before || !plans.length) return { changed: applyEdit(next, before) };
948
+ const deckDir = dirname(deckPath);
949
+ let moved;
950
+ try { ({ moved } = applyPlans(deckDir, plans)); } catch (e) {
951
+ return { error: `the recordings could not follow the slides — ${oneline(e)} — nothing was changed` };
952
+ }
953
+ try {
954
+ applyEdit(next, before, { voices: plans.map((p) => p.inverse) });
955
+ } catch (e) {
956
+ try { applyPlans(deckDir, planSteps(deckDir, plans.map((p) => p.inverse)).plans, { aside: true }); } catch { /* the deck error below is the one to say */ }
957
+ throw e;
958
+ }
959
+ console.log(` recordings followed their slides: ${moved} file${moved === 1 ? '' : 's'} in ${plans.map((p) => `${p.dir}/`).join(', ')}`);
960
+ return { changed: true };
961
+ }
962
+
963
+ const SLIDE_OPS = new Set(['new', 'duplicate', 'delete', 'up', 'down', 'move', 'paste']);
437
964
 
438
965
  /**
439
966
  * Slide `from` moved so that it ends up at position `to` — what a drag in
@@ -464,12 +991,28 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
464
991
  *
465
992
  * Numbering is by SOURCE ORDER, hidden slides counted (DECK_ANATOMY), which
466
993
  * is how comments, review anchors and history already number them.
994
+ *
995
+ * The deck's recordings are numbered the same way, so they move in the same
996
+ * step (#916): a new or duplicated slide has nothing recorded, a deleted
997
+ * one's files go to its folder's `.trash/`, and the same undo entry holds
998
+ * the moves.
467
999
  */
468
1000
  function slideRoute({ body, json }) {
469
- const { op, slide, to } = JSON.parse(body || '{}');
1001
+ const { op, slide, to, kind = null, section: pasted = null, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
470
1002
  if (!SLIDE_OPS.has(op) || !Number.isInteger(slide) || slide < 1) {
471
1003
  return json(400, { ok: false, error: 'bad payload' });
472
1004
  }
1005
+ // a slide from the clipboard (paste): cleaned as an element is, one <section>, after slide N
1006
+ let paste = null;
1007
+ if (op === 'paste') {
1008
+ if (typeof pasted !== 'string' || pasted.length > 1_000_000) return json(400, { ok: false, error: 'bad payload' });
1009
+ try { paste = pasteSection(pasted, withoutPageIds); } catch (e) { return json(e.status ?? 400, { ok: false, error: oneline(e) }); }
1010
+ }
1011
+ // a new slide of a kind (PRESENTING_EDITING): one of a closed set, and
1012
+ // only a new slide has one; no kind is the blank slide it always was
1013
+ if (kind !== null && (op !== 'new' || !SLIDE_KINDS.includes(kind))) {
1014
+ return json(400, { ok: false, error: op !== 'new' ? 'only a new slide has a kind' : `no slide kind "${String(kind).slice(0, 40)}" (one of: ${SLIDE_KINDS.join(', ')})` });
1015
+ }
473
1016
  if (op === 'move' && (!Number.isInteger(to) || to < 1)) return json(400, { ok: false, error: 'bad payload' });
474
1017
  const before = readDeck();
475
1018
  const total = sectionBodies(before).length;
@@ -485,24 +1028,70 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
485
1028
  const after = op === 'delete' ? total - 1 : (op === 'up' || op === 'down' || op === 'move') ? total : total + 1;
486
1029
  const show = {
487
1030
  new: slide + 1,
1031
+ paste: slide + 1,
488
1032
  duplicate: slide + 1,
489
1033
  delete: Math.min(slide, after), // deleting the last slide leaves you on the new last
490
1034
  up: slide - 1,
491
1035
  down: slide + 1,
492
1036
  move: to,
493
1037
  }[op];
494
- applyEdit((html) => {
1038
+ // every recording goes where its slide goes, in the same step (#916); a
1039
+ // pasted slide comes without its recordings, so the later ones move as for a new one
1040
+ const voices = voicePlans(before, op === 'paste' ? 'new' : op, slide, to);
1041
+ if (voices.error) return json(409, { ok: false, error: voices.error });
1042
+ const done = editWithVoices((html) => {
495
1043
  switch (op) {
496
- case 'new': return insertBlankSlide(html, slide);
1044
+ case 'new': return kind ? insertSlideOfKind(html, slide, kind) : insertBlankSlide(html, slide);
1045
+ case 'paste': return insertSectionsAfter(html, slide, [paste.section]);
497
1046
  case 'duplicate': return duplicateSlide(html, slide);
498
1047
  case 'delete': return deleteSlide(html, slide);
499
1048
  case 'up': return swapSlides(html, slide - 1, slide);
500
1049
  case 'move': return moveSlide(html, slide, to);
501
1050
  default: return swapSlides(html, slide, slide + 1);
502
1051
  }
503
- }, before);
504
- console.log(` slide ${op}: ${slide}${op === 'move' ? ` → ${to}` : ''} → ${after} slide${after === 1 ? '' : 's'}`);
505
- return json(200, { ok: true, slide: show, total: after, ...history.counts() });
1052
+ }, before, voices.plans);
1053
+ if (done.error) return json(409, { ok: false, error: done.error });
1054
+ console.log(` slide ${op}${kind ? ` (${kind})` : ''}: ${slide}${op === 'move' ? ` → ${to}` : ''} → ${after} slide${after === 1 ? '' : 's'}`);
1055
+ // Asked for IN PLACE (PRESENTING_EDITING), and no recording moved with
1056
+ // it: the page that asked makes the same change itself, so the write is
1057
+ // quiet (no reload there, its selection and scroll kept) and every other
1058
+ // page hears it as content changed elsewhere. A new slide's own markup
1059
+ // goes back with the answer, so the page puts in exactly what the file
1060
+ // has. Recordings that moved need the voice reloaded with them: that
1061
+ // stays a reload.
1062
+ const quietly = inPlace && done.changed && !voices.plans.length;
1063
+ let section;
1064
+ if (quietly) {
1065
+ const now = readDeck();
1066
+ quiet(now);
1067
+ broadcast('content', { from: typeof from === 'string' ? from.slice(0, 64) : null, slide: show });
1068
+ if (op === 'new' || op === 'paste') {
1069
+ const b = sectionBodies(now)[slide] ?? '';
1070
+ const end = b.lastIndexOf('</section>');
1071
+ if (end >= 0) section = `<section${b.slice(0, end + '</section>'.length)}`;
1072
+ }
1073
+ }
1074
+ const extra = paste ? { dropped: paste.dropped, missing: missingFiles(paste.section) } : {};
1075
+ return json(200, { ok: true, slide: show, total: after, inPlace: quietly, ...(section ? { section } : {}), ...extra, ...history.counts() });
1076
+ }
1077
+
1078
+ /** The relative files `markup` points at that the deck's folder does not have: a copy's pictures, still beside the deck it came from. */
1079
+ function missingFiles(markup) {
1080
+ const here = dirname(deckPath);
1081
+ return relativeAssets(markup).filter((p) => { const at = resolve(here, p); return !at.startsWith(here + sep) || !existsSync(at); });
1082
+ }
1083
+
1084
+ /** `GET /deck/edit/slide/source?slide=N`: slide N's `<section>` as the file has it, for Copy slide. */
1085
+ function slideSourceRoute({ url, json }) {
1086
+ const slide = Number(url.searchParams.get('slide'));
1087
+ if (!Number.isInteger(slide) || slide < 1) return json(400, { ok: false, error: 'bad payload' });
1088
+ try {
1089
+ const html = readDeck();
1090
+ const r = slideRange(html, slide);
1091
+ return json(200, { ok: true, html: html.slice(r.start, r.end) });
1092
+ } catch (e) {
1093
+ return json(404, { ok: false, error: oneline(e) });
1094
+ }
506
1095
  }
507
1096
 
508
1097
  // ── an image dropped on the stage ────────────────────────────────────────
@@ -517,6 +1106,14 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
517
1106
  ['image/webp', 'webp'], ['image/svg+xml', 'svg'], ['image/avif', 'avif'],
518
1107
  ]);
519
1108
  const MAX_ASSET_BYTES = 25e6;
1109
+ /**
1110
+ * A video put on a slide (Add ▾ › Video, DECK_ANATOMY): mp4 and webm, the
1111
+ * two every browser plays, under a cap of its own and said in its refusal.
1112
+ * Never buffered: written to a scratch file as it arrives.
1113
+ */
1114
+ const VIDEO_TYPES = new Map([['video/mp4', 'mp4'], ['video/webm', 'webm']]);
1115
+ const MAX_VIDEO_BYTES = 200e6;
1116
+ const mb = (n) => `${Math.round(n / 1e6)} MB`;
520
1117
 
521
1118
  /**
522
1119
  * The basename an upload is saved under: lower-case, `[a-z0-9._-]`, no
@@ -561,8 +1158,9 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
561
1158
  */
562
1159
  async function assetRoute({ req, json }) {
563
1160
  const type = String(req.headers['content-type'] ?? '').split(';')[0].trim().toLowerCase();
1161
+ if (VIDEO_TYPES.has(type)) return videoAsset({ req, json, ext: VIDEO_TYPES.get(type) });
564
1162
  const ext = IMAGE_TYPES.get(type);
565
- if (!ext) return json(415, { ok: false, error: `${type || 'that'} is not an image a slide can carry` });
1163
+ if (!ext) return json(415, { ok: false, error: `${type || 'that'} is not an image a slide can carry, nor an mp4 or webm video` });
566
1164
  const declared = Number(req.headers['content-length']);
567
1165
  if (Number.isFinite(declared) && declared > MAX_ASSET_BYTES) {
568
1166
  return json(413, { ok: false, error: 'image too large' });
@@ -609,40 +1207,83 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
609
1207
  }
610
1208
 
611
1209
  /**
612
- * Is `src` a path this deck can carry? Relative, and only relative.
613
- *
614
- * A scheme is somebody else's server (or, for `javascript:` and `data:`,
615
- * somebody else's code); a leading slash is the serving root rather than the
616
- * folder the deck lives in, so it breaks the moment the deck is opened over
617
- * `file://` or published under a path; and `..` points outside what travels
618
- * with the file. A deck is one HTML file and what sits beside it
619
- * (DECK_ANATOMY), and an `<img>` the author cannot send anybody is worse
620
- * than a refusal.
621
- */
622
- const relativeSrc = (s) => typeof s === 'string' && !!s.trim()
623
- && !/^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(s)
624
- && !/^[/\\]/.test(s)
625
- && !s.split(/[/\\]/).includes('..');
1210
+ * A video's bytes, saved into `assets/` as the image's are, but streamed:
1211
+ * to a scratch file (a dotfile, which no-trust mode never serves) as they
1212
+ * arrive, then linked to its own name with the same de-duplication, so a
1213
+ * half-written file never stands under a real name. The cap is refused on
1214
+ * `content-length` before a byte is read, and again on the stream. The
1215
+ * deck's autocommits carry the deck alone, so the answer says the file is
1216
+ * not in them (`committed: false`).
1217
+ */
1218
+ async function videoAsset({ req, json, ext }) {
1219
+ const tooBig = (n) => json(413, { ok: false, error: `a video on a slide is at most ${mb(MAX_VIDEO_BYTES)}${n ? `: this one is ${mb(n)}` : ''}` });
1220
+ const declared = Number(req.headers['content-length']);
1221
+ if (Number.isFinite(declared) && declared > MAX_VIDEO_BYTES) return tooBig(declared);
1222
+ const dir = resolve(deckPath, '..', 'assets');
1223
+ const stem = safeStem(req.headers['x-decklight-name']).replace(/^image$/, 'video');
1224
+ const scratch = resolve(dir, `.upload-${process.pid}-${Date.now()}.${ext}`);
1225
+ let size = 0;
1226
+ try {
1227
+ mkdirSync(dir, { recursive: true });
1228
+ const out = createWriteStream(scratch, { flags: 'wx' });
1229
+ const done = new Promise((ok, fail) => { out.on('finish', ok); out.on('error', fail); });
1230
+ for await (const chunk of req) {
1231
+ size += chunk.length;
1232
+ if (size > MAX_VIDEO_BYTES) { out.destroy(); rmSync(scratch, { force: true }); return tooBig(0); }
1233
+ if (!out.write(chunk)) await new Promise((ok) => out.once('drain', ok));
1234
+ }
1235
+ out.end();
1236
+ await done;
1237
+ if (!size) { rmSync(scratch, { force: true }); return json(400, { ok: false, error: 'no video in the request body' }); }
1238
+ let name = `${stem}.${ext}`;
1239
+ for (let i = 2; ; i++) {
1240
+ const at = resolve(dir, name);
1241
+ if (at !== resolve(dir, basename(at)) || !at.startsWith(dir + sep)) { rmSync(scratch, { force: true }); return json(400, { ok: false, error: 'bad video name' }); }
1242
+ // a link takes the name only if it is free, as `wx` does for an image
1243
+ try { linkSync(scratch, at); break; }
1244
+ catch (e) {
1245
+ if (e.code !== 'EEXIST') throw e;
1246
+ if (i > 999) { rmSync(scratch, { force: true }); return json(409, { ok: false, error: `too many videos called ${stem}` }); }
1247
+ name = `${stem}-${i}.${ext}`;
1248
+ }
1249
+ }
1250
+ rmSync(scratch, { force: true });
1251
+ console.log(` video saved: assets/${name} (${mb(size)})`);
1252
+ return json(200, { ok: true, src: `assets/${name}`, bytes: size, video: true, committed: false });
1253
+ } catch (e) {
1254
+ rmSync(scratch, { force: true });
1255
+ return json(500, { ok: false, error: oneline(e) });
1256
+ }
1257
+ }
626
1258
 
627
1259
  /**
628
- * `POST /deck/edit/element/image` — `{ slide, index, src, alt }`, an `<img>` onto a
629
- * slide, addressed by the same top-level child index every element route
630
- * uses (`sectionChildRanges`).
1260
+ * `POST /deck/edit/element/image` — `{ slide, index, path?, src, alt }`, an
1261
+ * `<img>` onto a slide, addressed by the same top-level child index every
1262
+ * element route uses (`sectionChildRanges`), and placed by the rule every
1263
+ * add follows (`whereNewBlockLands`): a picture dropped on a column, or
1264
+ * added with one selected, goes inside it.
631
1265
  *
632
1266
  * `index: null` means "wherever it belongs on this slide": after the last
633
1267
  * content child and before the asides, so a picture dropped on a slide that
634
1268
  * has speaker notes lands on the slide instead of inside the notes, where
635
1269
  * the audience would never see it.
636
1270
  *
637
- * The answer names the new element's index, because everything after the
638
- * insertion has just shifted and the caller's next act is usually to open
639
- * element edit mode on what it just made.
1271
+ * The answer names the new element's index (and its `path` below it, when
1272
+ * it went inside a column), because everything after the insertion has
1273
+ * just shifted and the caller's next act is usually to open element edit
1274
+ * mode on what it just made.
640
1275
  */
1276
+ /** An optional `path` below an element: null, or up to 16 child indices. */
1277
+ const pathShape = (path) => path === null
1278
+ || (Array.isArray(path) && path.length <= 16 && path.every((n) => Number.isInteger(n) && n >= 0));
1279
+
641
1280
  function imageRoute({ body, json }) {
642
- const { slide, index = null, src, alt } = JSON.parse(body || '{}');
1281
+ // `more: true` — another picture of the same drop follows: no reload yet,
1282
+ // or the reload this write causes cut the drop off after its first file
1283
+ const { slide, index = null, path = null, src, alt, more = false } = JSON.parse(body || '{}');
643
1284
  const text = alt == null ? '' : alt;
644
1285
  if (!Number.isInteger(slide) || slide < 1 || typeof text !== 'string'
645
- || (index !== null && (!Number.isInteger(index) || index < 0))) {
1286
+ || (index !== null && (!Number.isInteger(index) || index < 0)) || !pathShape(path)) {
646
1287
  return json(400, { ok: false, error: 'bad payload' });
647
1288
  }
648
1289
  if (!relativeSrc(src)) {
@@ -651,13 +1292,324 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
651
1292
  let at = null;
652
1293
  try {
653
1294
  applyEdit((html) => {
654
- const out = insertImage(html, slide, index, { src, alt: text });
655
- at = out.index;
656
- return out.html;
1295
+ at = insertBlock(html, slide, index, `<img src="${escapeHtml(src)}" alt="${escapeHtml(text)}">`, { path });
1296
+ return at.html;
657
1297
  });
658
1298
  } catch (e) { return json(404, { ok: false, error: oneline(e) }); }
659
- console.log(` image added: slide ${slide} #${at} → ${src}`);
660
- return json(200, { ok: true, index: at, ...history.counts() });
1299
+ if (more) quiet(readDeck());
1300
+ console.log(` image added: slide ${slide} #${at.index}${at.path.length ? ` › ${at.path.join('.')}` : ''} → ${src}${more ? ' (more to come)' : ''}`);
1301
+ return json(200, { ok: true, index: at.index, path: at.path, ...history.counts() });
1302
+ }
1303
+
1304
+ /**
1305
+ * `POST /deck/edit/element/insert` — `{ slide, index, path?, kind, quiet?,
1306
+ * from? }`: a starter of `kind` (heading, text, bullets, numbered, quote,
1307
+ * table, code, columns, diagram, chart) onto a slide, after top-level child
1308
+ * `index` (or the node at `path` below it), or with `index: null` after the
1309
+ * last content child and before the asides, the way a dropped picture lands
1310
+ * (PRESENTING_EDITING). Where it lands is the server's one rule
1311
+ * (`whereNewBlockLands`): with a column selected, inside that column.
1312
+ * With `words` (one line of inline words each, `kind` text, bullets or
1313
+ * numbered), the block is a paste from another app's clipboard: the server
1314
+ * builds the paragraph or the list around them and takes them only as words
1315
+ * and the editor's emphasis (`inlineWords`, tools/starters.mjs). The markup is the
1316
+ * server's (tools/starters.mjs): a kind outside the set is a 400, a slide
1317
+ * that follows a slide template, or two columns with content before them,
1318
+ * a 409 that says why.
1319
+ *
1320
+ * One applyEdit, so one undo entry, two columns' layout (or a bare
1321
+ * column's new wrapper) included. The answer names the new element's index
1322
+ * and `path` below it, and carries the markup the file got, so the page that asked shows exactly that IN PLACE: asked `quiet`,
1323
+ * the watcher skips the reload and every other page is sent `content`.
1324
+ */
1325
+ /**
1326
+ * `POST /deck/edit/element/paste` — `{ slide, index | null, path?, html,
1327
+ * quiet?, from? }`: an element from the clipboard onto slide N
1328
+ * (PRESENTING_EDITING), where a new block lands (pasteSlideElement): what
1329
+ * would run is left out first and named (`dropped`), and a picture the
1330
+ * deck's folder does not have is named too (`missing`), since its file is
1331
+ * still beside the deck it came from. One applyEdit, one undo. The answer
1332
+ * carries where it is and the markup the file got, for the page to put in.
1333
+ */
1334
+ function elementPasteRoute({ body, json }) {
1335
+ const { slide, index = null, path = null, html, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
1336
+ if (!Number.isInteger(slide) || slide < 1 || typeof html !== 'string' || html.length > 400_000
1337
+ || (index !== null && (!Number.isInteger(index) || index < 0)) || !pathShape(path)) {
1338
+ return json(400, { ok: false, error: 'bad payload' });
1339
+ }
1340
+ let done = null;
1341
+ try {
1342
+ applyEdit((deck) => {
1343
+ done = pasteSlideElement(deck, slide, { index, path, markup: html });
1344
+ return done.html;
1345
+ });
1346
+ } catch (e) {
1347
+ return json(e.status ?? (/^no slide \d|no element at index/.test(e.message) ? 404 : 400), { ok: false, error: oneline(e) });
1348
+ }
1349
+ const missing = missingFiles(done.markup);
1350
+ console.log(` element pasted: slide ${slide} #${done.index}${done.path.length ? ` › ${done.path.join('.')}` : ''}`
1351
+ + (done.dropped.length ? ` — left out ${done.dropped.join(', ')}` : '') + (missing.length ? ` — not in this deck's folder: ${missing.join(', ')}` : ''));
1352
+ if (inPlace === true) {
1353
+ quiet(readDeck());
1354
+ broadcast('content', { slide, index: done.index, from: typeof from === 'string' ? from.slice(0, 64) : null });
1355
+ }
1356
+ return json(200, {
1357
+ ok: true, index: done.index, path: done.path, wrapped: done.wrapped, html: done.markup,
1358
+ dropped: done.dropped, missing, ...history.counts(),
1359
+ });
1360
+ }
1361
+
1362
+ function elementInsertRoute({ body, json }) {
1363
+ const { slide, index = null, path = null, kind, words = null, with: given = null, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
1364
+ if (!Number.isInteger(slide) || slide < 1 || typeof kind !== 'string'
1365
+ || (index !== null && (!Number.isInteger(index) || index < 0)) || !pathShape(path)
1366
+ || (words !== null && (!Array.isArray(words) || words.some((w) => typeof w !== 'string')))
1367
+ || (given !== null && (typeof given !== 'object' || Array.isArray(given)))) {
1368
+ return json(400, { ok: false, error: 'bad payload' });
1369
+ }
1370
+ let done = null;
1371
+ try {
1372
+ applyEdit((html) => {
1373
+ done = insertStarter(html, slide, index, kind, { path, words, with: given ?? {} });
1374
+ return done.html;
1375
+ });
1376
+ } catch (e) {
1377
+ return json(e.status ?? 404, { ok: false, error: oneline(e) });
1378
+ }
1379
+ console.log(` element added: slide ${slide} #${done.index}${done.path.length ? ` › ${done.path.join('.')}` : ''} (${kind}${words ? ', pasted' : ''}${done.wrapped ? ', its column wrapped' : ''})`);
1380
+ if (inPlace === true) {
1381
+ quiet(readDeck());
1382
+ broadcast('content', { slide, index: done.index, from: typeof from === 'string' ? from.slice(0, 64) : null });
1383
+ }
1384
+ return json(200, {
1385
+ ok: true, index: done.index, path: done.path, ...(done.wrapped ? { wrapped: true } : {}), count: done.count, kind, html: done.markup,
1386
+ ...(done.layout ? { layout: done.layout } : {}), ...(done.section ? { section: done.section } : {}), inPlace: inPlace === true, ...history.counts(),
1387
+ });
1388
+ }
1389
+
1390
+ // ── the recordings a terminal can play (TERMINAL_PLAYER) ─────────────────
1391
+ /**
1392
+ * `GET /deck/edit/casts` — the terminal recordings found beside the deck,
1393
+ * for Add ▾ › Terminal recording: every `*.cast.json` (and asciicast
1394
+ * `*.cast`) under the deck's folder, searched a few folders deep, never into
1395
+ * a hidden folder or `node_modules`, and at most a couple of hundred. Each
1396
+ * is its path relative to the deck (what `data-cast` is written as) and
1397
+ * its size; the nearest first.
1398
+ */
1399
+ function castsRoute({ json }) {
1400
+ const root = dirname(deckPath);
1401
+ const found = [];
1402
+ const walk = (dir, depth) => {
1403
+ if (depth > 4 || found.length >= 200) return;
1404
+ let entries;
1405
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
1406
+ for (const e of entries) {
1407
+ if (found.length >= 200) return;
1408
+ if (e.name.startsWith('.') || e.name === 'node_modules') continue;
1409
+ const at = resolve(dir, e.name);
1410
+ if (e.isDirectory()) walk(at, depth + 1);
1411
+ else if (e.isFile() && /\.cast(\.json)?$/i.test(e.name)) {
1412
+ let bytes = 0;
1413
+ try { bytes = statSync(at).size; } catch { /* gone since the listing */ }
1414
+ found.push({ path: relative(root, at).split(sep).join('/'), bytes, depth });
1415
+ }
1416
+ }
1417
+ };
1418
+ walk(root, 0);
1419
+ found.sort((a, b) => a.depth - b.depth || a.path.localeCompare(b.path));
1420
+ return json(200, { ok: true, casts: found.map(({ path, bytes }) => ({ path, bytes })) });
1421
+ }
1422
+
1423
+ // ── pictures after the drop (PRESENTING_EDITING) ───────────────────────
1424
+ // A refusal is said in the transform's own words: a shape it does not take
1425
+ // is a 400, a slide or element the file does not have a 404, and a path
1426
+ // that lands on something else the 409 every element route answers.
1427
+ const refusal = (e, json) => {
1428
+ if (e.code === 'STALE') return json(409, { ok: false, error: oneline(e) });
1429
+ if (/^no slide \d|no element at index/.test(e.message)) return json(404, { ok: false, error: oneline(e) });
1430
+ return json(400, { ok: false, error: oneline(e) });
1431
+ };
1432
+ /** A write the page already shows: no reload there, every other page told. */
1433
+ const inPlaceWrite = (changed, inPlace, slide, index, from) => {
1434
+ if (!changed || inPlace !== true) return false;
1435
+ quiet(readDeck());
1436
+ broadcast('content', { slide, index, from: typeof from === 'string' ? from.slice(0, 64) : null });
1437
+ return true;
1438
+ };
1439
+
1440
+ /**
1441
+ * `POST /deck/edit/element/picture` — `{ slide, index, path?, tag?, width?,
1442
+ * alt?, src?, caption? }`: one picture's size, alt text, file, or a caption
1443
+ * around it (setElementPicture), each field a closed shape and one undo
1444
+ * entry for the lot. `path` addresses a picture inside the element (a
1445
+ * figure's, a column's); `[]` or none is the element itself. A caption
1446
+ * answers where the new `<figcaption>` is, for the page to edit it there.
1447
+ */
1448
+ function elementPictureRoute({ body, json }) {
1449
+ const b = JSON.parse(body || '{}');
1450
+ const { slide, index, path = [], tag = 'img', quiet: inPlace = false, from = null } = b;
1451
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || (tag !== null && typeof tag !== 'string')) {
1452
+ return json(400, { ok: false, error: 'bad payload' });
1453
+ }
1454
+ const fields = {};
1455
+ for (const k of ['width', 'alt', 'src', 'caption']) if (Object.hasOwn(b, k)) fields[k] = b[k];
1456
+ let changed;
1457
+ try { changed = applyEdit((html) => setElementPicture(html, slide, index, { path, tag, ...fields })); }
1458
+ catch (e) { return refusal(e, json); }
1459
+ const said = Object.entries(fields).map(([k, v]) => `${k} ${v === null ? '(removed)' : JSON.stringify(v).slice(0, 60)}`).join(', ');
1460
+ if (changed) console.log(` picture changed: slide ${slide} #${index}${path.length ? ` › ${path.join('.')}` : ''} → ${said}`);
1461
+ const placed = inPlaceWrite(changed, inPlace, slide, index, from);
1462
+ const caption = Object.hasOwn(fields, 'caption') && changed ? { figure: path, img: [...path, 0], figcaption: [...path, 1] } : undefined;
1463
+ return json(200, { ok: true, changed, inPlace: placed, ...(caption ? { caption } : {}), ...history.counts() });
1464
+ }
1465
+
1466
+ /**
1467
+ * `POST /deck/edit/element/options` — `{ slide, index, path?, tag, set }`:
1468
+ * the settings the inspector's Options tab changes on one element
1469
+ * (setElementOptions), a closed set per tag, every value checked, and one
1470
+ * undo entry for the lot: the tab sends a burst of changes as one.
1471
+ */
1472
+ function elementOptionsRoute({ body, json }) {
1473
+ const { slide, index, path = [], tag = null, set = null, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
1474
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || typeof tag !== 'string'
1475
+ || !set || typeof set !== 'object' || Array.isArray(set)) {
1476
+ return json(400, { ok: false, error: 'bad payload' });
1477
+ }
1478
+ let changed;
1479
+ try { changed = applyEdit((html) => setElementOptions(html, slide, index, { path, tag, set })); }
1480
+ catch (e) { return refusal(e, json); }
1481
+ const said = Object.entries(set).map(([k, v]) => `${k} ${v === null ? '(removed)' : JSON.stringify(v).slice(0, 60)}`).join(', ');
1482
+ if (changed) console.log(` settings changed: slide ${slide} #${index}${path.length ? ` › ${path.join('.')}` : ''} → ${said}`);
1483
+ const placed = inPlaceWrite(changed, inPlace, slide, index, from);
1484
+ return json(200, { ok: true, changed, inPlace: placed, ...history.counts() });
1485
+ }
1486
+
1487
+ /**
1488
+ * `POST /deck/edit/element/turn` — `{ slide, index, path, tag, op, value? }`:
1489
+ * one turn of a conversation (DECK_ANATOMY) given a role or a kind, a turn
1490
+ * added after it, or it removed (setConversationTurn), one undo entry.
1491
+ * Answers the path of the turn it leaves selected: the new one after an add.
1492
+ */
1493
+ function elementTurnRoute({ body, json }) {
1494
+ const { slide, index, path = null, tag = 'p', op = null, value = null, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
1495
+ if (!Number.isInteger(slide) || slide < 1 || !Number.isInteger(index) || index < 0 || !Array.isArray(path) || typeof tag !== 'string' || typeof op !== 'string') {
1496
+ return json(400, { ok: false, error: 'bad payload' });
1497
+ }
1498
+ let changed;
1499
+ let at = path;
1500
+ try {
1501
+ changed = applyEdit((html) => {
1502
+ const out = setConversationTurn(html, slide, index, { path, tag, op, value });
1503
+ at = out.path;
1504
+ return out.html;
1505
+ });
1506
+ } catch (e) { return refusal(e, json); }
1507
+ if (changed) console.log(` conversation turn: slide ${slide} #${index} › ${path.join('.')} → ${op}${value === null ? '' : ` ${JSON.stringify(value).slice(0, 40)}`}`);
1508
+ const placed = inPlaceWrite(changed, inPlace, slide, index, from);
1509
+ return json(200, { ok: true, changed, inPlace: placed, path: at, ...history.counts() });
1510
+ }
1511
+
1512
+ /**
1513
+ * `POST /deck/edit/slide/background` — `{ slide, src }`: slide N's
1514
+ * background picture (`data-background-image`, DECK_ANATOMY), a relative
1515
+ * path beside the deck, or null to take it off. With `take: { index, path?,
1516
+ * tag? }` the picture there becomes it: it leaves the slide's content and
1517
+ * its file is the background, in the same one edit (`src` is then the
1518
+ * file's, whatever the body said).
1519
+ */
1520
+ function slideBackgroundRoute({ body, json }) {
1521
+ const { slide, src = null, take = null, quiet: inPlace = false, from = null } = JSON.parse(body || '{}');
1522
+ if (!Number.isInteger(slide) || slide < 1 || (take !== null && (typeof take !== 'object' || !Number.isInteger(take.index) || take.index < 0))) {
1523
+ return json(400, { ok: false, error: 'bad payload' });
1524
+ }
1525
+ if (!take && src !== null && !relativeSrc(src)) {
1526
+ return json(400, { ok: false, error: 'a background src must be a relative path beside the deck' });
1527
+ }
1528
+ let changed;
1529
+ let out = { src, removed: null };
1530
+ try {
1531
+ changed = applyEdit((html) => {
1532
+ if (!take) return setSlideBackground(html, slide, src);
1533
+ const moved = pictureToBackground(html, slide, take.index, { path: take.path ?? [], tag: take.tag ?? 'img' });
1534
+ out = { src: moved.src, removed: moved.removed };
1535
+ return moved.html;
1536
+ });
1537
+ } catch (e) { return refusal(e, json); }
1538
+ if (changed) console.log(` slide background: slide ${slide} → ${out.src ?? '(removed)'}${take ? ` (the picture at #${take.index} moved there)` : ''}`);
1539
+ const placed = inPlaceWrite(changed, inPlace, slide, take?.index ?? null, from);
1540
+ return json(200, { ok: true, changed, inPlace: placed, src: out.src, ...(take ? { removed: out.removed } : {}), ...history.counts() });
1541
+ }
1542
+
1543
+ /**
1544
+ * `POST /deck/edit/slide/attr` — `{ slide, set: { name: value } }`: slide
1545
+ * N's own settings (the inspector's Slide tab, PRESENTING_EDITING), each a
1546
+ * `<section>` attribute written in its place (setSlideAttrs): a string its
1547
+ * value, `true` bare, null off. `edits: [{ slide, set }]` writes more than
1548
+ * one slide in the same one edit (a morph is this slide's and the one
1549
+ * before's). Quiet, the page that asked already shows it and every other
1550
+ * page is sent the edits to put on its slides.
1551
+ */
1552
+ function slideAttrRoute({ body, json }) {
1553
+ const b = JSON.parse(body || '{}');
1554
+ const { quiet: inPlace = false, from = null } = b;
1555
+ const edits = Array.isArray(b.edits) ? b.edits : [{ slide: b.slide, set: b.set }];
1556
+ if (!edits.length || edits.length > 4 || !edits.every((e) => Number.isInteger(e?.slide) && e.slide >= 1 && e.set && typeof e.set === 'object')) {
1557
+ return json(400, { ok: false, error: 'bad payload' });
1558
+ }
1559
+ let changed;
1560
+ try { changed = applyEdit((html) => edits.reduce((h, e) => setSlideAttrs(h, e.slide, e.set), html)); }
1561
+ catch (e) { return refusal(e, json); }
1562
+ if (changed) {
1563
+ const said = edits.map((e) => `slide ${e.slide}: ${Object.entries(e.set).map(([k, v]) => `${k}${v === null ? ' (removed)' : v === true ? '' : `=${JSON.stringify(v).slice(0, 60)}`}`).join(', ')}`);
1564
+ console.log(` slide settings: ${said.join('; ')}`);
1565
+ }
1566
+ const placed = !!changed && inPlace === true;
1567
+ if (placed) {
1568
+ quiet(readDeck());
1569
+ broadcast('slide-attrs', { edits: edits.map((e) => ({ slide: e.slide, set: e.set })), from: typeof from === 'string' ? from.slice(0, 64) : null });
1570
+ }
1571
+ return json(200, { ok: true, changed, inPlace: placed, ...history.counts() });
1572
+ }
1573
+
1574
+ /**
1575
+ * Find and replace (PRESENTING_EDITING, find-replace.mjs). `GET
1576
+ * /deck/edit/find?q=&notes=1&code=1&case=1&word=1`: every match in the
1577
+ * file's text, with its slide and the words around it. `POST
1578
+ * /deck/edit/replace` `{ find, replace, opts, only?, expect }`: those
1579
+ * matches (all of them, or the ids in `only`) replaced in ONE edit and one
1580
+ * undo; `expect` is how many the search found, and a deck that has changed
1581
+ * since (another count) is a 409 that says so, nothing written.
1582
+ */
1583
+ const findOpts = (o = {}) => ({ notes: o.notes === true, code: o.code === true, caseSensitive: o.caseSensitive === true, wholeWord: o.wholeWord === true });
1584
+ function findRoute({ url, json }) {
1585
+ const q = url.searchParams;
1586
+ const opts = findOpts({ notes: q.get('notes') === '1', code: q.get('code') === '1', caseSensitive: q.get('case') === '1', wholeWord: q.get('word') === '1' });
1587
+ let matches;
1588
+ try { matches = findInDeck(readDeck(), q.get('q') ?? '', opts); } catch (e) { return json(400, { ok: false, error: oneline(e) }); }
1589
+ return json(200, { ok: true, count: matches.length, matches: matches.slice(0, 500).map(({ id, slide, notes, before, text, after }) => ({ id, slide, notes, before, text, after })) });
1590
+ }
1591
+ function replaceRoute({ body, json }) {
1592
+ const b = JSON.parse(body || '{}');
1593
+ const opts = findOpts(b.opts ?? {});
1594
+ const only = Array.isArray(b.only) ? b.only.filter((x) => typeof x === 'string').slice(0, 500) : null;
1595
+ if (typeof b.find !== 'string' || typeof b.replace !== 'string' || !Number.isInteger(b.expect)) return json(400, { ok: false, error: 'bad payload' });
1596
+ let count = 0;
1597
+ let drift = null;
1598
+ try {
1599
+ const changed = applyEdit((html) => {
1600
+ const found = findInDeck(html, b.find, opts);
1601
+ const want = only ? found.filter((m) => only.includes(m.id)) : found;
1602
+ if (found.length !== b.expect || (only && want.length !== only.length)) { drift = found.length; return html; }
1603
+ const out = replaceInDeck(html, { find: b.find, replace: b.replace, opts, only });
1604
+ count = out.count;
1605
+ return out.html;
1606
+ });
1607
+ if (drift !== null) {
1608
+ return json(409, { ok: false, error: `the deck has changed since the search: it now has ${drift} match${drift === 1 ? '' : 'es'}, not ${b.expect}. Search again.`, count: drift });
1609
+ }
1610
+ if (changed) console.log(` replaced ${count}× ${JSON.stringify(b.find).slice(0, 60)} → ${JSON.stringify(b.replace).slice(0, 60)}`);
1611
+ return json(200, { ok: true, changed, count, ...history.counts() });
1612
+ } catch (e) { return json(400, { ok: false, error: oneline(e) }); }
661
1613
  }
662
1614
 
663
1615
  routes.set('POST /deck/edit/slide/notes', notesRoute);
@@ -666,18 +1618,42 @@ export function registerSlideRoutes(routes, { readDeck, applyEdit, history, deck
666
1618
  routes.set('POST /deck/edit/slide/layout', layoutRoute);
667
1619
  routes.set('POST /deck/edit/slide/template', slideTemplateRoute);
668
1620
  routes.set('POST /deck/edit/slide/hidden', hiddenRoute);
1621
+ routes.set('POST /deck/edit/slide/attr', slideAttrRoute);
1622
+ routes.set('GET /deck/edit/find', findRoute);
1623
+ routes.set('POST /deck/edit/replace', replaceRoute);
1624
+ routes.set('POST /deck/edit/slide/face', faceRoute);
669
1625
  routes.set('POST /deck/edit/narration', narrationRoute);
670
1626
  routes.set('GET /deck/edit/element/source', elementSourceRoute);
671
1627
  routes.set('POST /deck/edit/element/remove', elementRemoveRoute);
1628
+ routes.set('POST /deck/edit/element/paste', elementPasteRoute);
1629
+ routes.set('GET /deck/edit/slide/source', slideSourceRoute);
1630
+ routes.set('GET /deck/edit/slide/template/preview', slideTemplatePreviewRoute);
672
1631
  routes.set('POST /deck/edit/element/content', elementContentRoute);
673
1632
  routes.set('POST /deck/edit/element/effect', elementEffectRoute);
1633
+ routes.set('POST /deck/edit/element/build', elementBuildRoute);
1634
+ routes.set('POST /deck/edit/element/move', elementMoveRoute);
1635
+ routes.set('POST /deck/edit/element/order', elementOrderRoute);
1636
+ routes.set('POST /deck/edit/element/group', elementGroupRoute);
1637
+ routes.set('POST /deck/edit/element/duplicate', elementDuplicateRoute);
1638
+ routes.set('POST /deck/edit/element/join', elementJoinRoute);
674
1639
  routes.set('POST /deck/edit/element/style', elementStyleRoute);
675
1640
  routes.set('POST /deck/edit/element/concept', elementConceptRoute);
676
1641
  routes.set('POST /deck/edit/element/concepts', elementConceptsRoute);
677
1642
  routes.set('POST /deck/edit/element/text', elementTextRoute);
1643
+ routes.set('POST /deck/edit/element/geometry', elementGeometryRoute);
1644
+ routes.set('POST /deck/edit/element/canvas', elementCanvasRoute);
1645
+ routes.set('POST /deck/edit/element/shape', elementShapeRoute);
1646
+ routes.set('POST /deck/edit/element/connector', elementConnectorRoute);
678
1647
  routes.set('POST /deck/edit/concepts', conceptsRoute);
679
1648
  routes.set('POST /deck/edit/slide', slideRoute);
680
1649
  routes.set('POST /deck/edit/asset', assetRoute);
1650
+ routes.set('GET /deck/edit/casts', castsRoute);
681
1651
  routes.set('POST /deck/edit/element/image', imageRoute);
1652
+ routes.set('POST /deck/edit/element/insert', elementInsertRoute);
1653
+ routes.set('POST /deck/edit/element/picture', elementPictureRoute);
1654
+ routes.set('POST /deck/edit/element/options', elementOptionsRoute);
1655
+ routes.set('POST /deck/edit/element/turn', elementTurnRoute);
1656
+ routes.set('POST /deck/edit/slide/background', slideBackgroundRoute);
1657
+ routes.set('POST /deck/edit/slide/builds', slideBuildsRoute);
682
1658
  return routes;
683
1659
  }