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.
- package/NOTICE +2 -0
- package/PLATFORM.md +17 -0
- package/README.md +53 -25
- package/SPEC.md +1239 -67
- package/cli/agents.mjs +139 -15
- package/cli/bundle.mjs +68 -2
- package/cli/cast.mjs +45 -14
- package/cli/check-fixes.mjs +12 -4
- package/cli/check-watch.mjs +151 -0
- package/cli/check.mjs +460 -71
- package/cli/code-editor.mjs +287 -0
- package/cli/commands.mjs +13 -2
- package/cli/commit-message.mjs +34 -7
- package/cli/commit-split.mjs +123 -23
- package/cli/decklight.mjs +11 -1
- package/cli/design-system-edit.mjs +37 -1
- package/cli/edit-address.mjs +184 -0
- package/cli/edit-git.mjs +21 -4
- package/cli/edit-handover.mjs +136 -25
- package/cli/edit-look.mjs +45 -1
- package/cli/edit-open.mjs +143 -0
- package/cli/edit-slides.mjs +1043 -67
- package/cli/edit-translate.mjs +243 -0
- package/cli/edit.mjs +3182 -267
- package/cli/editor-support.mjs +286 -0
- package/cli/enhance.mjs +148 -20
- package/cli/find-replace.mjs +142 -0
- package/cli/fix-review.mjs +368 -0
- package/cli/init.mjs +93 -19
- package/cli/keep-awake.mjs +68 -0
- package/cli/migrate-writing.mjs +214 -0
- package/cli/narrate.mjs +51 -10
- package/cli/open.mjs +29 -9
- package/cli/outside-edit.mjs +257 -0
- package/cli/paste.mjs +92 -0
- package/cli/pdf.mjs +61 -2
- package/cli/pptx-export.mjs +3 -1
- package/cli/publish.mjs +24 -3
- package/cli/record.mjs +19 -8
- package/cli/rewrite.mjs +265 -0
- package/cli/runtime-link.mjs +218 -17
- package/cli/serve.mjs +7 -4
- package/cli/setup.mjs +2 -2
- package/cli/skill-content.mjs +212 -8
- package/cli/skills/slide-writing.md +333 -0
- package/cli/skills/voiceover.md +423 -0
- package/cli/skills.mjs +36 -13
- package/cli/starter-full.mjs +353 -0
- package/cli/supervise.mjs +14 -0
- package/cli/theme.mjs +3 -2
- package/cli/translate-core.mjs +466 -0
- package/cli/translate-files.mjs +149 -0
- package/cli/translate.mjs +458 -0
- package/cli/util.mjs +25 -0
- package/cli/vocabulary-docs.mjs +138 -0
- package/dist/decklight.css +2087 -91
- package/dist/decklight.js +367 -203
- package/dist/decklight.js.map +4 -4
- package/docs/GLOSSARY.md +9 -2
- package/docs/WRITING_RESEARCH.md +327 -0
- package/package.json +5 -3
- package/themes/coastal.css +3 -0
- package/themes/metropolis.css +2 -0
- package/themes/reveal-blood.css +3 -0
- package/themes/reveal-league.css +2 -0
- package/themes/reveal-moon.css +2 -0
- package/themes/reveal-serif.css +1 -0
- package/themes/reveal-sky.css +1 -0
- package/themes/reveal-solarized.css +4 -0
- package/tools/brand-palette.mjs +6 -1
- package/tools/build-groups.mjs +28 -8
- package/tools/cdp.mjs +176 -0
- package/tools/chart-spec.mjs +242 -0
- package/tools/click-match.mjs +70 -0
- package/tools/code-options.mjs +174 -0
- package/tools/conversation.mjs +49 -0
- package/tools/deck-family.mjs +101 -0
- package/tools/deck-html.mjs +212 -15
- package/tools/design-system-format.mjs +15 -1
- package/tools/diagram-shapes.mjs +221 -0
- package/tools/elevenlabs-tts.mjs +62 -53
- package/tools/face-clip.mjs +96 -0
- package/tools/face-layout.mjs +94 -0
- package/tools/gemini-tts.mjs +1 -1
- package/tools/invisible-in-print.mjs +27 -0
- package/tools/lipsync-auto.mjs +197 -0
- package/tools/lipsync-config.mjs +16 -0
- package/tools/lipsync-engines.mjs +22 -4
- package/tools/lipsync-server.mjs +8 -5
- package/tools/lipsync.mjs +122 -30
- package/tools/local-voice.mjs +1 -1
- package/tools/mouth-file.mjs +26 -0
- package/tools/mouth.mjs +320 -0
- package/tools/narration-manifest.mjs +24 -4
- package/tools/narration-synth.mjs +96 -76
- package/tools/recording-impact.mjs +16 -1
- package/tools/sentences.mjs +7 -1
- package/tools/starters.mjs +402 -0
- package/tools/steps.mjs +118 -0
- package/tools/take-check.mjs +146 -0
- package/tools/template-theme.mjs +3 -1
- package/tools/test-impact.mjs +36 -12
- package/tools/theme-check.mjs +196 -1
- package/tools/tone-cue.mjs +108 -0
- package/tools/tts-cache.mjs +9 -3
- package/tools/tts-engines.mjs +100 -11
- package/tools/video-cache.mjs +93 -0
- package/tools/video-live.mjs +349 -0
- package/tools/video-options.mjs +11 -0
- package/tools/video.mjs +772 -127
- package/tools/viseme-fit.mjs +27 -0
- package/tools/viseme-match.mjs +77 -0
- package/tools/vocabulary.mjs +397 -0
- package/tools/voice-renumber.mjs +605 -0
- package/tools/voiceover-server.mjs +42 -11
- package/tools/voiceover.mjs +48 -20
- package/dist/build-info.json +0 -1
package/cli/edit.mjs
CHANGED
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
// POST /deck/edit/timings → { timings: [{ slide, seconds }] } rehearsed times onto the sections
|
|
24
24
|
// POST /deck/edit/slide/layout → { slide, layout } write data-layout to the file
|
|
25
25
|
// POST /deck/edit/slide/hidden → { slide, hidden } data-hidden on or off (HIDDEN_SLIDES)
|
|
26
|
+
// POST /deck/edit/slide/face → { slides, face } data-face on each slide (FACE_LAYOUT)
|
|
26
27
|
// POST /deck/edit/export → { kind } write the deck out as a file (the palette's hand-over rows)
|
|
27
28
|
// POST /deck/edit/export/stop → stop that export part-way: its children killed, nothing half-written left
|
|
28
29
|
// GET /deck/edit/publish/plan → where publishing would put this deck, without putting it there
|
|
@@ -32,12 +33,26 @@
|
|
|
32
33
|
// POST /deck/edit/element/remove → { slide, index } delete that element
|
|
33
34
|
// POST /deck/edit/element/content → { slide, index, html } replace its outerHTML
|
|
34
35
|
// POST /deck/edit/element/effect → { slide, index, effect } write data-build (null strips it)
|
|
36
|
+
// POST /deck/edit/element/move → { slide, index, to, path?, tag? } move it (or a node inside it) to place `to`
|
|
37
|
+
// POST /deck/edit/element/order → { slide, index, path, tag, to, groups? } a diagram's node to the front, forward, backward or back
|
|
38
|
+
// POST /deck/edit/element/group → { slide, index, op, paths? | path, tag } a diagram's shapes grouped, a group taken apart, a <g> marked
|
|
39
|
+
// POST /deck/edit/element/canvas → { slide, index, path, viewBox, width?, height? } a diagram's canvas: more room, or less
|
|
40
|
+
// POST /deck/edit/element/duplicate → { slide, index, path?, tag? } a copy of it (or of a node inside it) right after it
|
|
41
|
+
// POST /deck/edit/element/picture → { slide, index, path?, width?, alt?, src?, caption? } one picture's size, alt, file or caption
|
|
42
|
+
// POST /deck/edit/element/options → { slide, index, path?, tag, set } a code block's language, line numbers, fit, line steps
|
|
43
|
+
// POST /deck/edit/element/turn → { slide, index, path, tag, op, value? } a conversation's turn: its role, its kind, one added after, one removed
|
|
44
|
+
// POST /deck/edit/slide/background → { slide, src | null, take? } the slide's background picture, or a picture made it
|
|
35
45
|
// POST /deck/edit/undo → step the deck file back through the edit history
|
|
36
46
|
// POST /deck/edit/redo → step it forward again
|
|
37
47
|
// POST /deck/edit/agent → { prompt, agent?, slide?, offer?, place? } one-shot AI agent edit, the skill offered first
|
|
48
|
+
// GET /deck/edit/candidate → the quick fix held for review (#907): its changes, slide by slide
|
|
49
|
+
// GET /deck/edit/candidate/at → ?id=&side=before|after either side of it, as a page
|
|
50
|
+
// POST /deck/edit/candidate/apply → { id, take, rejected } the approved slides, one undo entry
|
|
51
|
+
// POST /deck/edit/candidate/adjust → { id, key, comment } one slide of it back to the agent
|
|
52
|
+
// POST /deck/edit/candidate/discard → { id } drop it; the deck was never touched
|
|
38
53
|
// POST /deck/edit/agent/stop → stop the agent job in flight: that edit, an enhancement or a review
|
|
39
|
-
// POST /deck/edit/enhance → { slides: [n…]|'all', agent?, kind? } audio tags ('tags')
|
|
40
|
-
// POST /deck/edit/
|
|
54
|
+
// POST /deck/edit/enhance → { slides: [n…]|'all', agent?, kind? } audio tags ('tags'), written for the ear ('spoken') or matched to the slide ('match-slide'), held for review
|
|
55
|
+
// POST /deck/edit/rewrite → { slides: [n…]|'all', tool, instruction?, agent? } the slide's own text: tighten, typos, match, custom (cli/rewrite.mjs), held for review
|
|
41
56
|
// POST /deck/edit/review → { agent? } the agent reads the deck, read-only, for Check deck…'s agent review (writes nothing)
|
|
42
57
|
// GET /deck/edit/review → the last review's findings that still hold, each with the prompt that fixes it
|
|
43
58
|
// POST /deck/edit/shutdown → final autocommit, then exit — same as Ctrl-C, so a
|
|
@@ -59,16 +74,18 @@
|
|
|
59
74
|
// `decklight <deck>` asks interactively before passing --git down.
|
|
60
75
|
|
|
61
76
|
import { createServer, request as httpRequest } from 'node:http';
|
|
62
|
-
import { readFileSync, writeFileSync, mkdirSync, readdirSync, appendFileSync, watch, existsSync } from 'node:fs';
|
|
77
|
+
import { readFileSync, writeFileSync, mkdirSync, readdirSync, appendFileSync, watch, existsSync, rmSync } from 'node:fs';
|
|
63
78
|
// Every write of the DECK goes through this rather than writeFileSync: the
|
|
64
79
|
// edit server rewrites the whole file on every small edit, and a truncate
|
|
65
80
|
// that is interrupted leaves a prefix of a talk where the talk was.
|
|
66
81
|
import { writeFileAtomic } from '../tools/atomic-write.mjs';
|
|
82
|
+
import { LINE_DASHES, SHAPES, SHAPE_LABELS, shapeGeometry, shapeBox } from '../tools/diagram-shapes.mjs';
|
|
67
83
|
import { resolve, relative, dirname, sep, basename } from 'node:path';
|
|
68
|
-
import { VIDEO_FORMATS, VIDEO_QUALITIES, VIDEO_SUBTITLES, valuesOf } from '../tools/video-options.mjs';
|
|
84
|
+
import { VIDEO_FORMATS, VIDEO_QUALITIES, VIDEO_SUBTITLES, VIDEO_FACE, VIDEO_RENDER_MODES, valuesOf } from '../tools/video-options.mjs';
|
|
85
|
+
import { visemesWhyNot } from '../tools/lipsync-config.mjs';
|
|
69
86
|
import { spawn, execFileSync } from 'node:child_process';
|
|
70
87
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
71
|
-
import { agentAsk, agentCommand, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent, claudeActivity } from './agents.mjs';
|
|
88
|
+
import { agentAsk, agentCommand, agentModel, applyModelFlags, detectAgents, agentUnavailable, preferredAgent, setPreferredAgent, setAgentModel, takesModel, MODEL_ENV, claudeActivity } from './agents.mjs';
|
|
72
89
|
import { exitWhenOrphaned } from './supervise.mjs';
|
|
73
90
|
import { readyLine } from './banner.mjs';
|
|
74
91
|
|
|
@@ -87,22 +104,34 @@ const startup = (key, text, human, mark) => {
|
|
|
87
104
|
else console.log(human);
|
|
88
105
|
};
|
|
89
106
|
import { argReader, firstPositional, isMain, parsePort, badPort } from '../tools/args.mjs';
|
|
90
|
-
import { runMain } from './util.mjs';
|
|
107
|
+
import { runMain, afterOutput } from './util.mjs';
|
|
91
108
|
import { PKG, AGENTS_MARKER, skillVersionOf } from './skill-content.mjs';
|
|
92
109
|
import { selfCommand } from './pkg.mjs';
|
|
93
|
-
import { slidesSinceHead } from './commit-split.mjs';
|
|
110
|
+
import { slidesSinceHead, slideRenumber } from './commit-split.mjs';
|
|
111
|
+
import { outsideEdit } from './outside-edit.mjs';
|
|
94
112
|
import { semverCompare } from '../tools/semver.mjs';
|
|
95
113
|
|
|
96
114
|
// The flags that take a value, so the deck can be found past them. `--git-mode`
|
|
97
115
|
// was missing, so `edit.mjs --git-mode agent deck.html` refused a deck called
|
|
98
116
|
// "agent". (`decklight <deck>` builds this argv itself and was never affected.)
|
|
99
|
-
const VALUE_FLAGS = ['--port', '--commit-every', '--agent', '--git-mode', '--tts-port', '--lipsync-port',
|
|
117
|
+
const VALUE_FLAGS = ['--port', '--commit-every', '--agent', '--agent-model', '--agent-ask-model', '--git-mode', '--tts-port', '--lipsync-port',
|
|
100
118
|
'--host', '--root', '--branch', '--into', '--upstream-every'];
|
|
101
|
-
import { NOTES_ASIDE, locateSlide, sectionChildRanges, elementChildRanges, splitOpenTag } from '../tools/deck-html.mjs';
|
|
119
|
+
import { NOTES_ASIDE, locateSlide, sectionChildRanges, elementChildRanges, splitOpenTag, carriedChild, readAttrs } from '../tools/deck-html.mjs';
|
|
120
|
+
import { splitColumns, insertBlock } from '../tools/starters.mjs';
|
|
121
|
+
import { sanitizePasted } from './paste.mjs';
|
|
122
|
+
import { attributeEntry } from '../tools/vocabulary.mjs';
|
|
123
|
+
import {
|
|
124
|
+
stale, checkPath, locateElement, nodeAt, openElement, attrList, attrOf, withAttr, withStyle, decodeText, withoutNodes,
|
|
125
|
+
} from './edit-address.mjs';
|
|
102
126
|
import { canonMarks, writtenMarks, CLICK_MARK } from '../tools/sentences.mjs';
|
|
127
|
+
import { CODE_LANGUAGES, languageOf, lineCount, linesError } from '../tools/code-options.mjs';
|
|
128
|
+
import { webAddress } from '../tools/starters.mjs';
|
|
129
|
+
import { TURN_KINDS, ROLE_WORD, nextTurnRole, callName } from '../tools/conversation.mjs';
|
|
103
130
|
import { configBlock, hasEmbeddedRuntime, linkRuntime } from './runtime-link.mjs';
|
|
104
131
|
import { linkReferences } from './deck-refs.mjs';
|
|
105
132
|
import { slideTexts, priorSlideTexts, staleSlides, trackDrift } from '../tools/narration-manifest.mjs';
|
|
133
|
+
import { deckFamily, ownsTrack, readManifest, tracksRoot } from '../tools/deck-family.mjs';
|
|
134
|
+
import { applyPlans, voiceFolders, realignMoves, planFolder, planMoves, planSteps, movesRenumber, trackScripts, followedSaid } from '../tools/voice-renumber.mjs';
|
|
106
135
|
// The routes that rewrite a slide, which took three of editMain's bindings and
|
|
107
136
|
// nothing else with them. The import back — edit-slides reaches here for the
|
|
108
137
|
// pure transforms — is a deliberate static cycle and not a dynamic one: this
|
|
@@ -111,7 +140,7 @@ import { slideTexts, priorSlideTexts, staleSlides, trackDrift } from '../tools/n
|
|
|
111
140
|
// evaluation that is waiting on IT, and the server would never come up.
|
|
112
141
|
// A static cycle has no such moment: both bodies are function declarations,
|
|
113
142
|
// hoisted before either runs, and nothing is read until a request arrives.
|
|
114
|
-
import { registerSlideRoutes } from './edit-slides.mjs';
|
|
143
|
+
import { registerSlideRoutes, relativeSrc } from './edit-slides.mjs';
|
|
115
144
|
// The route groups split out after it, imported the same way and for the same
|
|
116
145
|
// reason: the deck's look (themes, design systems, fonts), and handing the
|
|
117
146
|
// deck over (export, publish, the inspector's read), and git (the commit
|
|
@@ -119,6 +148,8 @@ import { registerSlideRoutes } from './edit-slides.mjs';
|
|
|
119
148
|
import { registerLookRoutes, runMarketplace, autoCheckInBackground } from './edit-look.mjs';
|
|
120
149
|
import { registerHandoverRoutes } from './edit-handover.mjs';
|
|
121
150
|
import { registerGitRoutes } from './edit-git.mjs';
|
|
151
|
+
import { registerOpenRoutes } from './edit-open.mjs';
|
|
152
|
+
import { registerFixReviewRoutes, adjustPrompt } from './fix-review.mjs';
|
|
122
153
|
// the boot-call locator audit and upgrade share — three commands, one answer
|
|
123
154
|
// about which <script> is the init call
|
|
124
155
|
import { classifyScripts, auditDeck, formatLabel, stripUnaccounted } from './audit.mjs';
|
|
@@ -147,6 +178,8 @@ import { deckAt } from './restore.mjs';
|
|
|
147
178
|
import { escapeHtml, staticFiles, listenTakingOverIfNeeded, allowEditRequest, allowRemote, lanAddress, isOwnOrigin, CSP } from './serve.mjs';
|
|
148
179
|
import { reviewsWaiting, reviewLine, reviewCheckSuppressed } from './review-remote.mjs';
|
|
149
180
|
import { configureEngine, loadCredentials, forgetCredentials, redactAnswers, validateSchema, provenance, BRIDGE_ADDR, CONFIGURED, UNREACHABLE, PREREQUISITE } from './wizard.mjs';
|
|
181
|
+
import { parseSteps, STEP_NAME_MAX } from '../tools/steps.mjs';
|
|
182
|
+
import { registerTranslateRoutes, structureRefusal, newlyBehind } from './edit-translate.mjs';
|
|
150
183
|
|
|
151
184
|
// The `/deck/edit/*` surface answers loopback only — but "loopback" is the wrong
|
|
152
185
|
// boundary for the threat (#222). The dangerous caller is not off-machine: it
|
|
@@ -312,7 +345,9 @@ export function previewError(why) {
|
|
|
312
345
|
* page, so every one is checked before anything runs.
|
|
313
346
|
*
|
|
314
347
|
* - `slides` is the command's own `--slides` spelling; `format`, `quality` and
|
|
315
|
-
* `subtitles` its `--format`, `--quality` and `--subtitles
|
|
348
|
+
* `subtitles` its `--format`, `--quality` and `--subtitles`; `face: 'off'`
|
|
349
|
+
* its `--no-face`; `character` its `--character` (who is on screen in the
|
|
350
|
+
* deck, which a fresh browser cannot see).
|
|
316
351
|
* - The voice is ONE of three: `narration` names a recorded folder (inside the
|
|
317
352
|
* deck's directory, holding a manifest or whole-slide audio — a render that cannot find its audio
|
|
318
353
|
* should refuse, not come out silent); `synthesize` asks for the live voice
|
|
@@ -323,10 +358,13 @@ export function previewError(why) {
|
|
|
323
358
|
* engine and this voice; anything else — a manifest for another voice, or
|
|
324
359
|
* audio with no manifest at all, which is what your own voice leaves — refuses.
|
|
325
360
|
*/
|
|
326
|
-
export function videoExportProblem({ slides, narration, synthesize, silent, format, quality, subtitles, allowStale } = {}, deckDir) {
|
|
361
|
+
export function videoExportProblem({ slides, narration, synthesize, silent, format, quality, subtitles, face, character, render, allowStale, fix } = {}, deckDir) {
|
|
327
362
|
if (allowStale != null && typeof allowStale !== 'boolean') return 'allowStale is yes or no';
|
|
363
|
+
if (fix != null && typeof fix !== 'boolean') return 'fix is yes or no';
|
|
364
|
+
if (fix && allowStale) return 'choose either fixing the track or exporting as it is';
|
|
365
|
+
if (character != null && !['viseme', 'off'].includes(character)) return 'character must be viseme, off';
|
|
328
366
|
// the card's rows and the command's flags read one list (src/core/video-options.js)
|
|
329
|
-
for (const [field, value, list] of [['format', format, VIDEO_FORMATS], ['quality', quality, VIDEO_QUALITIES], ['subtitles', subtitles, VIDEO_SUBTITLES]]) {
|
|
367
|
+
for (const [field, value, list] of [['format', format, VIDEO_FORMATS], ['quality', quality, VIDEO_QUALITIES], ['subtitles', subtitles, VIDEO_SUBTITLES], ['face', face, VIDEO_FACE], ['render', render, VIDEO_RENDER_MODES]]) {
|
|
330
368
|
if (value != null && !valuesOf(list).includes(value)) return `${field} must be ${valuesOf(list).join(', ')}`;
|
|
331
369
|
}
|
|
332
370
|
if (slides != null && slides !== '' && !(typeof slides === 'string' && /^\d+(?:-\d+)?$/.test(slides))) {
|
|
@@ -360,12 +398,10 @@ export function videoExportProblem({ slides, narration, synthesize, silent, form
|
|
|
360
398
|
if (narration == null || narration === '') return null;
|
|
361
399
|
const bad = folderProblem(narration, deckDir, 'the narration');
|
|
362
400
|
if (bad) return bad;
|
|
363
|
-
//
|
|
364
|
-
//
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if (!audio && !existsSync(resolve(deckDir, narration, 'manifest.json'))) {
|
|
368
|
-
return `no recorded narration in ${narration}/ — record the deck first (V → Record this deck…)`;
|
|
401
|
+
// An existing folder may have lost all its recordings. Preflight reports
|
|
402
|
+
// that the same way it reports a partly missing track.
|
|
403
|
+
try { readdirSync(resolve(deckDir, narration)); } catch {
|
|
404
|
+
return `no recorded narration in ${narration}/ — record the deck first (V → My voice → Record…)`;
|
|
369
405
|
}
|
|
370
406
|
return null;
|
|
371
407
|
}
|
|
@@ -429,48 +465,88 @@ export function setSlideHidden(html, slide, hidden) {
|
|
|
429
465
|
return parts.join('');
|
|
430
466
|
}
|
|
431
467
|
|
|
432
|
-
/**
|
|
433
|
-
|
|
468
|
+
/**
|
|
469
|
+
* Where the filmed face shows on a slide (FACE_LAYOUT): `data-face` on the
|
|
470
|
+
* section, written from the V panel's Where…. An empty value is the
|
|
471
|
+
* default corner, which is no attribute at all.
|
|
472
|
+
*/
|
|
473
|
+
export function setSlideFace(html, slide, face) {
|
|
434
474
|
const { parts, idx } = locateSlide(html, slide);
|
|
435
475
|
const seg = parts[idx];
|
|
436
|
-
const
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
476
|
+
const gt = seg.indexOf('>');
|
|
477
|
+
if (gt < 0) throw new Error(`slide ${slide}: malformed <section> tag`);
|
|
478
|
+
let head = seg.slice(0, gt).replace(/\s+data-face(?:=("[^"]*"|'[^']*'|[^\s>]*))?(?=[\s>\/]|$)/, '');
|
|
479
|
+
if (face) head += ` data-face="${face}"`;
|
|
480
|
+
parts[idx] = head + seg.slice(gt);
|
|
481
|
+
return parts.join('');
|
|
440
482
|
}
|
|
441
483
|
|
|
442
484
|
/** Remove slide N's element at raw child index `index` (title included). */
|
|
443
485
|
export function removeSlideElement(html, slide, index) {
|
|
444
|
-
const
|
|
445
|
-
|
|
446
|
-
return
|
|
486
|
+
const e = openElement(html, slide, index);
|
|
487
|
+
e.el = '';
|
|
488
|
+
return e.html();
|
|
447
489
|
}
|
|
448
490
|
|
|
449
491
|
/**
|
|
450
492
|
* Remove ONE element inside slide N's element `index` (PRESENTING, a shape
|
|
451
493
|
* selected inside a diagram): the node at `path`, addressed and checked the
|
|
452
|
-
* way
|
|
453
|
-
* whole element and removeSlideElement's job. A
|
|
454
|
-
* the line with it, so the file is left without
|
|
494
|
+
* way every element edit addresses one (cli/edit-address.mjs). `[]` is
|
|
495
|
+
* refused, since that is the whole element and removeSlideElement's job. A
|
|
496
|
+
* node alone on its line takes the line with it, so the file is left without
|
|
497
|
+
* a blank one. A diagram node with connectors (a `data-node` in what goes)
|
|
498
|
+
* takes the wires that name it along, in the same write (SVG_DIAGRAMS).
|
|
455
499
|
*/
|
|
456
500
|
export function removeNestedElement(html, slide, index, { path, tag }) {
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
const
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
const
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
501
|
+
return removeNestedElements(html, slide, index, [{ path, tag }]);
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** What removing the node at `path` takes out of `e`: its range, and its connectors' (offsets into `e.el`). */
|
|
505
|
+
function removalRanges(e, path, tag) {
|
|
506
|
+
checkPath(path, { nested: true });
|
|
507
|
+
const at = e.at(path, tag);
|
|
508
|
+
// a node's connectors go with it (SVG_DIAGRAMS): a wire left naming a node
|
|
509
|
+
// that is gone would be drawn where the file last put it, joined to nothing
|
|
510
|
+
const ranges = [[at.start, at.end]];
|
|
511
|
+
const names = nodeNamesIn(e.src(at));
|
|
512
|
+
// the wires going with it, and the node itself when it is one: their labels go too
|
|
513
|
+
const wires = new Set(wireNamesIn(e.src(at)));
|
|
514
|
+
if (names.length && at.svg) {
|
|
515
|
+
for (const n of drawnNodes(e.src(at.svg))) {
|
|
516
|
+
const s = at.svg.start + n.start; const end = at.svg.start + n.end;
|
|
517
|
+
if (!WIRE_TAGS.has(n.tag) || (s >= at.start && end <= at.end)) continue;
|
|
518
|
+
if (names.includes(attrOf(n.attrs, 'data-from')) || names.includes(attrOf(n.attrs, 'data-to'))) {
|
|
519
|
+
ranges.push([s, end]);
|
|
520
|
+
const w = attrOf(n.attrs, 'data-wire');
|
|
521
|
+
if (w) wires.add(w);
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
if (wires.size && at.svg) {
|
|
526
|
+
for (const n of drawnNodes(e.src(at.svg))) {
|
|
527
|
+
const s = at.svg.start + n.start; const end = at.svg.start + n.end;
|
|
528
|
+
if (n.tag === 'text' && wires.has(attrOf(n.attrs, 'data-on-wire')) && !(s >= at.start && end <= at.end)) ranges.push([s, end]);
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
return ranges;
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Several nodes inside slide N's element `index` removed in ONE write
|
|
536
|
+
* (several shapes of a diagram, SVG_DIAGRAMS): each `{ path, tag }` as
|
|
537
|
+
* removeNestedElement addresses one, every path read in the file as it is
|
|
538
|
+
* before any goes, their connectors with them, and a node inside another
|
|
539
|
+
* that goes taken with it, never twice.
|
|
540
|
+
*/
|
|
541
|
+
export function removeNestedElements(html, slide, index, nodes) {
|
|
542
|
+
if (!Array.isArray(nodes) || !nodes.length || nodes.length > 200) throw new Error('bad nodes');
|
|
543
|
+
const e = openElement(html, slide, index);
|
|
544
|
+
const all = nodes.flatMap((n) => removalRanges(e, n?.path, n?.tag ?? null)).sort((a, b) => a[0] - b[0] || b[1] - a[1]);
|
|
545
|
+
// one range a node: what another holds goes with it
|
|
546
|
+
const kept = [];
|
|
547
|
+
for (const r of all) if (!kept.some((k) => r[0] >= k[0] && r[1] <= k[1])) kept.push(r);
|
|
548
|
+
e.el = withoutNodes(e.el, kept);
|
|
549
|
+
return e.html();
|
|
474
550
|
}
|
|
475
551
|
|
|
476
552
|
/**
|
|
@@ -500,18 +576,30 @@ const TYPE_VALUES = {
|
|
|
500
576
|
'text-anchor': /^(?:start|middle|end)$/,
|
|
501
577
|
'text-align': /^(?:left|center|right)$/,
|
|
502
578
|
};
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
const
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
579
|
+
// a line's style (SVG_DIAGRAMS): Line ▸ solid, dashed, dotted. Closed values,
|
|
580
|
+
// written inline so a `draw` build keeps the dashes as it draws (BUILD_AUTHORING:
|
|
581
|
+
// a dash set by a class would draw solid, then snap); the attribute of the
|
|
582
|
+
// same name goes when one is written, so the file never says two things
|
|
583
|
+
const LINE_VALUES = {
|
|
584
|
+
'stroke-dasharray': new RegExp(`^(?:${Object.values(LINE_DASHES).join('|')})$`),
|
|
585
|
+
'stroke-linecap': /^(?:butt|round|square)$/,
|
|
586
|
+
};
|
|
587
|
+
// how wide a block may be (a side handle's drag, PRESENTING_EDITING): whole
|
|
588
|
+
// px in deck units, 40 to 4096, and nothing else
|
|
589
|
+
const BLOCK_VALUES = { 'max-width': /^(?:[4-9]\d|[1-9]\d{2}|[1-3]\d{3}|40[0-8]\d|409[0-6])px$/ };
|
|
590
|
+
// how a picture sits in its frame (Picture ▸ Fit, Position, Rounded corners):
|
|
591
|
+
// a frame of one of four shapes, filled or shown whole, nine places, three roundings
|
|
592
|
+
const PLACE = '(?:top|bottom|center)(?: (?:left|right|center))?|left|right';
|
|
593
|
+
const PICTURE_VALUES = {
|
|
594
|
+
'object-fit': /^(?:cover|contain)$/,
|
|
595
|
+
'aspect-ratio': /^(?:16 \/ 9|4 \/ 3|3 \/ 2|1 \/ 1)$/,
|
|
596
|
+
'object-position': new RegExp(`^(?:${PLACE})$`),
|
|
597
|
+
'border-radius': /^(?:8px|16px|50%)$/,
|
|
598
|
+
};
|
|
599
|
+
const kindOf = (prop) => (STYLE_PROPS.has(prop) ? 'colour' : WIDTH_PROPS.has(prop) ? 'width'
|
|
600
|
+
: Object.hasOwn(TYPE_VALUES, prop) ? prop.replace('-', ' ') : Object.hasOwn(LINE_VALUES, prop) ? 'line style'
|
|
601
|
+
: Object.hasOwn(BLOCK_VALUES, prop) ? 'block width' : Object.hasOwn(PICTURE_VALUES, prop) ? 'picture fit' : null);
|
|
602
|
+
const valueShape = (prop) => (STYLE_PROPS.has(prop) ? STYLE_VALUE : WIDTH_PROPS.has(prop) ? WIDTH_VALUE : TYPE_VALUES[prop] ?? LINE_VALUES[prop] ?? BLOCK_VALUES[prop] ?? PICTURE_VALUES[prop]);
|
|
515
603
|
|
|
516
604
|
/**
|
|
517
605
|
* Set style properties on elements INSIDE slide N's element `index` — a shape
|
|
@@ -530,36 +618,31 @@ export function withStyleProp(style, prop, value) {
|
|
|
530
618
|
* legible where it sits — `data-nest="off"` in the markup is the opt-out.
|
|
531
619
|
*/
|
|
532
620
|
export function setElementStyles(html, slide, index, edits) {
|
|
533
|
-
if (!Array.isArray(edits) || !edits.length || edits.length >
|
|
534
|
-
const
|
|
535
|
-
let el = seg.slice(r.start, r.end);
|
|
621
|
+
if (!Array.isArray(edits) || !edits.length || edits.length > 400) throw new Error('bad edits');
|
|
622
|
+
const e = openElement(html, slide, index);
|
|
536
623
|
// each edit re-walks from the top: the one before it changed the offsets
|
|
537
|
-
for (const
|
|
538
|
-
|
|
539
|
-
const kind = kindOf(
|
|
540
|
-
if (!kind) throw new Error(`not a property this server writes: ${String(
|
|
541
|
-
if (
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
const
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
el = el.slice(0, start) + head + close + rest + el.slice(end);
|
|
560
|
-
}
|
|
561
|
-
parts[idx] = seg.slice(0, r.start) + el + seg.slice(r.end);
|
|
562
|
-
return parts.join('');
|
|
624
|
+
for (const ed of edits) {
|
|
625
|
+
checkPath(ed?.path);
|
|
626
|
+
const kind = kindOf(ed.prop);
|
|
627
|
+
if (!kind) throw new Error(`not a property this server writes: ${String(ed.prop).slice(0, 40)}`);
|
|
628
|
+
if (ed.value !== null && (typeof ed.value !== 'string' || !valueShape(ed.prop).test(ed.value))) throw new Error(`not a ${kind} this server writes: ${String(ed.value).slice(0, 40)}`);
|
|
629
|
+
e.edit(ed.path, ed.tag, (attrs) => {
|
|
630
|
+
const styled = withStyle(attrs, ed.prop, ed.value);
|
|
631
|
+
return Object.hasOwn(LINE_VALUES, ed.prop) ? withAttr(styled, ed.prop, null) : styled;
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
return e.html();
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** The markup of the nodes `edits` addressed in slide N's element `index`, once each: what a page puts back in place of a drawn stroke. */
|
|
638
|
+
export function editedNodes(html, slide, index, edits) {
|
|
639
|
+
const e = openElement(html, slide, index);
|
|
640
|
+
const seen = new Map();
|
|
641
|
+
for (const ed of edits ?? []) {
|
|
642
|
+
const key = JSON.stringify(ed.path);
|
|
643
|
+
if (!seen.has(key)) seen.set(key, { path: ed.path, html: e.src(e.at(ed.path, ed.tag ?? null)) });
|
|
644
|
+
}
|
|
645
|
+
return [...seen.values()];
|
|
563
646
|
}
|
|
564
647
|
|
|
565
648
|
/**
|
|
@@ -572,34 +655,14 @@ export function setElementStyles(html, slide, index, edits) {
|
|
|
572
655
|
const ATTR_NAMES = new Set(['data-concept']);
|
|
573
656
|
const ATTR_VALUE = /^[a-z][a-z0-9-]{0,40}$/i;
|
|
574
657
|
export function setElementAttr(html, slide, index, { path, tag, name, value }) {
|
|
575
|
-
|
|
658
|
+
checkPath(path);
|
|
576
659
|
if (!ATTR_NAMES.has(name)) throw new Error(`not an attribute this server writes: ${name}`);
|
|
577
660
|
if (value !== null && (typeof value !== 'string' || !ATTR_VALUE.test(value))) throw new Error(`not a name: ${String(value).slice(0, 40)}`);
|
|
578
|
-
const
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
for (const n of path) {
|
|
582
|
-
const kid = elementChildRanges(el.slice(start, end))[n];
|
|
583
|
-
if (!kid) throw stale(`slide ${slide} #${index}: the file has no element at ${path.join('.')} — reload and try again`);
|
|
584
|
-
end = start + kid.end; start += kid.start;
|
|
585
|
-
}
|
|
586
|
-
const node = el.slice(start, end);
|
|
587
|
-
const found = /^<([a-zA-Z][\w:-]*)/.exec(node)?.[1]?.toLowerCase();
|
|
588
|
-
if (tag && found !== String(tag).toLowerCase()) throw stale(`slide ${slide} #${index}: the page found <${tag}> at ${path.join('.') || 'the element'}, the file has <${found}> — reload and try again`);
|
|
589
|
-
const { attrs, close, rest } = splitOpenTag(node);
|
|
590
|
-
const re = new RegExp(`\\s${name}(?:\\s*=\\s*(?:"[^"]*"|'[^']*'|[^\\s>]+))?`, 'i');
|
|
591
|
-
const head = value === null ? attrs.replace(re, '') : (re.test(attrs) ? attrs.replace(re, () => ` ${name}="${value}"`) : `${attrs} ${name}="${value}"`);
|
|
592
|
-
el = el.slice(0, start) + head + close + rest + el.slice(end);
|
|
593
|
-
parts[idx] = seg.slice(0, r.start) + el + seg.slice(r.end);
|
|
594
|
-
return parts.join('');
|
|
661
|
+
const e = openElement(html, slide, index);
|
|
662
|
+
e.edit(path, tag, (attrs) => withAttr(attrs, name, value));
|
|
663
|
+
return e.html();
|
|
595
664
|
}
|
|
596
665
|
|
|
597
|
-
/** The text a run of markup reads as: the entities a label is likely to carry, decoded. */
|
|
598
|
-
const decodeText = (s) => String(s).replace(/&(#x[0-9a-f]+|#\d+|amp|lt|gt|quot|apos|nbsp);/gi, (m, e) => {
|
|
599
|
-
const k = e.toLowerCase();
|
|
600
|
-
if (k[0] === '#') return String.fromCodePoint(k[1] === 'x' ? parseInt(k.slice(2), 16) : parseInt(k.slice(1), 10));
|
|
601
|
-
return { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' }[k];
|
|
602
|
-
});
|
|
603
666
|
const sameWords = (a, b) => String(a).replace(/\s+/g, ' ').trim() === String(b).replace(/\s+/g, ' ').trim();
|
|
604
667
|
|
|
605
668
|
/**
|
|
@@ -615,42 +678,1635 @@ const sameWords = (a, b) => String(a).replace(/\s+/g, ' ').trim() === String(b).
|
|
|
615
678
|
*/
|
|
616
679
|
const LABEL_TAGS = new Set(['text', 'tspan']);
|
|
617
680
|
export function setElementText(html, slide, index, { path, tag, was, text }) {
|
|
618
|
-
|
|
681
|
+
checkPath(path);
|
|
619
682
|
if (typeof text !== 'string' || text.length > 400 || /[\u0000-\u001f\u007f]/.test(text)) throw new Error('a label is one line of at most 400 characters');
|
|
620
683
|
if (typeof was !== 'string') throw new Error('bad payload');
|
|
621
|
-
const
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
end = start + kid.end; start += kid.start;
|
|
628
|
-
}
|
|
629
|
-
const node = el.slice(start, end);
|
|
630
|
-
const found = /^<([a-zA-Z][\w:-]*)/.exec(node)?.[1]?.toLowerCase();
|
|
631
|
-
if (tag && found !== String(tag).toLowerCase()) throw stale(`slide ${slide} #${index}: the page found <${tag}> at ${path.join('.') || 'the element'}, the file has <${found}> — reload and try again`);
|
|
632
|
-
if (!LABEL_TAGS.has(found)) throw new Error(`not a diagram label: <${found}>`);
|
|
633
|
-
const { attrs, close, rest } = splitOpenTag(node);
|
|
634
|
-
const closeAt = rest.toLowerCase().lastIndexOf(`</${found}`);
|
|
635
|
-
if (close.endsWith('/>') || closeAt < 0) throw new Error(`<${found}> has no words to edit`);
|
|
684
|
+
const e = openElement(html, slide, index);
|
|
685
|
+
const at = e.at(path, tag);
|
|
686
|
+
if (!LABEL_TAGS.has(at.found)) throw new Error(`not a diagram label: <${at.found}>`);
|
|
687
|
+
const { attrs, close, rest } = splitOpenTag(e.src(at));
|
|
688
|
+
const closeAt = rest.toLowerCase().lastIndexOf(`</${at.found}`);
|
|
689
|
+
if (close.endsWith('/>') || closeAt < 0) throw new Error(`<${at.found}> has no words to edit`);
|
|
636
690
|
const inner = rest.slice(0, closeAt);
|
|
637
|
-
if (/<(?!!--)/.test(inner)) throw new Error(`this <${found}> holds other elements — edit one line at a time`);
|
|
691
|
+
if (/<(?!!--)/.test(inner)) throw new Error(`this <${at.found}> holds other elements — edit one line at a time`);
|
|
638
692
|
if (!sameWords(decodeText(inner.replace(/<!--[\s\S]*?-->/g, '')), was)) {
|
|
639
693
|
throw stale(`slide ${slide} #${index}: the file's label is not the one the page showed — reload and try again`);
|
|
640
694
|
}
|
|
641
|
-
const escaped = text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
642
|
-
const lead = /^\s*/.exec(inner)[0]; const trail = /\s*$/.exec(inner)[0];
|
|
643
|
-
const words = inner.trim() ? lead + escaped + trail : escaped;
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
695
|
+
const escaped = text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
696
|
+
const lead = /^\s*/.exec(inner)[0]; const trail = /\s*$/.exec(inner)[0];
|
|
697
|
+
const words = inner.trim() ? lead + escaped + trail : escaped;
|
|
698
|
+
e.splice(at.start, at.end, attrs + close + words + rest.slice(closeAt));
|
|
699
|
+
return e.html();
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
/**
|
|
703
|
+
* A label's lines (SVG_DIAGRAMS, labels that wrap): ONE `<text>` at `path`
|
|
704
|
+
* written as `lines`, its words as the page broke them to fit the shape it
|
|
705
|
+
* is on (only a page can measure text; the file keeps explicit lines, so the
|
|
706
|
+
* diagram renders the same with no runtime). One line is plain words; more
|
|
707
|
+
* are positioned `<tspan>` lines, each at the text's `x` and a `dy` in `em`,
|
|
708
|
+
* the block centred on the text's `y`. The `<text>` must hold words or such
|
|
709
|
+
* lines and nothing else: a `<tspan>` with no position is a run inside one
|
|
710
|
+
* line (bold, code), edited with the words around it, not here. `was` is the
|
|
711
|
+
* page's reading (its lines joined by line breaks); a file that says other
|
|
712
|
+
* words is stale.
|
|
713
|
+
*/
|
|
714
|
+
export const LINE_HEIGHT_EM = 1.2;
|
|
715
|
+
const MAX_LINES = 12;
|
|
716
|
+
export function setElementLines(html, slide, index, { path, tag = 'text', was, lines }) {
|
|
717
|
+
checkPath(path);
|
|
718
|
+
if (!Array.isArray(lines) || !lines.length || lines.length > MAX_LINES
|
|
719
|
+
|| lines.some((l) => typeof l !== 'string' || !l.trim() || /[\u0000-\u001f\u007f]/.test(l))
|
|
720
|
+
|| lines.join(' ').length > 400) throw new Error(`a label is 1 to ${MAX_LINES} lines of words, at most 400 characters in all`);
|
|
721
|
+
if (typeof was !== 'string') throw new Error('bad payload');
|
|
722
|
+
const e = openElement(html, slide, index);
|
|
723
|
+
const at = e.at(path, tag);
|
|
724
|
+
if (at.found !== 'text') throw new Error(`lines are written to a diagram's <text>, not a <${at.found}>`);
|
|
725
|
+
const { attrs, close, rest } = splitOpenTag(e.src(at));
|
|
726
|
+
const closeAt = rest.toLowerCase().lastIndexOf('</text');
|
|
727
|
+
if (close.endsWith('/>') || closeAt < 0) throw new Error('this <text> has no words to edit');
|
|
728
|
+
const inner = rest.slice(0, closeAt).replace(/<!--[\s\S]*?-->/g, '');
|
|
729
|
+
const now = labelLinesOf(inner);
|
|
730
|
+
if (!now) throw new Error('this <text> holds runs or other elements: edit its words one line at a time');
|
|
731
|
+
if (!sameWords(now.join(' '), was.replace(/\n/g, ' '))) {
|
|
732
|
+
throw stale(`slide ${slide} #${index}: the file's label is not the one the page showed — reload and try again`);
|
|
733
|
+
}
|
|
734
|
+
const esc = (t) => t.replace(/\s+/g, ' ').trim().replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
735
|
+
let words;
|
|
736
|
+
if (lines.length === 1) {
|
|
737
|
+
// back to one line: plain words, the whitespace the file had around plain words kept
|
|
738
|
+
const plain = !/</.test(inner);
|
|
739
|
+
const raw = rest.slice(0, closeAt);
|
|
740
|
+
words = plain && raw.trim() ? /^\s*/.exec(raw)[0] + esc(lines[0]) + /\s*$/.exec(raw)[0] : esc(lines[0]);
|
|
741
|
+
} else {
|
|
742
|
+
const x = attrOf(attrs, 'x');
|
|
743
|
+
if (x === null || !COORD.test(x.trim())) throw new Error('a label of several lines needs the x it is written at');
|
|
744
|
+
const first = formatCoord(-((lines.length - 1) * LINE_HEIGHT_EM) / 2);
|
|
745
|
+
words = lines.map((l, i) => `<tspan x="${x.trim()}" dy="${i ? LINE_HEIGHT_EM : first}em">${esc(l)}</tspan>`).join('');
|
|
746
|
+
}
|
|
747
|
+
e.splice(at.start, at.end, attrs + close + words + rest.slice(closeAt));
|
|
748
|
+
return e.html();
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
/**
|
|
752
|
+
* What a `<text>`'s inner markup says as lines: its words as one line, or the
|
|
753
|
+
* words of each positioned `<tspan>` (one with `x`, `y` or `dy`) when that is
|
|
754
|
+
* all it holds. Null for anything else: a run without a position, another
|
|
755
|
+
* element, words beside the lines.
|
|
756
|
+
*/
|
|
757
|
+
export function labelLinesOf(inner) {
|
|
758
|
+
const src = String(inner ?? '').replace(/<!--[\s\S]*?-->/g, '');
|
|
759
|
+
if (!/</.test(src)) return [decodeText(src).replace(/\s+/g, ' ').trim()];
|
|
760
|
+
const out = [];
|
|
761
|
+
const re = /<tspan\b([^>]*)>([^<]*)<\/tspan\s*>/giy;
|
|
762
|
+
let at = 0;
|
|
763
|
+
for (;;) {
|
|
764
|
+
const gap = /^\s*/.exec(src.slice(at))[0].length;
|
|
765
|
+
at += gap;
|
|
766
|
+
if (at >= src.length) break;
|
|
767
|
+
re.lastIndex = at;
|
|
768
|
+
const m = re.exec(src);
|
|
769
|
+
if (!m) return null;
|
|
770
|
+
const head = `<tspan${m[1]}`;
|
|
771
|
+
if (attrOf(head, 'x') === null && attrOf(head, 'y') === null && attrOf(head, 'dy') === null) return null;
|
|
772
|
+
out.push(decodeText(m[2]).replace(/\s+/g, ' ').trim());
|
|
773
|
+
at = re.lastIndex;
|
|
774
|
+
}
|
|
775
|
+
return out.length ? out : null;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
/** Replace slide N's element at raw child index `index` with `outerHtml` verbatim. */
|
|
779
|
+
export function setSlideElementHtml(html, slide, index, outerHtml) {
|
|
780
|
+
const e = openElement(html, slide, index);
|
|
781
|
+
e.el = outerHtml;
|
|
782
|
+
return e.html();
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// ── moving an element within its slide (PRESENTING_EDITING, Moving) ────────
|
|
786
|
+
|
|
787
|
+
/** A move the slide's own shape rules out (an end of the list, the asides): a 409 said as a sentence. */
|
|
788
|
+
const refusedMove = (message) => Object.assign(new Error(message), { code: 'REFUSED' });
|
|
789
|
+
|
|
790
|
+
/**
|
|
791
|
+
* `text` with child `from` of `ranges` moved to position `to` among them, the
|
|
792
|
+
* text between them left where it was. When every one of them begins its own
|
|
793
|
+
* line, a child takes its line's indentation with it: whole lines move, so a
|
|
794
|
+
* child indented its own way keeps it. Otherwise (a slide written on one line,
|
|
795
|
+
* a first child sharing the `<section>`'s line) only the children move and the
|
|
796
|
+
* whitespace stays put, so a one-line slide stays one line.
|
|
797
|
+
*/
|
|
798
|
+
function reorderChildren(text, ranges, from, to) {
|
|
799
|
+
const indentOf = (r) => /\n([ \t]*)$/.exec(text.slice(0, r.start))?.[1];
|
|
800
|
+
const ownLines = ranges.every((r) => indentOf(r) !== undefined);
|
|
801
|
+
const units = ranges.map((r) => ({ start: ownLines ? r.start - indentOf(r).length : r.start, end: r.end }));
|
|
802
|
+
const order = units.map((u) => text.slice(u.start, u.end));
|
|
803
|
+
const [moved] = order.splice(from, 1);
|
|
804
|
+
order.splice(to, 0, moved);
|
|
805
|
+
let out = text.slice(0, units[0].start);
|
|
806
|
+
units.forEach((u, i) => { out += order[i] + (i + 1 < units.length ? text.slice(u.end, units[i + 1].start) : ''); });
|
|
807
|
+
return out + text.slice(units.at(-1).end);
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* Slide `slide` with element `index` (raw child position, title included, as
|
|
812
|
+
* every element route addresses one) moved to position `to` among the slide's
|
|
813
|
+
* CONTENT children, the ones it shows: its notes, sources and rehearsed time
|
|
814
|
+
* stay where they are (last), so a move reaches neither them nor past them.
|
|
815
|
+
* With `path` (and the `tag` the page saw there) the node at that path inside
|
|
816
|
+
* the element moves among its OWN siblings instead, `to` counted among them:
|
|
817
|
+
* a list item up or down its list.
|
|
818
|
+
*
|
|
819
|
+
* Returns `{ html, index, path }`: where the element is now, since every
|
|
820
|
+
* element route addresses by position and the move has just changed it. A
|
|
821
|
+
* path or a tag the file does not have is a STALE error (409), an end of the
|
|
822
|
+
* list or an aside a REFUSED one (409, said as a sentence).
|
|
823
|
+
*/
|
|
824
|
+
export function moveSlideElement(html, slide, index, { to, path = null, tag = null } = {}) {
|
|
825
|
+
const { parts, idx } = locateSlide(String(html ?? ''), slide);
|
|
826
|
+
const seg = parts[idx];
|
|
827
|
+
const ranges = sectionChildRanges(seg);
|
|
828
|
+
const r = ranges[index];
|
|
829
|
+
if (!r) throw stale(`slide ${slide}: the file has no element at ${index} (it has ${ranges.length}) — reload and try again`);
|
|
830
|
+
if (!Number.isInteger(to) || to < 0) throw new Error('bad position');
|
|
831
|
+
if (path?.length) {
|
|
832
|
+
const el = seg.slice(r.start, r.end);
|
|
833
|
+
const { parent } = nodeAt(el, path, { slide, index, tag });
|
|
834
|
+
// the node's siblings: its parent's children, offsets into `el`
|
|
835
|
+
const siblings = elementChildRanges(el.slice(parent.start, parent.end)).map((k) => ({ ...k, start: parent.start + k.start, end: parent.start + k.end }));
|
|
836
|
+
const from = path.at(-1);
|
|
837
|
+
if (to >= siblings.length) throw refusedMove(`it is already the last of ${siblings.length}`);
|
|
838
|
+
if (to === from) throw refusedMove(`it is already ${from === 0 ? 'the first' : from === siblings.length - 1 ? 'the last' : 'there'}`);
|
|
839
|
+
parts[idx] = seg.slice(0, r.start) + reorderChildren(el, siblings, from, to) + seg.slice(r.end);
|
|
840
|
+
return { html: parts.join(''), index, path: [...path.slice(0, -1), to] };
|
|
841
|
+
}
|
|
842
|
+
if (tag && r.tag !== String(tag).toLowerCase()) throw stale(`slide ${slide}: the page found <${tag}> at ${index}, the file has <${r.tag}> — reload and try again`);
|
|
843
|
+
if (carriedChild(seg, r)) throw refusedMove(`the slide's ${r.tag === 'aside' ? 'notes and sources stay' : `<${r.tag}> stays`} where it is: only what the slide shows moves`);
|
|
844
|
+
const content = ranges.map((x, i) => ({ ...x, raw: i })).filter((x) => !carriedChild(seg, x));
|
|
845
|
+
const from = content.findIndex((x) => x.raw === index);
|
|
846
|
+
if (to >= content.length) throw refusedMove(content.length === 1 ? 'it is the only thing on the slide' : 'the notes and sources stay last: it is already as far down as it goes');
|
|
847
|
+
if (to === from) throw refusedMove(`it is already ${from === 0 ? 'first on the slide' : from === content.length - 1 ? 'last on the slide' : 'there'}`);
|
|
848
|
+
parts[idx] = reorderChildren(seg, content, from, to);
|
|
849
|
+
return { html: parts.join(''), index: content[to].raw, path: null };
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
// ── several elements at once (PRESENTING_EDITING, selecting several) ───────
|
|
853
|
+
// A selection of several top-level elements of one slide is changed in ONE
|
|
854
|
+
// edit, so one undo takes it all back. Indices shift with every write, so
|
|
855
|
+
// each batch works from the end of the slide back (remove, duplicate) or
|
|
856
|
+
// counts the slide's content again after each step (move).
|
|
857
|
+
|
|
858
|
+
/** `items` (`[{ index, tag? }]`) checked against the file: each a different element, with the tag the page saw. Sorted by index. */
|
|
859
|
+
function batchOf(html, slide, items) {
|
|
860
|
+
if (!Array.isArray(items) || !items.length || items.length > 64) throw new Error('items are the elements selected, one to 64');
|
|
861
|
+
const { parts, idx } = locateSlide(String(html ?? ''), slide);
|
|
862
|
+
const ranges = sectionChildRanges(parts[idx]);
|
|
863
|
+
const seen = new Set();
|
|
864
|
+
for (const it of items) {
|
|
865
|
+
if (!it || !Number.isInteger(it.index) || it.index < 0) throw new Error('bad item');
|
|
866
|
+
if (it.tag != null && typeof it.tag !== 'string') throw new Error('bad tag');
|
|
867
|
+
if (seen.has(it.index)) throw new Error(`element ${it.index} is named twice`);
|
|
868
|
+
seen.add(it.index);
|
|
869
|
+
const r = ranges[it.index];
|
|
870
|
+
if (!r) throw stale(`slide ${slide}: the file has no element at ${it.index} (it has ${ranges.length}) — reload and try again`);
|
|
871
|
+
if (it.tag && r.tag !== String(it.tag).toLowerCase()) throw stale(`slide ${slide}: the page found <${it.tag}> at ${it.index}, the file has <${r.tag}> — reload and try again`);
|
|
872
|
+
}
|
|
873
|
+
return [...items].sort((a, b) => a.index - b.index);
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
/** Several elements of slide N taken off, in one edit, each index naming what the page saw. */
|
|
877
|
+
export function removeSlideElements(html, slide, items) {
|
|
878
|
+
const sorted = batchOf(html, slide, items);
|
|
879
|
+
const { parts, idx } = locateSlide(String(html), slide);
|
|
880
|
+
const ranges = sectionChildRanges(parts[idx]);
|
|
881
|
+
// each with its line when it stood alone on one, so the slide is left without a blank one
|
|
882
|
+
parts[idx] = withoutNodes(parts[idx], sorted.map((it) => [ranges[it.index].start, ranges[it.index].end]));
|
|
883
|
+
return parts.join('');
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/**
|
|
887
|
+
* Several elements of slide N each copied right after itself, in one edit.
|
|
888
|
+
* Returns `{ html, copies: [{ index, markup }] }`, the copies in slide order
|
|
889
|
+
* where they are now: the k-th original (from the top) moved down by the k-1
|
|
890
|
+
* copies before it, and its copy right after it.
|
|
891
|
+
*/
|
|
892
|
+
export function duplicateSlideElements(html, slide, items) {
|
|
893
|
+
const sorted = batchOf(html, slide, items);
|
|
894
|
+
let out = html;
|
|
895
|
+
const markups = [];
|
|
896
|
+
for (const it of [...sorted].reverse()) {
|
|
897
|
+
const done = duplicateSlideElement(out, slide, it.index, { tag: it.tag ?? null });
|
|
898
|
+
out = done.html;
|
|
899
|
+
markups.unshift(done.markup);
|
|
900
|
+
}
|
|
901
|
+
return { html: out, copies: sorted.map((it, k) => ({ index: it.index + k + 1, markup: markups[k] })) };
|
|
902
|
+
}
|
|
903
|
+
|
|
904
|
+
/**
|
|
905
|
+
* Several elements of slide N moved one place up (`dir` -1) or down (+1)
|
|
906
|
+
* together, in one edit: each steps past the element beside it that is not
|
|
907
|
+
* selected, so a block keeps together and a gap between two closes up as
|
|
908
|
+
* they reach it. Refused when the first (up) or last (down) is already at
|
|
909
|
+
* that end of what the slide shows. Returns `{ html, indices }`, where each
|
|
910
|
+
* one is now, in slide order.
|
|
911
|
+
*/
|
|
912
|
+
export function moveSlideElements(html, slide, items, dir) {
|
|
913
|
+
if (dir !== -1 && dir !== 1) throw new Error('dir is -1 (up) or 1 (down)');
|
|
914
|
+
batchOf(html, slide, items);
|
|
915
|
+
const contentOf = (h) => {
|
|
916
|
+
const { parts, idx } = locateSlide(String(h), slide);
|
|
917
|
+
const seg = parts[idx];
|
|
918
|
+
return sectionChildRanges(seg).map((x, i) => ({ ...x, raw: i })).filter((x) => !carriedChild(seg, x)).map((x) => x.raw);
|
|
919
|
+
};
|
|
920
|
+
const content = contentOf(html);
|
|
921
|
+
let at = items.map((it) => content.indexOf(it.index));
|
|
922
|
+
if (at.some((p) => p < 0)) throw refusedMove('only what the slide shows moves: its notes and sources stay where they are');
|
|
923
|
+
at.sort((a, b) => a - b);
|
|
924
|
+
if (dir === -1 ? at[0] === 0 : at.at(-1) === content.length - 1) {
|
|
925
|
+
throw refusedMove(dir === -1 ? 'the first of them is already first on the slide' : 'the last of them is already as far down as it goes');
|
|
926
|
+
}
|
|
927
|
+
let out = html;
|
|
928
|
+
for (const p of dir === -1 ? at : [...at].reverse()) {
|
|
929
|
+
const now = contentOf(out);
|
|
930
|
+
out = moveSlideElement(out, slide, now[p], { to: p + dir }).html;
|
|
931
|
+
}
|
|
932
|
+
const after = contentOf(out);
|
|
933
|
+
at = at.map((p) => after[p + dir]);
|
|
934
|
+
return { html: out, indices: at };
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
/**
|
|
938
|
+
* Several elements of slide N joined into one (Turn into ▸ with several
|
|
939
|
+
* selected): `markup`, the joined block the page made from their sources,
|
|
940
|
+
* goes where the first of them stands, at its indent (the markup's later
|
|
941
|
+
* lines indented from its first), and the others are taken out with their
|
|
942
|
+
* lines. One edit. Returns `{ html, index }`, where the joined block is.
|
|
943
|
+
*/
|
|
944
|
+
export function joinSlideElements(html, slide, items, markup) {
|
|
945
|
+
if (typeof markup !== 'string' || !markup.trim() || markup.length > 200_000) throw new Error('the joined block is its markup');
|
|
946
|
+
const sorted = batchOf(html, slide, items);
|
|
947
|
+
if (sorted.length < 2) throw new Error('joining takes two elements or more');
|
|
948
|
+
const { parts, idx } = locateSlide(String(html), slide);
|
|
949
|
+
const seg = parts[idx];
|
|
950
|
+
const ranges = sectionChildRanges(seg);
|
|
951
|
+
const first = ranges[sorted[0].index];
|
|
952
|
+
const lead = /\n([ \t]*)$/.exec(seg.slice(0, first.start))?.[1] ?? '';
|
|
953
|
+
const block = markup.trim().split('\n').map((l, i) => (i && l ? lead + l : l)).join('\n');
|
|
954
|
+
// the others out first: each lies after the first, so its offsets hold
|
|
955
|
+
const rest = withoutNodes(seg, sorted.slice(1).map((it) => [ranges[it.index].start, ranges[it.index].end]));
|
|
956
|
+
parts[idx] = rest.slice(0, first.start) + block + rest.slice(first.end);
|
|
957
|
+
return { html: parts.join(''), index: sorted[0].index };
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
// ── front and back (SVG_DIAGRAMS) ─────────────────────────────────────────
|
|
961
|
+
|
|
962
|
+
/** What a diagram holds that is not drawn: never moved past by front and back, and never counted. */
|
|
963
|
+
const NOT_PAINTED = new Set(['defs', 'title', 'desc', 'style', 'metadata', 'script']);
|
|
964
|
+
export const ORDER_MOVES = ['front', 'forward', 'backward', 'back'];
|
|
965
|
+
|
|
966
|
+
/**
|
|
967
|
+
* A node of a diagram brought to the front, forward one, backward one or
|
|
968
|
+
* sent to the back (`to`) among its drawn siblings: what covers what is the
|
|
969
|
+
* order they are written in. Its `<defs>`, `<title>` and the like are not
|
|
970
|
+
* drawn and stay where they are. The node moves textually with its line
|
|
971
|
+
* (moveSlideElement). Returns `{ html, path }`, the path it is at now.
|
|
972
|
+
* Refused: a node outside a diagram, a move it is already at the end for.
|
|
973
|
+
*/
|
|
974
|
+
export function setDiagramOrder(html, slide, index, { path, tag = null, to }) {
|
|
975
|
+
if (!ORDER_MOVES.includes(to)) throw new Error(`front, forward, backward or back, not: ${String(to).slice(0, 20)}`);
|
|
976
|
+
checkPath(path);
|
|
977
|
+
if (!path?.length) throw new Error('front and back is for a node inside a diagram');
|
|
978
|
+
const e = openElement(html, slide, index);
|
|
979
|
+
const at = e.at(path, tag);
|
|
980
|
+
if (!at.inSvg || at.found === 'svg') throw new Error(`front and back is for a node inside a diagram, not a <${at.found}>`);
|
|
981
|
+
const parentPath = path.slice(0, -1);
|
|
982
|
+
const parent = parentPath.length ? e.at(parentPath) : { start: 0, end: e.el.length };
|
|
983
|
+
const kids = elementChildRanges(e.el.slice(parent.start, parent.end));
|
|
984
|
+
const from = path.at(-1);
|
|
985
|
+
if (NOT_PAINTED.has(kids[from]?.tag)) throw new Error(`a <${kids[from]?.tag}> is not drawn: it has no front or back`);
|
|
986
|
+
const drawn = kids.map((k, i) => ({ ...k, i })).filter((k) => !NOT_PAINTED.has(k.tag));
|
|
987
|
+
const here = drawn.findIndex((k) => k.i === from);
|
|
988
|
+
const want = to === 'front' ? drawn.length - 1 : to === 'back' ? 0 : here + (to === 'forward' ? 1 : -1);
|
|
989
|
+
if (want < 0 || want >= drawn.length || want === here) throw refusedMove(`it is already ${want > here || to === 'front' || to === 'forward' ? 'at the front' : 'at the back'}`);
|
|
990
|
+
const moved = moveSlideElement(html, slide, index, { to: drawn[want].i, path, tag });
|
|
991
|
+
return { html: moved.html, path: moved.path };
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
// ── groups (SVG_DIAGRAMS) ────────────────────────────────────────────────────
|
|
995
|
+
// A group is a `<g data-group>` in a diagram, holding two or more drawn
|
|
996
|
+
// things. Write mode's Group wraps several shapes in one, Ungroup puts a
|
|
997
|
+
// group's members back where it stood, and "Make it a group" marks a `<g>`
|
|
998
|
+
// the author wrote. The `<g>` carries no paint: its members keep their own.
|
|
999
|
+
|
|
1000
|
+
export const GROUP_OPS = ['group', 'ungroup', 'mark'];
|
|
1001
|
+
/** What a group's `<g>` may carry and still come apart with nothing lost: its move, its mark, its name. */
|
|
1002
|
+
const GROUP_OWN = new Set(['transform', 'data-group', 'data-node', 'data-build', 'data-build-self', 'data-build-order', 'data-build-stay']);
|
|
1003
|
+
/** Does this diagram build: a `data-build` on it or in it, or a stroke drawn in stages? */
|
|
1004
|
+
const buildsIn = (svgSrc) => /\sdata-(?:build|draw-stops)(?=[\s=/>])/i.test(svgSrc);
|
|
1005
|
+
const NOT_FROZEN = 'this diagram builds, and the slide\'s clicks were not sent with the change: reload the page and try again';
|
|
1006
|
+
/** Does a node with these attributes build its children one by one (builds.js isContainer, over the file)? */
|
|
1007
|
+
const buildsChildren = (tag, attrs, kids) => attrOf(attrs, 'data-build') !== null && attrOf(attrs, 'data-build-self') === null
|
|
1008
|
+
&& (tag === 'svg' || ((tag === 'g' || tag === 'div') && kids.filter((k) => !NOT_PAINTED.has(k.tag)).length >= 2));
|
|
1009
|
+
const ONLY_SPACE = /^[ \t]*$/;
|
|
1010
|
+
|
|
1011
|
+
/**
|
|
1012
|
+
* What a group's `<g>` at `at` holds, put back as its siblings would stand:
|
|
1013
|
+
* each member moved by the group's translate (`dx`, `dy`) in its own
|
|
1014
|
+
* coordinates (shiftSource, as a build step's are), or by its own
|
|
1015
|
+
* `transform` when it has one, so nothing moves on screen; then one level
|
|
1016
|
+
* of indentation taken off, `lead` being the group's. Comments between the
|
|
1017
|
+
* members stay. Returns `{ src, members }`: the text and each member's
|
|
1018
|
+
* markup, in order.
|
|
1019
|
+
*/
|
|
1020
|
+
function ungroupedSource(src, lead, dx, dy, adjust = (m) => m) {
|
|
1021
|
+
const { attrs, close } = splitOpenTag(src);
|
|
1022
|
+
const open = attrs.length + close.length;
|
|
1023
|
+
const kids = elementChildRanges(src);
|
|
1024
|
+
const shift = (s) => {
|
|
1025
|
+
if (!dx && !dy) return s;
|
|
1026
|
+
const head = splitOpenTag(s);
|
|
1027
|
+
const t = attrOf(head.attrs, 'transform');
|
|
1028
|
+
// a member that is rotated or scaled takes the move in front of its own transform: exact
|
|
1029
|
+
if (t !== null) { const at = translateOf(t); return withAttr(head.attrs, 'transform', withTranslate(t, at.x + dx, at.y + dy) || null) + head.close + head.rest; }
|
|
1030
|
+
try { return shiftSource(s, dx, dy, { step: true }); } catch { return shiftSource(s, dx, dy); }
|
|
1031
|
+
};
|
|
1032
|
+
const members = kids.map((k) => (NOT_PAINTED.has(k.tag) ? src.slice(k.start, k.end) : shift(adjust(src.slice(k.start, k.end)))));
|
|
1033
|
+
let inner = src.slice(open, src.lastIndexOf('</'));
|
|
1034
|
+
for (let i = kids.length - 1; i >= 0; i--) inner = inner.slice(0, kids[i].start - open) + members[i] + inner.slice(kids[i].end - open);
|
|
1035
|
+
const first = kids[0] ? src.slice(src.lastIndexOf('\n', kids[0].start - 1) + 1, kids[0].start) : '';
|
|
1036
|
+
const own = ONLY_SPACE.test(lead) && kids.every((k) => { const nl = src.lastIndexOf('\n', k.start - 1); return nl >= 0 && ONLY_SPACE.test(src.slice(nl + 1, k.start)); });
|
|
1037
|
+
if (!own) return { src: inner.trim(), members };
|
|
1038
|
+
// one level of indentation off: what the first member stands at past the group's
|
|
1039
|
+
const step = first.startsWith(lead) ? first.slice(lead.length) : '';
|
|
1040
|
+
const lines = inner.split('\n').map((l) => (step && l.startsWith(lead + step) ? lead + l.slice(lead.length + step.length) : l));
|
|
1041
|
+
while (lines.length && !lines[0].trim()) lines.shift();
|
|
1042
|
+
while (lines.length && !lines.at(-1).trim()) lines.pop();
|
|
1043
|
+
if (lines.length) lines[0] = lines[0].slice(lead.length);
|
|
1044
|
+
return { src: lines.join('\n'), members: members.map((m) => (step ? m.split('\n').map((l, i) => (i && l.startsWith(lead + step) ? lead + l.slice(lead.length + step.length) : l)).join('\n') : m)) };
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/** Where a wire's end is (`which`: 'from' its start, 'to' its end), in the svg's coordinates, or null. */
|
|
1048
|
+
function wireEnd(n, which) {
|
|
1049
|
+
const a = n.attrs; const t = translateOf(attrOf(a, 'transform'));
|
|
1050
|
+
const off = (p) => (p ? { x: n.at.x + t.x + p.x, y: n.at.y + t.y + p.y } : null);
|
|
1051
|
+
if (n.tag === 'line') return off(which === 'from' ? { x: num(a, 'x1'), y: num(a, 'y1') } : { x: num(a, 'x2'), y: num(a, 'y2') });
|
|
1052
|
+
const nums = String(attrOf(a, n.tag === 'path' ? 'd' : 'points') ?? '').match(/-?\d+(?:\.\d+)?/g)?.map(Number) ?? [];
|
|
1053
|
+
if (nums.length < 2) return null;
|
|
1054
|
+
return off(which === 'from' ? { x: nums[0], y: nums[1] } : { x: nums.at(-2), y: nums.at(-1) });
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
/**
|
|
1058
|
+
* Group, Ungroup and "Make it a group" in a diagram (SVG_DIAGRAMS, groups),
|
|
1059
|
+
* each one write:
|
|
1060
|
+
*
|
|
1061
|
+
* `group` the nodes at `paths` (`[{ path, tag }]`, two or more, siblings
|
|
1062
|
+
* in the file) wrapped in one `<g data-group>` standing where the
|
|
1063
|
+
* frontmost of them stood, their order kept. A node between them
|
|
1064
|
+
* that is not one ends up behind the group.
|
|
1065
|
+
* `ungroup` the `<g>` at `path` taken apart: its members put back where it
|
|
1066
|
+
* stood, in their order, its translate given to each (nothing
|
|
1067
|
+
* moves). A `<g>` with another transform, or with paint or a
|
|
1068
|
+
* name of its own its members would lose, is refused. A wire
|
|
1069
|
+
* joined to the group itself (its `data-node`) is joined to the
|
|
1070
|
+
* member nearest where it meets the group, that member named
|
|
1071
|
+
* when it is not, so no wire is left naming a node that is gone.
|
|
1072
|
+
* `mark` the `<g>` at `path` (one the author wrote) given `data-group`.
|
|
1073
|
+
*
|
|
1074
|
+
* In a diagram that builds, the caller freezes the slide's play order first
|
|
1075
|
+
* (`frozen`; refused without it) and the clicks are kept: a group made in a
|
|
1076
|
+
* container that builds its children takes the container's `data-build`, so
|
|
1077
|
+
* its members stay steps (builds.js isBuildingGroup); Ungroup gives a group
|
|
1078
|
+
* that was one step's key, effect or stay to each member. Returns `{ html, path, markup }` (the group's path
|
|
1079
|
+
* and markup) for group and mark; `{ html, members: [{ path, html }], wires }`
|
|
1080
|
+
* for ungroup, `wires` the new ends of each wire that was joined to the
|
|
1081
|
+
* group, in the file's order.
|
|
1082
|
+
*/
|
|
1083
|
+
export function groupDiagramNodes(html, slide, index, { op, paths = null, path = null, tag = null, frozen = false }) {
|
|
1084
|
+
if (!GROUP_OPS.includes(op)) throw new Error(`group, ungroup or mark, not: ${String(op).slice(0, 20)}`);
|
|
1085
|
+
const e = openElement(html, slide, index);
|
|
1086
|
+
if (op === 'group') {
|
|
1087
|
+
if (!Array.isArray(paths) || paths.length > 100) throw new Error('bad paths');
|
|
1088
|
+
if (paths.length < 2) throw refusedMove('a group is two shapes or more: ⇧-click another to add it');
|
|
1089
|
+
const ats = paths.map((p) => { checkPath(p?.path, { nested: true }); return { ...e.at(p.path, p.tag ?? null), path: p.path }; });
|
|
1090
|
+
for (const a of ats) if (!a.inSvg || !DIAGRAM_NODES.has(a.found) || a.found === 'tspan') throw new Error(`a group is made of a diagram's shapes, not a <${a.found}>`);
|
|
1091
|
+
if (new Set(ats.map((a) => a.path.slice(0, -1).join('.'))).size !== 1) throw refusedMove('these do not stand side by side in the file (one is inside a group or a box of its own): group shapes that share a parent');
|
|
1092
|
+
if (new Set(ats.map((a) => a.path.at(-1))).size !== ats.length) throw new Error('the same shape twice');
|
|
1093
|
+
if (buildsIn(e.src(ats[0].svg)) && !frozen) throw refusedMove(NOT_FROZEN);
|
|
1094
|
+
const sorted = [...ats].sort((a, b) => a.start - b.start);
|
|
1095
|
+
const front = sorted.at(-1);
|
|
1096
|
+
const lead = e.lead(front);
|
|
1097
|
+
const own = sorted.every((a) => ONLY_SPACE.test(e.lead(a)));
|
|
1098
|
+
// one level in: the step from the parent's indentation to the front member's, else two spaces
|
|
1099
|
+
const parentLead = e.lead(front.parent);
|
|
1100
|
+
const step = own && lead.startsWith(parentLead) && lead.length > parentLead.length ? lead.slice(parentLead.length) : ' ';
|
|
1101
|
+
// in a container that builds its children one by one, the group builds its members the same way,
|
|
1102
|
+
// so each keeps its step (builds.js isBuildingGroup); every one of them there from the start, so is it
|
|
1103
|
+
const parentSrc = e.src(front.parent);
|
|
1104
|
+
const parentAttrs = splitOpenTag(parentSrc).attrs;
|
|
1105
|
+
let open = '<g data-group';
|
|
1106
|
+
if (buildsChildren(front.parent.tag, parentAttrs, elementChildRanges(parentSrc))) {
|
|
1107
|
+
const stays = sorted.every((a) => attrOf(splitOpenTag(e.src(a)).attrs, 'data-build-stay') !== null);
|
|
1108
|
+
const effect = attrOf(parentAttrs, 'data-build');
|
|
1109
|
+
open += stays ? ' data-build-stay' : effect ? ` data-build="${escapeHtml(effect)}"` : ' data-build';
|
|
1110
|
+
}
|
|
1111
|
+
open += '>';
|
|
1112
|
+
const markup = own
|
|
1113
|
+
? `${open}\n${sorted.map((a) => `${lead}${step}${e.src(a).replace(/\n/g, `\n${step}`)}`).join('\n')}\n${lead}</g>`
|
|
1114
|
+
: `${open}${sorted.map((a) => e.src(a)).join('')}</g>`;
|
|
1115
|
+
e.splice(front.start, front.end, markup);
|
|
1116
|
+
e.el = withoutNodes(e.el, sorted.slice(0, -1).map((a) => [a.start, a.end]));
|
|
1117
|
+
return { html: e.html(), path: [...front.path.slice(0, -1), front.path.at(-1) - (sorted.length - 1)], markup };
|
|
1118
|
+
}
|
|
1119
|
+
checkPath(path, { nested: true });
|
|
1120
|
+
let at = e.at(path, tag);
|
|
1121
|
+
if (at.found !== 'g' || !at.inSvg) throw new Error(`${op === 'mark' ? 'Make it a group' : 'Ungroup'} is for a group in a diagram, not a <${at.found}>`);
|
|
1122
|
+
if (op === 'mark') {
|
|
1123
|
+
if (attrOf(splitOpenTag(e.src(at)).attrs, 'data-group') !== null) throw refusedMove('it is a group already');
|
|
1124
|
+
e.edit(path, 'g', (a) => withAttr(a, 'data-group', true));
|
|
1125
|
+
return { html: e.html(), path, markup: e.src(e.at(path, 'g')) };
|
|
1126
|
+
}
|
|
1127
|
+
if (buildsIn(e.src(at.svg)) && !frozen) throw refusedMove(NOT_FROZEN);
|
|
1128
|
+
const { attrs } = splitOpenTag(e.src(at));
|
|
1129
|
+
const extra = attrList(attrs).find((a) => !GROUP_OWN.has(a.name));
|
|
1130
|
+
if (extra) throw refusedMove(`this group carries ${extra.written}${extra.raw === null ? '' : `="${extra.value.slice(0, 40)}"`}, which its shapes would lose: take it off in the HTML first, or keep the group`);
|
|
1131
|
+
const transform = attrOf(attrs, 'transform');
|
|
1132
|
+
if (transform !== null && transform.trim() && !/^\s*translate\([^)]*\)\s*$/i.test(transform)) throw refusedMove(`this group is ${transform.trim().slice(0, 40)}: only a group that was moved comes apart, its move given to each shape`);
|
|
1133
|
+
if (!elementChildRanges(e.src(at)).length) throw refusedMove('this group holds nothing');
|
|
1134
|
+
const { x: dx, y: dy } = translateOf(transform);
|
|
1135
|
+
// a wire joined to the group: joined to the member nearest where it meets it
|
|
1136
|
+
const name = attrOf(attrs, 'data-node');
|
|
1137
|
+
const svgDepth = at.chain.indexOf(at.svg);
|
|
1138
|
+
const svgPath = path.slice(0, svgDepth);
|
|
1139
|
+
const wires = [];
|
|
1140
|
+
if (name) {
|
|
1141
|
+
const drawn = drawnNodes(e.src(at.svg));
|
|
1142
|
+
const gRel = at.start - at.svg.start;
|
|
1143
|
+
const gNode = drawn.find((n) => n.start === gRel);
|
|
1144
|
+
const kids = drawn.filter((n) => n.path.length === gNode.path.length + 1 && n.start > gNode.start && n.end <= gNode.end);
|
|
1145
|
+
// a member's middle in the svg's space: its own, or the first shape's inside it (a box group)
|
|
1146
|
+
const middle = (k) => middleOf(k) ?? drawn.filter((n) => n.start >= k.start && n.end <= k.end && !WIRE_TAGS.has(n.tag) && n.tag !== 'text').map(middleOf).find(Boolean)
|
|
1147
|
+
?? drawn.filter((n) => n.start >= k.start && n.end <= k.end).map(middleOf).find(Boolean) ?? null;
|
|
1148
|
+
const shapes = kids.filter((k) => !WIRE_TAGS.has(k.tag) || k.tag === 'path').map((k) => ({ ...k, middle: middle(k) })).filter((k) => k.middle);
|
|
1149
|
+
if (!shapes.length) throw refusedMove('a wire is joined to this group and it holds no shape to join it to instead: remove the wire first');
|
|
1150
|
+
const taken = new Set(nodeNamesIn(e.src(at.svg)));
|
|
1151
|
+
const named = new Map(); // a member's path below the svg → the name it has now
|
|
1152
|
+
const nameOf = (k) => {
|
|
1153
|
+
const key = k.path.join('.');
|
|
1154
|
+
if (named.has(key)) return named.get(key);
|
|
1155
|
+
const own = attrOf(k.attrs, 'data-node');
|
|
1156
|
+
const n = own ?? uniqueName(slugNode(wordsOf(k.src) || 'node'), taken);
|
|
1157
|
+
taken.add(n);
|
|
1158
|
+
named.set(key, n);
|
|
1159
|
+
if (own === null) e.edit([...svgPath, ...k.path], k.tag, (a) => withAttr(a, 'data-node', n));
|
|
1160
|
+
return n;
|
|
1161
|
+
};
|
|
1162
|
+
const attached = drawn.filter((n) => WIRE_TAGS.has(n.tag) && !(n.start >= gNode.start && n.end <= gNode.end)
|
|
1163
|
+
&& (attrOf(n.attrs, 'data-from') === name || attrOf(n.attrs, 'data-to') === name));
|
|
1164
|
+
for (const w of attached) {
|
|
1165
|
+
const ends = {};
|
|
1166
|
+
for (const end of ['from', 'to']) {
|
|
1167
|
+
if (attrOf(w.attrs, `data-${end}`) !== name) continue;
|
|
1168
|
+
const p = wireEnd(w, end);
|
|
1169
|
+
ends[end] = nameOf(nearest(shapes, p) ?? shapes[0]);
|
|
1170
|
+
}
|
|
1171
|
+
e.edit([...svgPath, ...w.path], w.tag, (a) => Object.entries(ends).reduce((h, [end, n]) => withAttr(h, `data-${end}`, n), a));
|
|
1172
|
+
wires.push({ from: ends.from ?? attrOf(w.attrs, 'data-from'), to: ends.to ?? attrOf(w.attrs, 'data-to') });
|
|
1173
|
+
}
|
|
1174
|
+
at = e.at(path, 'g');
|
|
1175
|
+
}
|
|
1176
|
+
// its builds kept (BUILD_SEMANTICS): members that were steps keep their keys (the order was
|
|
1177
|
+
// frozen first); a group that was one step gives each member its key, so they still arrive
|
|
1178
|
+
// together; its own effect and "there from the start" go to each member
|
|
1179
|
+
const building = buildsIn(e.src(at.svg));
|
|
1180
|
+
const stepsInside = buildsChildren('g', attrs, elementChildRanges(e.src(at)));
|
|
1181
|
+
const key = attrOf(attrs, 'data-build-order');
|
|
1182
|
+
const effect = attrOf(attrs, 'data-build');
|
|
1183
|
+
const parentEffect = attrOf(splitOpenTag(e.src(at.parent)).attrs, 'data-build');
|
|
1184
|
+
const stays = attrOf(attrs, 'data-build-stay') !== null;
|
|
1185
|
+
const adjust = (m) => {
|
|
1186
|
+
if (!building) return m;
|
|
1187
|
+
const h = splitOpenTag(m);
|
|
1188
|
+
let a = h.attrs;
|
|
1189
|
+
if (stays) a = withAttr(a, 'data-build-stay', true);
|
|
1190
|
+
else if (!stepsInside && key !== null) a = withAttr(a, 'data-build-order', key);
|
|
1191
|
+
if (effect && effect !== parentEffect && attrOf(a, 'data-build') === null) a = withAttr(a, 'data-build', effect);
|
|
1192
|
+
return a + h.close + h.rest;
|
|
1193
|
+
};
|
|
1194
|
+
const out = ungroupedSource(e.src(at), e.lead(at), dx, dy, adjust);
|
|
1195
|
+
e.splice(at.start, at.end, out.src);
|
|
1196
|
+
const kidsAt = elementChildRanges(`<g>${out.members.join('')}</g>`);
|
|
1197
|
+
return {
|
|
1198
|
+
html: e.html(),
|
|
1199
|
+
members: out.members.map((m, i) => ({ path: [...path.slice(0, -1), path.at(-1) + i], html: m, tag: kidsAt[i]?.tag ?? null })),
|
|
1200
|
+
wires,
|
|
1201
|
+
};
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
// ── a diagram's canvas (SVG_DIAGRAMS) ────────────────────────────────────────
|
|
1205
|
+
|
|
1206
|
+
/**
|
|
1207
|
+
* A diagram's canvas made bigger or smaller (SVG_DIAGRAMS, the canvas): the
|
|
1208
|
+
* `<svg>` at `path` below slide N's element `index` given `viewBox` `{ x, y,
|
|
1209
|
+
* w, h }`, the room the drawing has, and, when the page sends them, the
|
|
1210
|
+
* `width` (and `height`) it is drawn at on the slide, so more room does not
|
|
1211
|
+
* shrink what is drawn. Only those attributes change, each where it stands,
|
|
1212
|
+
* `viewBox` keeping the casing the file wrote it in. Numbers only: a size is
|
|
1213
|
+
* positive, and the canvas never smaller than 1 unit.
|
|
1214
|
+
*/
|
|
1215
|
+
export function setDiagramCanvas(html, slide, index, { path = [], tag = 'svg', viewBox, width = null, height = null }) {
|
|
1216
|
+
checkPath(path);
|
|
1217
|
+
const v = viewBox ?? {};
|
|
1218
|
+
const [x, y, w, h] = ['x', 'y', 'w', 'h'].map((k) => coordOf(v[k]));
|
|
1219
|
+
if (![x, y, w, h].every(Number.isFinite) || w < 1 || h < 1) throw new Error('a canvas is x, y, a width and a height, the sizes at least 1');
|
|
1220
|
+
const size = (n, what) => {
|
|
1221
|
+
if (n === null || n === undefined) return null;
|
|
1222
|
+
const c = coordOf(n);
|
|
1223
|
+
if (!Number.isFinite(c) || c < 1 || c > 4096) throw new Error(`not a ${what} on the slide: ${String(n).slice(0, 20)}`);
|
|
1224
|
+
return formatCoord(c);
|
|
1225
|
+
};
|
|
1226
|
+
const wOn = size(width, 'width'); const hOn = size(height, 'height');
|
|
1227
|
+
const e = openElement(html, slide, index);
|
|
1228
|
+
e.edit(path, tag, (attrs, at) => {
|
|
1229
|
+
if (at.found !== 'svg') throw new Error(`a canvas is a diagram's <svg>, not a <${at.found}>`);
|
|
1230
|
+
if (/\sdata-chart\b/i.test(attrs)) throw new Error('a chart draws itself from its data');
|
|
1231
|
+
const value = [x, y, w, h].map(formatCoord).join(' ');
|
|
1232
|
+
// the name as the file wrote it (`viewBox`, or `viewbox`), and `viewBox` when it had none
|
|
1233
|
+
let out = attrOf(attrs, 'viewbox') !== null ? withAttr(attrs, 'viewbox', value) : withAttr(attrs, 'viewBox', value);
|
|
1234
|
+
if (wOn !== null) out = withAttr(out, 'width', wOn);
|
|
1235
|
+
if (hOn !== null) out = withAttr(out, 'height', hOn);
|
|
1236
|
+
return out;
|
|
1237
|
+
});
|
|
1238
|
+
return e.html();
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// ── a diagram's shapes: moved, resized, added, duplicated (SVG_DIAGRAMS) ────
|
|
1242
|
+
// Write mode drags a box, pulls a handle, adds a shape from the element menu
|
|
1243
|
+
// and duplicates one. The page shows each at once; these are what the file
|
|
1244
|
+
// gets. Like the colour card's writes they are addressed by the FILE's path
|
|
1245
|
+
// below the slide's element and the tag the page saw there (a mismatch is a
|
|
1246
|
+
// 409, never a guess), and they change the file textually: one attribute
|
|
1247
|
+
// where it stands, or one node's markup inserted on its own line at the
|
|
1248
|
+
// indentation its neighbours have, so every other byte of the diagram stays.
|
|
1249
|
+
|
|
1250
|
+
/** Attributes a move or a resize writes, and the ones that can never be negative. */
|
|
1251
|
+
const GEOMETRY_ATTRS = new Set(['x', 'y', 'width', 'height', 'cx', 'cy', 'r', 'rx', 'ry', 'x1', 'y1', 'x2', 'y2', 'transform', 'd', 'points', 'data-along']);
|
|
1252
|
+
/** The attributes that are a shape of their own, and the only tags that may carry them. */
|
|
1253
|
+
const SHAPE_DATA = { d: new Set(['path']), points: new Set(['polyline', 'polygon']) };
|
|
1254
|
+
const NON_NEGATIVE = new Set(['width', 'height', 'r', 'rx', 'ry']);
|
|
1255
|
+
/** What a `null` takes off: a box's rounded corners. */
|
|
1256
|
+
const CORNER_ATTRS = new Set(['rx', 'ry']);
|
|
1257
|
+
/** The drawn nodes of a diagram that have a geometry to write (a label's line moves with it). */
|
|
1258
|
+
const DIAGRAM_NODES = new Set(['rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'path', 'text', 'tspan', 'image', 'use', 'g', 'foreignobject']);
|
|
1259
|
+
/** A coordinate as a page may send it: a number, at most one decimal written. */
|
|
1260
|
+
const COORD = /^-?\d{1,6}(?:\.\d+)?$/;
|
|
1261
|
+
const MAX_COORD = 100000;
|
|
1262
|
+
|
|
1263
|
+
/** `v` as a coordinate, or NaN: a finite number (or the text of one) within reach of any diagram. */
|
|
1264
|
+
function coordOf(v) {
|
|
1265
|
+
const n = typeof v === 'number' ? v : (typeof v === 'string' && COORD.test(v.trim()) ? Number(v) : NaN);
|
|
1266
|
+
return Number.isFinite(n) && Math.abs(n) <= MAX_COORD ? n : NaN;
|
|
1267
|
+
}
|
|
1268
|
+
/** A coordinate as the file gets it: rounded to one decimal, no trailing `.0`, never `-0`. */
|
|
1269
|
+
export const formatCoord = (n) => {
|
|
1270
|
+
const r = Math.round(n * 10) / 10;
|
|
1271
|
+
return String(Object.is(r, -0) ? 0 : r);
|
|
1272
|
+
};
|
|
1273
|
+
|
|
1274
|
+
const LEADING_TRANSLATE = /^\s*translate\(\s*([^)]*)\)\s*/i;
|
|
1275
|
+
const TRANSLATE_VALUE = /^translate\(\s*(-?\d{1,6}(?:\.\d+)?)(?:\s*[\s,]\s*(-?\d{1,6}(?:\.\d+)?))?\s*\)$/;
|
|
1276
|
+
|
|
1277
|
+
/** The leading `translate()` of a `transform`, `{ x, y }` (0, 0 when it has none). */
|
|
1278
|
+
export function translateOf(transform) {
|
|
1279
|
+
const m = LEADING_TRANSLATE.exec(String(transform ?? ''));
|
|
1280
|
+
if (!m) return { x: 0, y: 0 };
|
|
1281
|
+
const [a = 0, b = 0] = m[1].split(/[\s,]+/).filter(Boolean).map(Number);
|
|
1282
|
+
return { x: Number.isFinite(a) ? a : 0, y: Number.isFinite(b) ? b : 0 };
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
/**
|
|
1286
|
+
* `transform` with its leading `translate()` made `translate(x y)`: replaced
|
|
1287
|
+
* where there is one (its comma kept when it had one), put in front of the
|
|
1288
|
+
* rest when there is none, so a `rotate()` or a `scale()` the author wrote is
|
|
1289
|
+
* never lost. A move back to (0, 0) takes the translate off; '' is no
|
|
1290
|
+
* transform left at all.
|
|
1291
|
+
*/
|
|
1292
|
+
export function withTranslate(transform, x, y) {
|
|
1293
|
+
const t = String(transform ?? '');
|
|
1294
|
+
const m = LEADING_TRANSLATE.exec(t);
|
|
1295
|
+
const rest = (m ? t.slice(m[0].length) : t).trim();
|
|
1296
|
+
const sep = m && m[1].includes(',') ? ', ' : ' ';
|
|
1297
|
+
const tr = x === 0 && y === 0 ? '' : `translate(${formatCoord(x)}${sep}${formatCoord(y)})`;
|
|
1298
|
+
return [tr, rest].filter(Boolean).join(' ');
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
// A wire's own geometry (SVG_DIAGRAMS, connectors): path data and a list of
|
|
1302
|
+
// points, each in a closed shape. Path data is absolute M, L, H, V, C, Q and
|
|
1303
|
+
// Z with numbers only (no arcs, no relative commands, no exponents), and is
|
|
1304
|
+
// written back in one canonical spelling, `M 10 20 L 30 40`, the spelling
|
|
1305
|
+
// the page routes in, so the file and the page agree byte for byte.
|
|
1306
|
+
const PATH_ARGS = { M: 2, L: 2, H: 1, V: 1, C: 6, Q: 4, Z: 0 };
|
|
1307
|
+
const MAX_PATH_COMMANDS = 200;
|
|
1308
|
+
const MAX_POINTS = 500;
|
|
1309
|
+
|
|
1310
|
+
/** Path data in its canonical spelling, or a refusal saying what it cannot be. */
|
|
1311
|
+
export function pathDataValue(value) {
|
|
1312
|
+
const src = String(value ?? '').trim();
|
|
1313
|
+
if (src.length > 6000 || !/^[MLHVCQZ\s\d.,-]*$/.test(src)) throw new Error(`path data is absolute M, L, H, V, C, Q and Z with numbers: ${src.slice(0, 40)}`);
|
|
1314
|
+
const tokens = src.match(/[MLHVCQZ]|-?\d+(?:\.\d+)?/g) ?? [];
|
|
1315
|
+
if (tokens.join('').length !== src.replace(/[\s,]/g, '').length) throw new Error(`not path data: ${src.slice(0, 40)}`);
|
|
1316
|
+
if (tokens[0] !== 'M') throw new Error('path data starts with M');
|
|
1317
|
+
const out = [];
|
|
1318
|
+
let cmd = null; let args = [];
|
|
1319
|
+
const flush = () => {
|
|
1320
|
+
if (!cmd) return;
|
|
1321
|
+
const n = PATH_ARGS[cmd];
|
|
1322
|
+
if (n === 0) { if (args.length) throw new Error('Z takes no numbers'); out.push('Z'); return; }
|
|
1323
|
+
if (!args.length || args.length % n) throw new Error(`${cmd} takes ${n} number${n === 1 ? '' : 's'} at a time`);
|
|
1324
|
+
for (let i = 0; i < args.length; i += n) out.push(`${cmd} ${args.slice(i, i + n).map(formatCoord).join(' ')}`);
|
|
1325
|
+
};
|
|
1326
|
+
for (const t of tokens) {
|
|
1327
|
+
if (t in PATH_ARGS) { flush(); cmd = t; args = []; continue; }
|
|
1328
|
+
const n = coordOf(t);
|
|
1329
|
+
if (!Number.isFinite(n)) throw new Error(`not a coordinate: ${t.slice(0, 20)}`);
|
|
1330
|
+
args.push(n);
|
|
1331
|
+
}
|
|
1332
|
+
flush();
|
|
1333
|
+
if (out.length > MAX_PATH_COMMANDS) throw new Error('too long a path');
|
|
1334
|
+
return out.join(' ');
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
/** A list of points in its canonical spelling, `x,y x,y`, or a refusal. */
|
|
1338
|
+
export function pointsValue(value) {
|
|
1339
|
+
const nums = String(value ?? '').trim().split(/[\s,]+/).filter(Boolean);
|
|
1340
|
+
if (nums.length < 4 || nums.length % 2 || nums.length > 2 * MAX_POINTS) throw new Error('points are pairs of numbers, two pairs at least');
|
|
1341
|
+
const n = nums.map(coordOf);
|
|
1342
|
+
if (n.some((v) => !Number.isFinite(v))) throw new Error(`not a list of coordinates: ${String(value).slice(0, 40)}`);
|
|
1343
|
+
const out = [];
|
|
1344
|
+
for (let i = 0; i < n.length; i += 2) out.push(`${formatCoord(n[i])},${formatCoord(n[i + 1])}`);
|
|
1345
|
+
return out.join(' ');
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
/** One geometry value as the file gets it, or a refusal naming what was sent. */
|
|
1349
|
+
function geometryValue(attr, value) {
|
|
1350
|
+
if (attr === 'd') return pathDataValue(value);
|
|
1351
|
+
// where a wire's label sits along it (SVG_DIAGRAMS): a fraction of its length
|
|
1352
|
+
if (attr === 'data-along') {
|
|
1353
|
+
const n = typeof value === 'number' ? value : Number(value);
|
|
1354
|
+
if (!Number.isFinite(n) || n < 0 || n > 1) throw new Error(`a label sits 0 to 1 along its wire, not: ${String(value).slice(0, 20)}`);
|
|
1355
|
+
return String(Math.round(n * 1000) / 1000);
|
|
1356
|
+
}
|
|
1357
|
+
if (attr === 'points') return pointsValue(value);
|
|
1358
|
+
if (attr === 'transform') {
|
|
1359
|
+
const m = TRANSLATE_VALUE.exec(String(value ?? '').trim());
|
|
1360
|
+
const x = m ? coordOf(m[1]) : NaN; const y = m ? coordOf(m[2] ?? '0') : NaN;
|
|
1361
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error(`a move is written as translate(x y), not: ${String(value).slice(0, 40)}`);
|
|
1362
|
+
return { x, y };
|
|
1363
|
+
}
|
|
1364
|
+
const n = coordOf(value);
|
|
1365
|
+
if (!Number.isFinite(n)) throw new Error(`not a coordinate: ${String(value).slice(0, 40)}`);
|
|
1366
|
+
if (NON_NEGATIVE.has(attr) && n < 0) throw new Error(`${attr} cannot be negative`);
|
|
1367
|
+
return formatCoord(n);
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
/**
|
|
1371
|
+
* Move or resize nodes of a diagram (SVG_DIAGRAMS): slide N's element
|
|
1372
|
+
* `index`, each edit `{ path, tag, attr, value }` addressed the way
|
|
1373
|
+
* setElementStyles addresses one, all of them ONE write (so `Z` takes a box
|
|
1374
|
+
* and the label that moved with it back in one press). `attr` is one of a
|
|
1375
|
+
* closed set, `x` `y` `width` `height` `cx` `cy` `r` `rx` `ry` `x1` `y1` `x2`
|
|
1376
|
+
* `y2` (a number, written to at most one decimal; a size never negative) or
|
|
1377
|
+
* `transform`, whose value is `translate(x y)`: the translate the node is to
|
|
1378
|
+
* have, which REPLACES a leading translate the file has and is put in front
|
|
1379
|
+
* of whatever else the transform says (a `rotate()` survives the move), and
|
|
1380
|
+
* `translate(0 0)` takes it off again. A connector's own geometry is `d` on a
|
|
1381
|
+
* path (pathDataValue) or `points` on a polyline or a polygon (pointsValue),
|
|
1382
|
+
* so a move re-routes the wires it drags along in the same write. Only nodes
|
|
1383
|
+
* inside an `<svg>` are written, and only the one attribute's text changes.
|
|
1384
|
+
* An edit `{ path, tag: 'text', was, lines }` writes a label's lines instead
|
|
1385
|
+
* (setElementLines): a resize that re-wraps the label on the shape it resized.
|
|
1386
|
+
*/
|
|
1387
|
+
export function setElementGeometry(html, slide, index, edits) {
|
|
1388
|
+
// several shapes moved together, their wires and labels with them, are one write (SVG_DIAGRAMS)
|
|
1389
|
+
if (!Array.isArray(edits) || !edits.length || edits.length > 600) throw new Error('bad edits');
|
|
1390
|
+
let e = openElement(html, slide, index);
|
|
1391
|
+
for (const ed of edits) {
|
|
1392
|
+
// a label re-wrapped by the resize of its shape: its lines, in the same write (SVG_DIAGRAMS)
|
|
1393
|
+
if (ed && Array.isArray(ed.lines)) {
|
|
1394
|
+
e = openElement(setElementLines(e.html(), slide, index, { path: ed.path, tag: ed.tag ?? 'text', was: ed.was, lines: ed.lines }), slide, index);
|
|
1395
|
+
continue;
|
|
1396
|
+
}
|
|
1397
|
+
if (!GEOMETRY_ATTRS.has(ed?.attr)) throw new Error(`not an attribute this server moves: ${String(ed?.attr).slice(0, 40)}`);
|
|
1398
|
+
// a box's corners squared again (Corners ▸ square): its rx and ry taken off
|
|
1399
|
+
if (ed.value === null && CORNER_ATTRS.has(ed.attr)) {
|
|
1400
|
+
e.edit(ed.path, ed.tag, (attrs, at) => {
|
|
1401
|
+
if (!at.inSvg || at.found !== 'rect') throw new Error(`only a box's corners are squared, not a <${at.found}>'s`);
|
|
1402
|
+
return withAttr(attrs, ed.attr, null);
|
|
1403
|
+
});
|
|
1404
|
+
continue;
|
|
1405
|
+
}
|
|
1406
|
+
const value = geometryValue(ed.attr, ed.value);
|
|
1407
|
+
e.edit(ed.path, ed.tag, (attrs, at) => {
|
|
1408
|
+
if (!at.inSvg || !DIAGRAM_NODES.has(at.found)) throw new Error(`not a node of a diagram: <${at.found}>`);
|
|
1409
|
+
if (SHAPE_DATA[ed.attr] && !SHAPE_DATA[ed.attr].has(at.found)) throw new Error(`a <${at.found}> has no ${ed.attr}`);
|
|
1410
|
+
return ed.attr === 'transform' ? withAttr(attrs, 'transform', withTranslate(attrOf(attrs, 'transform'), value.x, value.y) || null)
|
|
1411
|
+
: withAttr(attrs, ed.attr, value);
|
|
1412
|
+
});
|
|
1413
|
+
}
|
|
1414
|
+
return e.html();
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
// ── a copy, moved by a step ──────────────────────────────────────────────────
|
|
1418
|
+
|
|
1419
|
+
/** A list of numbers (`x="10 20"`), each moved by `d`; null when it is not one. */
|
|
1420
|
+
function shiftList(v, d) {
|
|
1421
|
+
if (v === null) return formatCoord(d);
|
|
1422
|
+
const nums = String(v).trim().split(/[\s,]+/);
|
|
1423
|
+
if (!nums.length || nums.some((n) => !COORD.test(n))) return null;
|
|
1424
|
+
return nums.map((n) => formatCoord(Number(n) + d)).join(' ');
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
/** `points` moved by (dx, dy), pair by pair; null when it is not a list of numbers. */
|
|
1428
|
+
export function shiftPoints(points, dx, dy) {
|
|
1429
|
+
const nums = String(points ?? '').trim().split(/[\s,]+/).filter(Boolean);
|
|
1430
|
+
if (!nums.length || nums.length % 2 || nums.some((n) => !COORD.test(n))) return null;
|
|
1431
|
+
const out = [];
|
|
1432
|
+
for (let i = 0; i < nums.length; i += 2) out.push(`${formatCoord(Number(nums[i]) + dx)},${formatCoord(Number(nums[i + 1]) + dy)}`);
|
|
1433
|
+
return out.join(' ');
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
/**
|
|
1437
|
+
* A path's `d` moved by (dx, dy): every ABSOLUTE coordinate shifted (an arc's
|
|
1438
|
+
* radii and flags, and relative commands, are not positions), the first
|
|
1439
|
+
* moveto included even when it is relative, since it is taken from the
|
|
1440
|
+
* origin. Null when `d` holds something this does not read.
|
|
1441
|
+
*/
|
|
1442
|
+
export function shiftPathData(d, dx, dy) {
|
|
1443
|
+
const src = String(d ?? '');
|
|
1444
|
+
if (!/^\s*[mM]/.test(src)) return null;
|
|
1445
|
+
// per command, which of its numbers are x (1) and y (2) when absolute
|
|
1446
|
+
const ROLE = { M: [1, 2], L: [1, 2], T: [1, 2], H: [1], V: [2], C: [1, 2, 1, 2, 1, 2], S: [1, 2, 1, 2], Q: [1, 2, 1, 2], A: [0, 0, 0, 0, 0, 1, 2], Z: [] };
|
|
1447
|
+
let cmd = null; let k = 0; let first = true; let bad = false;
|
|
1448
|
+
// each number replaced where it stands, so the path keeps its own spacing
|
|
1449
|
+
const out = src.replace(/[a-zA-Z]|-?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g, (t) => {
|
|
1450
|
+
if (/^[a-zA-Z]$/.test(t)) {
|
|
1451
|
+
if (!(t.toUpperCase() in ROLE)) bad = true;
|
|
1452
|
+
cmd = t; k = 0;
|
|
1453
|
+
return t;
|
|
1454
|
+
}
|
|
1455
|
+
const roles = cmd && ROLE[cmd.toUpperCase()];
|
|
1456
|
+
if (!roles?.length) { bad = true; return t; }
|
|
1457
|
+
const role = roles[k % roles.length];
|
|
1458
|
+
const absolute = cmd === cmd.toUpperCase() || (first && cmd === 'm' && k < 2);
|
|
1459
|
+
k++;
|
|
1460
|
+
if (k >= 2 && /^m$/i.test(cmd)) first = false;
|
|
1461
|
+
const by = !absolute ? 0 : role === 1 ? dx : role === 2 ? dy : 0;
|
|
1462
|
+
return by ? formatCoord(Number(t) + by) : t;
|
|
1463
|
+
});
|
|
1464
|
+
return bad || /[^\s\d.,eE+\-a-zA-Z]/.test(src) ? null : out;
|
|
1465
|
+
}
|
|
1466
|
+
|
|
1467
|
+
/**
|
|
1468
|
+
* A node's source moved by (dx, dy), in the geometry it already uses: `x`/`y`
|
|
1469
|
+
* on a rect, text, image, use; `cx`/`cy` on a circle or an ellipse; the two
|
|
1470
|
+
* ends of a line; a leading translate on a group, a path, a polygon. A BUILD
|
|
1471
|
+
* STEP owns its transform (the build's CSS sets it while it plays, and a
|
|
1472
|
+
* transform it writes would be overridden), so one that would move by a
|
|
1473
|
+
* translate moves what it holds instead: a group's children each by their
|
|
1474
|
+
* own geometry, a polygon's points, a path's coordinates.
|
|
1475
|
+
*/
|
|
1476
|
+
function shiftSource(src, dx, dy, { step = false } = {}) {
|
|
1477
|
+
const tag = /^<([a-zA-Z][\w:-]*)/.exec(src)?.[1]?.toLowerCase();
|
|
1478
|
+
const { attrs, close, rest } = splitOpenTag(src);
|
|
1479
|
+
const set = (head, pairs) => pairs.reduce((h, [name, d]) => {
|
|
1480
|
+
const moved = shiftList(attrOf(h, name), d);
|
|
1481
|
+
if (moved === null) throw new Error(`<${tag}> has a ${name} this cannot move`);
|
|
1482
|
+
return withAttr(h, name, moved);
|
|
1483
|
+
}, head);
|
|
1484
|
+
const translate = (head) => {
|
|
1485
|
+
const t = attrOf(head, 'transform');
|
|
1486
|
+
const { x, y } = translateOf(t);
|
|
1487
|
+
return withAttr(head, 'transform', withTranslate(t, x + dx, y + dy) || null);
|
|
1488
|
+
};
|
|
1489
|
+
if (['rect', 'image', 'use', 'foreignobject'].includes(tag)) return set(attrs, [['x', dx], ['y', dy]]) + close + rest;
|
|
1490
|
+
if (tag === 'circle' || tag === 'ellipse') return set(attrs, [['cx', dx], ['cy', dy]]) + close + rest;
|
|
1491
|
+
if (tag === 'line') return set(attrs, [['x1', dx], ['y1', dy], ['x2', dx], ['y2', dy]]) + close + rest;
|
|
1492
|
+
if (tag === 'text' || tag === 'tspan') {
|
|
1493
|
+
// a label's lines that are placed themselves move with it
|
|
1494
|
+
const inner = rest.replace(/<tspan\b[^>]*>/gi, (open) => {
|
|
1495
|
+
let o = open;
|
|
1496
|
+
for (const [name, d] of [['x', dx], ['y', dy]]) {
|
|
1497
|
+
if (attrOf(o, name) === null) continue;
|
|
1498
|
+
const moved = shiftList(attrOf(o, name), d);
|
|
1499
|
+
if (moved === null) throw new Error(`a line of this label has a ${name} this cannot move`);
|
|
1500
|
+
o = withAttr(o, name, moved);
|
|
1501
|
+
}
|
|
1502
|
+
return o;
|
|
1503
|
+
});
|
|
1504
|
+
return set(attrs, [['x', dx], ['y', dy]]) + close + inner;
|
|
1505
|
+
}
|
|
1506
|
+
if (!step) return translate(attrs) + close + rest;
|
|
1507
|
+
if (tag === 'polygon' || tag === 'polyline') {
|
|
1508
|
+
const pts = shiftPoints(attrOf(attrs, 'points'), dx, dy);
|
|
1509
|
+
if (pts === null) throw new Error(`<${tag}> has points this cannot move`);
|
|
1510
|
+
return withAttr(attrs, 'points', pts) + close + rest;
|
|
1511
|
+
}
|
|
1512
|
+
if (tag === 'path') {
|
|
1513
|
+
const d = shiftPathData(attrOf(attrs, 'd'), dx, dy);
|
|
1514
|
+
if (d === null) throw new Error('<path> has a d this cannot move');
|
|
1515
|
+
return withAttr(attrs, 'd', d) + close + rest;
|
|
1516
|
+
}
|
|
1517
|
+
if (tag === 'g' || tag === 'a') {
|
|
1518
|
+
let out = src;
|
|
1519
|
+
// from the last child back, so the offsets before each are still good
|
|
1520
|
+
for (const kid of elementChildRanges(src).reverse()) {
|
|
1521
|
+
out = out.slice(0, kid.start) + shiftSource(out.slice(kid.start, kid.end), dx, dy) + out.slice(kid.end);
|
|
1522
|
+
}
|
|
1523
|
+
return out;
|
|
1524
|
+
}
|
|
1525
|
+
throw new Error(`<${tag}> cannot be moved`);
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
/** A copy's markup with every `id` taken off: two nodes with one id would be one target for every `url(#…)`. */
|
|
1529
|
+
const withoutIds = (src) => src.replace(/<[a-zA-Z][^<>]*>/g, (open) => attrList(open.replace(/\/?>$/, '')).filter((a) => a.name === 'id')
|
|
1530
|
+
.reverse().reduce((o, a) => o.slice(0, a.start) + o.slice(a.end), open));
|
|
1531
|
+
|
|
1532
|
+
// ── the markup the server owns for each kind of new shape ───────────────────
|
|
1533
|
+
|
|
1534
|
+
/** An svg's coordinate box: its viewBox, else its width and height, else 800 × 450. */
|
|
1535
|
+
function viewBoxOf(svgAttrs) {
|
|
1536
|
+
const vb = String(attrOf(svgAttrs, 'viewbox') ?? '').trim().split(/[\s,]+/).map(Number);
|
|
1537
|
+
if (vb.length === 4 && vb.every(Number.isFinite) && vb[2] > 0 && vb[3] > 0) return { x: vb[0], y: vb[1], w: vb[2], h: vb[3] };
|
|
1538
|
+
const w = parseFloat(attrOf(svgAttrs, 'width')); const h = parseFloat(attrOf(svgAttrs, 'height'));
|
|
1539
|
+
return { x: 0, y: 0, w: w > 0 ? w : 800, h: h > 0 ? h : 450 };
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
const NOT_DRAWN = new Set(['defs', 'marker', 'mask', 'clippath', 'pattern', 'symbol', 'lineargradient', 'radialgradient', 'filter', 'style', 'title', 'desc', 'metadata', 'animate', 'animatemotion', 'animatetransform', 'set']);
|
|
1543
|
+
|
|
1544
|
+
/** Every node an svg's source draws, in paint order: `{ tag, attrs, src, start, end, path, at }`, `at` the translate it sits under. */
|
|
1545
|
+
function drawnNodes(svgSrc) {
|
|
1546
|
+
const out = [];
|
|
1547
|
+
const walk = (src, base, path, at) => {
|
|
1548
|
+
elementChildRanges(src).forEach((k, i) => {
|
|
1549
|
+
const s = src.slice(k.start, k.end);
|
|
1550
|
+
const tag = k.tag;
|
|
1551
|
+
if (NOT_DRAWN.has(tag)) return;
|
|
1552
|
+
const { attrs } = splitOpenTag(s);
|
|
1553
|
+
const t = translateOf(attrOf(attrs, 'transform'));
|
|
1554
|
+
const node = { tag, attrs, src: s, start: base + k.start, end: base + k.end, path: [...path, i], at };
|
|
1555
|
+
out.push(node);
|
|
1556
|
+
if (tag === 'g' || tag === 'a') walk(s, base + k.start, [...path, i], { x: at.x + t.x, y: at.y + t.y });
|
|
1557
|
+
});
|
|
1558
|
+
};
|
|
1559
|
+
walk(svgSrc, 0, [], { x: 0, y: 0 });
|
|
1560
|
+
return out;
|
|
1561
|
+
}
|
|
1562
|
+
|
|
1563
|
+
const num = (attrs, name, dflt = 0) => { const v = parseFloat(attrOf(attrs, name)); return Number.isFinite(v) ? v : dflt; };
|
|
1564
|
+
/** Where a node's middle is, in the svg's coordinates (its group translates added). */
|
|
1565
|
+
function middleOf(n) {
|
|
1566
|
+
const a = n.attrs; const t = translateOf(attrOf(a, 'transform'));
|
|
1567
|
+
const at = { x: n.at.x + t.x, y: n.at.y + t.y };
|
|
1568
|
+
switch (n.tag) {
|
|
1569
|
+
case 'rect': case 'image': case 'use': return { x: at.x + num(a, 'x') + num(a, 'width') / 2, y: at.y + num(a, 'y') + num(a, 'height') / 2 };
|
|
1570
|
+
case 'circle': case 'ellipse': return { x: at.x + num(a, 'cx'), y: at.y + num(a, 'cy') };
|
|
1571
|
+
case 'line': return { x: at.x + (num(a, 'x1') + num(a, 'x2')) / 2, y: at.y + (num(a, 'y1') + num(a, 'y2')) / 2 };
|
|
1572
|
+
case 'text': return { x: at.x + num(a, 'x'), y: at.y + num(a, 'y') };
|
|
1573
|
+
case 'polygon': case 'path': {
|
|
1574
|
+
const b = shapeBox(n.tag === 'path' ? 'd' : 'points', attrOf(a, n.tag === 'path' ? 'd' : 'points'));
|
|
1575
|
+
return b ? { x: at.x + b.x + b.w / 2, y: at.y + b.y + b.h / 2 } : null;
|
|
1576
|
+
}
|
|
1577
|
+
default: return null;
|
|
1578
|
+
}
|
|
1579
|
+
}
|
|
1580
|
+
/** The node of `list` nearest `at` (the last one when there is no `at`), or null. */
|
|
1581
|
+
function nearest(list, at) {
|
|
1582
|
+
if (!list.length) return null;
|
|
1583
|
+
if (!at) return list.at(-1);
|
|
1584
|
+
let best = null; let d = Infinity;
|
|
1585
|
+
for (const n of list) {
|
|
1586
|
+
const m = n.middle ?? middleOf(n);
|
|
1587
|
+
if (!m) continue;
|
|
1588
|
+
const e = Math.hypot(m.x - at.x, m.y - at.y);
|
|
1589
|
+
if (e < d) { d = e; best = n; }
|
|
1590
|
+
}
|
|
1591
|
+
return best ?? list.at(-1);
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
/** Attributes not copied from a model onto a new shape: who it is, where it is, which build and concept it belongs to. */
|
|
1595
|
+
const NOT_COPIED = /^(?:id|transform|x|y|x1|y1|x2|y2|cx|cy|dx|dy|points|d|data-build.*|data-concept|data-draw-.*|data-ds-.*|data-nest-fill|data-node|data-from|data-to|data-route|aria-.*|role)$/;
|
|
1596
|
+
/**
|
|
1597
|
+
* An open tag for `tag` written like `modelAttrs`: its attributes that are
|
|
1598
|
+
* look, not place, in its order, with `place` (where the new node is) put
|
|
1599
|
+
* where the model has those attributes and after them otherwise; a `place`
|
|
1600
|
+
* value of null leaves the model's out.
|
|
1601
|
+
*/
|
|
1602
|
+
function openTag(tag, modelAttrs, place) {
|
|
1603
|
+
let head = `<${tag}`;
|
|
1604
|
+
const used = new Set();
|
|
1605
|
+
for (const a of modelAttrs ? attrList(modelAttrs) : []) {
|
|
1606
|
+
if (a.name in place) {
|
|
1607
|
+
used.add(a.name);
|
|
1608
|
+
if (place[a.name] !== null) head += ` ${a.written}="${escapeHtml(place[a.name])}"`;
|
|
1609
|
+
continue;
|
|
1610
|
+
}
|
|
1611
|
+
if (NOT_COPIED.test(a.name)) continue;
|
|
1612
|
+
head += a.raw === null ? ` ${a.written}` : ` ${a.written}=${a.raw}`;
|
|
1613
|
+
}
|
|
1614
|
+
for (const [k, v] of Object.entries(place)) if (!used.has(k) && v !== null && v !== undefined) head += ` ${k}="${escapeHtml(v)}"`;
|
|
1615
|
+
return head;
|
|
1616
|
+
}
|
|
1617
|
+
|
|
1618
|
+
const ARROW_ID = 'dl-arrow';
|
|
1619
|
+
/** The shipped arrowhead (SVG_DIAGRAMS, Arrowheads), in the diagram's ink. */
|
|
1620
|
+
const arrowMarker = (id, orient = 'auto') => `<marker id="${id}" markerWidth="6" markerHeight="4" refX="5" refY="2" orient="${orient}"><polygon points="0 0, 6 2, 0 4" style="fill: var(--d-stroke)"/></marker>`;
|
|
1621
|
+
|
|
1622
|
+
/** Every `<marker>` an svg's source defines: `{ id, orient }`. */
|
|
1623
|
+
function markersIn(svgSrc) {
|
|
1624
|
+
return [...svgSrc.matchAll(/<marker\b[^>]*>/gi)].map((m) => {
|
|
1625
|
+
const head = m[0].replace(/\/?>$/, '');
|
|
1626
|
+
return { id: attrOf(head, 'id'), orient: String(attrOf(head, 'orient') ?? '').trim() };
|
|
1627
|
+
}).filter((m) => m.id);
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
/**
|
|
1631
|
+
* The arrowhead a wire in this svg ends in, as `url(#id)`: `prefer` (the
|
|
1632
|
+
* model's own) when there is one, else the marker another wire of the
|
|
1633
|
+
* diagram ends in, else the first the svg defines, else the shipped one,
|
|
1634
|
+
* added to its `<defs>` (`defs` says where). `start` asks for a head at a
|
|
1635
|
+
* wire's START: a marker oriented `auto-start-reverse` (the shipped one so
|
|
1636
|
+
* oriented when the svg has none), so it points away from the line.
|
|
1637
|
+
*/
|
|
1638
|
+
function arrowheadFor(svgSrc, lay, path, { prefer = null, start = false } = {}) {
|
|
1639
|
+
const markers = markersIn(svgSrc);
|
|
1640
|
+
let id = null;
|
|
1641
|
+
if (start) id = markers.find((m) => m.orient === 'auto-start-reverse')?.id ?? null;
|
|
1642
|
+
else {
|
|
1643
|
+
if (prefer) return { svgSrc, defs: null, marker: prefer };
|
|
1644
|
+
const used = /\smarker-end\s*=\s*["']\s*url\(\s*#([^)'"\s]+)\s*\)/i.exec(svgSrc)?.[1];
|
|
1645
|
+
id = (used && markers.some((m) => m.id === used) ? used : null) ?? markers[0]?.id ?? null;
|
|
1646
|
+
}
|
|
1647
|
+
if (id) return { svgSrc, defs: null, marker: `url(#${id})` };
|
|
1648
|
+
const taken = new Set([...svgSrc.matchAll(/\sid\s*=\s*["']([^"']+)["']/gi)].map((m) => m[1]));
|
|
1649
|
+
const base = start ? `${ARROW_ID}-start` : ARROW_ID;
|
|
1650
|
+
id = base;
|
|
1651
|
+
for (let k = 2; taken.has(id); k++) id = `${base}-${k}`;
|
|
1652
|
+
const out = withMarker(svgSrc, arrowMarker(id, start ? 'auto-start-reverse' : 'auto'), lay, path);
|
|
1653
|
+
return { svgSrc: out.svgSrc, defs: out.defs, marker: `url(#${id})` };
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
/** `markup` put last in the svg, on a line of its own at its siblings' indentation: the svg's source, and the new child's index. */
|
|
1657
|
+
function appendToSvg(svgSrc, markup, lay, svgIndent) {
|
|
1658
|
+
const kids = elementChildRanges(svgSrc);
|
|
1659
|
+
const last = kids.at(-1);
|
|
1660
|
+
const where = last ? last.end : svgSrc.toLowerCase().lastIndexOf('</svg');
|
|
1661
|
+
const lead = lay.lines ? `\n${lay.indent}` : '';
|
|
1662
|
+
const trail = !last && lay.lines ? `\n${svgIndent}` : '';
|
|
1663
|
+
return { svgSrc: svgSrc.slice(0, where) + lead + markup + trail + svgSrc.slice(where), index: kids.length };
|
|
1664
|
+
}
|
|
1665
|
+
|
|
1666
|
+
/** The indentation of the line the svg at `at` starts on, read in the slide (the svg may be the element itself). */
|
|
1667
|
+
const svgIndentOf = (e, at) => /^[ \t]*/.exec(e.lead(at))[0];
|
|
1668
|
+
|
|
1669
|
+
/** How the svg's children are laid out: on their own lines (and how far in), or all on one. */
|
|
1670
|
+
function layoutOf(svgSrc, svgLineIndent) {
|
|
1671
|
+
const kids = elementChildRanges(svgSrc);
|
|
1672
|
+
const indentAt = (at) => {
|
|
1673
|
+
const ls = svgSrc.lastIndexOf('\n', at - 1);
|
|
1674
|
+
const lead = svgSrc.slice(ls + 1, at);
|
|
1675
|
+
return ls >= 0 && /^[ \t]*$/.test(lead) ? lead : null;
|
|
1676
|
+
};
|
|
1677
|
+
const kid = kids.find((k) => indentAt(k.start) !== null);
|
|
1678
|
+
const indent = kid ? indentAt(kid.start) : null;
|
|
1679
|
+
const lines = indent !== null;
|
|
1680
|
+
const unit = lines && indent.startsWith(svgLineIndent) && indent.length > svgLineIndent.length ? indent.slice(svgLineIndent.length) : ' ';
|
|
1681
|
+
return { kids, lines, indent: lines ? indent : `${svgLineIndent} `, unit };
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
/**
|
|
1685
|
+
* Add a shape to a diagram (SVG_DIAGRAMS): the `<svg>` at `path` below slide
|
|
1686
|
+
* N's element `index` gets, as its last child, one of four kinds whose markup
|
|
1687
|
+
* this server owns, centred on `at` (the svg's own coordinates; its viewBox
|
|
1688
|
+
* centre without one):
|
|
1689
|
+
*
|
|
1690
|
+
* box a group of a rect and a centred label, the way the nearest box
|
|
1691
|
+
* in this diagram is written when it has one (its look, not its
|
|
1692
|
+
* place, its concept or its build), else in theme tokens only
|
|
1693
|
+
* ellipse likewise from the nearest ellipse
|
|
1694
|
+
* label a text, from the nearest label
|
|
1695
|
+
* line a line ending in an arrowhead: the marker the svg already
|
|
1696
|
+
* defines, or the shipped one added to its `<defs>`
|
|
1697
|
+
* diamond, hexagon, cylinder, document, note, cloud
|
|
1698
|
+
* a group of one shape marked `data-shape` (its geometry from
|
|
1699
|
+
* shapeGeometry, tools/diagram-shapes.mjs) and a centred label,
|
|
1700
|
+
* the look and the size of the nearest of its kind, else of the
|
|
1701
|
+
* nearest box, else theme tokens
|
|
1702
|
+
*
|
|
1703
|
+
* Returns `{ html, added: { path, html }, defs }`: the deck, the new node's
|
|
1704
|
+
* path and markup (the page puts the same node on the slide), and, when an
|
|
1705
|
+
* arrowhead had to be added, where (`{ path, html, created }`: a new
|
|
1706
|
+
* `<defs>`, or a marker appended to the one there).
|
|
1707
|
+
*/
|
|
1708
|
+
export const SHAPE_KINDS = ['box', 'ellipse', 'label', 'line', ...Object.keys(SHAPES)];
|
|
1709
|
+
export function addDiagramShape(html, slide, index, { path, tag = 'svg', kind, at = null }) {
|
|
1710
|
+
if (!SHAPE_KINDS.includes(kind)) throw new Error(`not a shape this server adds: ${String(kind).slice(0, 20)}`);
|
|
1711
|
+
if (at !== null && (typeof at !== 'object' || !Number.isFinite(coordOf(at.x)) || !Number.isFinite(coordOf(at.y)))) throw new Error('bad position');
|
|
1712
|
+
const e = openElement(html, slide, index);
|
|
1713
|
+
const node = e.at(path, tag);
|
|
1714
|
+
if (node.found !== 'svg') throw new Error(`shapes are added to a diagram's <svg>, not a <${node.found}>`);
|
|
1715
|
+
let svgSrc = e.src(node);
|
|
1716
|
+
const { attrs: svgAttrs, close: svgClose } = splitOpenTag(svgSrc);
|
|
1717
|
+
if (svgClose.endsWith('/>')) throw new Error('this <svg> is empty and self-closed: give it a closing tag first');
|
|
1718
|
+
if (/\sdata-chart\b/i.test(svgAttrs)) throw new Error('a chart draws itself from its data');
|
|
1719
|
+
const vb = viewBoxOf(svgAttrs);
|
|
1720
|
+
const c = at ? { x: coordOf(at.x), y: coordOf(at.y) } : { x: vb.x + vb.w / 2, y: vb.y + vb.h / 2 };
|
|
1721
|
+
const f = formatCoord;
|
|
1722
|
+
// the svg's own indentation, read in the slide (the svg may be the element itself)
|
|
1723
|
+
const svgIndent = svgIndentOf(e, node);
|
|
1724
|
+
const lay = layoutOf(svgSrc, svgIndent);
|
|
1725
|
+
const drawn = drawnNodes(svgSrc);
|
|
1726
|
+
const inner = lay.lines ? `\n${lay.indent}${lay.unit}` : '';
|
|
1727
|
+
const outer = lay.lines ? `\n${lay.indent}` : '';
|
|
1728
|
+
let markup;
|
|
1729
|
+
let defs = null;
|
|
1730
|
+
// a box group: one shape and its labels; `which` says what the shape must be
|
|
1731
|
+
const boxGroups = (which) => drawn.filter((n) => n.tag === 'g').map((g) => {
|
|
1732
|
+
const kids = drawnNodes(g.src).filter((k) => k.path.length === 1);
|
|
1733
|
+
const shapes = kids.filter((k) => k.tag !== 'text'); const texts = kids.filter((k) => k.tag === 'text');
|
|
1734
|
+
if (shapes.length !== 1 || !texts.length || !which(shapes[0])) return null;
|
|
1735
|
+
const rect = { ...shapes[0], at: { x: 0, y: 0 } };
|
|
1736
|
+
const m = middleOf(rect);
|
|
1737
|
+
if (!m) return null;
|
|
1738
|
+
const t = translateOf(attrOf(g.attrs, 'transform'));
|
|
1739
|
+
return { g, rect, text: texts[0], middle: { x: g.at.x + t.x + m.x, y: g.at.y + t.y + m.y }, local: m };
|
|
1740
|
+
}).filter(Boolean);
|
|
1741
|
+
const isBox = (k) => k.tag === 'rect';
|
|
1742
|
+
if (Object.hasOwn(SHAPES, kind)) {
|
|
1743
|
+
// the nearest of its kind gives its look and its size; else the nearest box its look, its size kept to its height
|
|
1744
|
+
const own = nearest(boxGroups((k) => attrOf(k.attrs, 'data-shape') === kind), at && c);
|
|
1745
|
+
const model = own ?? nearest(boxGroups(isBox), at && c);
|
|
1746
|
+
const sized = own ? shapeBox(SHAPES[kind] === 'path' ? 'd' : 'points', attrOf(own.rect.attrs, SHAPES[kind] === 'path' ? 'd' : 'points')) : null;
|
|
1747
|
+
const w = sized?.w ?? (model ? num(model.rect.attrs, 'width', 160) : Math.round(vb.w * 0.2));
|
|
1748
|
+
const h = sized?.h ?? (model ? num(model.rect.attrs, 'height', 64) : Math.round(w * 0.5));
|
|
1749
|
+
const geom = shapeGeometry(kind, { x: c.x - w / 2, y: c.y - h / 2, w, h });
|
|
1750
|
+
const drop = { x: null, y: null, width: null, height: null, rx: null, ry: null, points: null, d: null };
|
|
1751
|
+
const shape = model
|
|
1752
|
+
? openTag(geom.tag, model.rect.attrs, { ...drop, 'data-shape': kind, [geom.attr]: geom.value })
|
|
1753
|
+
: openTag(geom.tag, null, { 'data-shape': kind, [geom.attr]: geom.value, style: 'fill: var(--d-fill-1); stroke: var(--d-stroke)', 'stroke-width': '2' });
|
|
1754
|
+
const label = labelModel(drawn, c);
|
|
1755
|
+
const text = model
|
|
1756
|
+
? openTag('text', model.text.attrs, { x: f(c.x), y: f(c.y) })
|
|
1757
|
+
: openTag('text', label?.attrs ?? null, { x: f(c.x), y: f(c.y), 'text-anchor': 'middle', 'dominant-baseline': 'central',
|
|
1758
|
+
...(label ? {} : { 'font-size': f(Math.max(8, Math.round(h * 0.3))), style: 'fill: var(--d-text)' }) });
|
|
1759
|
+
const g = model ? openTag('g', model.g.attrs, {}) : '<g';
|
|
1760
|
+
markup = `${g}>${inner}${shape}/>${inner}${text}>${SHAPE_LABELS[kind]}</text>${outer}</g>`;
|
|
1761
|
+
} else if (kind === 'box') {
|
|
1762
|
+
// a box is a group holding one rect and its labels
|
|
1763
|
+
const boxes = boxGroups(isBox);
|
|
1764
|
+
const model = nearest(boxes, at && c);
|
|
1765
|
+
const w = model ? num(model.rect.attrs, 'width', 160) : Math.round(vb.w * 0.2);
|
|
1766
|
+
const h = model ? num(model.rect.attrs, 'height', 64) : Math.round(w * 0.4);
|
|
1767
|
+
const rect = model
|
|
1768
|
+
? openTag('rect', model.rect.attrs, { x: f(c.x - w / 2), y: f(c.y - h / 2), width: f(w), height: f(h) })
|
|
1769
|
+
: openTag('rect', null, { x: f(c.x - w / 2), y: f(c.y - h / 2), width: f(w), height: f(h), rx: f(Math.round(h * 0.15)),
|
|
1770
|
+
style: 'fill: var(--d-fill-1); stroke: var(--d-stroke)', 'stroke-width': '2' });
|
|
1771
|
+
// the label sits where the model's sits on its box: its centre, usually
|
|
1772
|
+
const off = model ? { x: num(model.text.attrs, 'x') - model.local.x, y: num(model.text.attrs, 'y') - model.local.y } : { x: 0, y: 0 };
|
|
1773
|
+
const label = labelModel(drawn, c);
|
|
1774
|
+
const text = model
|
|
1775
|
+
? openTag('text', model.text.attrs, { x: f(c.x + off.x), y: f(c.y + off.y) })
|
|
1776
|
+
: openTag('text', label?.attrs ?? null, { x: f(c.x), y: f(c.y), 'text-anchor': 'middle', 'dominant-baseline': 'central',
|
|
1777
|
+
...(label ? {} : { 'font-size': f(Math.max(8, Math.round(h * 0.3))), style: 'fill: var(--d-text)' }) });
|
|
1778
|
+
const g = model ? openTag('g', model.g.attrs, {}) : '<g';
|
|
1779
|
+
markup = `${g}>${inner}${rect}/>${inner}${text}>Box</text>${outer}</g>`;
|
|
1780
|
+
} else if (kind === 'ellipse') {
|
|
1781
|
+
const model = nearest(drawn.filter((n) => n.tag === 'ellipse'), at && c);
|
|
1782
|
+
const rx = model ? num(model.attrs, 'rx', 70) : Math.round(vb.w * 0.09);
|
|
1783
|
+
const ry = model ? num(model.attrs, 'ry', 40) : Math.round(rx * 0.6);
|
|
1784
|
+
markup = (model ? openTag('ellipse', model.attrs, { cx: f(c.x), cy: f(c.y), rx: f(rx), ry: f(ry) })
|
|
1785
|
+
: openTag('ellipse', null, { cx: f(c.x), cy: f(c.y), rx: f(rx), ry: f(ry), style: 'fill: var(--d-fill-2); stroke: var(--d-stroke)', 'stroke-width': '2' })) + '/>';
|
|
1786
|
+
} else if (kind === 'label') {
|
|
1787
|
+
const model = labelModel(drawn, c);
|
|
1788
|
+
markup = `${model ? openTag('text', model.attrs, { x: f(c.x), y: f(c.y) })
|
|
1789
|
+
: openTag('text', null, { x: f(c.x), y: f(c.y), 'text-anchor': 'middle', 'dominant-baseline': 'central', 'font-size': f(Math.max(8, Math.round(vb.w * 0.025))), style: 'fill: var(--d-text)' })}>Label</text>`;
|
|
1790
|
+
} else {
|
|
1791
|
+
const model = nearest(drawn.filter((n) => n.tag === 'line'), at && c);
|
|
1792
|
+
const half = model ? Math.max(10, Math.hypot(num(model.attrs, 'x2') - num(model.attrs, 'x1'), num(model.attrs, 'y2') - num(model.attrs, 'y1')) / 2) : Math.round(vb.w * 0.075);
|
|
1793
|
+
// the arrowhead the diagram already has, else the shipped one in its <defs>
|
|
1794
|
+
let marker;
|
|
1795
|
+
({ svgSrc, defs, marker } = arrowheadFor(svgSrc, lay, path, { prefer: model && attrOf(model.attrs, 'marker-end') }));
|
|
1796
|
+
markup = `${model ? openTag('line', model.attrs, { x1: f(c.x - half), y1: f(c.y), x2: f(c.x + half), y2: f(c.y), 'marker-end': marker })
|
|
1797
|
+
: openTag('line', null, { x1: f(c.x - half), y1: f(c.y), x2: f(c.x + half), y2: f(c.y), 'stroke-width': '2', style: 'stroke: var(--d-stroke)', 'marker-end': marker })}/>`;
|
|
1798
|
+
}
|
|
1799
|
+
// a diagram whose builds were frozen (front and back stamps every step) plays
|
|
1800
|
+
// its steps by key: a new one takes the next, so it arrives last, not mid-order
|
|
1801
|
+
if (/\sdata-build-order\s*=/i.test(svgSrc)) {
|
|
1802
|
+
const { parts, idx } = locateSlide(html, slide);
|
|
1803
|
+
const keys = [...parts[idx].matchAll(/\sdata-build-order\s*=\s*["']?(\d+)/gi)].map((m) => Number(m[1]));
|
|
1804
|
+
const head = /^<[a-z]+/i.exec(markup)[0];
|
|
1805
|
+
markup = `${head} data-build-order="${Math.max(0, ...keys) + 1}"${markup.slice(head.length)}`;
|
|
1806
|
+
}
|
|
1807
|
+
// last in the svg, on a line of its own at its siblings' indentation
|
|
1808
|
+
let at2;
|
|
1809
|
+
({ svgSrc, index: at2 } = appendToSvg(svgSrc, markup, lay, svgIndent));
|
|
1810
|
+
e.splice(node.start, node.end, svgSrc);
|
|
1811
|
+
return { html: e.html(), added: { path: [...path, at2], html: markup }, defs };
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
/** The label a new one is written like: the nearest text, its look kept. */
|
|
1815
|
+
function labelModel(drawn, c) {
|
|
1816
|
+
return nearest(drawn.filter((n) => n.tag === 'text'), c);
|
|
1817
|
+
}
|
|
1818
|
+
|
|
1819
|
+
/** `svgSrc` with `marker` in its `<defs>` (one made first when it has none), and where it went. */
|
|
1820
|
+
function withMarker(svgSrc, marker, lay, path) {
|
|
1821
|
+
const kids = elementChildRanges(svgSrc);
|
|
1822
|
+
const i = kids.findIndex((k) => k.tag === 'defs');
|
|
1823
|
+
if (i >= 0) {
|
|
1824
|
+
const k = kids[i];
|
|
1825
|
+
const d = svgSrc.slice(k.start, k.end);
|
|
1826
|
+
const { attrs, close } = splitOpenTag(d);
|
|
1827
|
+
if (close.endsWith('/>')) {
|
|
1828
|
+
const full = `${attrs}>${marker}</defs>`;
|
|
1829
|
+
return { svgSrc: svgSrc.slice(0, k.start) + full + svgSrc.slice(k.end), defs: { path: [...path, i], html: full, created: true, replaced: true } };
|
|
1830
|
+
}
|
|
1831
|
+
const n = elementChildRanges(d).length;
|
|
1832
|
+
const at = d.toLowerCase().lastIndexOf('</defs');
|
|
1833
|
+
const multi = /\n[ \t]*$/.test(d.slice(0, at));
|
|
1834
|
+
const ins = multi ? `${lay.unit}${marker}\n${lay.indent}` : marker;
|
|
1835
|
+
const into = multi ? d.slice(0, at) + ins + d.slice(at) : d.slice(0, at) + marker + d.slice(at);
|
|
1836
|
+
return { svgSrc: svgSrc.slice(0, k.start) + into + svgSrc.slice(k.end), defs: { path: [...path, i, n], html: marker, created: false } };
|
|
1837
|
+
}
|
|
1838
|
+
const full = `<defs>${marker}</defs>`;
|
|
1839
|
+
const first = kids[0];
|
|
1840
|
+
const at = first ? first.start : svgSrc.toLowerCase().lastIndexOf('</svg');
|
|
1841
|
+
const sep = lay.lines ? `\n${lay.indent}` : '';
|
|
1842
|
+
const ins = first ? full + sep : sep + full;
|
|
1843
|
+
return { svgSrc: svgSrc.slice(0, at) + ins + svgSrc.slice(at), defs: { path: [...path, 0], html: full, created: true } };
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
/**
|
|
1847
|
+
* Duplicate one node of a diagram (SVG_DIAGRAMS): the node at `path` below
|
|
1848
|
+
* slide N's element `index` is copied from the FILE, its ids taken off,
|
|
1849
|
+
* moved by `by` (`{ dx, dy }` in its own coordinates; a fiftieth of the
|
|
1850
|
+
* viewBox's width down and right without one) the way shiftSource moves a
|
|
1851
|
+
* node, and put right after it, on its own line when it stands on one. Its
|
|
1852
|
+
* node names are made its own (ownNames), so a copied pair of boxes and the
|
|
1853
|
+
* connector between them is a second pair joined by a second connector.
|
|
1854
|
+
* Returns `{ html, added: { path, html } }`.
|
|
1855
|
+
*/
|
|
1856
|
+
/**
|
|
1857
|
+
* Several nodes of a diagram duplicated in ONE write (SVG_DIAGRAMS), each as
|
|
1858
|
+
* duplicateDiagramNode duplicates one, right after itself: the last in the
|
|
1859
|
+
* file first, so each path still names what the page saw. Returns `{ html,
|
|
1860
|
+
* added: [{ path, html }] }`, in the order asked, each copy where it ends up.
|
|
1861
|
+
*/
|
|
1862
|
+
export function duplicateDiagramNodes(html, slide, index, nodes, { by = null } = {}) {
|
|
1863
|
+
if (!Array.isArray(nodes) || !nodes.length || nodes.length > 100) throw new Error('bad nodes');
|
|
1864
|
+
for (const n of nodes) checkPath(n?.path);
|
|
1865
|
+
const later = (a, b) => { for (let i = 0; i < Math.min(a.length, b.length); i++) if (a[i] !== b[i]) return b[i] - a[i]; return b.length - a.length; };
|
|
1866
|
+
const order = nodes.map((n, i) => ({ ...n, i })).sort((a, b) => later(a.path, b.path));
|
|
1867
|
+
let out = html;
|
|
1868
|
+
const added = [];
|
|
1869
|
+
for (const n of order) {
|
|
1870
|
+
const d = duplicateDiagramNode(out, slide, index, { path: n.path, tag: n.tag ?? null, by });
|
|
1871
|
+
out = d.html;
|
|
1872
|
+
added[n.i] = d.added;
|
|
1873
|
+
}
|
|
1874
|
+
// a copy put in before another's moves it one along among its siblings
|
|
1875
|
+
const final = added.map((a, i) => {
|
|
1876
|
+
const p = [...a.path];
|
|
1877
|
+
for (const m of nodes) {
|
|
1878
|
+
const q = m.path;
|
|
1879
|
+
if (m === nodes[i] || q.length !== p.length || q.slice(0, -1).join('.') !== p.slice(0, -1).join('.')) continue;
|
|
1880
|
+
if (q.at(-1) < nodes[i].path.at(-1)) p[p.length - 1] += 1;
|
|
1881
|
+
}
|
|
1882
|
+
return { path: p, html: a.html };
|
|
1883
|
+
});
|
|
1884
|
+
return { html: out, added: final };
|
|
1885
|
+
}
|
|
1886
|
+
|
|
1887
|
+
export function duplicateDiagramNode(html, slide, index, { path, tag = null, by = null }) {
|
|
1888
|
+
checkPath(path, { nested: true });
|
|
1889
|
+
if (by !== null && (typeof by !== 'object' || !Number.isFinite(coordOf(by.dx)) || !Number.isFinite(coordOf(by.dy)))) throw new Error('bad step');
|
|
1890
|
+
const e = openElement(html, slide, index);
|
|
1891
|
+
const at = e.at(path, tag);
|
|
1892
|
+
if (!at.inSvg || !DIAGRAM_NODES.has(at.found) || at.found === 'tspan') throw new Error(`not a node of a diagram: <${at.found}>`);
|
|
1893
|
+
const step = by ? null : Math.max(4, Math.round(viewBoxOf(splitOpenTag(e.src(at.svg)).attrs).w / 50));
|
|
1894
|
+
const dx = by ? coordOf(by.dx) : step; const dy = by ? coordOf(by.dy) : step;
|
|
1895
|
+
const isStep = attrOf(splitOpenTag(e.src(at.parent)).attrs, 'data-build') !== null;
|
|
1896
|
+
const copy = ownNames(shiftSource(withoutIds(e.src(at)), dx, dy, { step: isStep }), e.src(at.svg));
|
|
1897
|
+
// on its own line when the original stands on one
|
|
1898
|
+
const lead = e.lead(at);
|
|
1899
|
+
e.splice(at.end, at.end, /^[ \t]*$/.test(lead) ? `\n${lead}${copy}` : copy);
|
|
1900
|
+
return { html: e.html(), added: { path: [...path.slice(0, -1), path.at(-1) + 1], html: copy } };
|
|
1901
|
+
}
|
|
1902
|
+
|
|
1903
|
+
/**
|
|
1904
|
+
* A copy's markup without the ids the page would then have twice: every `id`
|
|
1905
|
+
* on an HTML element, and on an `<svg>` itself, goes; the ids INSIDE an svg
|
|
1906
|
+
* stay, since the engine scopes each diagram's ids to it (namespaceSvgIds)
|
|
1907
|
+
* and a copied diagram's arrowheads and gradients need their own.
|
|
1908
|
+
*/
|
|
1909
|
+
export function withoutPageIds(src) {
|
|
1910
|
+
return src.split(/(<svg\b[^>]*>[\s\S]*?<\/svg>)/i).map((part, i) => {
|
|
1911
|
+
if (!(i % 2)) return withoutIds(part);
|
|
1912
|
+
const gt = part.indexOf('>') + 1;
|
|
1913
|
+
return withoutIds(part.slice(0, gt)) + part.slice(gt);
|
|
1914
|
+
}).join('');
|
|
1915
|
+
}
|
|
1916
|
+
|
|
1917
|
+
/**
|
|
1918
|
+
* Duplicate one element of slide N (PRESENTING_EDITING, Duplicate): element
|
|
1919
|
+
* `index`, or with `path` the node there below it (outside a diagram: a
|
|
1920
|
+
* diagram's node is duplicateDiagramNode's), copied from the FILE and put
|
|
1921
|
+
* right after it, on its own line(s) when it stands on its own. The copy
|
|
1922
|
+
* loses its ids (withoutPageIds) and its `data-node` names are made its own
|
|
1923
|
+
* (ownNames), so a copied diagram is a second diagram, not a second view of
|
|
1924
|
+
* the first. The slide's notes, a script or a style are not what it shows:
|
|
1925
|
+
* refused. Returns `{ html, index, path, markup }`: where the copy is, and
|
|
1926
|
+
* what it is.
|
|
1927
|
+
*/
|
|
1928
|
+
export function duplicateSlideElement(html, slide, index, { path = null, tag = null } = {}) {
|
|
1929
|
+
const nested = Array.isArray(path) && path.length > 0;
|
|
1930
|
+
if (path !== null) checkPath(path);
|
|
1931
|
+
const { seg, r } = locateElement(html, slide, index);
|
|
1932
|
+
if (!nested) {
|
|
1933
|
+
if (tag && r.tag !== String(tag).toLowerCase()) throw stale(`slide ${slide}: the page found <${tag}> at ${index}, the file has <${r.tag}> — reload and try again`);
|
|
1934
|
+
if (carriedChild(seg, r)) throw refusedMove(`the slide's ${r.tag === 'aside' ? 'notes and sources are' : `<${r.tag}> is`} not something it shows: nothing to duplicate`);
|
|
1935
|
+
// COMPARISON_SLIDES: a split slide has one pair, and a copy would be a third column
|
|
1936
|
+
if (splitColumns(seg)?.includes(index)) throw refusedMove('a column is not duplicated: a split slide has two columns, and a copy would make a third, which drops underneath as a footer. Duplicate what is inside the column instead');
|
|
1937
|
+
}
|
|
1938
|
+
const e = openElement(html, slide, index);
|
|
1939
|
+
const at = e.at(nested ? path : [], nested ? tag : null);
|
|
1940
|
+
if (nested && at.inSvg) throw new Error('a node of a diagram is duplicated by the shape route');
|
|
1941
|
+
const copy = ownNames(withoutPageIds(e.src(at)), seg);
|
|
1942
|
+
// on its own line(s) when the original stands on its own
|
|
1943
|
+
const lead = e.lead(at);
|
|
1944
|
+
e.splice(at.end, at.end, /^[ \t]*$/.test(lead) ? `\n${lead}${copy}` : copy);
|
|
1945
|
+
return nested
|
|
1946
|
+
? { html: e.html(), index, path: [...path.slice(0, -1), path.at(-1) + 1], markup: copy }
|
|
1947
|
+
: { html: e.html(), index: index + 1, path: [], markup: copy };
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
// ── connectors: wires that stay attached (SVG_DIAGRAMS) ─────────────────────
|
|
1951
|
+
// A shape or a box group names itself `data-node`, a wire says which nodes it
|
|
1952
|
+
// joins with `data-from` / `data-to` and how with `data-route`, and keeps real
|
|
1953
|
+
// coordinates (the runtime routes it again at load: src/core/connectors.js).
|
|
1954
|
+
// The page measures and routes, since only it can measure a label; the server
|
|
1955
|
+
// validates every value it is sent and owns the markup: the names, the
|
|
1956
|
+
// arrowheads, the element a wire becomes when it bends.
|
|
1957
|
+
|
|
1958
|
+
const WIRE_TAGS = new Set(['line', 'path', 'polyline']);
|
|
1959
|
+
const NODE_TAGS = new Set(['g', 'rect', 'circle', 'ellipse', 'polygon', 'path', 'image', 'use', 'text', 'foreignobject']);
|
|
1960
|
+
export const CONNECTOR_OPS = ['add', 'reconnect', 'detach', 'route', 'arrows', 'reverse', 'label', 'token'];
|
|
1961
|
+
export const CONNECTOR_ROUTES = ['straight', 'elbow', 'curve'];
|
|
1962
|
+
export const CONNECTOR_ARROWS = ['none', 'end', 'both'];
|
|
1963
|
+
const LINE_GEOMETRY = ['x1', 'y1', 'x2', 'y2'];
|
|
1964
|
+
|
|
1965
|
+
/** The open tags of a source, each `{ head, close }` replaceable by a function of them. */
|
|
1966
|
+
const eachOpenTag = (src, fn) => src.replace(/<[a-zA-Z][^<>]*>/g, (open) => {
|
|
1967
|
+
const close = /\/?>$/.exec(open)[0];
|
|
1968
|
+
return fn(open.slice(0, -close.length), close);
|
|
1969
|
+
});
|
|
1970
|
+
/** The node names a source uses, in order. */
|
|
1971
|
+
function nodeNamesIn(src) {
|
|
1972
|
+
const out = [];
|
|
1973
|
+
eachOpenTag(src, (head) => { const n = attrOf(head, 'data-node'); if (n) out.push(n); return head; });
|
|
1974
|
+
return out;
|
|
1975
|
+
}
|
|
1976
|
+
/** A node's name from its words: lowercase, dashes between, a letter first, 32 characters at most. */
|
|
1977
|
+
export function slugNode(label) {
|
|
1978
|
+
const s = String(label ?? '').normalize('NFKD').replace(/[̀-ͯ]/g, '').toLowerCase()
|
|
1979
|
+
.replace(/[^a-z0-9]+/g, '-').replace(/^-+/, '').slice(0, 32).replace(/-+$/, '');
|
|
1980
|
+
return /^[a-z]/.test(s) ? s : s ? `n-${s}`.slice(0, 32) : 'node';
|
|
1981
|
+
}
|
|
1982
|
+
/** `base`, or `base-2`, `base-3`… : the first `taken` does not have. */
|
|
1983
|
+
function uniqueName(base, taken) {
|
|
1984
|
+
if (!taken.has(base)) return base;
|
|
1985
|
+
const stem = base.replace(/-\d+$/, '') || base;
|
|
1986
|
+
let k = 2;
|
|
1987
|
+
while (taken.has(`${stem}-${k}`)) k++;
|
|
1988
|
+
return `${stem}-${k}`;
|
|
1989
|
+
}
|
|
1990
|
+
/** The wire names a source uses (`data-wire`), in order. */
|
|
1991
|
+
function wireNamesIn(src) {
|
|
1992
|
+
const out = [];
|
|
1993
|
+
eachOpenTag(src, (head) => { const n = attrOf(head, 'data-wire'); if (n) out.push(n); return head; });
|
|
1994
|
+
return out;
|
|
1995
|
+
}
|
|
1996
|
+
|
|
1997
|
+
/**
|
|
1998
|
+
* A label on a wire (SVG_DIAGRAMS, a label on a wire): the wire named
|
|
1999
|
+
* `data-wire` when it is not, and a `<text data-on-wire>` naming it
|
|
2000
|
+
* appended last in its svg at `req.at`, the page's measure of its middle.
|
|
2001
|
+
*/
|
|
2002
|
+
function labelWire(e, { wPath, tag, svgPath, head, ends }, req) {
|
|
2003
|
+
const text = typeof req.text === 'string' ? req.text.replace(/\s+/g, ' ').trim() : '';
|
|
2004
|
+
if (!text || text.length > 120 || /[\u0000-\u001f\u007f]/.test(text)) throw new Error('a wire\'s label is one line of at most 120 characters');
|
|
2005
|
+
const x = coordOf(req.at?.x); const y = coordOf(req.at?.y);
|
|
2006
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error('bad position');
|
|
2007
|
+
let svg = e.at(svgPath, 'svg');
|
|
2008
|
+
let name = attrOf(head, 'data-wire');
|
|
2009
|
+
if (name && new RegExp(`\\sdata-on-wire\\s*=\\s*["']${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}["']`).test(e.src(svg))) throw new Error('this wire has a label: double-click it to change its words');
|
|
2010
|
+
if (!name) {
|
|
2011
|
+
name = uniqueName(slugNode([ends.from, ends.to].filter(Boolean).join(' ') || 'wire'), new Set(wireNamesIn(e.src(svg))));
|
|
2012
|
+
e.edit(wPath, tag, (a) => withAttr(a, 'data-wire', name));
|
|
2013
|
+
svg = e.at(svgPath, 'svg');
|
|
2014
|
+
}
|
|
2015
|
+
let svgSrc = e.src(svg);
|
|
2016
|
+
const lay = layoutOf(svgSrc, svgIndentOf(e, svg));
|
|
2017
|
+
const drawn = drawnNodes(svgSrc);
|
|
2018
|
+
const c = { x, y };
|
|
2019
|
+
// the look of the diagram's other wire labels, else of its labels, else tokens and a halo
|
|
2020
|
+
const model = nearest(drawn.filter((n) => n.tag === 'text' && attrOf(n.attrs, 'data-on-wire') !== null), c);
|
|
2021
|
+
const place = { 'data-on-wire': name, x: formatCoord(x), y: formatCoord(y), 'text-anchor': 'middle', 'dominant-baseline': 'central', 'data-along': null };
|
|
2022
|
+
const markup = `${model ? openTag('text', model.attrs, place)
|
|
2023
|
+
: openTag('text', labelModel(drawn, c)?.attrs ?? null, { ...place, style: 'fill: var(--d-text); paint-order: stroke; stroke: var(--bg); stroke-width: 6px; stroke-linejoin: round' })}>${escapeHtml(text)}</text>`;
|
|
2024
|
+
let at;
|
|
2025
|
+
({ svgSrc, index: at } = appendToSvg(svgSrc, markup, lay, svgIndentOf(e, svg)));
|
|
2026
|
+
e.splice(svg.start, svg.end, svgSrc);
|
|
2027
|
+
return { wire: { path: wPath, html: e.src(e.at(wPath, tag)) }, added: { path: [...svgPath, at], html: markup }, defs: [], named: { wire: name } };
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
/**
|
|
2031
|
+
* A token along a wire (BUILD_ENTRANCES, travel; Wire ▸ Send a token along
|
|
2032
|
+
* it): the wire named `data-wire` when it is not, and a build step
|
|
2033
|
+
* `<g data-build="travel" data-along-wire>` naming it appended last in its
|
|
2034
|
+
* svg, so it plays on a click of its own after the diagram's others. An
|
|
2035
|
+
* empty `<g>`: the token is the runtime's, drawn from the wire as it runs.
|
|
2036
|
+
*/
|
|
2037
|
+
function tokenWire(e, { wPath, tag, svgPath, head, ends }) {
|
|
2038
|
+
let svg = e.at(svgPath, 'svg');
|
|
2039
|
+
if (/\sdata-chart\b/i.test(splitOpenTag(e.src(svg)).attrs)) throw new Error('a chart draws itself from its data');
|
|
2040
|
+
let name = attrOf(head, 'data-wire');
|
|
2041
|
+
if (!name) {
|
|
2042
|
+
name = uniqueName(slugNode([ends.from, ends.to].filter(Boolean).join(' ') || 'wire'), new Set(wireNamesIn(e.src(svg))));
|
|
2043
|
+
e.edit(wPath, tag, (a) => withAttr(a, 'data-wire', name));
|
|
2044
|
+
svg = e.at(svgPath, 'svg');
|
|
2045
|
+
}
|
|
2046
|
+
let svgSrc = e.src(svg);
|
|
2047
|
+
const lay = layoutOf(svgSrc, svgIndentOf(e, svg));
|
|
2048
|
+
const markup = `${openTag('g', null, { 'data-build': 'travel', 'data-along-wire': name })}></g>`;
|
|
2049
|
+
let at;
|
|
2050
|
+
({ svgSrc, index: at } = appendToSvg(svgSrc, markup, lay, svgIndentOf(e, svg)));
|
|
2051
|
+
e.splice(svg.start, svg.end, svgSrc);
|
|
2052
|
+
return { wire: { path: wPath, html: e.src(e.at(wPath, tag)) }, added: { path: [...svgPath, at], html: markup }, defs: [], named: { wire: name } };
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
/** What a node says: the words of its own text, or of the first label inside it. */
|
|
2056
|
+
function wordsOf(src) {
|
|
2057
|
+
const t = /<text\b[^>]*>([\s\S]*?)<\/text>/i.exec(src);
|
|
2058
|
+
return t ? decodeText(t[1].replace(/<[^>]*>/g, ' ')).replace(/\s+/g, ' ').trim() : '';
|
|
2059
|
+
}
|
|
2060
|
+
|
|
2061
|
+
/**
|
|
2062
|
+
* A copy's node names made its own (Duplicate): each `data-node` renamed to
|
|
2063
|
+
* one `svgSrc` does not have, the copy's wires following their nodes; a
|
|
2064
|
+
* wire's end on a node outside the copy is let go, its coordinates kept, so
|
|
2065
|
+
* a copy is never joined to its original's neighbours. A copied wire's
|
|
2066
|
+
* `data-wire` name is made its own too, its label following it, so a label
|
|
2067
|
+
* never rides on two wires.
|
|
2068
|
+
*/
|
|
2069
|
+
function ownNames(copy, svgSrc) {
|
|
2070
|
+
const taken = new Set(nodeNamesIn(svgSrc));
|
|
2071
|
+
const renamed = new Map();
|
|
2072
|
+
for (const name of nodeNamesIn(copy)) {
|
|
2073
|
+
const n = uniqueName(name, taken);
|
|
2074
|
+
taken.add(n);
|
|
2075
|
+
renamed.set(name, n);
|
|
2076
|
+
}
|
|
2077
|
+
const wiresTaken = new Set(wireNamesIn(svgSrc));
|
|
2078
|
+
const wires = new Map();
|
|
2079
|
+
for (const name of wireNamesIn(copy)) {
|
|
2080
|
+
const n = uniqueName(name, wiresTaken);
|
|
2081
|
+
wiresTaken.add(n);
|
|
2082
|
+
wires.set(name, n);
|
|
2083
|
+
}
|
|
2084
|
+
if (!renamed.size && !wires.size && !/\sdata-(?:from|to)\s*=/i.test(copy)) return copy;
|
|
2085
|
+
return eachOpenTag(copy, (head, close) => {
|
|
2086
|
+
let h = head;
|
|
2087
|
+
const own = attrOf(h, 'data-node');
|
|
2088
|
+
if (own !== null && renamed.has(own)) h = withAttr(h, 'data-node', renamed.get(own));
|
|
2089
|
+
for (const a of ['data-from', 'data-to']) {
|
|
2090
|
+
const v = attrOf(h, a);
|
|
2091
|
+
if (v !== null) h = withAttr(h, a, renamed.get(v) ?? null);
|
|
2092
|
+
}
|
|
2093
|
+
for (const a of ['data-wire', 'data-on-wire']) {
|
|
2094
|
+
const v = attrOf(h, a);
|
|
2095
|
+
if (v !== null && wires.has(v)) h = withAttr(h, a, wires.get(v));
|
|
2096
|
+
}
|
|
2097
|
+
return h + close;
|
|
2098
|
+
});
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
/**
|
|
2102
|
+
* An element pasted onto slide N (PRESENTING_EDITING, the clipboard): `markup`
|
|
2103
|
+
* is what a copy took from a deck's file, this one's or another's, and
|
|
2104
|
+
* anything else a web page put on the clipboard. It is cleaned first
|
|
2105
|
+
* (sanitizePasted: nothing that runs is ever written), loses its page ids
|
|
2106
|
+
* (withoutPageIds) and has its diagrams' node names made its own on this
|
|
2107
|
+
* slide (ownNames), then lands where a new block does (insertBlock): after
|
|
2108
|
+
* top-level child `index`, or the node at `path` below it, inside a column
|
|
2109
|
+
* when that is where the selection is, or last on the slide with `index`
|
|
2110
|
+
* null. A slide that follows a design-system template takes its content in
|
|
2111
|
+
* its slots: refused (409). Returns `{ html, index, path, wrapped, markup,
|
|
2112
|
+
* dropped }`: where it is, what the file got, and what was left out.
|
|
2113
|
+
*/
|
|
2114
|
+
export function pasteSlideElement(html, slide, { index = null, path = null, markup }) {
|
|
2115
|
+
if (typeof markup !== 'string' || !markup.trim()) throw Object.assign(new Error('nothing to paste'), { status: 400 });
|
|
2116
|
+
const { html: clean, dropped } = sanitizePasted(markup);
|
|
2117
|
+
if (!/<[a-zA-Z]/.test(clean)) {
|
|
2118
|
+
throw Object.assign(new Error(`nothing left to paste${dropped.length ? `: ${dropped.join(', ')} ${dropped.length === 1 ? 'was' : 'were'} left out` : ''}`), { status: 400 });
|
|
2119
|
+
}
|
|
2120
|
+
const { parts, idx } = locateSlide(html, slide);
|
|
2121
|
+
const seg = parts[idx];
|
|
2122
|
+
const template = readAttrs(splitOpenTag(seg).attrs)['data-template'];
|
|
2123
|
+
if (template) {
|
|
2124
|
+
throw Object.assign(new Error(`slide ${slide} follows the "${template}" slide template: what it says goes in the template's slots, so nothing is pasted beside them. Paste on a plain slide, or take this one out of the template first`), { status: 409 });
|
|
2125
|
+
}
|
|
2126
|
+
const copy = ownNames(withoutPageIds(clean.trim()), seg);
|
|
2127
|
+
const out = insertBlock(html, slide, index, copy, { path });
|
|
2128
|
+
return { html: out.html, index: out.index, path: out.path, wrapped: out.wrapped, markup: copy, dropped };
|
|
647
2129
|
}
|
|
648
2130
|
|
|
649
|
-
/**
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
2131
|
+
/** A wire's geometry as a `<tag>` is written with it, each value in its closed shape: `{ attr: value }`, or a refusal. */
|
|
2132
|
+
function connectorGeometry(tag, geometry) {
|
|
2133
|
+
if (!geometry || typeof geometry !== 'object' || Array.isArray(geometry)) throw new Error('a connector is written with its geometry');
|
|
2134
|
+
const want = tag === 'line' ? LINE_GEOMETRY : tag === 'path' ? ['d'] : ['points'];
|
|
2135
|
+
const keys = Object.keys(geometry);
|
|
2136
|
+
if (keys.length !== want.length || !want.every((k) => keys.includes(k))) throw new Error(`a <${tag}> wire is written with ${want.join(', ')}`);
|
|
2137
|
+
return Object.fromEntries(want.map((k) => [k, geometryValue(k, geometry[k])]));
|
|
2138
|
+
}
|
|
2139
|
+
/** The element a wire is once routed: a line that bends becomes a path, and so does a polyline that curves. */
|
|
2140
|
+
const tagForRoute = (tag, route) => ((tag === 'line' && route !== 'straight') || (tag === 'polyline' && route === 'curve') ? 'path' : tag);
|
|
2141
|
+
/** A wire's source as a `<to>`: its tags renamed, the geometry of what it was taken off, and unfilled (a bent path would fill). */
|
|
2142
|
+
function retag(src, to) {
|
|
2143
|
+
const from = /^<([a-zA-Z][\w:-]*)/.exec(src)[1];
|
|
2144
|
+
if (from.toLowerCase() === to) return src;
|
|
2145
|
+
const { attrs, close, rest } = splitOpenTag(src);
|
|
2146
|
+
let head = `<${to}${attrs.slice(1 + from.length)}`;
|
|
2147
|
+
for (const a of [...LINE_GEOMETRY, 'points', 'd']) head = withAttr(head, a, null);
|
|
2148
|
+
if (attrOf(head, 'fill') === null && !/(?:^|;)\s*fill\s*:/i.test(attrOf(head, 'style') ?? '')) head = withAttr(head, 'fill', 'none');
|
|
2149
|
+
return head + close + rest.replace(new RegExp(`</${from}(\\s*>)$`, 'i'), `</${to}$1`);
|
|
2150
|
+
}
|
|
2151
|
+
|
|
2152
|
+
/**
|
|
2153
|
+
* Add or change a connector (SVG_DIAGRAMS), slide N's element `index`, as
|
|
2154
|
+
* ONE write. Every request names its nodes and its wire the way the colour
|
|
2155
|
+
* card names a shape (`{ path, tag }`, the FILE's element-child path below
|
|
2156
|
+
* the element, a mismatch a 409) and sends the geometry the page routed:
|
|
2157
|
+
* `{ x1, y1, x2, y2 }` for a line, `{ d }` for a path, `{ points }` for a
|
|
2158
|
+
* polyline, each value in the geometry route's closed shapes.
|
|
2159
|
+
*
|
|
2160
|
+
* add `{ path, nodes: { from, to }, geometry }`: a line from node
|
|
2161
|
+
* `from` to node `to` (each `{ path, tag, label }`; not top-level
|
|
2162
|
+
* fields, since `from` is the page a quiet write names) last in the svg at
|
|
2163
|
+
* `path`, written like the diagram's other wires (their look,
|
|
2164
|
+
* never their place or their build), else in theme tokens,
|
|
2165
|
+
* ending in the arrowhead the svg has, else the shipped one
|
|
2166
|
+
* reconnect `{ wire, end, node, geometry }`: `end` ('from' or 'to') on
|
|
2167
|
+
* `node`; a hand-drawn line becomes attached this way
|
|
2168
|
+
* detach `{ wire, end, geometry }`: that end let go where it is
|
|
2169
|
+
* route `{ wire, route, geometry }`: straight, elbow or curve; a line
|
|
2170
|
+
* that bends becomes a `<path>`
|
|
2171
|
+
* arrows `{ wire, arrows }`: none, end, or both ends (a start head
|
|
2172
|
+
* is a marker oriented `auto-start-reverse`)
|
|
2173
|
+
* reverse `{ wire, geometry }`: from and to swapped, the geometry run
|
|
2174
|
+
* the other way, so the arrowhead points the other way
|
|
2175
|
+
* label `{ wire, text, at }`: a label put on the wire, at `at` (its
|
|
2176
|
+
* middle, as the page measured it): a `<text data-on-wire>`
|
|
2177
|
+
* naming the wire, which is given a `data-wire` name when it
|
|
2178
|
+
* has none (from the nodes it joins), last in the svg so it is
|
|
2179
|
+
* drawn over the line; written like the diagram's other wire
|
|
2180
|
+
* labels, else in theme tokens with a halo of the slide's
|
|
2181
|
+
* background. One label a wire: a second is refused.
|
|
2182
|
+
*
|
|
2183
|
+
* A node without a `data-node` is given one, from its words (a group's
|
|
2184
|
+
* label, else the `label` the page read beside it), slugged and unique in
|
|
2185
|
+
* the svg. Returns `{ html, wire: { path, html }, defs: [...], named }`
|
|
2186
|
+
* (`added` for `add`): the wire's markup as the file has it, and each
|
|
2187
|
+
* arrowhead definition added, in order, the way addDiagramShape says one.
|
|
2188
|
+
*/
|
|
2189
|
+
export function editConnector(html, slide, index, req) {
|
|
2190
|
+
const { op } = req ?? {};
|
|
2191
|
+
if (!CONNECTOR_OPS.includes(op)) throw new Error(`not a connector edit: ${String(op).slice(0, 20)}`);
|
|
2192
|
+
const e = openElement(html, slide, index);
|
|
2193
|
+
const loc = e.at;
|
|
2194
|
+
const setAttrs = (p, tag, fn) => e.edit(p, tag, fn);
|
|
2195
|
+
const ref = (n, what) => {
|
|
2196
|
+
if (!n || typeof n !== 'object' || !Array.isArray(n.path)) throw new Error(`which ${what}?`);
|
|
2197
|
+
return n;
|
|
2198
|
+
};
|
|
2199
|
+
/** The name of a node of the svg at `svgPath`, given one when it has none. */
|
|
2200
|
+
const nameNode = (n, svgPath) => {
|
|
2201
|
+
ref(n, 'node');
|
|
2202
|
+
const svg = loc(svgPath, 'svg');
|
|
2203
|
+
const at = loc(n.path, n.tag ?? null);
|
|
2204
|
+
if (!NODE_TAGS.has(at.found)) throw new Error(`a connector joins shapes and boxes, not a <${at.found}>`);
|
|
2205
|
+
if (!at.svg || at.svg.start !== svg.start || n.path.length <= svgPath.length) throw new Error('a connector joins nodes of its own diagram');
|
|
2206
|
+
const head = splitOpenTag(e.src(at)).attrs;
|
|
2207
|
+
if (attrOf(head, 'data-from') !== null || attrOf(head, 'data-to') !== null) throw new Error('a connector joins shapes, not another connector');
|
|
2208
|
+
const own = attrOf(head, 'data-node');
|
|
2209
|
+
if (own) return own;
|
|
2210
|
+
const said = wordsOf(e.src(at)) || (typeof n.label === 'string' ? n.label.slice(0, 80) : '');
|
|
2211
|
+
const name = uniqueName(slugNode(said || (at.found === 'g' || at.found === 'rect' ? 'box' : at.found)), new Set(nodeNamesIn(e.src(svg))));
|
|
2212
|
+
setAttrs(n.path, at.found, (a) => withAttr(a, 'data-node', name));
|
|
2213
|
+
return name;
|
|
2214
|
+
};
|
|
2215
|
+
const finish = (out) => ({ html: e.html(), ...out });
|
|
2216
|
+
|
|
2217
|
+
if (op === 'add') {
|
|
2218
|
+
const svgPath = ref(req, 'diagram').path;
|
|
2219
|
+
let svg = loc(svgPath, req.tag ?? 'svg');
|
|
2220
|
+
if (svg.found !== 'svg') throw new Error(`a connector is added to a diagram's <svg>, not a <${svg.found}>`);
|
|
2221
|
+
if (/\sdata-chart\b/i.test(splitOpenTag(e.src(svg)).attrs)) throw new Error('a chart draws itself from its data');
|
|
2222
|
+
const ends = req.nodes ?? {};
|
|
2223
|
+
ref(ends.from, 'node'); ref(ends.to, 'node');
|
|
2224
|
+
if (JSON.stringify(ends.from.path) === JSON.stringify(ends.to.path)) throw new Error('a connector joins two different nodes');
|
|
2225
|
+
const geom = connectorGeometry('line', req.geometry);
|
|
2226
|
+
const from = nameNode(ends.from, svgPath);
|
|
2227
|
+
const to = nameNode(ends.to, svgPath);
|
|
2228
|
+
svg = loc(svgPath, 'svg');
|
|
2229
|
+
let svgSrc = e.src(svg);
|
|
2230
|
+
const svgIndent = svgIndentOf(e, svg);
|
|
2231
|
+
const lay = layoutOf(svgSrc, svgIndent);
|
|
2232
|
+
// written like the diagram's connectors, else its wires: their look, never their place
|
|
2233
|
+
const lines = drawnNodes(svgSrc).filter((n) => n.tag === 'line');
|
|
2234
|
+
const model = lines.findLast((n) => attrOf(n.attrs, 'data-from') !== null || attrOf(n.attrs, 'data-to') !== null) ?? lines.at(-1) ?? null;
|
|
2235
|
+
let defs; let marker;
|
|
2236
|
+
({ svgSrc, defs, marker } = arrowheadFor(svgSrc, lay, svgPath, { prefer: model && attrOf(model.attrs, 'marker-end') }));
|
|
2237
|
+
const place = { 'data-from': from, 'data-to': to, ...geom, 'marker-end': marker };
|
|
2238
|
+
const markup = `${model ? openTag('line', model.attrs, place) : openTag('line', null, { ...place, 'stroke-width': '2', style: 'stroke: var(--d-stroke)' })}/>`;
|
|
2239
|
+
let at;
|
|
2240
|
+
({ svgSrc, index: at } = appendToSvg(svgSrc, markup, lay, svgIndent));
|
|
2241
|
+
e.splice(svg.start, svg.end, svgSrc);
|
|
2242
|
+
return finish({ added: { path: [...svgPath, at], html: markup }, wire: { path: [...svgPath, at], html: markup }, defs: defs ? [defs] : [], named: { from, to } });
|
|
2243
|
+
}
|
|
2244
|
+
|
|
2245
|
+
const w = ref(req.wire, 'wire');
|
|
2246
|
+
let wPath = w.path;
|
|
2247
|
+
const wAt = loc(wPath, w.tag ?? null);
|
|
2248
|
+
if (!wAt.inSvg || !WIRE_TAGS.has(wAt.found)) throw new Error(`not a wire: <${wAt.found}>`);
|
|
2249
|
+
const svgPath = wPath.slice(0, wAt.chain.map((c) => c.tag).lastIndexOf('svg'));
|
|
2250
|
+
let tag = wAt.found;
|
|
2251
|
+
const head0 = splitOpenTag(e.src(wAt)).attrs;
|
|
2252
|
+
const ends = { from: attrOf(head0, 'data-from'), to: attrOf(head0, 'data-to') };
|
|
2253
|
+
if (op === 'label') return finish(labelWire(e, { wPath, tag, svgPath, head: head0, ends }, req));
|
|
2254
|
+
if (op === 'token') return finish(tokenWire(e, { wPath, tag, svgPath, head: head0, ends }));
|
|
2255
|
+
if ((op === 'reconnect' || op === 'detach') && !['from', 'to'].includes(req.end)) throw new Error('which end: from or to?');
|
|
2256
|
+
if (op === 'route' && !CONNECTOR_ROUTES.includes(req.route)) throw new Error(`a route is straight, elbow or curve, not: ${String(req.route).slice(0, 20)}`);
|
|
2257
|
+
if (op === 'arrows' && !CONNECTOR_ARROWS.includes(req.arrows)) throw new Error(`arrows are none, end or both, not: ${String(req.arrows).slice(0, 20)}`);
|
|
2258
|
+
const toTag = op === 'route' ? tagForRoute(tag, req.route) : tag;
|
|
2259
|
+
const geom = op === 'arrows' ? null : connectorGeometry(toTag, req.geometry);
|
|
2260
|
+
let named = null;
|
|
2261
|
+
if (op === 'reconnect') {
|
|
2262
|
+
named = nameNode(req.node, svgPath);
|
|
2263
|
+
if (ends[req.end === 'from' ? 'to' : 'from'] === named) throw new Error('both ends of a connector on one node');
|
|
2264
|
+
}
|
|
2265
|
+
const edit = (fn) => setAttrs(wPath, tag, fn);
|
|
2266
|
+
if (op === 'reconnect') edit((a) => withAttr(a, `data-${req.end}`, named));
|
|
2267
|
+
if (op === 'detach') {
|
|
2268
|
+
edit((a) => {
|
|
2269
|
+
const h = withAttr(a, `data-${req.end}`, null);
|
|
2270
|
+
return attrOf(h, 'data-from') === null && attrOf(h, 'data-to') === null ? withAttr(h, 'data-route', null) : h;
|
|
2271
|
+
});
|
|
2272
|
+
}
|
|
2273
|
+
if (op === 'reverse') edit((a) => withAttr(withAttr(a, 'data-from', ends.to), 'data-to', ends.from));
|
|
2274
|
+
if (op === 'route') {
|
|
2275
|
+
if (toTag !== tag) {
|
|
2276
|
+
const at = loc(wPath, tag);
|
|
2277
|
+
e.splice(at.start, at.end, retag(e.src(at), toTag));
|
|
2278
|
+
tag = toTag;
|
|
2279
|
+
}
|
|
2280
|
+
edit((a) => withAttr(a, 'data-route', req.route === 'straight' ? null : req.route));
|
|
2281
|
+
}
|
|
2282
|
+
if (geom) edit((a) => Object.entries(geom).reduce((h, [k, v]) => withAttr(h, k, v), a));
|
|
2283
|
+
const defs = [];
|
|
2284
|
+
if (op === 'arrows') {
|
|
2285
|
+
const head = splitOpenTag(e.src(loc(wPath, tag))).attrs;
|
|
2286
|
+
const svg = loc(svgPath, 'svg');
|
|
2287
|
+
let svgSrc = e.src(svg);
|
|
2288
|
+
const lay = layoutOf(svgSrc, svgIndentOf(e, svg));
|
|
2289
|
+
let end = null; let start = null; let d = null;
|
|
2290
|
+
if (req.arrows !== 'none') {
|
|
2291
|
+
({ svgSrc, defs: d, marker: end } = arrowheadFor(svgSrc, lay, svgPath, { prefer: attrOf(head, 'marker-end') }));
|
|
2292
|
+
if (d) defs.push(d);
|
|
2293
|
+
}
|
|
2294
|
+
if (req.arrows === 'both') {
|
|
2295
|
+
start = attrOf(head, 'marker-start');
|
|
2296
|
+
if (!start) {
|
|
2297
|
+
({ svgSrc, defs: d, marker: start } = arrowheadFor(svgSrc, lay, svgPath, { start: true }));
|
|
2298
|
+
if (d) defs.push(d);
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
e.splice(svg.start, svg.end, svgSrc);
|
|
2302
|
+
// a <defs> made first in the svg moves everything after it one along
|
|
2303
|
+
if (defs.some((x) => x.created && !x.replaced) && wPath.length > svgPath.length) {
|
|
2304
|
+
wPath = [...wPath.slice(0, svgPath.length), wPath[svgPath.length] + 1, ...wPath.slice(svgPath.length + 1)];
|
|
2305
|
+
}
|
|
2306
|
+
edit((a) => withAttr(withAttr(a, 'marker-end', end), 'marker-start', start));
|
|
2307
|
+
}
|
|
2308
|
+
const at = loc(wPath, tag);
|
|
2309
|
+
return finish({ wire: { path: wPath, html: e.src(at) }, defs, named: named ? { [req.end]: named } : null });
|
|
654
2310
|
}
|
|
655
2311
|
|
|
656
2312
|
// The spec's 7 entrance styles (MOTION), plus 'none' — an explicit, instant
|
|
@@ -793,6 +2449,31 @@ function arrayEntries(arr) {
|
|
|
793
2449
|
return out;
|
|
794
2450
|
}
|
|
795
2451
|
|
|
2452
|
+
/**
|
|
2453
|
+
* An entry literal with `track`'s keys written into it and every other key
|
|
2454
|
+
* left exactly as it was typed (#926). Each key is set in place where the
|
|
2455
|
+
* entry already has it, and appended where it does not — so `segments: true`,
|
|
2456
|
+
* a label, a comment, anything the author added by hand, survives an update
|
|
2457
|
+
* that did not mention it.
|
|
2458
|
+
*/
|
|
2459
|
+
function mergeLiteral(entry, track) {
|
|
2460
|
+
let out = entry;
|
|
2461
|
+
for (const [k, v] of Object.entries(track)) {
|
|
2462
|
+
if (v === undefined || v === null) continue;
|
|
2463
|
+
const val = narrationLiteral({ [k]: v }).slice(2 + k.length + 2, -2);
|
|
2464
|
+
const span = objectKey(out, k);
|
|
2465
|
+
if (span) {
|
|
2466
|
+
const old = out.slice(span.valueFrom, span.to);
|
|
2467
|
+
out = out.slice(0, span.valueFrom) + ` ${val}${/\s*$/.exec(old)[0]}` + out.slice(span.to);
|
|
2468
|
+
} else {
|
|
2469
|
+
const close = out.lastIndexOf('}');
|
|
2470
|
+
const head = out.slice(0, close).replace(/[\s,]*$/, '');
|
|
2471
|
+
out = `${head}${head.endsWith('{') ? ' ' : ', '}${k}: ${val} ${out.slice(close)}`;
|
|
2472
|
+
}
|
|
2473
|
+
}
|
|
2474
|
+
return out;
|
|
2475
|
+
}
|
|
2476
|
+
|
|
796
2477
|
/** `{ files: 'voiceover', ext: 'wav', segments: true }`, as a person writes it. */
|
|
797
2478
|
export function narrationLiteral(cfg) {
|
|
798
2479
|
const parts = [];
|
|
@@ -901,10 +2582,14 @@ export function upsertNarrationTrack(html, track) {
|
|
|
901
2582
|
// the one-string form becomes the first entry, ext/segments moving into it
|
|
902
2583
|
const kept = { label: narr.files, dir: narr.files };
|
|
903
2584
|
for (const k of ['ext', 'segments']) if (narr[k] !== undefined) { kept[k] = narr[k]; delete narr[k]; }
|
|
904
|
-
list =
|
|
2585
|
+
list = [kept];
|
|
905
2586
|
} else list = [];
|
|
906
2587
|
const same = list.findIndex((e) => (typeof e === 'string' ? e : e?.dir) === track.dir);
|
|
907
|
-
|
|
2588
|
+
// MERGED into, never replaced (#926): a key the update does not mention —
|
|
2589
|
+
// `segments`, a label, anything added by hand — is not a key to delete
|
|
2590
|
+
const was = list[same];
|
|
2591
|
+
if (same >= 0) list[same] = was && typeof was === 'object' ? { ...was, ...entry } : entry;
|
|
2592
|
+
else list.push(entry);
|
|
908
2593
|
narr.files = list;
|
|
909
2594
|
const indent = /(?:^|\n)([ \t]*)[^\n]*$/.exec(html.slice(0, block.start))?.[1] ?? '';
|
|
910
2595
|
const json = JSON.stringify(cfg, null, 2).split('\n').map((l) => indent + l).join('\n');
|
|
@@ -955,7 +2640,7 @@ export function upsertNarrationTrack(html, track) {
|
|
|
955
2640
|
const m = /\bdir\s*:\s*(['"`])([^'"`]*)\1/.exec(fval.slice(e.from, e.to));
|
|
956
2641
|
return m && m[2] === track.dir;
|
|
957
2642
|
});
|
|
958
|
-
if (same) return splice(fvalStart + same.from, fvalStart + same.to,
|
|
2643
|
+
if (same) return splice(fvalStart + same.from, fvalStart + same.to, mergeLiteral(fval.slice(same.from, same.to), track));
|
|
959
2644
|
const closeAt = fval.lastIndexOf(']');
|
|
960
2645
|
const body = entries.length ? `,\n ${one}\n ` : one;
|
|
961
2646
|
return splice(fvalStart + closeAt, fvalStart + closeAt, body);
|
|
@@ -971,7 +2656,7 @@ export function upsertNarrationTrack(html, track) {
|
|
|
971
2656
|
const v = nval.slice(found.valueFrom, found.to).trim();
|
|
972
2657
|
kept[k] = v === 'true' ? true : v === 'false' ? false : v.replace(/^['"`]|['"`]$/g, '');
|
|
973
2658
|
}
|
|
974
|
-
const list = kept.dir === track.dir ? [
|
|
2659
|
+
const list = kept.dir === track.dir ? [narrationLiteral({ ...kept, ...track })] : [narrationLiteral(kept), one];
|
|
975
2660
|
// the sibling ext/segments moved INTO the entry they described, so they must
|
|
976
2661
|
// not stay behind saying it about every track
|
|
977
2662
|
const rest = [];
|
|
@@ -986,19 +2671,495 @@ export function upsertNarrationTrack(html, track) {
|
|
|
986
2671
|
export const BUILD_EFFECTS = ['fade', 'fade-up', 'fade-down', 'zoom', 'pop', 'draw', 'highlight', 'none'];
|
|
987
2672
|
|
|
988
2673
|
/**
|
|
989
|
-
* Set slide N's element `index
|
|
990
|
-
*
|
|
991
|
-
* effect
|
|
2674
|
+
* Set the build/entrance effect of slide N's element `index`, or of the node
|
|
2675
|
+
* at `path` below it (a point of a list, a block inside a column; `[]` is the
|
|
2676
|
+
* element), or — when `effect` is `null` — take `data-build` off entirely (the
|
|
2677
|
+
* menu's separate "remove effect" action). The attribute is changed where it
|
|
2678
|
+
* stands, so a bare `data-build` (the default build) is replaced, not joined
|
|
2679
|
+
* by a second one the first would win over, and removed by null.
|
|
992
2680
|
*/
|
|
993
|
-
export function setSlideElementBuild(html, slide, index, effect) {
|
|
2681
|
+
export function setSlideElementBuild(html, slide, index, effect, { path = [], tag = null } = {}) {
|
|
994
2682
|
if (effect !== null && !BUILD_EFFECTS.includes(effect)) throw new Error(`unknown build effect "${effect}"`);
|
|
995
|
-
|
|
996
|
-
const
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
2683
|
+
checkPath(path);
|
|
2684
|
+
const e = openElement(html, slide, index);
|
|
2685
|
+
e.edit(path, tag, (attrs) => withAttr(attrs, 'data-build', effect));
|
|
2686
|
+
return e.html();
|
|
2687
|
+
}
|
|
2688
|
+
|
|
2689
|
+
/** The looping animations an element can carry (`data-animate`, the vocabulary's list). */
|
|
2690
|
+
export const ANIMATIONS = Object.freeze([...attributeEntry('data-animate').values]);
|
|
2691
|
+
|
|
2692
|
+
/**
|
|
2693
|
+
* The build settings of ONE node (PRESENTING_EDITING, the Builds tab): slide
|
|
2694
|
+
* N's element `index`, or the node at `path` below it. Each field left out is
|
|
2695
|
+
* left alone, so one write changes what the tab changed and nothing else:
|
|
2696
|
+
* effect a BUILD_EFFECTS name (`data-build="…"`), '' for the bare
|
|
2697
|
+
* default build (`data-build`), null for no build
|
|
2698
|
+
* stay true: there from the start (`data-build-stay`, bare); false: not
|
|
2699
|
+
* self true: the list, table or group is one step (`data-build-self`,
|
|
2700
|
+
* bare); false: one step an item
|
|
2701
|
+
* animate an ANIMATIONS name (`data-animate`), null for none
|
|
2702
|
+
* drawStops a stroke's stages (`data-draw-stops`): fractions of its length,
|
|
2703
|
+
* rising, the last 1 (`0.333 0.667 1`), or null to draw it at once
|
|
2704
|
+
* drawSpeed its pace in path units a second (`data-draw-speed`, DRAW_SPEED),
|
|
2705
|
+
* or null for the default
|
|
2706
|
+
* travelMs a token's trip along its wire, in ms (`data-travel-ms`,
|
|
2707
|
+
* TRAVEL_MS), or null for the deck's pace (BUILD_ENTRANCES, travel)
|
|
2708
|
+
* arrive what the token does at the wire's end (`data-arrive`, ARRIVALS):
|
|
2709
|
+
* 'fade' is the default and is written as no attribute
|
|
2710
|
+
* repeat true: it keeps travelling while its step is current
|
|
2711
|
+
* (`data-travel-repeat`, bare); false: once
|
|
2712
|
+
* Every attribute is changed where it stands, a bare one replaced, never
|
|
2713
|
+
* joined by a second. A path the file does not have is stale.
|
|
2714
|
+
*/
|
|
2715
|
+
/** The pace a staged stroke can be given, in path units a second. */
|
|
2716
|
+
export const DRAW_SPEED = Object.freeze({ min: 20, max: 5000 });
|
|
2717
|
+
/** A travelling token's pace (BUILD_ENTRANCES, travel), in ms: the runtime's own bounds (src/core/travel.js). */
|
|
2718
|
+
export const TRAVEL_MS = Object.freeze({ min: 100, max: 20000 });
|
|
2719
|
+
/** How a travelling token arrives (`data-arrive`, the vocabulary's list): the default first. */
|
|
2720
|
+
export const ARRIVALS = Object.freeze([...attributeEntry('data-arrive').values]);
|
|
2721
|
+
|
|
2722
|
+
export function setElementBuildAttrs(html, slide, index, { path = [], tag = null, effect, stay, self, animate, drawStops, drawSpeed, travelMs, arrive, repeat } = {}) {
|
|
2723
|
+
checkPath(path);
|
|
2724
|
+
if (effect !== undefined && effect !== null && effect !== '' && !BUILD_EFFECTS.includes(effect)) throw new Error(`unknown build effect "${effect}"`);
|
|
2725
|
+
for (const [k, v] of [['stay', stay], ['self', self]]) if (v !== undefined && typeof v !== 'boolean') throw new Error(`${k} is true or false`);
|
|
2726
|
+
if (animate !== undefined && animate !== null && !ANIMATIONS.includes(animate)) throw new Error(`unknown animation "${animate}"`);
|
|
2727
|
+
if (drawStops !== undefined && drawStops !== null) {
|
|
2728
|
+
const f = typeof drawStops === 'string' ? drawStops.trim().split(/\s+/).map(Number) : [];
|
|
2729
|
+
if (!f.length || f.length > 32 || f.some((x) => !(x > 0 && x <= 1)) || f.some((x, i) => i && x <= f[i - 1]) || f.at(-1) !== 1) {
|
|
2730
|
+
throw new Error('a stroke\'s stages are fractions of its length, rising, the last 1');
|
|
2731
|
+
}
|
|
2732
|
+
}
|
|
2733
|
+
if (drawSpeed !== undefined && drawSpeed !== null
|
|
2734
|
+
&& (typeof drawSpeed !== 'number' || !Number.isFinite(drawSpeed) || drawSpeed < DRAW_SPEED.min || drawSpeed > DRAW_SPEED.max)) {
|
|
2735
|
+
throw new Error(`a stroke's pace is ${DRAW_SPEED.min} to ${DRAW_SPEED.max} path units a second, or null`);
|
|
2736
|
+
}
|
|
2737
|
+
if (travelMs !== undefined && travelMs !== null
|
|
2738
|
+
&& (typeof travelMs !== 'number' || !Number.isFinite(travelMs) || travelMs < TRAVEL_MS.min || travelMs > TRAVEL_MS.max)) {
|
|
2739
|
+
throw new Error(`a token's trip takes ${TRAVEL_MS.min} to ${TRAVEL_MS.max} ms, or null`);
|
|
2740
|
+
}
|
|
2741
|
+
if (arrive !== undefined && arrive !== null && !ARRIVALS.includes(arrive)) throw new Error(`a token arrives ${ARRIVALS.join(', ')}, not "${String(arrive).slice(0, 20)}"`);
|
|
2742
|
+
if (repeat !== undefined && typeof repeat !== 'boolean') throw new Error('repeat is true or false');
|
|
2743
|
+
if ([effect, stay, self, animate, drawStops, drawSpeed, travelMs, arrive, repeat].every((v) => v === undefined)) throw new Error('nothing to set');
|
|
2744
|
+
const e = openElement(html, slide, index);
|
|
2745
|
+
// a diagram's group made one step ("all at once", SVG_DIAGRAMS): it plays on its first member's click,
|
|
2746
|
+
// the key its members had (Group froze them); made one step an item again, they play on their own
|
|
2747
|
+
let groupKey = null;
|
|
2748
|
+
if (self === true && path.length) {
|
|
2749
|
+
const g = e.src(e.at(path, tag));
|
|
2750
|
+
const head = splitOpenTag(g).attrs;
|
|
2751
|
+
if (/^<g\b/i.test(g) && attrOf(head, 'data-group') !== null && attrOf(head, 'data-build-order') === null) {
|
|
2752
|
+
const keys = elementChildRanges(g).map((k) => Number.parseInt(attrOf(splitOpenTag(g.slice(k.start, k.end)).attrs, 'data-build-order') ?? '', 10)).filter(Number.isFinite);
|
|
2753
|
+
if (keys.length) groupKey = String(Math.min(...keys));
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
e.edit(path, tag, (attrs) => {
|
|
2757
|
+
let a = attrs;
|
|
2758
|
+
if (effect !== undefined) a = withAttr(a, 'data-build', effect === '' ? true : effect);
|
|
2759
|
+
if (stay !== undefined) a = withAttr(a, 'data-build-stay', stay ? true : null);
|
|
2760
|
+
if (self !== undefined) a = withAttr(a, 'data-build-self', self ? true : null);
|
|
2761
|
+
if (groupKey !== null) a = withAttr(a, 'data-build-order', groupKey);
|
|
2762
|
+
if (animate !== undefined) a = withAttr(a, 'data-animate', animate);
|
|
2763
|
+
if (drawStops !== undefined) a = withAttr(a, 'data-draw-stops', drawStops === null ? null : drawStops.trim().split(/\s+/).join(' '));
|
|
2764
|
+
if (drawSpeed !== undefined) a = withAttr(a, 'data-draw-speed', drawSpeed === null ? null : String(Math.round(drawSpeed)));
|
|
2765
|
+
if (travelMs !== undefined) a = withAttr(a, 'data-travel-ms', travelMs === null ? null : String(Math.round(travelMs)));
|
|
2766
|
+
if (arrive !== undefined) a = withAttr(a, 'data-arrive', arrive === null || arrive === ARRIVALS[0] ? null : arrive);
|
|
2767
|
+
if (repeat !== undefined) a = withAttr(a, 'data-travel-repeat', repeat ? true : null);
|
|
2768
|
+
return a;
|
|
2769
|
+
});
|
|
2770
|
+
return e.html();
|
|
2771
|
+
}
|
|
2772
|
+
|
|
2773
|
+
/** Does node `a` come before node `b` in the file (an element's index, then its path below it; an ancestor first)? */
|
|
2774
|
+
const fileBefore = (a, b) => {
|
|
2775
|
+
if (a.index !== b.index) return a.index < b.index;
|
|
2776
|
+
for (let i = 0; i < Math.min(a.path.length, b.path.length); i++) if (a.path[i] !== b.path[i]) return a.path[i] < b.path[i];
|
|
2777
|
+
return a.path.length < b.path.length;
|
|
2778
|
+
};
|
|
2779
|
+
|
|
2780
|
+
/**
|
|
2781
|
+
* Slide N's build order (PRESENTING_EDITING, the Builds tab; SVG_DIAGRAMS'
|
|
2782
|
+
* front and back), as the author arranged it: `groups` is the slide's clicks
|
|
2783
|
+
* in the order they are to play, each a list of the nodes that arrive on it,
|
|
2784
|
+
* `{ index, path?, tag?, count? }` (a node addressed as every element edit
|
|
2785
|
+
* addresses one; `count` the steps it brings, a code block's lines or a
|
|
2786
|
+
* stroke's stages, 1 when left out). Every step of the slide is to be named:
|
|
2787
|
+
* an order key competes with the document position of a step that has none.
|
|
2788
|
+
*
|
|
2789
|
+
* Each node is stamped `data-build-order` with its click's key, the keys
|
|
2790
|
+
* counting up from 1, nodes on one click sharing theirs (equal explicit keys
|
|
2791
|
+
* arrive together, BUILD_SEMANTICS) and a node of several steps taking a key
|
|
2792
|
+
* a step. When the order asked for is the file's own (one node a click, each
|
|
2793
|
+
* after the one before it), every `data-build-order` named is taken off
|
|
2794
|
+
* instead, so a deck put back as it was says nothing about its order.
|
|
2795
|
+
* Returns `{ html, orders }`: the deck, and each node's order as written
|
|
2796
|
+
* (`order` a string, or null where it was taken off) for a page to show.
|
|
2797
|
+
* `freeze` stamps every node even when the order is the file's own: what
|
|
2798
|
+
* front and back needs before it moves a node (setDiagramOrder), since the
|
|
2799
|
+
* order the file's positions give is about to change.
|
|
2800
|
+
*/
|
|
2801
|
+
export function setSlideBuildOrder(html, slide, groups, { freeze = false } = {}) {
|
|
2802
|
+
if (!Array.isArray(groups) || !groups.length || groups.some((g) => !Array.isArray(g) || !g.length)) throw new Error('groups are lists of the nodes each click brings');
|
|
2803
|
+
const flat = groups.flat();
|
|
2804
|
+
if (flat.length > 512) throw new Error('too many steps');
|
|
2805
|
+
for (const n of flat) {
|
|
2806
|
+
if (!n || !Number.isInteger(n.index) || n.index < 0) throw new Error('bad node');
|
|
2807
|
+
checkPath(n.path ?? []);
|
|
2808
|
+
if (n.tag != null && typeof n.tag !== 'string') throw new Error('bad tag');
|
|
2809
|
+
if (n.count !== undefined && (!Number.isInteger(n.count) || n.count < 1 || n.count > 256)) throw new Error('bad count');
|
|
2810
|
+
}
|
|
2811
|
+
const seen = new Set();
|
|
2812
|
+
for (const n of flat) {
|
|
2813
|
+
const k = `${n.index}:${(n.path ?? []).join('.')}`;
|
|
2814
|
+
if (seen.has(k)) throw new Error(`a node is named twice: #${n.index}${n.path?.length ? ` › ${n.path.join('.')}` : ''}`);
|
|
2815
|
+
seen.add(k);
|
|
2816
|
+
}
|
|
2817
|
+
const at = (n) => ({ index: n.index, path: n.path ?? [] });
|
|
2818
|
+
const asWritten = !freeze && groups.every((g) => g.length === 1) && flat.every((n, i) => i === 0 || fileBefore(at(flat[i - 1]), at(n)));
|
|
2819
|
+
const orders = [];
|
|
2820
|
+
let out = html;
|
|
2821
|
+
let key = 1;
|
|
2822
|
+
for (const g of groups) {
|
|
2823
|
+
for (const n of g) {
|
|
2824
|
+
const order = asWritten ? null : String(key);
|
|
2825
|
+
const e = openElement(out, slide, n.index);
|
|
2826
|
+
e.edit(n.path ?? [], n.tag ?? null, (attrs) => withAttr(attrs, 'data-build-order', order));
|
|
2827
|
+
out = e.html();
|
|
2828
|
+
orders.push({ index: n.index, path: n.path ?? [], order });
|
|
2829
|
+
}
|
|
2830
|
+
key += Math.max(...g.map((n) => n.count ?? 1));
|
|
2831
|
+
}
|
|
2832
|
+
return { html: out, orders };
|
|
2833
|
+
}
|
|
2834
|
+
|
|
2835
|
+
// ── pictures after the drop (PRESENTING_EDITING) ─────────────────────────
|
|
2836
|
+
// A dropped picture is an `<img>`, and these are what can be done to it
|
|
2837
|
+
// without the HTML: its size, its alt text, the file it points at, a caption
|
|
2838
|
+
// around it, and the slide's own background. Each is a closed shape, written
|
|
2839
|
+
// textually into the one open tag (or the one section tag) it is about, so
|
|
2840
|
+
// the author's bytes around it survive.
|
|
2841
|
+
|
|
2842
|
+
/** The bounds of a picture's written width, in deck units (the stage is scaled, not the picture). */
|
|
2843
|
+
export const PICTURE_WIDTH = Object.freeze({ min: 16, max: 4096 });
|
|
2844
|
+
/** What a corner handle sizes by its width: a picture, a diagram, a framed web page. */
|
|
2845
|
+
const SIZED = new Set(['img', 'svg', 'iframe']);
|
|
2846
|
+
|
|
2847
|
+
/**
|
|
2848
|
+
* Change ONE picture: the `<img>` at `path` below slide N's element `index`
|
|
2849
|
+
* (`[]` when the picture is the element). Each field left out is left alone:
|
|
2850
|
+
* width a whole number of deck units in PICTURE_WIDTH, or null for the
|
|
2851
|
+
* picture's natural size. Written as the `width` attribute, which
|
|
2852
|
+
* every theme's `max-width: 100%` still caps and the stage scales
|
|
2853
|
+
* with the slide; a `height` attribute and an inline width or
|
|
2854
|
+
* height would fight it (stretch it, or win), so they go.
|
|
2855
|
+
* alt any string, escaped; '' says the picture is decoration.
|
|
2856
|
+
* src a relative path beside the deck (relativeSrc), nothing else.
|
|
2857
|
+
* caption a string: the picture is wrapped in a `<figure>` with that
|
|
2858
|
+
* `<figcaption>`, unless it is in one already.
|
|
2859
|
+
* Anything but an `<img>` there is refused, and a path that lands elsewhere
|
|
2860
|
+
* is stale.
|
|
2861
|
+
*/
|
|
2862
|
+
export function setElementPicture(html, slide, index, { path = [], tag = 'img', width, alt, src, caption } = {}) {
|
|
2863
|
+
if (width !== undefined && width !== null
|
|
2864
|
+
&& (typeof width !== 'number' || !Number.isFinite(width) || Math.round(width) < PICTURE_WIDTH.min || Math.round(width) > PICTURE_WIDTH.max)) {
|
|
2865
|
+
throw new Error(`a picture's width is a number of deck units from ${PICTURE_WIDTH.min} to ${PICTURE_WIDTH.max}, or null for its own size`);
|
|
2866
|
+
}
|
|
2867
|
+
if (alt !== undefined && (typeof alt !== 'string' || alt.length > 2000)) throw new Error('alt text is a string of at most 2000 characters');
|
|
2868
|
+
if (src !== undefined && !relativeSrc(src)) throw new Error('an image src must be a relative path beside the deck');
|
|
2869
|
+
if (caption !== undefined && (typeof caption !== 'string' || caption.length > 400 || /[\u0000-\u001f\u007f]/.test(caption))) throw new Error('a caption is one line of at most 400 characters');
|
|
2870
|
+
if (width === undefined && alt === undefined && src === undefined && caption === undefined) throw new Error('nothing to change on the picture');
|
|
2871
|
+
const e = openElement(html, slide, index);
|
|
2872
|
+
const at = e.at(path, tag);
|
|
2873
|
+
// a diagram and a framed web page are sized the way a picture is, by its
|
|
2874
|
+
// width alone; the rest (alt, a new file, a caption) is a picture's
|
|
2875
|
+
if (!SIZED.has(at.found)) throw new Error(`not a picture: <${at.found}>`);
|
|
2876
|
+
if (at.found !== 'img' && (alt !== undefined || src !== undefined || caption !== undefined)) throw new Error(`a <${at.found}> takes a width, nothing else of a picture's`);
|
|
2877
|
+
let { attrs, close, rest } = splitOpenTag(e.src(at));
|
|
2878
|
+
if (width !== undefined) {
|
|
2879
|
+
attrs = withAttr(withAttr(attrs, 'height', null), 'width', width === null ? null : Math.round(width));
|
|
2880
|
+
attrs = withStyle(withStyle(attrs, 'width', null), 'height', null);
|
|
2881
|
+
}
|
|
2882
|
+
if (alt !== undefined) attrs = withAttr(attrs, 'alt', alt);
|
|
2883
|
+
if (src !== undefined) attrs = withAttr(attrs, 'src', src);
|
|
2884
|
+
let node = attrs + close + rest;
|
|
2885
|
+
if (caption !== undefined) {
|
|
2886
|
+
if (at.parent?.tag === 'figure') throw new Error('this picture has a caption already: it is in a <figure>');
|
|
2887
|
+
const words = escapeHtml(caption);
|
|
2888
|
+
// the figure opens where the picture's line did, one step in for what it holds
|
|
2889
|
+
const lead = e.lead(at);
|
|
2890
|
+
node = /^[ \t]*$/.test(lead)
|
|
2891
|
+
? `<figure>\n${lead} ${node}\n${lead} <figcaption>${words}</figcaption>\n${lead}</figure>`
|
|
2892
|
+
: `<figure>${node}<figcaption>${words}</figcaption></figure>`;
|
|
2893
|
+
}
|
|
2894
|
+
e.splice(at.start, at.end, node);
|
|
2895
|
+
return e.html();
|
|
2896
|
+
}
|
|
2897
|
+
|
|
2898
|
+
/** What a turn edit may do (Turn ▸, DECK_ANATOMY): its role, its kind, a turn after it, or it gone. */
|
|
2899
|
+
export const TURN_OPS = ['role', 'kind', 'add', 'remove'];
|
|
2900
|
+
|
|
2901
|
+
/**
|
|
2902
|
+
* One turn of a conversation (`<div class="conversation">`, DECK_ANATOMY), at
|
|
2903
|
+
* `path` below slide N's element `index` (the conversation itself, or a column
|
|
2904
|
+
* holding it), changed in ONE edit:
|
|
2905
|
+
* role `value` a word (user, agent, tool, system or the author's own), written as `data-role`
|
|
2906
|
+
* kind `value` speech, thought or tool-call: `data-kind`, none for speech
|
|
2907
|
+
* add a turn after it, at its indentation: whoever speaks next (nextTurnRole),
|
|
2908
|
+
* a tool's answer named after the call it answers; answers the new turn's `path`
|
|
2909
|
+
* remove it out of the conversation; the last turn stays (remove the conversation instead)
|
|
2910
|
+
* A path that is not a turn of a conversation is refused, as a stale one is.
|
|
2911
|
+
*/
|
|
2912
|
+
export function setConversationTurn(html, slide, index, { path = [], tag = 'p', op, value = null } = {}) {
|
|
2913
|
+
if (!TURN_OPS.includes(op)) throw new Error(`a turn's edit is ${TURN_OPS.join(', ')}`);
|
|
2914
|
+
checkPath(path, { nested: true });
|
|
2915
|
+
if (op === 'role' && !(typeof value === 'string' && ROLE_WORD.test(value))) throw new Error('a role is one word, like user, agent, tool or system');
|
|
2916
|
+
if (op === 'kind' && !TURN_KINDS.includes(value)) throw new Error(`a turn's kind is ${TURN_KINDS.join(', ')}`);
|
|
2917
|
+
const e = openElement(html, slide, index);
|
|
2918
|
+
const at = e.at(path, tag);
|
|
2919
|
+
const holder = e.at(path.slice(0, -1));
|
|
2920
|
+
const holderAttrs = splitOpenTag(e.el.slice(holder.start, holder.end)).attrs;
|
|
2921
|
+
if (!/^<div\b/i.test(holderAttrs) || !/(^|\s)conversation(\s|$)/.test(attrOf(holderAttrs, 'class') ?? '')) {
|
|
2922
|
+
throw stale(`slide ${slide} #${index}: the file has no conversation turn at ${path.join('.')} — reload and try again`);
|
|
2923
|
+
}
|
|
2924
|
+
if (op === 'role') { e.edit(path, tag, (attrs) => withAttr(attrs, 'data-role', value)); return { html: e.html(), path }; }
|
|
2925
|
+
if (op === 'kind') { e.edit(path, tag, (attrs) => withAttr(attrs, 'data-kind', value === 'speech' ? null : value)); return { html: e.html(), path }; }
|
|
2926
|
+
const turns = elementChildRanges(e.el.slice(holder.start, holder.end)).filter((r) => !['aside', 'script', 'style', 'template'].includes(r.tag));
|
|
2927
|
+
if (op === 'remove') {
|
|
2928
|
+
if (turns.length <= 1) throw new Error('a conversation keeps one turn: remove the conversation instead');
|
|
2929
|
+
e.el = withoutNodes(e.el, [[at.start, at.end]]);
|
|
2930
|
+
return { html: e.html(), path };
|
|
2931
|
+
}
|
|
2932
|
+
// add: whoever speaks next, at the turn's own indentation
|
|
2933
|
+
const { attrs, rest } = splitOpenTag(e.src(at));
|
|
2934
|
+
const role = attrOf(attrs, 'data-role') ?? '';
|
|
2935
|
+
const kind = attrOf(attrs, 'data-kind');
|
|
2936
|
+
const next = nextTurnRole(role, kind);
|
|
2937
|
+
const named = next === 'tool' ? callName(decodeText(rest.replace(/<\/[a-z][\w-]*>\s*$/i, '').replace(/<[^>]*>/g, ''))) : null;
|
|
2938
|
+
const turn = `<p data-role="${escapeHtml(next)}"${named ? ` data-name="${escapeHtml(named)}"` : ''}>New turn</p>`;
|
|
2939
|
+
const lead = e.lead(at);
|
|
2940
|
+
e.splice(at.end, at.end, /^[ \t]*$/.test(lead) ? `\n${lead}${turn}` : turn);
|
|
2941
|
+
return { html: e.html(), path: [...path.slice(0, -1), path.at(-1) + 1] };
|
|
2942
|
+
}
|
|
2943
|
+
|
|
2944
|
+
/**
|
|
2945
|
+
* The settings an element's Options tab writes (PRESENTING_EDITING), a closed
|
|
2946
|
+
* set per tag. A code block's (CODE_AND_MATH): its language (the `language-`
|
|
2947
|
+
* class of its `<code>`), line numbers (bare), its fit (`data-fit` bare, or
|
|
2948
|
+
* `"fill"`, CODE_AND_MATH), its line
|
|
2949
|
+
* steps (`data-lines`), whether the walk ends with every line lit
|
|
2950
|
+
* (`data-lines-end="all"`), each step's callout (`data-callouts`, #1182) and
|
|
2951
|
+
* whether earlier callouts stay (`data-callouts-keep`, bare).
|
|
2952
|
+
*/
|
|
2953
|
+
export const ELEMENT_OPTIONS = {
|
|
2954
|
+
pre: ['language', 'data-lines-numbers', 'data-fit', 'data-lines', 'data-lines-end', 'data-callouts', 'data-callouts-keep'],
|
|
2955
|
+
// a video on a slide (DECK_ANATOMY): its file, its toggles (bare), its poster
|
|
2956
|
+
video: ['src', 'controls', 'loop', 'muted', 'autoplay', 'poster'],
|
|
2957
|
+
// a terminal (TERMINAL_PLAYER): a `<div class="terminal">`, its recording and how it plays
|
|
2958
|
+
div: ['data-cast', 'data-mode', 'data-title', 'data-rows', 'data-type-speed', 'data-type-sound', 'data-poster'],
|
|
2959
|
+
// a framed web page: its address (https only) and the title a screen reader says
|
|
2960
|
+
iframe: ['src', 'title'],
|
|
2961
|
+
// a figure's value (DECK_ANATOMY): whether it counts up as it arrives, and from where
|
|
2962
|
+
p: ['data-count', 'data-count-from'],
|
|
2963
|
+
};
|
|
2964
|
+
const OPTION_HOLDER = { pre: 'a code block', video: 'a video', div: 'a terminal', iframe: 'a web page', p: 'a figure' };
|
|
2965
|
+
/** A terminal's settings, each its one shape (TERMINAL_PLAYER); null takes one off. */
|
|
2966
|
+
const TERMINAL_SHAPES = {
|
|
2967
|
+
'data-cast': [(v) => relativeSrc(v) && /\.cast(\.json)?$/i.test(v), 'a recording is a .cast.json (or .cast) beside the deck, given by its relative path'],
|
|
2968
|
+
'data-mode': [(v) => v === 'step' || v === 'play', 'a terminal plays step (a command a click) or play (by itself)'],
|
|
2969
|
+
'data-title': [(v) => typeof v === 'string' && v.length <= 80 && !/[\u0000-\u001f]/.test(v), 'a title is one line of at most 80 characters'],
|
|
2970
|
+
'data-rows': [(v) => /^\d+$/.test(String(v)) && +v >= 4 && +v <= 60, 'rows is a whole number from 4 to 60'],
|
|
2971
|
+
'data-type-speed': [(v) => /^\d+$/.test(String(v)) && +v >= 1 && +v <= 10, 'typing speed is 1 (slow) to 10 (fast)'],
|
|
2972
|
+
'data-type-sound': [(v) => ['thocky', 'creamy', 'clacky', 'off'].includes(v), 'a typing sound is thocky, creamy, clacky or off'],
|
|
2973
|
+
'data-poster': [(v) => /^\d+$/.test(String(v)) && +v >= 0 && +v <= 99, 'a poster is how many steps show before it plays, 0 to 99'],
|
|
2974
|
+
};
|
|
2975
|
+
const BARE_OPTIONS = new Set(['data-lines-numbers', 'data-callouts-keep', 'controls', 'loop', 'muted', 'autoplay', 'data-count']);
|
|
2976
|
+
/** Where a figure's count starts: a plain number, as the runtime reads it (figure.js countFrom). */
|
|
2977
|
+
const COUNT_FROM = /^-?\d{1,12}(?:\.\d{1,6})?$/;
|
|
2978
|
+
|
|
2979
|
+
/**
|
|
2980
|
+
* Slide N's element `index` (or the node at `path` inside it) given the
|
|
2981
|
+
* settings in `set` (`{ name: value | null }`, null taking one off), each
|
|
2982
|
+
* checked against its tag's closed set, in ONE edit. A code block's language
|
|
2983
|
+
* is one the runtime highlights or '' (plain), its toggles `true` or null,
|
|
2984
|
+
* and its steps lines the block has: a line past its end is refused, in words.
|
|
2985
|
+
*/
|
|
2986
|
+
export function setElementOptions(html, slide, index, { path = [], tag = 'pre', set } = {}) {
|
|
2987
|
+
const names = ELEMENT_OPTIONS[String(tag)];
|
|
2988
|
+
if (!names) throw new Error(`no settings are written for <${tag}>`);
|
|
2989
|
+
if (!set || typeof set !== 'object' || Array.isArray(set) || !Object.keys(set).length) throw new Error('nothing to change');
|
|
2990
|
+
for (const [k, v] of Object.entries(set)) {
|
|
2991
|
+
if (!names.includes(k)) throw new Error(`${OPTION_HOLDER[tag]} has no setting ${JSON.stringify(k).slice(0, 40)}`);
|
|
2992
|
+
if (BARE_OPTIONS.has(k) && v !== true && v !== null) throw new Error(`${k} is on (true) or off (null)`);
|
|
2993
|
+
if (tag === 'iframe' && k === 'src' && !webAddress(v)) throw new Error('a web page is an https address (https://example.com/page)');
|
|
2994
|
+
if (tag === 'iframe' && k === 'title' && !(typeof v === 'string' && v.trim() && v.length <= 120 && !/[\u0000-\u001f]/.test(v))) throw new Error('a web page keeps a title, one line of at most 120 characters: a screen reader says it');
|
|
2995
|
+
if (tag === 'video' && k === 'src' && !(relativeSrc(v) && /\.(mp4|webm)$/i.test(v))) throw new Error('a video is an mp4 or a webm beside the deck, given by its relative path');
|
|
2996
|
+
if (k === 'poster' && v !== null && !(relativeSrc(v) && /\.(png|jpe?g|gif|webp|avif|svg)$/i.test(v))) throw new Error('a poster is a picture beside the deck, given by its relative path, or null for none');
|
|
2997
|
+
if (tag === 'div' && v !== null && !TERMINAL_SHAPES[k][0](v)) throw new Error(TERMINAL_SHAPES[k][1]);
|
|
2998
|
+
if (tag === 'div' && k === 'data-cast' && v === null) throw new Error('a terminal keeps its recording: remove the terminal instead');
|
|
2999
|
+
if (k === 'language' && v !== null && v !== '' && !CODE_LANGUAGES.some(([l]) => l === v)) throw new Error(`not a language the runtime highlights: ${String(v).slice(0, 40)}`);
|
|
3000
|
+
if (k === 'data-lines' && v !== null && (typeof v !== 'string' || v.length > 400)) throw new Error('data-lines is its steps, like 1-2|4, or null');
|
|
3001
|
+
if (k === 'data-fit' && v !== true && v !== 'fill' && v !== null) throw new Error('a fit is shrink (true), fill ("fill") or off (null)');
|
|
3002
|
+
if (k === 'data-lines-end' && v !== null && v !== 'all') throw new Error('a line walk ends lit (all) or on its last step (null)');
|
|
3003
|
+
if (k === 'data-count-from' && v !== null && !COUNT_FROM.test(String(v))) throw new Error('a count starts from a plain number, like 0, 50 or 1.5, or null for 0');
|
|
3004
|
+
if (k === 'data-callouts' && v !== null && !(typeof v === 'string' && v.length <= 2000 && !/[\u0000-\u001f]/.test(v))) throw new Error('data-callouts is a label a step, like The model|The tools, or null');
|
|
3005
|
+
}
|
|
3006
|
+
const e = openElement(html, slide, index);
|
|
3007
|
+
const at = e.at(path, tag);
|
|
3008
|
+
if (tag === 'iframe') {
|
|
3009
|
+
e.edit(path, tag, (attrs) => Object.entries(set).reduce((a, [n, v]) => withAttr(a, n, v), attrs));
|
|
3010
|
+
return e.html();
|
|
3011
|
+
}
|
|
3012
|
+
if (tag === 'p') {
|
|
3013
|
+
if (attrOf(splitOpenTag(e.src(at)).attrs, 'data-figure') === null) throw new Error('only a figure\'s value (data-figure) has these settings');
|
|
3014
|
+
e.edit(path, tag, (attrs) => Object.entries(set).reduce((a, [n, v]) => withAttr(a, n, v === null || v === true ? v : String(v)), attrs));
|
|
3015
|
+
return e.html();
|
|
3016
|
+
}
|
|
3017
|
+
if (tag === 'div') {
|
|
3018
|
+
if (!/(^|\s)terminal(\s|$)/.test(attrOf(splitOpenTag(e.src(at)).attrs, 'class') ?? '')) throw new Error('only a terminal has these settings');
|
|
3019
|
+
e.edit(path, tag, (attrs) => Object.entries(set).reduce((a, [n, v]) => withAttr(a, n, v === null ? null : String(v)), attrs));
|
|
3020
|
+
return e.html();
|
|
3021
|
+
}
|
|
3022
|
+
if (tag === 'video') {
|
|
3023
|
+
// one that plays on arrival is muted: a browser refuses to start one with sound
|
|
3024
|
+
const had = splitOpenTag(e.src(at)).attrs;
|
|
3025
|
+
const on = (k) => (Object.hasOwn(set, k) ? set[k] === true : attrOf(had, k) !== null);
|
|
3026
|
+
if (on('autoplay') && !on('muted')) throw new Error('a video that plays when its slide arrives is muted: a browser will not start one with sound');
|
|
3027
|
+
e.edit(path, tag, (attrs) => Object.entries(set).reduce((a, [n, v]) => withAttr(a, n, v), attrs));
|
|
3028
|
+
return e.html();
|
|
3029
|
+
}
|
|
3030
|
+
const kids = elementChildRanges(e.src(at));
|
|
3031
|
+
const k = kids.findIndex((r) => r.tag === 'code');
|
|
3032
|
+
if (k < 0) throw new Error('this code block has no <code> in the file');
|
|
3033
|
+
const codeAt = e.at([...path, k], 'code');
|
|
3034
|
+
if (typeof set['data-lines'] === 'string') {
|
|
3035
|
+
const total = lineCount(decodeText(splitOpenTag(e.src(codeAt)).rest.replace(/<\/code>\s*$/i, '')));
|
|
3036
|
+
const why = linesError(set['data-lines'], total);
|
|
3037
|
+
if (why) throw new Error(why);
|
|
3038
|
+
}
|
|
3039
|
+
// the <code> first: it is inside the <pre>, so the <pre>'s edit moves nothing it needs
|
|
3040
|
+
if (Object.hasOwn(set, 'language')) {
|
|
3041
|
+
e.edit([...path, k], 'code', (attrs) => {
|
|
3042
|
+
const had = (attrOf(attrs, 'class') ?? '').split(/\s+/).filter(Boolean);
|
|
3043
|
+
const at0 = had.findIndex((c) => c.startsWith('language-'));
|
|
3044
|
+
// the name the file has stays when it already means this language (js, not javascript)
|
|
3045
|
+
if (at0 >= 0 && languageOf(had[at0].slice(9)) === (set.language ?? '')) return attrs;
|
|
3046
|
+
const rest = had.filter((c) => !c.startsWith('language-'));
|
|
3047
|
+
const cls = set.language ? [...rest.slice(0, Math.max(at0, 0)), `language-${set.language}`, ...rest.slice(Math.max(at0, 0))] : rest;
|
|
3048
|
+
return withAttr(attrs, 'class', cls.length ? cls.join(' ') : null);
|
|
3049
|
+
});
|
|
3050
|
+
}
|
|
3051
|
+
const own = Object.entries(set).filter(([n]) => n !== 'language');
|
|
3052
|
+
if (own.length) e.edit(path, tag, (attrs) => own.reduce((a, [n, v]) => withAttr(a, n, v === '' ? null : v), attrs));
|
|
3053
|
+
return e.html();
|
|
3054
|
+
}
|
|
3055
|
+
|
|
3056
|
+
/** The background attributes that mean nothing once a slide has no background media. */
|
|
3057
|
+
const BACKGROUND_TUNING = ['data-background-size', 'data-background-position', 'data-background-dim'];
|
|
3058
|
+
|
|
3059
|
+
/**
|
|
3060
|
+
* Slide N's background picture (DECK_ANATOMY, background media):
|
|
3061
|
+
* `data-background-image` set to `src` (a relative path beside the deck) in
|
|
3062
|
+
* its own place on the `<section>` tag, or added; null takes it off, and with
|
|
3063
|
+
* it the size, position and dim that tuned it, unless a background video is
|
|
3064
|
+
* still there to be tuned.
|
|
3065
|
+
*/
|
|
3066
|
+
export function setSlideBackground(html, slide, src) {
|
|
3067
|
+
if (src !== null && !relativeSrc(src)) throw new Error('a background src must be a relative path beside the deck');
|
|
3068
|
+
const { parts, idx } = locateSlide(html, slide);
|
|
3069
|
+
const { attrs: had, close, rest } = splitOpenTag(parts[idx]);
|
|
3070
|
+
let attrs = withAttr(had, 'data-background-image', src);
|
|
3071
|
+
if (src === null && attrOf(attrs, 'data-background-video') === null) {
|
|
3072
|
+
for (const name of BACKGROUND_TUNING) attrs = withAttr(attrs, name, null);
|
|
3073
|
+
}
|
|
3074
|
+
parts[idx] = attrs + close + rest;
|
|
3075
|
+
return parts.join('');
|
|
3076
|
+
}
|
|
3077
|
+
|
|
3078
|
+
/**
|
|
3079
|
+
* "Use as slide background": the picture at `path` below slide N's element
|
|
3080
|
+
* `index` leaves the slide's content and becomes its background, in ONE edit.
|
|
3081
|
+
* Its `src` is the file's, and must be a path beside the deck (a data: URI or
|
|
3082
|
+
* a link is refused: a background is a file the deck carries). A `<figure>`
|
|
3083
|
+
* the picture leaves empty goes with it; one with a caption keeps the caption.
|
|
3084
|
+
* Returns `{ html, src, removed }`: `removed` is the path that went (`[]` for
|
|
3085
|
+
* the element itself).
|
|
3086
|
+
*/
|
|
3087
|
+
export function pictureToBackground(html, slide, index, { path = [], tag = 'img' } = {}) {
|
|
3088
|
+
const e = openElement(html, slide, index);
|
|
3089
|
+
const at = e.at(path, tag);
|
|
3090
|
+
if (at.found !== 'img') throw new Error(`not a picture: <${at.found}>`);
|
|
3091
|
+
const src = attrOf(splitOpenTag(e.src(at)).attrs, 'src');
|
|
3092
|
+
if (!relativeSrc(src)) throw new Error('only a picture beside the deck can become its background (this one is inline or a link)');
|
|
3093
|
+
const removed = at.parent?.tag === 'figure' && elementChildRanges(e.src(at.parent)).length === 1 ? path.slice(0, -1) : path;
|
|
3094
|
+
const out = removed.length ? removeNestedElement(html, slide, index, { path: removed }) : removeSlideElement(html, slide, index);
|
|
3095
|
+
return { html: setSlideBackground(out, slide, src), src, removed };
|
|
3096
|
+
}
|
|
3097
|
+
|
|
3098
|
+
/**
|
|
3099
|
+
* What a slide's settings write (the inspector's Slide tab, PRESENTING_EDITING):
|
|
3100
|
+
* each `<section>` attribute the vocabulary lists (DECK_ANATOMY) that has no
|
|
3101
|
+
* route of its own, with the one shape of value it takes. `true` is the
|
|
3102
|
+
* attribute written bare, null takes it off; anything else is refused. Left
|
|
3103
|
+
* out, because a route of their own writes them: `data-layout`,
|
|
3104
|
+
* `data-template`, `data-hidden` (HIDDEN_SLIDES), `data-background-image`
|
|
3105
|
+
* and `data-face`.
|
|
3106
|
+
*/
|
|
3107
|
+
const SLIDE_NUMBER = /^\d{1,4}(?:\.\d{1,3})?$/;
|
|
3108
|
+
const seconds = (max) => (v) => typeof v === 'string' && SLIDE_NUMBER.test(v) && Number(v) <= max;
|
|
3109
|
+
const bareOnly = (v) => v === true;
|
|
3110
|
+
const oneOf = (...vs) => (v) => vs.includes(v);
|
|
3111
|
+
const POSITION_WORD = '(?:left|center|right|top|bottom|\\d{1,3}%)';
|
|
3112
|
+
/** Words on one line, trimmed, 1 to `max` characters. */
|
|
3113
|
+
const oneLine = (v, max) => v.trim() === v && v.length >= 1 && v.length <= max && !/[\u0000-\u001f\u007f]/.test(v);
|
|
3114
|
+
const SLIDE_ATTRS = {
|
|
3115
|
+
// a chapter's name: words on one line, bounded
|
|
3116
|
+
'data-module': (v) => typeof v === 'string' && v.trim() === v && v.length >= 1 && v.length <= 120 && !/[\u0000-\u001f\u007f]/.test(v),
|
|
3117
|
+
// a run of slides (DECK_ANATOMY, #1188): its groups, a slide's group, its count and where it ends
|
|
3118
|
+
'data-steps': (v) => typeof v === 'string' && oneLine(v, 600) && parseSteps(v).length >= 1,
|
|
3119
|
+
'data-step': (v) => typeof v === 'string' && oneLine(v, STEP_NAME_MAX),
|
|
3120
|
+
'data-steps-count': bareOnly,
|
|
3121
|
+
'data-steps-end': bareOnly,
|
|
3122
|
+
'data-transition': oneOf('none', 'fade', 'slide', 'scale', 'flip'),
|
|
3123
|
+
'data-auto-animate': bareOnly,
|
|
3124
|
+
// planned seconds, whole (setSlideTiming writes the same)
|
|
3125
|
+
'data-timing': (v) => typeof v === 'string' && /^[1-9]\d{0,4}$/.test(v),
|
|
3126
|
+
'data-pin': (v) => v === true || v === 'none' || seconds(2000)(v),
|
|
3127
|
+
'data-subtitle': oneOf('none'),
|
|
3128
|
+
'data-background-video': (v) => typeof v === 'string' && relativeSrc(v),
|
|
3129
|
+
'data-background-poster': (v) => typeof v === 'string' && relativeSrc(v),
|
|
3130
|
+
'data-background-size': oneOf('cover', 'contain'),
|
|
3131
|
+
'data-background-position': (v) => typeof v === 'string' && new RegExp(`^${POSITION_WORD}(?: ${POSITION_WORD})?$`).test(v),
|
|
3132
|
+
'data-background-dim': (v) => typeof v === 'string' && /^(?:0(?:\.\d{1,3})?|1(?:\.0{1,3})?)$/.test(v),
|
|
3133
|
+
'data-logo': (v) => v === true || seconds(2000)(v),
|
|
3134
|
+
'data-math': bareOnly,
|
|
3135
|
+
'data-static-ok': bareOnly,
|
|
3136
|
+
'data-dense-ok': bareOnly,
|
|
3137
|
+
'data-narration': oneOf('hold'),
|
|
3138
|
+
'data-narration-pause': seconds(60),
|
|
3139
|
+
'data-narration-beat-pause': seconds(60),
|
|
3140
|
+
'data-narration-sentence-pause': seconds(60),
|
|
3141
|
+
'data-video-hold': seconds(600),
|
|
3142
|
+
};
|
|
3143
|
+
export const SLIDE_ATTR_NAMES = Object.freeze(Object.keys(SLIDE_ATTRS));
|
|
3144
|
+
|
|
3145
|
+
/**
|
|
3146
|
+
* Slide N's `<section>` with each attribute of `set` (`{ name: value }`)
|
|
3147
|
+
* written in its own place, its quote kept (withAttr), or added last: a
|
|
3148
|
+
* string is its value, `true` writes it bare, null takes it off. Every name
|
|
3149
|
+
* and value is checked first (SLIDE_ATTRS), so a refusal writes nothing.
|
|
3150
|
+
*/
|
|
3151
|
+
export function setSlideAttrs(html, slide, set) {
|
|
3152
|
+
if (!set || typeof set !== 'object' || Array.isArray(set)) throw new Error('bad set');
|
|
3153
|
+
const entries = Object.entries(set);
|
|
3154
|
+
if (!entries.length || entries.length > SLIDE_ATTR_NAMES.length) throw new Error('bad set');
|
|
3155
|
+
for (const [name, value] of entries) {
|
|
3156
|
+
const ok = Object.hasOwn(SLIDE_ATTRS, name) ? SLIDE_ATTRS[name] : null;
|
|
3157
|
+
if (!ok) throw new Error(`not a slide attribute this server writes: ${String(name).slice(0, 40)}`);
|
|
3158
|
+
if (value !== null && !ok(value)) throw new Error(`not a value ${name} takes: ${String(value).slice(0, 40)}`);
|
|
3159
|
+
}
|
|
3160
|
+
const { parts, idx } = locateSlide(html, slide);
|
|
3161
|
+
const { attrs: had, close, rest } = splitOpenTag(parts[idx]);
|
|
3162
|
+
parts[idx] = entries.reduce((a, [name, value]) => withAttr(a, name, value), had) + close + rest;
|
|
1002
3163
|
return parts.join('');
|
|
1003
3164
|
}
|
|
1004
3165
|
|
|
@@ -1022,20 +3183,41 @@ const WRITE_LABELS = {
|
|
|
1022
3183
|
'/deck/edit/slide/layout': 'layout picked',
|
|
1023
3184
|
'/deck/edit/slide/template': 'template switched',
|
|
1024
3185
|
'/deck/edit/slide/hidden': 'slide hidden or shown',
|
|
3186
|
+
'/deck/edit/slide/attr': 'slide settings changed',
|
|
3187
|
+
'/deck/edit/config': 'deck settings changed',
|
|
3188
|
+
'/deck/edit/replace': 'text replaced',
|
|
3189
|
+
'/deck/edit/element/paste': 'element pasted',
|
|
3190
|
+
'/deck/edit/slide/face': 'face placed',
|
|
1025
3191
|
'/deck/edit/slide': 'slides rearranged',
|
|
1026
3192
|
'/deck/edit/narration': 'narration track saved',
|
|
1027
3193
|
'/deck/edit/narration/record': 'narration recorded',
|
|
1028
3194
|
'/deck/edit/element/remove': 'element removed',
|
|
1029
3195
|
'/deck/edit/element/content': 'element content saved',
|
|
1030
3196
|
'/deck/edit/element/effect': 'build effect set',
|
|
3197
|
+
'/deck/edit/element/build': 'build changed',
|
|
3198
|
+
'/deck/edit/element/move': 'element moved',
|
|
3199
|
+
'/deck/edit/element/order': 'diagram order changed',
|
|
3200
|
+
'/deck/edit/element/group': 'diagram shapes grouped',
|
|
3201
|
+
'/deck/edit/element/duplicate': 'element duplicated',
|
|
3202
|
+
'/deck/edit/element/join': 'elements joined into one',
|
|
1031
3203
|
'/deck/edit/element/style': 'colours saved',
|
|
1032
3204
|
'/deck/edit/element/concept': 'concept set',
|
|
1033
3205
|
'/deck/edit/element/text': 'text saved',
|
|
3206
|
+
'/deck/edit/element/geometry': 'diagram shapes moved',
|
|
3207
|
+
'/deck/edit/element/canvas': 'diagram canvas changed',
|
|
3208
|
+
'/deck/edit/element/shape': 'diagram shape added',
|
|
3209
|
+
'/deck/edit/element/connector': 'connector saved',
|
|
1034
3210
|
'/deck/edit/element/image': 'image placed',
|
|
3211
|
+
'/deck/edit/element/insert': 'element added',
|
|
3212
|
+
'/deck/edit/element/picture': 'picture changed',
|
|
3213
|
+
'/deck/edit/element/options': 'element settings changed',
|
|
3214
|
+
'/deck/edit/element/turn': 'conversation turn changed',
|
|
3215
|
+
'/deck/edit/slide/background': 'slide background set',
|
|
3216
|
+
'/deck/edit/slide/builds': 'build order set',
|
|
1035
3217
|
'/deck/edit/concepts': 'concept colours saved',
|
|
1036
3218
|
'/deck/edit/asset': 'asset added',
|
|
1037
|
-
'/deck/edit/undo': 'undo
|
|
1038
|
-
'/deck/edit/redo': 'redo
|
|
3219
|
+
'/deck/edit/undo': 'undo',
|
|
3220
|
+
'/deck/edit/redo': 'redo',
|
|
1039
3221
|
'/deck/edit/restore': 'restored from git',
|
|
1040
3222
|
'/deck/edit/theme': 'theme picked',
|
|
1041
3223
|
'/deck/edit/brand-themes': 'brand themes set',
|
|
@@ -1046,6 +3228,7 @@ const WRITE_LABELS = {
|
|
|
1046
3228
|
'/deck/edit/design-system/mark': 'design system marked',
|
|
1047
3229
|
'/deck/edit/design-system/migrate': 'design system migrated',
|
|
1048
3230
|
'/deck/edit/check/fix': 'problem fixed',
|
|
3231
|
+
'/deck/edit/candidate/apply': 'reviewed fix applied',
|
|
1049
3232
|
'/deck/edit/enhance': 'script enhanced',
|
|
1050
3233
|
'/deck/edit/wizard': 'engine set up',
|
|
1051
3234
|
'/deck/upstream/pull': 'git pull',
|
|
@@ -1070,14 +3253,25 @@ export function reportText(text, max = 4000) {
|
|
|
1070
3253
|
* The reason a reload carries. A write of the server's own within the last
|
|
1071
3254
|
* moments is that write; the file changing while an agent runs is the
|
|
1072
3255
|
* agent's; anything else changed on disk by a hand this server never saw —
|
|
1073
|
-
* an editor, git, a tool
|
|
1074
|
-
*
|
|
3256
|
+
* an editor, git, a tool — and, given the bytes the pages show and the bytes
|
|
3257
|
+
* now, says which slides and how (null when nothing a page shows changed).
|
|
3258
|
+
* The page shows it as the first line after the reload, with "this tab" or
|
|
3259
|
+
* "another tab" when the write said which page.
|
|
1075
3260
|
*/
|
|
1076
3261
|
export const RELOAD_WRITE_WINDOW_MS = 2000;
|
|
1077
|
-
export function describeReload({ write = null, agent = null, now = Date.now() } = {}) {
|
|
3262
|
+
export function describeReload({ write = null, agent = null, now = Date.now(), before = null, after = null } = {}) {
|
|
1078
3263
|
if (write && now - write.at <= RELOAD_WRITE_WINDOW_MS) return { reload: write.what, from: write.from ?? null };
|
|
1079
3264
|
// a job that names its own reason says it (a migration: "migrated to acme 6.0.0")
|
|
1080
3265
|
if (agent) return { reload: agent.reload ?? `${agent.agent}'s edit`, from: null };
|
|
3266
|
+
// An outside edit, read against the bytes the pages show (cli/outside-edit.mjs):
|
|
3267
|
+
// said slide by slide, the changed slides' markup when the pages can swap
|
|
3268
|
+
// them in place, and where each slide went. `reload` stays the reason, so
|
|
3269
|
+
// an older page, which reloads on any message, still does.
|
|
3270
|
+
if (typeof before === 'string' && typeof after === 'string') {
|
|
3271
|
+
const o = outsideEdit(before, after);
|
|
3272
|
+
if (!o) return null;
|
|
3273
|
+
return { reload: o.said, from: null, ...(o.patch ? { patch: o.patch } : {}), land: o.land };
|
|
3274
|
+
}
|
|
1081
3275
|
return { reload: 'changed on disk — an editor, git, or a tool outside this server', from: null };
|
|
1082
3276
|
}
|
|
1083
3277
|
|
|
@@ -1088,39 +3282,127 @@ export function describeReload({ write = null, agent = null, now = Date.now() }
|
|
|
1088
3282
|
* Z puts them all back. `current` may be a function of the entry being
|
|
1089
3283
|
* taken, for the caller to snapshot exactly the files that entry names.
|
|
1090
3284
|
*/
|
|
1091
|
-
|
|
3285
|
+
/**
|
|
3286
|
+
* Each entry also carries what it was, `{ what, slide }`, so an undo can say
|
|
3287
|
+
* what it took back and the page can go to it (PRESENTING_EDITING). `describe`
|
|
3288
|
+
* names an entry recorded without one (the route doing the writing, below).
|
|
3289
|
+
*
|
|
3290
|
+
* A STRETCH is several writes that are one change to the person making them:
|
|
3291
|
+
* the notes card saves itself at every pause in the typing, and one undo per
|
|
3292
|
+
* pause took a paragraph back a phrase at a time. A record whose `stretch`
|
|
3293
|
+
* matches the newest entry's, made within `STRETCH_MS` of the last one and
|
|
3294
|
+
* straight on from what that one wrote (`after`), joins it instead of adding
|
|
3295
|
+
* one: the entry keeps the text from before the stretch began.
|
|
3296
|
+
*/
|
|
3297
|
+
export const STRETCH_MS = 60_000;
|
|
3298
|
+
export function createHistory(limit = 200, { describe = () => null, clock = Date.now } = {}) {
|
|
1092
3299
|
const past = [];
|
|
1093
3300
|
const future = [];
|
|
1094
3301
|
const now = (current, entry) => (typeof current === 'function' ? current(entry) : current);
|
|
1095
3302
|
return {
|
|
1096
|
-
record(before) {
|
|
1097
|
-
|
|
3303
|
+
record(before, meta = describe(), after = undefined) {
|
|
3304
|
+
const at = clock();
|
|
3305
|
+
const top = past.at(-1);
|
|
3306
|
+
if (meta?.stretch && top?.meta?.stretch === meta.stretch && !future.length
|
|
3307
|
+
&& at - top.at <= STRETCH_MS && typeof before === 'string' && before === top.after) {
|
|
3308
|
+
top.at = at;
|
|
3309
|
+
top.after = after;
|
|
3310
|
+
return;
|
|
3311
|
+
}
|
|
3312
|
+
past.push({ entry: before, meta: meta ?? null, at, after });
|
|
1098
3313
|
if (past.length > limit) past.shift();
|
|
1099
3314
|
future.length = 0;
|
|
1100
3315
|
},
|
|
1101
3316
|
undo(current) {
|
|
1102
3317
|
if (!past.length) return null;
|
|
1103
|
-
const
|
|
1104
|
-
future.push(now(current, entry));
|
|
1105
|
-
return entry;
|
|
3318
|
+
const it = past.pop();
|
|
3319
|
+
future.push({ ...it, entry: now(current, it.entry), after: undefined });
|
|
3320
|
+
return it.entry;
|
|
1106
3321
|
},
|
|
1107
3322
|
redo(current) {
|
|
1108
3323
|
if (!future.length) return null;
|
|
1109
|
-
const
|
|
1110
|
-
past.push(now(current, entry));
|
|
1111
|
-
return entry;
|
|
3324
|
+
const it = future.pop();
|
|
3325
|
+
past.push({ ...it, entry: now(current, it.entry), after: undefined });
|
|
3326
|
+
return it.entry;
|
|
3327
|
+
},
|
|
3328
|
+
/** What the next undo (or redo) takes back, `{ what, slide }`, or null when it was not said. */
|
|
3329
|
+
next(dir) {
|
|
3330
|
+
const meta = (dir === 'redo' ? future : past).at(-1)?.meta;
|
|
3331
|
+
return meta ? { what: meta.what ?? null, slide: meta.slide ?? null } : null;
|
|
1112
3332
|
},
|
|
1113
3333
|
counts() { return { undo: past.length, redo: future.length }; },
|
|
1114
3334
|
};
|
|
1115
3335
|
}
|
|
1116
3336
|
|
|
3337
|
+
/**
|
|
3338
|
+
* What an undo names, by the route that wrote it: "Undid: notes on slide 7".
|
|
3339
|
+
* Short nouns, not the reload's past tense ("notes saved"); a route not
|
|
3340
|
+
* named here says what the reload says.
|
|
3341
|
+
*/
|
|
3342
|
+
const UNDO_LABELS = {
|
|
3343
|
+
'/deck/edit/slide/notes': 'notes',
|
|
3344
|
+
'/deck/edit/slide/sources': 'sources',
|
|
3345
|
+
'/deck/edit/timings': 'rehearsal timings',
|
|
3346
|
+
'/deck/edit/slide/layout': 'layout',
|
|
3347
|
+
'/deck/edit/slide/template': 'template',
|
|
3348
|
+
'/deck/edit/slide/hidden': 'hiding the slide',
|
|
3349
|
+
'/deck/edit/slide/attr': 'slide settings',
|
|
3350
|
+
'/deck/edit/config': 'deck settings',
|
|
3351
|
+
'/deck/edit/replace': 'find and replace',
|
|
3352
|
+
'/deck/edit/element/paste': 'pasted element',
|
|
3353
|
+
'/deck/edit/slide/face': 'face placement',
|
|
3354
|
+
'/deck/edit/slide': 'slide change',
|
|
3355
|
+
'/deck/edit/element/remove': 'removed element',
|
|
3356
|
+
'/deck/edit/element/content': 'text edit',
|
|
3357
|
+
'/deck/edit/element/effect': 'build effect',
|
|
3358
|
+
'/deck/edit/element/build': 'build',
|
|
3359
|
+
'/deck/edit/element/move': 'move',
|
|
3360
|
+
'/deck/edit/element/order': 'front and back',
|
|
3361
|
+
'/deck/edit/element/group': 'group',
|
|
3362
|
+
'/deck/edit/element/duplicate': 'duplicate',
|
|
3363
|
+
'/deck/edit/element/join': 'joined into one',
|
|
3364
|
+
'/deck/edit/element/style': 'colours',
|
|
3365
|
+
'/deck/edit/element/concept': 'concept',
|
|
3366
|
+
'/deck/edit/element/text': 'label edit',
|
|
3367
|
+
'/deck/edit/element/geometry': 'move in a diagram',
|
|
3368
|
+
'/deck/edit/element/canvas': 'diagram canvas',
|
|
3369
|
+
'/deck/edit/element/shape': 'new shape in a diagram',
|
|
3370
|
+
'/deck/edit/element/connector': 'connector',
|
|
3371
|
+
'/deck/edit/element/image': 'picture',
|
|
3372
|
+
'/deck/edit/element/insert': 'added element',
|
|
3373
|
+
'/deck/edit/element/picture': 'picture',
|
|
3374
|
+
'/deck/edit/element/options': 'settings',
|
|
3375
|
+
'/deck/edit/element/turn': 'conversation turn',
|
|
3376
|
+
'/deck/edit/slide/background': 'slide background',
|
|
3377
|
+
'/deck/edit/slide/builds': 'build order',
|
|
3378
|
+
'/deck/edit/concepts': 'concept colours',
|
|
3379
|
+
'/deck/edit/restore': 'restore from git',
|
|
3380
|
+
'/deck/edit/theme': 'theme',
|
|
3381
|
+
'/deck/edit/check/fix': 'quick fix',
|
|
3382
|
+
'/deck/edit/candidate/apply': 'reviewed fix',
|
|
3383
|
+
};
|
|
3384
|
+
/**
|
|
3385
|
+
* The `{ what, slide, stretch }` of a write, from its route and its JSON body:
|
|
3386
|
+
* the slide it names, when it names one, and for a notes save the stretch it
|
|
3387
|
+
* belongs to (one slide, one page).
|
|
3388
|
+
*/
|
|
3389
|
+
export function undoMeta(route, body = '') {
|
|
3390
|
+
let b = null;
|
|
3391
|
+
try { b = body ? JSON.parse(body) : null; } catch { /* not json */ }
|
|
3392
|
+
const slide = Number.isInteger(b?.slide) && b.slide > 0 ? b.slide : null;
|
|
3393
|
+
const what = UNDO_LABELS[route] ?? whatWrote(route);
|
|
3394
|
+
const stretch = route === '/deck/edit/slide/notes' && slide ? `notes:${slide}:${typeof b?.from === 'string' ? b.from : ''}` : null;
|
|
3395
|
+
return { what, slide, ...(stretch ? { stretch } : {}) };
|
|
3396
|
+
}
|
|
3397
|
+
|
|
3398
|
+
|
|
1117
3399
|
// ── git: the durable record (the history above is the fast loop) ──────────
|
|
1118
3400
|
// The plumbing lives in git.mjs now; imported for editMain's use below and
|
|
1119
3401
|
// re-exported so long-standing importers (init, the tests) keep finding it
|
|
1120
3402
|
// where edit grew it.
|
|
1121
3403
|
import { inGitRepo, gitAvailable, createRepo, STARTER_GITIGNORE, gitAutocommit, lastCommitSha, resolveGitMode, shouldCommit, commitSubject, untrackedFiles, exitPushLine, oneline, remoteState } from './git.mjs';
|
|
1122
3404
|
import {
|
|
1123
|
-
describeCommit, messagesLine,
|
|
3405
|
+
describeCommit, messagesLine, deckOutline,
|
|
1124
3406
|
} from './commit-message.mjs';
|
|
1125
3407
|
import { WIP_REF, deckDirty, nagText, planNag, snapshotWip, wipLine } from './commit-flow.mjs';
|
|
1126
3408
|
export { inGitRepo, createRepo, STARTER_GITIGNORE, gitAutocommit };
|
|
@@ -1282,6 +3564,10 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
1282
3564
|
timer the old five-minute cadence, bookends included
|
|
1283
3565
|
off never commit [agent]
|
|
1284
3566
|
--agent <name> preferred AI agent for A (default: first one detected)
|
|
3567
|
+
--agent-model <id> the model that agent runs on, this run only (the remembered one
|
|
3568
|
+
otherwise; set it from A's card). Also DECKLIGHT_AGENT_MODEL
|
|
3569
|
+
--agent-ask-model <id> the model for its quick questions (commit subjects, the
|
|
3570
|
+
commit plan, enhance) when it should differ. DECKLIGHT_AGENT_ASK_MODEL
|
|
1285
3571
|
the server binds 127.0.0.1 unless --remote asks for the LAN`);
|
|
1286
3572
|
return;
|
|
1287
3573
|
}
|
|
@@ -1296,6 +3582,8 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
1296
3582
|
// know, and commit-messages on (only that path reads `agentPref`), which is
|
|
1297
3583
|
// why adding a SECOND deck to a repo was the way to find it.
|
|
1298
3584
|
let agentPref = opt('--agent') ?? preferredAgent();
|
|
3585
|
+
// this run's model (#918): into the env every agent spawn resolves it from
|
|
3586
|
+
applyModelFlags(opt);
|
|
1299
3587
|
const port = parsePort(opt('--port', 8788));
|
|
1300
3588
|
if (port === null) { console.error(`decklight: ${badPort('--port', opt('--port'))}`); process.exitCode = 1; return; }
|
|
1301
3589
|
const fail = (msg) => { console.error(`decklight: ${msg}`); process.exitCode = 1; return 1; };
|
|
@@ -1481,7 +3769,10 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
1481
3769
|
return resolve(root, '.' + rel) === deckPath;
|
|
1482
3770
|
};
|
|
1483
3771
|
|
|
1484
|
-
|
|
3772
|
+
// every entry says what wrote it: the route in flight (`writing`, below)
|
|
3773
|
+
const history = createHistory(200, {
|
|
3774
|
+
describe: () => { const ctx = writing.getStore(); return ctx?.route ? undoMeta(ctx.route, ctx.body) : null; },
|
|
3775
|
+
});
|
|
1485
3776
|
const readDeck = () => readFileSync(deckPath, 'utf8');
|
|
1486
3777
|
/** Files beside the deck as they are now, `{ path: text }` — for an undo entry that covers them. */
|
|
1487
3778
|
const snapshotFiles = (paths) => Object.fromEntries(paths.flatMap((p) => { try { return [[p, readFileSync(p, 'utf8')]]; } catch { return []; } }));
|
|
@@ -1525,25 +3816,109 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
1525
3816
|
const writing = new AsyncLocalStorage();
|
|
1526
3817
|
let lastWrite = null; // { at, what, from } — the server's latest write of the deck, for the watcher
|
|
1527
3818
|
const noteWrite = (what, from = null) => { lastWrite = { at: Date.now(), what, from }; };
|
|
3819
|
+
// The deck as this server last read or wrote it: what an edit from outside
|
|
3820
|
+
// the server is measured against when the voice folders follow it (#954).
|
|
3821
|
+
// Not git HEAD — an outside edit can land between two commits, or two of
|
|
3822
|
+
// them between two reloads.
|
|
3823
|
+
let knownDeck = null;
|
|
3824
|
+
try { knownDeck = readDeck(); } catch { /* not there yet: the first edit is not a move */ }
|
|
1528
3825
|
/** The one write of the deck file: atomic, and remembered for the reload it causes. */
|
|
1529
3826
|
const writeDeck = (next) => {
|
|
1530
3827
|
writeFileAtomic(deckPath, next);
|
|
3828
|
+
knownDeck = next;
|
|
3829
|
+
// an agent running: this server's own write is the author's, and the
|
|
3830
|
+
// agent's undo point moves past it (see `agentBase`)
|
|
3831
|
+
if (agentBase) agentBase.deck = next;
|
|
1531
3832
|
const ctx = writing.getStore();
|
|
1532
3833
|
let from = null;
|
|
1533
3834
|
if (ctx?.body) { try { const f = JSON.parse(ctx.body).from; if (typeof f === 'string') from = f.slice(0, 64); } catch { /* not json, or no page named */ } }
|
|
1534
3835
|
noteWrite(whatWrote(ctx?.route), from);
|
|
1535
3836
|
};
|
|
1536
|
-
|
|
3837
|
+
// `also` rides into the undo entry beside the deck: `{ voices }`, the voice
|
|
3838
|
+
// folders a slide op renumbered (#916), which Z moves back with it
|
|
3839
|
+
const applyEdit = (change, before = readDeck(), also = null) => {
|
|
1537
3840
|
const next = typeof change === 'function' ? change(before) : change;
|
|
1538
3841
|
if (next === before) return false;
|
|
1539
|
-
history.record(before);
|
|
3842
|
+
history.record(also ? { deck: before, ...also } : before, undefined, next);
|
|
1540
3843
|
writeDeck(next);
|
|
3844
|
+
// a save to a source that puts a language behind says so, once per
|
|
3845
|
+
// language until it is caught up (TRANSLATE_PANEL); nothing is translated
|
|
3846
|
+
if (/"languages"\s*:/.test(next)) {
|
|
3847
|
+
setImmediate(() => {
|
|
3848
|
+
try {
|
|
3849
|
+
const langs = newlyBehind(deckPath, before, next);
|
|
3850
|
+
if (langs.length) broadcast('translate', { state: 'behind', langs });
|
|
3851
|
+
} catch { /* a record that cannot be read is check's to say */ }
|
|
3852
|
+
});
|
|
3853
|
+
}
|
|
1541
3854
|
return true;
|
|
1542
3855
|
};
|
|
1543
3856
|
|
|
3857
|
+
/**
|
|
3858
|
+
* The voice folders follow an edit that rewrote the deck at once — an
|
|
3859
|
+
* agent's (#920) — as a slide op's do (#916): where each slide went is read
|
|
3860
|
+
* off the sections before and after (slideRenumber), never off the audio,
|
|
3861
|
+
* so a stale take moves with its slide too. The deck is already written, so
|
|
3862
|
+
* nothing here can refuse it: a folder that cannot follow is left exactly
|
|
3863
|
+
* as it was and said, and realign is still there for it.
|
|
3864
|
+
*
|
|
3865
|
+
* `null` when no slide moved; else `{ voices, said, renumber }`: the steps
|
|
3866
|
+
* that undo the moves (for the edit's undo entry), one line per folder, and
|
|
3867
|
+
* Map dir → renumbering for the folders that moved — or `{ error }`.
|
|
3868
|
+
*/
|
|
3869
|
+
const followSlides = (before, after) => {
|
|
3870
|
+
const pairs = slideRenumber(before, after);
|
|
3871
|
+
if (!pairs.length) return null;
|
|
3872
|
+
const deckDir = dirname(deckPath);
|
|
3873
|
+
const dirs = voiceFolders(deckPath, [...configuredTrackDirs(before), ...configuredTrackDirs(after)]);
|
|
3874
|
+
const r = planSteps(deckDir, dirs.map((dir) => ({ dir, pairs })));
|
|
3875
|
+
if (r.error) return { error: `${r.error} — they were left where they were; realign them from the narration panel` };
|
|
3876
|
+
if (!r.plans.length) return null;
|
|
3877
|
+
try { applyPlans(deckDir, r.plans); } catch (e) {
|
|
3878
|
+
return { error: `the recordings could not follow the slides — ${oneline(e)} — they were left where they were` };
|
|
3879
|
+
}
|
|
3880
|
+
const was = deckOutline(before).length, now = deckOutline(after).length;
|
|
3881
|
+
const said = r.plans.map((p) => followedSaid(p, pairs, was, now)).filter(Boolean);
|
|
3882
|
+
const renumber = new Map(r.plans.map((p) => [p.dir, movesRenumber(pairs)]));
|
|
3883
|
+
return { voices: r.plans.map((p) => p.inverse), said, renumber };
|
|
3884
|
+
};
|
|
3885
|
+
|
|
3886
|
+
/**
|
|
3887
|
+
* The voice folders follow an edit made OUTSIDE this server (#954) — a
|
|
3888
|
+
* terminal agent, a text editor — as they follow an `A`-panel agent's: read
|
|
3889
|
+
* against the last deck the server knew, on the file watch and before an
|
|
3890
|
+
* outside commit. The move is an undo entry, so Z puts the files back with
|
|
3891
|
+
* the deck; an edit that moved no slide records nothing and moves nothing.
|
|
3892
|
+
* Skipped while a held fix or an agent of this server's own is writing:
|
|
3893
|
+
* that run follows the slides itself when it is done.
|
|
3894
|
+
*
|
|
3895
|
+
* Answers what followSlides does, or null when there was nothing to follow.
|
|
3896
|
+
*/
|
|
3897
|
+
const followOutside = () => {
|
|
3898
|
+
if (noTrust || holding || agentJob) return null;
|
|
3899
|
+
let now;
|
|
3900
|
+
try { now = readDeck(); } catch { return null; }
|
|
3901
|
+
const was = knownDeck;
|
|
3902
|
+
knownDeck = now;
|
|
3903
|
+
if (was === null || was === now) return null;
|
|
3904
|
+
let followed = null;
|
|
3905
|
+
try { followed = followSlides(was, now); } catch (e) { followed = { error: oneline(e) }; }
|
|
3906
|
+
if (followed?.voices) history.record({ deck: was, voices: followed.voices });
|
|
3907
|
+
for (const line of followed?.said ?? []) console.log(` narration: ${line}`);
|
|
3908
|
+
if (followed?.error) console.log(` narration: ${followed.error}`);
|
|
3909
|
+
return followed;
|
|
3910
|
+
};
|
|
3911
|
+
|
|
1544
3912
|
// Declared before the git block below, which reads it to hold the cadence
|
|
1545
3913
|
// back while a job is in flight.
|
|
1546
3914
|
let agentJob = null; // { name, prompt, startedAt } — strictly one at a time
|
|
3915
|
+
// The deck an agent's edit is undone back to. It starts as the deck when
|
|
3916
|
+
// the run began, and every write THIS server makes meanwhile (the author
|
|
3917
|
+
// typing notes, fixing a word) moves it on: the agent writes the file
|
|
3918
|
+
// itself, so the last write that was not the agent's is the nearest thing
|
|
3919
|
+
// to "just before the agent wrote". Undoing the agent used to put the deck
|
|
3920
|
+
// back to the start of the run, and the author's own edits went with it.
|
|
3921
|
+
let agentBase = null;
|
|
1547
3922
|
let agentStop = null; // stops it (POST /deck/edit/agent/stop) — set while it runs
|
|
1548
3923
|
// The asks of this session, oldest first, with what came of each — what the
|
|
1549
3924
|
// docked agent panel shows. An agent's edit reloads every browser, so the
|
|
@@ -1823,7 +4198,8 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
1823
4198
|
// route with the rest of the write family, and a roster line under the
|
|
1824
4199
|
// ingredients label would promise a capability that mode does not have.
|
|
1825
4200
|
if (agents.length && !noTrust) {
|
|
1826
|
-
const mark = (a) => a.name + (a.name === agentPref ? ' (preferred)' : '') + (a.installed ? ' (installed)' : '')
|
|
4201
|
+
const mark = (a) => a.name + (a.name === agentPref ? ' (preferred)' : '') + (a.installed ? ' (installed)' : '')
|
|
4202
|
+
+ (agentModel(a.name).model ? ` · ${agentModel(a.name).model}` : '');
|
|
1827
4203
|
startup('agents', agents.map(mark).join(', '),
|
|
1828
4204
|
` agents: ${agents.map(mark).join(', ')} — “Ask agent” (A) is live`, 'ok');
|
|
1829
4205
|
}
|
|
@@ -1832,6 +4208,12 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
1832
4208
|
if (!noTrust && agentPref && !agents.some((a) => a.name === agentPref)) {
|
|
1833
4209
|
console.log(` agent: ${agentUnavailable(agentPref, agents)}`);
|
|
1834
4210
|
}
|
|
4211
|
+
// A model set for an agent whose CLI cannot take one is said too (#918):
|
|
4212
|
+
// it is not applied, and a setting that silently did nothing is the bug.
|
|
4213
|
+
for (const a of noTrust ? [] : agents) {
|
|
4214
|
+
const m = agentModel(a.name).model;
|
|
4215
|
+
if (m && !takesModel(a)) console.log(` agent: ${a.name} takes no model flag — "${m}" is not applied, it runs on its own default`);
|
|
4216
|
+
}
|
|
1835
4217
|
// A deck that EMBEDS a runtime older than this install is served as it is
|
|
1836
4218
|
// (the file is the author's), and that runtime probes routes this server
|
|
1837
4219
|
// may no longer have: it gets a 404, concludes there is no server, and
|
|
@@ -1934,6 +4316,8 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
1934
4316
|
// modes. What the probe carries beyond the mode is `extras`, computed on
|
|
1935
4317
|
// every ping like everything else on it: the toast is threshold-driven,
|
|
1936
4318
|
// not live.
|
|
4319
|
+
// The quick fix held for review (#907, cli/fix-review.mjs): set with the route table below.
|
|
4320
|
+
let fixReview = null;
|
|
1937
4321
|
const deck = createDeckRoutes(deckPath, {
|
|
1938
4322
|
noTrust,
|
|
1939
4323
|
locked: () => noTrust || locked,
|
|
@@ -1953,16 +4337,20 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
1953
4337
|
// What the player's one push nudge reads. Computed once, like everything
|
|
1954
4338
|
// else on ping: the toast is threshold-driven, not live.
|
|
1955
4339
|
remote: gitOn ? remoteState(root) : null,
|
|
1956
|
-
|
|
4340
|
+
// with the model each runs on (#918): null for the agent's own default,
|
|
4341
|
+
// `takesModel: false` for one whose CLI has no flag for it
|
|
4342
|
+
agents: agents.map((a) => ({ name: a.name, label: a.label, ...agentModelState(a) })),
|
|
1957
4343
|
// which one A reaches for, so the picker opens on it rather than
|
|
1958
4344
|
// defaulting to the first detected agent every session (#125)
|
|
1959
4345
|
preferredAgent: agentPref ?? null,
|
|
1960
|
-
agentBusy: agentJob && { agent: agentJob.agent, prompt: agentJob.prompt, startedAt: agentJob.startedAt, id: agentJob.id },
|
|
4346
|
+
agentBusy: agentJob && { agent: agentJob.agent, label: agentJob.label, model: agentJob.model, prompt: agentJob.prompt, startedAt: agentJob.startedAt, id: agentJob.id },
|
|
1961
4347
|
// the long jobs a page that loads mid-run can still stop
|
|
1962
4348
|
exportBusy: exportJob,
|
|
1963
4349
|
enhanceBusy: !!enhancing,
|
|
1964
4350
|
reviewBusy: !!reviewing,
|
|
1965
4351
|
agentAsks,
|
|
4352
|
+
// a quick fix waiting for review: a page that loads mid-review opens it again
|
|
4353
|
+
candidate: fixReview?.held() ? { id: fixReview.held().id } : null,
|
|
1966
4354
|
wizards: await configurableEngines(),
|
|
1967
4355
|
// What is uncommitted, so a deck that loads mid-session shows the
|
|
1968
4356
|
// chip without waiting for the next tick to broadcast one.
|
|
@@ -2229,6 +4617,15 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2229
4617
|
|
|
2230
4618
|
let pending = null;
|
|
2231
4619
|
let quietWrite = null; // the bytes of a write that updates the page itself (themeMarkRoute, cli/edit-look.mjs)
|
|
4620
|
+
// An agent working on a fix held for review (#907) edits the deck file in
|
|
4621
|
+
// place, and the file goes back to what it was when it is done: no page
|
|
4622
|
+
// reloads for any of it, because nothing it wrote has landed.
|
|
4623
|
+
let holding = false;
|
|
4624
|
+
// The deck as the pages show it: the bytes the last change sent them to.
|
|
4625
|
+
// An outside edit is measured against it. Kept apart from `knownDeck`,
|
|
4626
|
+
// which is the voice folders' and stands still through an agent's run.
|
|
4627
|
+
let shownDeck = null;
|
|
4628
|
+
try { shownDeck = readDeck(); } catch { /* not there yet: the first change reloads */ }
|
|
2232
4629
|
// The DIRECTORY, not the file. A path watch follows the inode, and an
|
|
2233
4630
|
// atomic write — temp file + rename, which is how an agent's editor and
|
|
2234
4631
|
// most careful tools save — replaces the inode: the watcher then sits deaf
|
|
@@ -2244,6 +4641,11 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2244
4641
|
// changed underneath it is not reloaded, because that would be new
|
|
2245
4642
|
// bytes under the old label. A pull re-audits.
|
|
2246
4643
|
if (noTrust) return;
|
|
4644
|
+
if (holding) return;
|
|
4645
|
+
// an edit from outside the server moves the recordings with its slides
|
|
4646
|
+
// (#954); one the server wrote itself reads as no change here
|
|
4647
|
+
const followed = followOutside();
|
|
4648
|
+
const voices = followed?.error ? `🎙 ${followed.error}` : followed?.said?.length ? `🎙 ${followed.said.join('; ')}` : null;
|
|
2247
4649
|
// A QUIET write is one the pages update themselves in place, which must
|
|
2248
4650
|
// not reload: a theme marked from the open picker (a reload closes the
|
|
2249
4651
|
// picker the author is still choosing in), or a notes save, whose new
|
|
@@ -2252,18 +4654,25 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2252
4654
|
// since (an editor save, an undo) reloads as it always has.
|
|
2253
4655
|
const quiet = quietWrite;
|
|
2254
4656
|
quietWrite = null;
|
|
2255
|
-
|
|
2256
|
-
|
|
2257
|
-
|
|
2258
|
-
if (now === quiet) { lastWrite = null; console.log(' changed → updated in place, no reload'); return; }
|
|
2259
|
-
}
|
|
4657
|
+
let now = null;
|
|
4658
|
+
try { now = readFileSync(deckPath, 'utf8'); } catch { /* gone — reload says so */ }
|
|
4659
|
+
if (quiet !== null && now === quiet) { shownDeck = now; lastWrite = null; console.log(' changed → updated in place, no reload'); return; }
|
|
2260
4660
|
// The message names what wrote the file (`describeReload`): the page
|
|
2261
4661
|
// stashes it with its debug log and says it first thing after the
|
|
2262
|
-
// reload. An
|
|
2263
|
-
|
|
4662
|
+
// reload. An outside edit is read against what the pages show: only
|
|
4663
|
+
// slides' own markup changed, and they are swapped in place (`patch`);
|
|
4664
|
+
// else the reload carries where each slide went (`land`). An older
|
|
4665
|
+
// page reloads on any message, as it always did.
|
|
4666
|
+
const why = describeReload({ write: lastWrite, agent: agentJob, before: shownDeck, after: now });
|
|
4667
|
+
if (now !== null) shownDeck = now;
|
|
2264
4668
|
lastWrite = null;
|
|
4669
|
+
if (!why) { console.log(' changed → nothing the slides show, no reload'); return; }
|
|
4670
|
+
// recordings that moved with the slides reload with them (#978)
|
|
4671
|
+
if (voices) { why.reload += ` — ${voices}`; delete why.patch; }
|
|
2265
4672
|
clients.raw(`data: ${JSON.stringify(why)}\n\n`);
|
|
2266
|
-
console.log(
|
|
4673
|
+
console.log(why.patch
|
|
4674
|
+
? ` changed → ${why.reload} · in place × ${clients.size}`
|
|
4675
|
+
: ` changed → reload × ${clients.size} — ${why.reload}${why.from ? ` (page ${why.from})` : ''}`);
|
|
2267
4676
|
}, 150);
|
|
2268
4677
|
});
|
|
2269
4678
|
|
|
@@ -2303,14 +4712,26 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2303
4712
|
* checks compare against it (a migration's before and after renders).
|
|
2304
4713
|
* `dirs` are folders outside the project the agent must read (a
|
|
2305
4714
|
* migration's skill, where it is installed).
|
|
4715
|
+
*
|
|
4716
|
+
* `hold` makes it a fix held for review (#907): `{ start?, done(after) }`.
|
|
4717
|
+
* The agent edits the deck file as it always does (from `start`, a held
|
|
4718
|
+
* candidate it is adjusting, when given), with every reload held; when it
|
|
4719
|
+
* exits the file is put back exactly as it was, and what it wrote goes to
|
|
4720
|
+
* `done` instead of the history and git. Nothing is committed, before or
|
|
4721
|
+
* after. `done` answers what the `done` event carries for the review.
|
|
2306
4722
|
*/
|
|
2307
|
-
function runAgent(prompt, name, message, slide, { files = [], reload = null, kind = null, title = null, subject: given = null, before: beforeSay = null, dirs = [] } = {}) {
|
|
2308
|
-
|
|
4723
|
+
function runAgent(prompt, name, message, slide, { files = [], reload = null, kind = null, title = null, subject: given = null, before: beforeSay = null, dirs = [], hold = null, explain = null } = {}) {
|
|
4724
|
+
// explain: a question, not an edit. The agent's read-only `ask` argv, the
|
|
4725
|
+
// prompt verbatim; no undo entry, no commit, no review. `explain.follow`
|
|
4726
|
+
// is the fix the panel offers once the answer is in.
|
|
4727
|
+
let cmd = explain ? agentAsk(name || agentPref, prompt) : agentCommand(name || agentPref, prompt, deckRel, { slide, dirs });
|
|
2309
4728
|
if (!cmd) return null;
|
|
2310
4729
|
const ask = {
|
|
2311
4730
|
id: ++askSeq, agent: cmd.name, label: cmd.label, prompt,
|
|
4731
|
+
...(cmd.model ? { model: cmd.model } : {}),
|
|
2312
4732
|
...(Number.isInteger(slide) && slide > 0 ? { slide } : {}),
|
|
2313
4733
|
...(kind ? { kind } : {}), ...(title ? { title } : {}),
|
|
4734
|
+
...(explain ? { kind: 'explain', ...(explain.follow ? { follow: explain.follow } : {}) } : {}),
|
|
2314
4735
|
startedAt: Date.now(), state: 'running',
|
|
2315
4736
|
};
|
|
2316
4737
|
agentAsks.push(ask);
|
|
@@ -2321,7 +4742,7 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2321
4742
|
// commit honest: otherwise a hand edit made just before pressing A lands
|
|
2322
4743
|
// under the agent's message, and a history that misattributes authorship is
|
|
2323
4744
|
// worse than one that only says "autosave".
|
|
2324
|
-
if (gitOn && shouldCommit(gitMode, { kind: 'bookend' })
|
|
4745
|
+
if (!hold && !explain && gitOn && shouldCommit(gitMode, { kind: 'bookend' })
|
|
2325
4746
|
&& ownCommit(`decklight: save before ${cmd.name} edits ${basename(deckPath)}`, files)) {
|
|
2326
4747
|
console.log(' git: committed your outstanding changes first');
|
|
2327
4748
|
}
|
|
@@ -2330,17 +4751,32 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2330
4751
|
if (head) {
|
|
2331
4752
|
prompt = `${prompt} ${beforeSay(head)}`;
|
|
2332
4753
|
ask.prompt = prompt;
|
|
2333
|
-
cmd = agentCommand(cmd.name, prompt, deckRel, { slide, dirs }) ?? cmd;
|
|
4754
|
+
cmd = (explain ? agentAsk(cmd.name, prompt) : agentCommand(cmd.name, prompt, deckRel, { slide, dirs })) ?? cmd;
|
|
2334
4755
|
}
|
|
2335
4756
|
}
|
|
4757
|
+
// held: the deck as it really is, put back when the agent is done
|
|
4758
|
+
const kept = hold ? readDeck() : null;
|
|
4759
|
+
if (hold) {
|
|
4760
|
+
holding = true;
|
|
4761
|
+
if (typeof hold.start === 'string' && hold.start !== kept) writeFileAtomic(deckPath, hold.start);
|
|
4762
|
+
}
|
|
4763
|
+
/** The deck file as it was before a held run, again; no reload for the trip. */
|
|
4764
|
+
const putBack = () => {
|
|
4765
|
+
if (!hold) return;
|
|
4766
|
+
let now = null;
|
|
4767
|
+
try { now = readDeck(); } catch { /* gone: written back below */ }
|
|
4768
|
+
if (now !== kept) { quietWrite = kept; writeFileAtomic(deckPath, kept); }
|
|
4769
|
+
holding = false;
|
|
4770
|
+
};
|
|
2336
4771
|
const before = readDeck();
|
|
4772
|
+
if (!hold && !explain) agentBase = { deck: before };
|
|
2337
4773
|
const filesBefore = snapshotFiles(files);
|
|
2338
4774
|
// what is already beside the deck, so what the run leaves there can be named
|
|
2339
4775
|
const leftBefore = new Set(besideDeck() ?? []);
|
|
2340
|
-
agentJob = { agent: cmd.name, label: cmd.label, prompt, startedAt: ask.startedAt, id: ask.id, slide: ask.slide, ...(reload ? { reload } : {}) };
|
|
4776
|
+
agentJob = { agent: cmd.name, label: cmd.label, ...(cmd.model ? { model: cmd.model } : {}), prompt, startedAt: ask.startedAt, id: ask.id, slide: ask.slide, ...(reload ? { reload } : {}) };
|
|
2341
4777
|
broadcast('agent', { state: 'start', ...agentJob });
|
|
2342
|
-
console.log(` agent: ${cmd.name} ← "${prompt.slice(0, 80)}"`);
|
|
2343
|
-
const child = spawn(cmd.bin, cmd.args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
4778
|
+
console.log(` agent: ${cmd.name}${cmd.model ? ` (${cmd.model})` : ''} ← "${prompt.slice(0, 80)}"`);
|
|
4779
|
+
const child = spawn(cmd.bin, cmd.args, { cwd: root, env: cmd.env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
2344
4780
|
let tail = '';
|
|
2345
4781
|
const keep = (chunk) => { tail = (tail + chunk).slice(-4000); };
|
|
2346
4782
|
// The clue the chip shows. An agent run used to be a timer and nothing
|
|
@@ -2357,17 +4793,23 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2357
4793
|
broadcast('agent', { state: 'activity', agent: cmd.name, text });
|
|
2358
4794
|
console.log(` agent: ${text}`);
|
|
2359
4795
|
};
|
|
4796
|
+
// the stream's last line, if it ended without a newline: read at the end
|
|
4797
|
+
let flushStream = () => {};
|
|
2360
4798
|
if (cmd.stream === 'claude-json') {
|
|
2361
4799
|
let buf = '';
|
|
4800
|
+
const read = (line) => {
|
|
4801
|
+
const clue = claudeActivity(line);
|
|
4802
|
+
if (clue?.activity) say(clue.activity);
|
|
4803
|
+
else if (clue?.result != null) resultText = clue.result;
|
|
4804
|
+
};
|
|
2362
4805
|
child.stdout.on('data', (chunk) => {
|
|
2363
4806
|
buf += chunk;
|
|
2364
4807
|
for (let nl = buf.indexOf('\n'); nl !== -1; nl = buf.indexOf('\n')) {
|
|
2365
4808
|
const line = buf.slice(0, nl); buf = buf.slice(nl + 1);
|
|
2366
|
-
|
|
2367
|
-
if (clue?.activity) say(clue.activity);
|
|
2368
|
-
else if (clue?.result != null) resultText = clue.result;
|
|
4809
|
+
read(line);
|
|
2369
4810
|
}
|
|
2370
4811
|
});
|
|
4812
|
+
flushStream = () => { if (buf.trim()) read(buf); buf = ''; };
|
|
2371
4813
|
child.stderr.on('data', keep);
|
|
2372
4814
|
} else {
|
|
2373
4815
|
child.stdout.on('data', (chunk) => {
|
|
@@ -2392,25 +4834,60 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2392
4834
|
child.on('error', (e) => {
|
|
2393
4835
|
clearTimeout(timeout);
|
|
2394
4836
|
clearTimeout(hard);
|
|
4837
|
+
putBack();
|
|
4838
|
+
hold?.done(null);
|
|
4839
|
+
try { knownDeck = readDeck(); } catch { /* gone: the watch says so */ }
|
|
2395
4840
|
agentJob = null;
|
|
4841
|
+
agentBase = null;
|
|
2396
4842
|
agentStop = null;
|
|
2397
4843
|
finish({ ok: false, changed: false, error: String(e.message || e) });
|
|
2398
4844
|
broadcast('agent', { state: 'done', id: ask.id, agent: cmd.name, ok: false, changed: false, error: String(e.message || e) });
|
|
2399
4845
|
});
|
|
2400
|
-
|
|
4846
|
+
// after its output, not at its exit: a result line still in the pipe
|
|
4847
|
+
// when the process went was a report lost (see afterOutput)
|
|
4848
|
+
afterOutput(child, (code) => {
|
|
2401
4849
|
clearTimeout(timeout);
|
|
2402
4850
|
clearTimeout(hard);
|
|
2403
4851
|
agentStop = null;
|
|
4852
|
+
flushStream();
|
|
2404
4853
|
const after = readDeck();
|
|
4854
|
+
// what the agent's edit is measured from, and undone back to: the run's
|
|
4855
|
+
// start, moved on past every write the author made meanwhile
|
|
4856
|
+
const base = agentBase?.deck ?? before;
|
|
4857
|
+
agentBase = null;
|
|
2405
4858
|
const filesAfter = snapshotFiles(files);
|
|
2406
4859
|
const filesChanged = Object.keys(filesBefore).some((p) => filesAfter[p] !== filesBefore[p]);
|
|
2407
|
-
const changed = after !==
|
|
4860
|
+
const changed = !explain && (after !== base || filesChanged);
|
|
4861
|
+
// held for review: the deck goes back, the edit becomes the candidate
|
|
4862
|
+
putBack();
|
|
4863
|
+
const held = hold ? hold.done(changed ? after : null, { ok: code === 0 && !stopped }) : null;
|
|
4864
|
+
// the voice folders follow the slides the edit added, removed or moved
|
|
4865
|
+
// (#920), before the impact is read and the commit made
|
|
4866
|
+
const landed = explain ? null : !hold ? (changed && after !== base ? base : null)
|
|
4867
|
+
: (changed && !held && hold.start === undefined && after !== kept ? kept : null);
|
|
4868
|
+
let followed = null;
|
|
4869
|
+
if (landed !== null) {
|
|
4870
|
+
try { followed = followSlides(landed, after); } catch (e) { followed = { error: oneline(e) }; }
|
|
4871
|
+
}
|
|
4872
|
+
// what an undo entry carries beside the deck: its files, and the folders' steps back
|
|
4873
|
+
const also = (deck, files) => (files || followed?.voices
|
|
4874
|
+
? { deck, ...(files ? { files } : {}), ...(followed?.voices ? { voices: followed.voices } : {}) }
|
|
4875
|
+
: deck);
|
|
4876
|
+
// a first run the review could not hold lands as it always did, never lost
|
|
4877
|
+
const agentSaid = { what: `${cmd.label ?? cmd.name}'s edit`, slide: null };
|
|
4878
|
+
if (hold && changed && !held && hold.start === undefined) { history.record(also(kept), agentSaid); writeDeck(after); }
|
|
2408
4879
|
// Z takes the agent's edit back — with the files beside the deck it wrote, in the same step
|
|
2409
|
-
if (changed) history.record(filesChanged ?
|
|
4880
|
+
if (changed && !hold) history.record(also(base, filesChanged ? filesBefore : null), agentSaid);
|
|
4881
|
+
// the run has followed its own slides: the file watch's next look must not again
|
|
4882
|
+
try { knownDeck = readDeck(); } catch { /* gone: the watch says so */ }
|
|
4883
|
+
const voicesFollowed = followed?.said?.length ? followed.said.join('; ') : null;
|
|
4884
|
+
const voicesStuck = followed?.error ? `🎙 ${followed.error}` : null;
|
|
4885
|
+
for (const line of followed?.said ?? []) console.log(` narration: ${line}`);
|
|
4886
|
+
if (voicesStuck) console.log(` narration: ${followed.error}`);
|
|
2410
4887
|
// One commit per completed agent edit, carrying the agent's own summary
|
|
2411
4888
|
// — the boundary and the message both come from the work, not a clock.
|
|
2412
4889
|
// A failed run or one that changed nothing commits nothing.
|
|
2413
|
-
if (gitOn && shouldCommit(gitMode, { kind: 'agent', ok: code === 0, changed })) {
|
|
4890
|
+
if (!hold && !explain && gitOn && shouldCommit(gitMode, { kind: 'agent', ok: code === 0, changed })) {
|
|
2414
4891
|
const subject = given ?? commitSubject(message ?? prompt, `decklight: ${cmd.name} edited ${basename(deckPath)}`);
|
|
2415
4892
|
if (gitAutocommit(deckPath, root, subject, { also: [...alsoNow().also, ...files] })) { pendingAttr = null; console.log(` git: committed "${subject}"`); }
|
|
2416
4893
|
}
|
|
@@ -2421,14 +4898,24 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2421
4898
|
// word is said. A warning, never a block: the file is already written,
|
|
2422
4899
|
// Z takes it back, and the audio never left the disk.
|
|
2423
4900
|
let recordingWarning = null;
|
|
2424
|
-
if (changed) {
|
|
4901
|
+
if (changed && !hold && !explain) {
|
|
2425
4902
|
try {
|
|
2426
|
-
|
|
4903
|
+
// the folders that followed are read where each take went, and as
|
|
4904
|
+
// they are now — which is already numbered like `after`
|
|
4905
|
+
const renumber = followed?.renumber ?? null;
|
|
4906
|
+
const back = (dir) => {
|
|
4907
|
+
const f = renumber?.get(String(dir).replace(/^\.\//, '').replace(/\/+$/, ''));
|
|
4908
|
+
return f ? (n) => { for (let k = 1; k <= n + 64; k++) if (f(k) === n) return k; return null; } : null;
|
|
4909
|
+
};
|
|
4910
|
+
const impact = recordingImpact(base, after, {
|
|
2427
4911
|
dirsOf: configuredTrackDirs,
|
|
2428
4912
|
recordedSlides: (dir) => {
|
|
2429
|
-
|
|
2430
|
-
catch { return []; }
|
|
4913
|
+
let now = [];
|
|
4914
|
+
try { now = slidesFromFiles(readdirSync(resolve(dirname(deckPath), dir))); } catch { return []; }
|
|
4915
|
+
const was = back(dir);
|
|
4916
|
+
return was ? now.map(was).filter((k) => k != null) : now;
|
|
2431
4917
|
},
|
|
4918
|
+
renumber,
|
|
2432
4919
|
});
|
|
2433
4920
|
recordingWarning = impactWarning(impact);
|
|
2434
4921
|
} catch { recordingWarning = null; } // a warning that throws is worse than none
|
|
@@ -2438,19 +4925,22 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2438
4925
|
// stdout is a wall of JSON nobody should be shown
|
|
2439
4926
|
// — from its start: a report leads with what it did (a migration's
|
|
2440
4927
|
// renames and their counts), and the panel scrolls
|
|
2441
|
-
const said = reportText(resultText ?? tail.trim().split('\n').slice(-6).join('\n'));
|
|
4928
|
+
const said = reportText(resultText ?? (explain ? tail : tail.trim().split('\n').slice(-6).join('\n')));
|
|
2442
4929
|
// Files the run created beside the deck and left there: never in the
|
|
2443
4930
|
// commit (it names its paths), and said, so the author can delete them
|
|
2444
4931
|
const left = (besideDeck() ?? []).filter((f) => !leftBefore.has(f));
|
|
2445
4932
|
if (left.length) console.log(` agent: ${cmd.name} left ${left.join(', ')} beside the deck (not committed)`);
|
|
2446
|
-
finish({ ok: code === 0, changed, code, tail: said, ...(left.length ? { left } : {}), ...(stopped ? { stopped } : {}) });
|
|
4933
|
+
finish({ ok: code === 0, changed, code, tail: said, ...(left.length ? { left } : {}), ...(stopped ? { stopped } : {}), ...(held ? { held: true } : {}), ...(voicesFollowed ? { voicesFollowed } : {}) });
|
|
2447
4934
|
broadcast('agent', {
|
|
2448
4935
|
state: 'done', id: ask.id, agent: cmd.name, ok: code === 0, changed, code, tail: said,
|
|
2449
4936
|
...(left.length ? { left } : {}),
|
|
2450
4937
|
...(stopped ? { stopped } : {}),
|
|
4938
|
+
...(held ? { candidate: held } : {}),
|
|
2451
4939
|
...(recordingWarning ? { recordingWarning } : {}),
|
|
4940
|
+
...(voicesFollowed ? { voicesFollowed } : {}),
|
|
4941
|
+
...(voicesStuck ? { voicesStuck } : {}),
|
|
2452
4942
|
});
|
|
2453
|
-
console.log(` agent: ${cmd.name} ${stopped ? 'stopped' : `exited (${code})`} — deck ${changed ? 'changed' : '
|
|
4943
|
+
console.log(` agent: ${cmd.name} ${stopped ? 'stopped' : `exited (${code})`} — deck ${!changed ? 'unchanged' : hold ? 'changed, held for review' : 'changed'}`);
|
|
2454
4944
|
if (recordingWarning) console.log(` ${recordingWarning}`);
|
|
2455
4945
|
});
|
|
2456
4946
|
return cmd;
|
|
@@ -2522,15 +5012,38 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2522
5012
|
function undoRedoRoute({ url, json }) {
|
|
2523
5013
|
const dir = url.pathname.endsWith('undo') ? 'undo' : 'redo';
|
|
2524
5014
|
const cur = readDeck();
|
|
5015
|
+
// what this step takes back, read before it moves: the page says it and goes there
|
|
5016
|
+
const said = history.next(dir);
|
|
2525
5017
|
// an entry that wrote files beside the deck is answered by those files as they are now
|
|
2526
|
-
|
|
5018
|
+
// …and one that renumbered voice folders (#916) by its steps, planned
|
|
5019
|
+
// against the folders as they are now: a take recorded since is carried
|
|
5020
|
+
// along, not written over, and redo gets the steps that undo this
|
|
5021
|
+
const deckDir = dirname(deckPath);
|
|
5022
|
+
let plans = null;
|
|
5023
|
+
const content = history[dir]((e) => {
|
|
5024
|
+
if (typeof e === 'string') return cur;
|
|
5025
|
+
plans = e.voices ? e.voices.map((step) => planFolder(deckDir, step)) : null;
|
|
5026
|
+
return {
|
|
5027
|
+
deck: cur,
|
|
5028
|
+
files: snapshotFiles(Object.keys(e.files ?? {})),
|
|
5029
|
+
...(plans ? { voices: plans.map((p) => p.inverse) } : {}),
|
|
5030
|
+
};
|
|
5031
|
+
});
|
|
2527
5032
|
if (content === null) return json(409, { ok: false, error: `nothing to ${dir}`, ...history.counts() });
|
|
2528
5033
|
if (typeof content !== 'string') {
|
|
2529
5034
|
for (const [p, text] of Object.entries(content.files ?? {})) writeFileAtomic(p, text);
|
|
5035
|
+
if (plans) {
|
|
5036
|
+
// a file in the way is set aside in the folder's .trash/, never written over
|
|
5037
|
+
try {
|
|
5038
|
+
const { moved, setAside } = applyPlans(deckDir, plans.filter(planMoves), { aside: true });
|
|
5039
|
+
if (moved) console.log(` ${dir}: ${moved} recording file${moved === 1 ? '' : 's'} moved with the slides`);
|
|
5040
|
+
for (const p of setAside) console.log(` ${dir}: ${p} was in the way, set aside rather than overwritten`);
|
|
5041
|
+
} catch (e) { console.log(` ${dir}: the voice folders could not follow — ${oneline(e)}; they are as they were`); }
|
|
5042
|
+
}
|
|
2530
5043
|
}
|
|
2531
5044
|
writeDeck(typeof content === 'string' ? content : content.deck);
|
|
2532
|
-
console.log(` ${dir} → ${JSON.stringify(history.counts())}`);
|
|
2533
|
-
return json(200, { ok: true, ...history.counts() });
|
|
5045
|
+
console.log(` ${dir} → ${JSON.stringify(history.counts())}${said?.what ? ` — ${said.what}${said.slide ? ` on slide ${said.slide}` : ''}` : ''}`);
|
|
5046
|
+
return json(200, { ok: true, ...history.counts(), ...(said ? { what: said.what, slide: said.slide } : {}) });
|
|
2534
5047
|
}
|
|
2535
5048
|
|
|
2536
5049
|
// ── review comments (SPEC REVIEW) ─────────────────────────────
|
|
@@ -2658,7 +5171,7 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2658
5171
|
return json(200, { ok: true, forgotten: had });
|
|
2659
5172
|
}
|
|
2660
5173
|
|
|
2661
|
-
// ── the recorder's offline recordings — V →
|
|
5174
|
+
// ── the recorder's offline recordings — V → Save with the deck, or your voice (PRESENTING) ───────────────────────────────
|
|
2662
5175
|
// The player used to hand every stitched slide to the browser's DOWNLOAD
|
|
2663
5176
|
// path, which is why a deck's voice arrived as thirty slide-NN.wav in
|
|
2664
5177
|
// whatever folder the OS calls Downloads — never the deck's, and on
|
|
@@ -2670,11 +5183,18 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2670
5183
|
// Ahead of the shared body read below because this body is BINARY and
|
|
2671
5184
|
// megabytes of it: a slide of speech is ~48 kB a second, so the string
|
|
2672
5185
|
// concat and its 1 MB ceiling would both be wrong.
|
|
5186
|
+
/** A track folder named by a request, inside the served root; null for one that is not. */
|
|
5187
|
+
function trackDir(want) {
|
|
5188
|
+
const bad = want.length > 200 || /^[/\\]/.test(want) || /^[a-zA-Z]:/.test(want)
|
|
5189
|
+
|| want.split(/[/\\]/).includes('..');
|
|
5190
|
+
const dir = bad ? null : resolve(deckPath, '..', want);
|
|
5191
|
+
return dir && (dir.startsWith(root + sep) || dir === root) ? dir : null;
|
|
5192
|
+
}
|
|
2673
5193
|
async function recordRoute({ req, url, json }) {
|
|
2674
5194
|
const slide = Number(url.searchParams.get('slide'));
|
|
2675
5195
|
const kind = url.searchParams.get('kind');
|
|
2676
5196
|
if (!Number.isInteger(slide) || slide < 1 || slide > 9999) return json(400, { ok: false, error: 'bad slide' });
|
|
2677
|
-
if (
|
|
5197
|
+
if (!['wav', 'visemes', 'manifest', 'voice', 'face', 'face-join'].includes(kind)) return json(400, { ok: false, error: 'bad kind' });
|
|
2678
5198
|
// `seg` is the per-⟨CLICK⟩ file number — the audio that lets a recording
|
|
2679
5199
|
// step the builds (slide-NN-KK.wav) and the viseme timeline cut to
|
|
2680
5200
|
// match it (slide-NN-KK.visemes.json). Absent means the whole slide.
|
|
@@ -2693,15 +5213,36 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2693
5213
|
// and `..`, absolute paths and Windows drive letters are refused before
|
|
2694
5214
|
// it, because `resolve` would happily swallow all three.
|
|
2695
5215
|
const want = url.searchParams.get('dir') || 'voiceover';
|
|
2696
|
-
const
|
|
2697
|
-
|
|
2698
|
-
const
|
|
2699
|
-
|
|
2700
|
-
|
|
5216
|
+
const dir = trackDir(want);
|
|
5217
|
+
if (!dir) return json(400, { ok: false, error: 'the recording folder must sit inside the deck\'s own directory' });
|
|
5218
|
+
const stem = `slide-${String(slide).padStart(2, '0')}`
|
|
5219
|
+
+ (seg === null ? '' : `-${String(seg).padStart(2, '0')}`);
|
|
5220
|
+
const name = `${stem}.${kind === 'wav' ? 'wav' : kind === 'face' ? 'mp4' : 'visemes.json'}`;
|
|
5221
|
+
// Your face, filmed with the beat (PRESENTING, the your-voice recorder):
|
|
5222
|
+
// made into a clip exactly as long as the beat's WAV, which is uploaded
|
|
5223
|
+
// first, so the face cannot drift from the voice across a slide
|
|
5224
|
+
// (tools/face-clip.mjs). Then `face-join` makes the slide's clip from its
|
|
5225
|
+
// beats', the way the runtime stitches the whole-slide WAV from them. A
|
|
5226
|
+
// beat with no clip (recorded before the camera was on) cannot be joined:
|
|
5227
|
+
// the slide's old clip is taken away rather than left to play over audio
|
|
5228
|
+
// it was not filmed with, and the answer names what is missing.
|
|
5229
|
+
if (kind === 'face-join') {
|
|
5230
|
+
const segs = String(url.searchParams.get('segs') ?? '').split(',').filter(Boolean).map(Number);
|
|
5231
|
+
if (!segs.length || segs.some((k) => !Number.isInteger(k) || k < 1 || k > 999)) return json(400, { ok: false, error: 'bad segs' });
|
|
5232
|
+
const nn = String(slide).padStart(2, '0');
|
|
5233
|
+
const parts = segs.map((k) => resolve(dir, `slide-${nn}-${String(k).padStart(2, '0')}.mp4`));
|
|
5234
|
+
const missing = segs.filter((_, i) => !existsSync(parts[i]));
|
|
5235
|
+
const out = resolve(dir, `slide-${nn}.mp4`);
|
|
5236
|
+
if (missing.length) {
|
|
5237
|
+
rmSync(out, { force: true });
|
|
5238
|
+
return json(200, { ok: false, dir: want, missing });
|
|
5239
|
+
}
|
|
5240
|
+
const { joinFaceClips, hasFfmpeg } = await import('../tools/face-clip.mjs');
|
|
5241
|
+
if (!(await hasFfmpeg())) return json(501, { ok: false, error: 'the face needs ffmpeg to be saved: install it (brew install ffmpeg / apt install ffmpeg)' });
|
|
5242
|
+
try { await joinFaceClips({ parts, out }); } catch (e) { rmSync(out, { force: true }); return json(500, { ok: false, error: oneline(e) }); }
|
|
5243
|
+
console.log(` filmed ${want}/slide-${nn}.mp4 (${segs.length} beat${segs.length === 1 ? '' : 's'})`);
|
|
5244
|
+
return json(200, { ok: true, dir: want, file: `slide-${nn}.mp4` });
|
|
2701
5245
|
}
|
|
2702
|
-
const name = `slide-${String(slide).padStart(2, '0')}`
|
|
2703
|
-
+ (seg === null ? '' : `-${String(seg).padStart(2, '0')}`)
|
|
2704
|
-
+ `.${kind === 'wav' ? 'wav' : 'visemes.json'}`;
|
|
2705
5246
|
const chunks = [];
|
|
2706
5247
|
let size = 0;
|
|
2707
5248
|
for await (const chunk of req) {
|
|
@@ -2716,17 +5257,31 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2716
5257
|
// the notes each hash covers are read from the deck file here, the way
|
|
2717
5258
|
// voiceover and video read them, so the three can never disagree on the
|
|
2718
5259
|
// text. Written after every slide, so an aborted take is a valid partial.
|
|
2719
|
-
if (kind === 'manifest') {
|
|
5260
|
+
if (kind === 'manifest' || kind === 'voice') {
|
|
2720
5261
|
if (size > 1e6) return json(413, { ok: false, error: 'manifest too large' });
|
|
2721
5262
|
let req2;
|
|
2722
5263
|
try { req2 = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return json(400, { ok: false, error: 'the manifest is not JSON' }); }
|
|
2723
5264
|
const str = (v, max = 120) => (typeof v === 'string' && v.length <= max && /^[\w .:+()'-]*$/.test(v) ? v : null);
|
|
5265
|
+
const voiceField = (v) => (typeof v === 'string' && v.length <= 500 && v.trim() && !/[\u0000-\u001f\u007f]/.test(v) ? v : null);
|
|
5266
|
+
const identity = { voice: voiceField(req2.voice), voiceId: voiceField(req2.voiceId) };
|
|
5267
|
+
const file = resolve(dir, 'manifest.json');
|
|
5268
|
+
const { recorderManifest, withTrackVoice, slideTexts, slideBeats } = await import('../tools/narration-manifest.mjs');
|
|
5269
|
+
let prev = null;
|
|
5270
|
+
try { prev = JSON.parse(readFileSync(file, 'utf8')); } catch { /* first take here */ }
|
|
5271
|
+
if (kind === 'voice') {
|
|
5272
|
+
if (!identity.voice || !identity.voiceId) return json(400, { ok: false, error: 'choose a voice from the engine’s roster' });
|
|
5273
|
+
if (!Array.isArray(prev?.slides) || !prev.engine || prev.engine !== req2.engine || prev.voice || prev.voiceId) {
|
|
5274
|
+
return json(409, { ok: false, error: 'the track has changed — reopen the voice panel' });
|
|
5275
|
+
}
|
|
5276
|
+
writeFileAtomic(file, JSON.stringify(withTrackVoice(prev, identity), null, 2) + '\n');
|
|
5277
|
+
return json(200, { ok: true, ...identity });
|
|
5278
|
+
}
|
|
2724
5279
|
// `mine`: your own voice (#850), which no engine voiced. Its manifest
|
|
2725
5280
|
// carries the beats as you read them, so a moved ⟨CLICK⟩ can be told
|
|
2726
5281
|
// from changed words, and the notes hash `decklight video` checks.
|
|
2727
5282
|
const mine = req2.mine === true;
|
|
2728
5283
|
const header = mine ? { engine: null, model: null, voice: null, style: null }
|
|
2729
|
-
: { engine: str(req2.engine, 40), model: str(req2.model),
|
|
5284
|
+
: { engine: str(req2.engine, 40), model: str(req2.model), ...identity, style: typeof req2.style === 'string' && req2.style.length <= 400 ? req2.style : null };
|
|
2730
5285
|
if (!mine && !header.engine) return json(400, { ok: false, error: 'the manifest names no engine' });
|
|
2731
5286
|
const from = Number(req2.range?.[0]), to = Number(req2.range?.[1]);
|
|
2732
5287
|
if (!Number.isInteger(from) || !Number.isInteger(to) || from < 1 || to < from || to > 9999) return json(400, { ok: false, error: 'bad range' });
|
|
@@ -2734,11 +5289,18 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2734
5289
|
for (const [k, v] of Object.entries(req2.slides ?? {})) {
|
|
2735
5290
|
const n = Number(k);
|
|
2736
5291
|
if (!Number.isInteger(n) || n < from || n > to) continue;
|
|
2737
|
-
recorded[n] = { segments: Array.isArray(v?.segments) ? v.segments.map(Number) : [] };
|
|
5292
|
+
recorded[n] = { segments: Array.isArray(v?.segments) ? v.segments.map(Number) : [], ...(v?.face === true ? { face: true } : {}) };
|
|
5293
|
+
}
|
|
5294
|
+
if (!mine && Array.isArray(prev?.slides) && prev.engine === header.engine && header.voice
|
|
5295
|
+
&& (prev.voiceId ? prev.voiceId === header.voiceId : prev.voice === header.voice
|
|
5296
|
+
|| (req2.revoice === true && prev.voice === req2.previousVoice))) {
|
|
5297
|
+
prev = withTrackVoice(prev, identity);
|
|
5298
|
+
if (prev.format) header.format = prev.format;
|
|
5299
|
+
if (req2.revoice === true) {
|
|
5300
|
+
header.model = prev.model;
|
|
5301
|
+
header.style = prev.style;
|
|
5302
|
+
}
|
|
2738
5303
|
}
|
|
2739
|
-
const { recorderManifest, slideTexts, slideBeats } = await import('../tools/narration-manifest.mjs');
|
|
2740
|
-
let prev = null;
|
|
2741
|
-
try { prev = JSON.parse(readFileSync(resolve(dir, 'manifest.json'), 'utf8')); } catch { /* first take here */ }
|
|
2742
5304
|
// A folder of your voice recorded before it had a manifest: its other
|
|
2743
5305
|
// slides are on disk, and a manifest naming only this one would hide
|
|
2744
5306
|
// them from `decklight video`, which trusts a manifest over the files.
|
|
@@ -2752,43 +5314,160 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2752
5314
|
prev: Array.isArray(prev?.slides) ? prev : null, header, texts: slideTexts(deckNow), range: { from, to }, recorded,
|
|
2753
5315
|
...(mine ? { recorder: 'mic', beats: slideBeats(deckNow) } : {}),
|
|
2754
5316
|
});
|
|
5317
|
+
// A slide recorded again without the camera (or whose beats could not
|
|
5318
|
+
// all be filmed): its clips show a face saying what was said before.
|
|
5319
|
+
// A beat's clip is only ever filmed, so it goes; the slide's goes when
|
|
5320
|
+
// the manifest said it was filmed, never one `decklight lipsync` made.
|
|
5321
|
+
if (mine) {
|
|
5322
|
+
let names = [];
|
|
5323
|
+
try { names = readdirSync(dir); } catch { /* no folder, nothing filmed */ }
|
|
5324
|
+
for (const n of Object.keys(recorded)) {
|
|
5325
|
+
if (recorded[n].face) continue;
|
|
5326
|
+
const nn = String(n).padStart(2, '0');
|
|
5327
|
+
const filmed = !!prev?.slides?.[n - 1]?.face;
|
|
5328
|
+
for (const f of names) {
|
|
5329
|
+
if (new RegExp(`^slide-${nn}-\\d+\\.mp4$`).test(f) || (filmed && f === `slide-${nn}.mp4`)) rmSync(resolve(dir, f), { force: true });
|
|
5330
|
+
}
|
|
5331
|
+
}
|
|
5332
|
+
}
|
|
2755
5333
|
try {
|
|
2756
5334
|
mkdirSync(dir, { recursive: true });
|
|
2757
|
-
|
|
5335
|
+
writeFileAtomic(file, JSON.stringify(manifest, null, 2) + '\n');
|
|
2758
5336
|
// the script beside each file, as voiceover writes it — `--reuse-text` reads it back
|
|
2759
5337
|
const texts = slideTexts(readDeck());
|
|
2760
5338
|
for (const n of Object.keys(recorded)) writeFileSync(resolve(dir, `slide-${String(n).padStart(2, '0')}.txt`), texts[n - 1] ?? '');
|
|
2761
5339
|
} catch (e) { return json(500, { ok: false, error: oneline(e) }); }
|
|
2762
5340
|
return json(200, { ok: true, dir: want, file: 'manifest.json', slides: manifest.slides.filter(Boolean).length });
|
|
2763
5341
|
}
|
|
5342
|
+
if (kind === 'face') {
|
|
5343
|
+
const { writeFaceClip, hasFfmpeg } = await import('../tools/face-clip.mjs');
|
|
5344
|
+
if (!(await hasFfmpeg())) return json(501, { ok: false, error: 'the face needs ffmpeg to be saved: install it (brew install ffmpeg / apt install ffmpeg)' });
|
|
5345
|
+
try {
|
|
5346
|
+
mkdirSync(dir, { recursive: true });
|
|
5347
|
+
await writeFaceClip({ bytes: Buffer.concat(chunks), out: resolve(dir, name), wav: resolve(dir, `${stem}.wav`) });
|
|
5348
|
+
} catch (e) { rmSync(resolve(dir, name), { force: true }); return json(500, { ok: false, error: oneline(e) }); }
|
|
5349
|
+
console.log(` filmed ${want}/${name} (${Math.round(size / 1024)} kB)`);
|
|
5350
|
+
return json(200, { ok: true, dir: want, file: name });
|
|
5351
|
+
}
|
|
5352
|
+
let body = Buffer.concat(chunks);
|
|
5353
|
+
// Lip-sync and its audio are one recording (#1244). A sidecar is stamped
|
|
5354
|
+
// with the hash of the WAV it was cut from (uploaded just before it), so
|
|
5355
|
+
// a reader can tell it from one another take left behind…
|
|
5356
|
+
if (kind === 'visemes') {
|
|
5357
|
+
try {
|
|
5358
|
+
const tl = JSON.parse(body.toString('utf8'));
|
|
5359
|
+
const wav = resolve(dir, `${stem}.wav`);
|
|
5360
|
+
if (tl && typeof tl === 'object' && existsSync(wav)) {
|
|
5361
|
+
const { audioStamp } = await import('../tools/viseme-match.mjs');
|
|
5362
|
+
body = Buffer.from(JSON.stringify({ ...tl, audio: audioStamp(readFileSync(wav)) }));
|
|
5363
|
+
}
|
|
5364
|
+
} catch { /* not JSON: written as sent, and the export will say so */ }
|
|
5365
|
+
}
|
|
2764
5366
|
try {
|
|
2765
5367
|
mkdirSync(dir, { recursive: true });
|
|
2766
|
-
writeFileSync(resolve(dir, name),
|
|
5368
|
+
writeFileSync(resolve(dir, name), body);
|
|
5369
|
+
// …and new audio takes the old sidecar away with it: when no new one
|
|
5370
|
+
// follows (the bridge was down), the character falls back to the voice's
|
|
5371
|
+
// loudness and the export remakes it, instead of mouthing the last take.
|
|
5372
|
+
if (kind === 'wav') rmSync(resolve(dir, `${stem}.visemes.json`), { force: true });
|
|
2767
5373
|
} catch (e) { return json(500, { ok: false, error: oneline(e) }); }
|
|
2768
5374
|
console.log(` recorded ${want}/${name} (${Math.round(size / 1024)} kB)`);
|
|
2769
5375
|
return json(200, { ok: true, dir: want, file: name });
|
|
2770
5376
|
}
|
|
2771
5377
|
|
|
5378
|
+
// Lip-sync that follows the audio (#1244, SPEC CHARACTER). A track's
|
|
5379
|
+
// sidecars are checked against its audio (tools/lipsync-auto.mjs) for the
|
|
5380
|
+
// voice card, and remade here in the background — Rhubarb takes minutes on
|
|
5381
|
+
// a long slide — after the deck generated a recording the bridge could not
|
|
5382
|
+
// cut lip-sync for, or when the card's "Update lip-sync" asks. One job per
|
|
5383
|
+
// folder; its progress is in the tracks answer, which the deck polls.
|
|
5384
|
+
const lipsyncJobs = new Map(); // track dir, as the deck names it → { total, done, made, error, running }
|
|
5385
|
+
async function lipsyncRoute({ url, json }) {
|
|
5386
|
+
const want = url.searchParams.get('dir') || 'voiceover';
|
|
5387
|
+
const dir = trackDir(want);
|
|
5388
|
+
if (!dir) return json(400, { ok: false, error: 'the track folder must sit inside the deck\'s own directory' });
|
|
5389
|
+
const key = want.split(/[/\\]/).filter(Boolean).join('/');
|
|
5390
|
+
const running = lipsyncJobs.get(key);
|
|
5391
|
+
if (running?.running) return json(200, { ok: true, ...running });
|
|
5392
|
+
const { lipsyncStatus, makeLipsync, haveRhubarb } = await import('../tools/lipsync-auto.mjs');
|
|
5393
|
+
const stems = lipsyncStatus(dir).stale.map((st) => st.stem);
|
|
5394
|
+
if (!stems.length) {
|
|
5395
|
+
lipsyncJobs.delete(key);
|
|
5396
|
+
return json(200, { ok: true, total: 0, done: 0, made: 0, error: null, running: false });
|
|
5397
|
+
}
|
|
5398
|
+
// without Rhubarb the files are read from the voice (tools/lipsync.mjs), and the job says which
|
|
5399
|
+
const rhubarb = haveRhubarb();
|
|
5400
|
+
const job = { total: stems.length, done: 0, made: 0, error: null, running: true, ...(rhubarb ? {} : { fromVoice: true }) };
|
|
5401
|
+
lipsyncJobs.set(key, job);
|
|
5402
|
+
console.log(` lip-sync: cutting ${stems.length} file${stems.length === 1 ? '' : 's'} in ${key}/${rhubarb ? ' with Rhubarb' : ', read from the voice'}…`);
|
|
5403
|
+
makeLipsync(dir, stems, {
|
|
5404
|
+
log: (line) => {
|
|
5405
|
+
console.log(line);
|
|
5406
|
+
const m = /\[(\d+)\/\d+\]/.exec(line);
|
|
5407
|
+
if (m) job.done = Math.max(job.done, Number(m[1]));
|
|
5408
|
+
},
|
|
5409
|
+
}).then((r) => {
|
|
5410
|
+
Object.assign(job, { running: false, made: r.made, error: r.why, done: r.ok ? job.total : job.done });
|
|
5411
|
+
console.log(r.ok ? ` lip-sync: ${r.made} file${r.made === 1 ? '' : 's'} made in ${key}/`
|
|
5412
|
+
: ` lip-sync: not made in ${key}/ — ${r.why}`);
|
|
5413
|
+
});
|
|
5414
|
+
return json(200, { ok: true, ...job });
|
|
5415
|
+
}
|
|
5416
|
+
|
|
5417
|
+
/**
|
|
5418
|
+
* A track's lip-sync, for the voice card: of the files the 2D character
|
|
5419
|
+
* plays, how many have a sidecar that is missing or another recording's,
|
|
5420
|
+
* the first reason, and the job remaking them, if there is one.
|
|
5421
|
+
*/
|
|
5422
|
+
function lipsyncOf(lips, rel) {
|
|
5423
|
+
const key = rel.split(/[/\\]/).filter(Boolean).join('/');
|
|
5424
|
+
const { stems, stale } = lips.lipsyncStatus(resolve(deckPath, '..', rel));
|
|
5425
|
+
const job = lipsyncJobs.get(key);
|
|
5426
|
+
return {
|
|
5427
|
+
of: stems.length,
|
|
5428
|
+
stale: stale.length,
|
|
5429
|
+
why: stale[0] ? `${stale[0].stem}: ${stale[0].why}` : null,
|
|
5430
|
+
...(job ? { job: { ...job } } : {}),
|
|
5431
|
+
};
|
|
5432
|
+
}
|
|
5433
|
+
|
|
2772
5434
|
// What tracks already sit next to this deck. The runtime cannot see the
|
|
2773
5435
|
// filesystem — which is why `segments: true` is opt-in at all — so it
|
|
2774
5436
|
// cannot know that `voices/rachel` is taken before proposing it. One
|
|
2775
5437
|
// question, asked when a recorder opens.
|
|
2776
|
-
function tracksRoute({ json }) {
|
|
5438
|
+
async function tracksRoute({ url, json }) {
|
|
2777
5439
|
const root2 = resolve(deckPath, '..');
|
|
2778
5440
|
const seen = [];
|
|
2779
5441
|
const deck = readDeck();
|
|
5442
|
+
// the deck says which character it plays (a viewer may have switched it
|
|
5443
|
+
// from what the file configures); only a 2D one mouths a sidecar
|
|
5444
|
+
const lips = url?.searchParams?.get('character') === 'viseme'
|
|
5445
|
+
? await import('../tools/lipsync-auto.mjs') : null;
|
|
2780
5446
|
const texts = slideTexts(deck);
|
|
2781
5447
|
const prior = priorSlideTexts(deck);
|
|
5448
|
+
// the deck in another language beside this one has its own tracks
|
|
5449
|
+
// (PRESENTING_VOICE): a folder the deck's config names is always its own
|
|
5450
|
+
const family = deckFamily(deckPath);
|
|
5451
|
+
const named = new Set(configuredTrackDirs(deck).map((d) => d.replace(/^\.\//, '').replace(/\/+$/, '')));
|
|
5452
|
+
const mineToList = (rel) => {
|
|
5453
|
+
const key = rel.split(sep).join('/');
|
|
5454
|
+
return named.has(key) || ownsTrack(family, key, readManifest(resolve(root2, rel)));
|
|
5455
|
+
};
|
|
2782
5456
|
const look = (rel) => {
|
|
2783
5457
|
let entries;
|
|
2784
5458
|
try { entries = readdirSync(resolve(root2, rel), { withFileTypes: true }); } catch { return; }
|
|
2785
5459
|
const wav = entries.filter((e) => e.isFile() && /^slide-\d+(-\d+)?\.(wav|m4a|mp3)$/.test(e.name));
|
|
2786
|
-
if (wav.length) {
|
|
2787
|
-
let engine = null; let voice = null; let manifest = false; let stale = 0; let mine = false;
|
|
5460
|
+
if (wav.length && mineToList(rel)) {
|
|
5461
|
+
let engine = null; let voice = null; let voiceId = null; let model = null; let style = null; let manifest = false; let stale = 0; let mine = false;
|
|
2788
5462
|
let drift = [];
|
|
5463
|
+
let realign = null;
|
|
5464
|
+
let faces = [];
|
|
2789
5465
|
try {
|
|
2790
5466
|
const m = JSON.parse(readFileSync(resolve(root2, rel, 'manifest.json'), 'utf8'));
|
|
2791
|
-
engine = m.engine ?? null; voice = m.voice ?? null; manifest = true; mine = m.recorder === 'mic';
|
|
5467
|
+
engine = m.engine ?? null; voice = m.voice ?? null; voiceId = m.voiceId ?? null; manifest = true; mine = m.recorder === 'mic';
|
|
5468
|
+
// …and the rest of who voiced it, so the V panel re-voices a
|
|
5469
|
+
// synthesized track as itself rather than as the live voice (#919)
|
|
5470
|
+
model = m.model ?? null; style = m.style ?? null;
|
|
2792
5471
|
// how many of its slides were voiced from other notes than the deck
|
|
2793
5472
|
// has now — the export card marks the track with it (#536)
|
|
2794
5473
|
if (Array.isArray(m.slides)) {
|
|
@@ -2796,6 +5475,13 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2796
5475
|
// …and which, and how (#850): the V panel and narrate --check
|
|
2797
5476
|
// say "the [click] moved" rather than only "different notes"
|
|
2798
5477
|
drift = trackDrift(m, deck).drift;
|
|
5478
|
+
// …and whether those recordings are only in the wrong place (#916):
|
|
5479
|
+
// the deck was reordered outside the slide ops, and each one's
|
|
5480
|
+
// stored words say which slide it belongs to now
|
|
5481
|
+
realign = realignMoves(m, deck, { scripts: trackScripts(resolve(root2, rel)) });
|
|
5482
|
+
// …and which slides were filmed with your face (FACE_LAYOUT), so
|
|
5483
|
+
// the panel offers to place it only where there is one
|
|
5484
|
+
faces = m.slides.map((e, i) => (e?.face === true ? i + 1 : null)).filter(Boolean);
|
|
2799
5485
|
}
|
|
2800
5486
|
} catch { /* a folder recorded by hand has no manifest, and needs none */ }
|
|
2801
5487
|
seen.push({
|
|
@@ -2811,14 +5497,24 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2811
5497
|
ext: (wav[0].name.split('.').pop()),
|
|
2812
5498
|
engine,
|
|
2813
5499
|
voice,
|
|
5500
|
+
voiceId,
|
|
5501
|
+
model,
|
|
5502
|
+
style,
|
|
2814
5503
|
manifest,
|
|
2815
5504
|
mine,
|
|
2816
5505
|
drift,
|
|
5506
|
+
faces,
|
|
5507
|
+
// the clips with no viseme sidecar beside them: what the drawn
|
|
5508
|
+
// character needs made before a video can have it (the export card says so)
|
|
5509
|
+
nolips: wav.filter((e) => !entries.some((x) => x.name === e.name.replace(/\.[^.]+$/, '.visemes.json'))).length,
|
|
5510
|
+
...(realign?.moves.length ? { realign: { moves: realign.moves, said: realign.said } } : {}),
|
|
2817
5511
|
// what `decklight video` can render from: a manifest, or a
|
|
2818
5512
|
// whole-slide file to read off the disk, which is what your own
|
|
2819
5513
|
// voice leaves (folderNarration). Beats alone render nothing.
|
|
2820
5514
|
renders: manifest || wav.some((e) => /^slide-\d+\./.test(e.name)),
|
|
2821
5515
|
stale,
|
|
5516
|
+
// …and whether the 2D character's lip-sync is this audio's (#1244)
|
|
5517
|
+
...(lips ? { lipsync: lipsyncOf(lips, rel) } : {}),
|
|
2822
5518
|
});
|
|
2823
5519
|
}
|
|
2824
5520
|
return entries;
|
|
@@ -2831,7 +5527,46 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2831
5527
|
if (k.isDirectory() && !k.name.startsWith('.')) look(`${e.name}${sep}${k.name}`);
|
|
2832
5528
|
}
|
|
2833
5529
|
}
|
|
2834
|
-
|
|
5530
|
+
// and whether the character's lip-sync can be made here, which a video
|
|
5531
|
+
// export with the character does before its render (PRESENTING_OUTPUT)
|
|
5532
|
+
// …and where a new take goes: `voices`, or `voices-fr` for the French of a deck
|
|
5533
|
+
return json(200, { ok: true, tracks: seen, root: tracksRoot(family), visemes: visemesWhyNot() });
|
|
5534
|
+
}
|
|
5535
|
+
|
|
5536
|
+
/**
|
|
5537
|
+
* `POST /deck/edit/narration/realign` — `{ dir }`: move a track's recordings
|
|
5538
|
+
* back onto the slides they were recorded from (#916), after a reorder this
|
|
5539
|
+
* server did not make (an agent, an editor, a hand-pasted section). The
|
|
5540
|
+
* moves are worked out here, from the manifest and the deck as they are
|
|
5541
|
+
* now, never taken from the page. One undo entry, the deck unchanged in
|
|
5542
|
+
* it, so Z puts the folder back. A rename that would overwrite a file
|
|
5543
|
+
* outside the plan refuses the whole realign and says which.
|
|
5544
|
+
*/
|
|
5545
|
+
function realignRoute({ body, json }) {
|
|
5546
|
+
const { dir: want } = JSON.parse(body || '{}');
|
|
5547
|
+
if (typeof want !== 'string' || !want.trim() || want.length > 200 || /^[/\\]/.test(want)
|
|
5548
|
+
|| /^[a-zA-Z]:/.test(want) || want.split(/[/\\]/).includes('..')) {
|
|
5549
|
+
return json(400, { ok: false, error: 'bad narration folder' });
|
|
5550
|
+
}
|
|
5551
|
+
const deckDir = dirname(deckPath);
|
|
5552
|
+
const rel = want.trim().replace(/^\.\//, '').replace(/\/+$/, '');
|
|
5553
|
+
if (!voiceFolders(deckPath, configuredTrackDirs(readDeck())).includes(rel)) {
|
|
5554
|
+
return json(404, { ok: false, error: `${rel}/ is not one of this deck's voice folders` });
|
|
5555
|
+
}
|
|
5556
|
+
let m = null;
|
|
5557
|
+
try { m = JSON.parse(readFileSync(resolve(deckDir, rel, 'manifest.json'), 'utf8')); } catch { /* said below */ }
|
|
5558
|
+
if (!Array.isArray(m?.slides)) return json(409, { ok: false, error: `${rel}/ has no manifest — nothing records which slide each take was read from` });
|
|
5559
|
+
const cur = readDeck();
|
|
5560
|
+
const { moves, said } = realignMoves(m, cur, { scripts: trackScripts(resolve(deckDir, rel)) });
|
|
5561
|
+
if (!moves.length) return json(200, { ok: true, moved: 0, said: 'every recording is already on its slide', ...history.counts() });
|
|
5562
|
+
const plan = planFolder(deckDir, { dir: rel, pairs: moves });
|
|
5563
|
+
if (plan.conflicts.length) return json(409, { ok: false, error: `${plan.conflicts[0]} — nothing was moved` });
|
|
5564
|
+
if (!planMoves(plan)) return json(200, { ok: true, moved: 0, said: 'every recording is already on its slide', ...history.counts() });
|
|
5565
|
+
// the folder first, the undo entry once it has moved: a failed move is put back, and leaves nothing to undo
|
|
5566
|
+
try { applyPlans(deckDir, [plan]); } catch (e) { return json(409, { ok: false, error: oneline(e), ...history.counts() }); }
|
|
5567
|
+
history.record({ deck: cur, voices: [plan.inverse] });
|
|
5568
|
+
console.log(` narration: ${rel}/ realigned — ${said}`);
|
|
5569
|
+
return json(200, { ok: true, moved: moves.filter(([, t]) => t !== null).length, said, ...history.counts() });
|
|
2835
5570
|
}
|
|
2836
5571
|
|
|
2837
5572
|
// ── AI agents — the one-shot editing task behind A ───────────────────────
|
|
@@ -2851,13 +5586,37 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2851
5586
|
return json(200, { ok: true, preferredAgent: agent ?? null });
|
|
2852
5587
|
}
|
|
2853
5588
|
|
|
5589
|
+
/** What the card shows for `agent`'s model: the one it runs on, where that came from, whether it can take one. */
|
|
5590
|
+
function agentModelState(agent) {
|
|
5591
|
+
const { model, source } = agentModel(agent.name);
|
|
5592
|
+
return { model, modelSource: source, takesModel: takesModel(agent), suggest: agent.models ?? [] };
|
|
5593
|
+
}
|
|
5594
|
+
|
|
5595
|
+
// Remember the model an agent runs on (#918): beside the preference, in
|
|
5596
|
+
// agent.json, for decklight's runs only. Picking one here is this session's
|
|
5597
|
+
// latest word, so it also replaces a --agent-model this run was started with.
|
|
5598
|
+
function agentModelRoute({ body, json }) {
|
|
5599
|
+
const { agent, model, task: asked } = JSON.parse(body);
|
|
5600
|
+
const task = asked === 'ask' ? 'ask' : 'edit';
|
|
5601
|
+
if (typeof agent !== 'string' || (model !== null && typeof model !== 'string')) throw new Error('bad payload');
|
|
5602
|
+
const entry = agents.find((a) => a.name === agent);
|
|
5603
|
+
if (!entry) return json(400, { ok: false, error: agentUnavailable(agent, agents) });
|
|
5604
|
+
if (!takesModel(entry)) return json(400, { ok: false, error: `${entry.label} takes no model flag — it runs on its own default` });
|
|
5605
|
+
setAgentModel(agent, model, { task });
|
|
5606
|
+
delete process.env[MODEL_ENV[task]];
|
|
5607
|
+
const now = agentModel(agent, { task }).model;
|
|
5608
|
+
console.log(` agent: ${agent}${task === 'ask' ? ' (questions)' : ''} → ${now ?? 'its own default model'}`);
|
|
5609
|
+
return json(200, { ok: true, agent, task, model: now });
|
|
5610
|
+
}
|
|
5611
|
+
|
|
2854
5612
|
// The voiceover script, given ElevenLabs v4's audio tags (cli/enhance.mjs):
|
|
2855
5613
|
// the agent drafts, read-only, a few slides at a time; decklight checks each
|
|
2856
5614
|
// answer kept the words and beats, and writes them in ONE edit so Z takes
|
|
2857
5615
|
// the whole run back. Progress rides the SSE channel as 'enhance' events.
|
|
2858
5616
|
async function enhanceRoute({ body, json }) {
|
|
2859
|
-
const { slides, agent, kind: asked } = JSON.parse(body);
|
|
2860
|
-
const
|
|
5617
|
+
const { slides, agent, kind: asked, passage: asking = null } = JSON.parse(body);
|
|
5618
|
+
const { enhanceDeck, applyEnhanced, enhanceable, findPassage, KINDS } = await import('./enhance.mjs');
|
|
5619
|
+
const kind = Object.hasOwn(KINDS, asked ?? '') ? asked : 'tags';
|
|
2861
5620
|
const which = slides === 'all' ? null
|
|
2862
5621
|
: Array.isArray(slides) && slides.length && slides.every((n) => Number.isInteger(n) && n > 0) ? slides : undefined;
|
|
2863
5622
|
if (which === undefined) throw new Error('bad payload');
|
|
@@ -2867,24 +5626,32 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2867
5626
|
const name = agent ?? agentPref ?? null;
|
|
2868
5627
|
const cmd = agentAsk(name, 'x');
|
|
2869
5628
|
if (!cmd) return json(400, { ok: false, error: agentUnavailable(name, agents) });
|
|
2870
|
-
const { enhanceDeck, applyEnhanced, enhanceable, KINDS } = await import('./enhance.mjs');
|
|
2871
5629
|
const verb = KINDS[kind].done;
|
|
2872
5630
|
const html = readDeck();
|
|
2873
5631
|
const of = enhanceable(html, which).length;
|
|
2874
5632
|
if (!of) return json(422, { ok: false, error: which?.length === 1 ? `slide ${which[0]} has no notes to enhance` : 'no notes to enhance' });
|
|
5633
|
+
// part of one slide's notes (the card's selection, or a build's part):
|
|
5634
|
+
// found in the notes as the file has them, or refused before anyone is asked
|
|
5635
|
+
let passage = null;
|
|
5636
|
+
if (asking) {
|
|
5637
|
+
if (!KINDS[kind].passage) return json(400, { ok: false, error: `${KINDS[kind].what.replace('script: ', '')} works on the whole slide, not a selection` });
|
|
5638
|
+
if (which?.length !== 1 || typeof asking.text !== 'string') throw new Error('bad payload');
|
|
5639
|
+
passage = findPassage(enhanceable(html, which)[0].script, asking);
|
|
5640
|
+
if (!passage) return json(422, { ok: false, error: 'the selected words are not in the saved notes once, as written — select them again' });
|
|
5641
|
+
}
|
|
2875
5642
|
const stop = new AbortController();
|
|
2876
5643
|
enhancing = { of, done: 0, stop: () => stop.abort() };
|
|
2877
5644
|
broadcast('enhance', { state: 'start', of, agent: cmd.name, kind });
|
|
2878
|
-
console.log(` enhance: ${of} slide${of === 1 ? '' : 's'}${
|
|
5645
|
+
console.log(` enhance: ${of} slide${of === 1 ? '' : 's'}${passage ? ' (a passage)' : ''}${KINDS[kind].doing ?? ''} ← ${cmd.name} (read-only)`);
|
|
2879
5646
|
enhanceDeck(html, which, {
|
|
2880
|
-
kind, agent: name, cwd: dirname(deckPath), signal: stop.signal,
|
|
5647
|
+
kind, agent: name, cwd: dirname(deckPath), signal: stop.signal, passage,
|
|
2881
5648
|
onSlide: (r) => {
|
|
2882
5649
|
enhancing.done = r.done;
|
|
2883
5650
|
broadcast('enhance', { state: 'slide', ...r });
|
|
2884
5651
|
console.log(` enhance: slide ${r.slide} ${r.ok ? (r.changed ? verb : 'unchanged') : `left as it was — ${r.why}`}`);
|
|
2885
5652
|
},
|
|
2886
5653
|
}).then(({ answers, results }) => {
|
|
2887
|
-
// Stopped: nothing is
|
|
5654
|
+
// Stopped: nothing is held. Half a deck tagged reads as a deck
|
|
2888
5655
|
// somebody forgot to finish, and the slides already answered are a
|
|
2889
5656
|
// cache hit for nobody — the agent is asked afresh next time.
|
|
2890
5657
|
if (stop.signal.aborted) {
|
|
@@ -2893,38 +5660,92 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
2893
5660
|
console.log(' enhance: stopped — nothing written');
|
|
2894
5661
|
return;
|
|
2895
5662
|
}
|
|
2896
|
-
let stale = [];
|
|
2897
5663
|
// against the deck as it is NOW: a slide edited while the agent thought keeps the edit
|
|
2898
|
-
|
|
5664
|
+
const cur = readDeck();
|
|
5665
|
+
const { html: next, stale } = applyEnhanced(cur, answers);
|
|
2899
5666
|
const changed = results.filter((r) => r.changed && !stale.includes(r.slide)).map((r) => r.slide);
|
|
2900
5667
|
const failed = results.filter((r) => !r.ok).map(({ slide, why }) => ({ slide, why }));
|
|
5668
|
+
const left = [...failed, ...stale.map((slide) => ({ slide, why: 'edited while the agent thought — kept as edited' }))].sort((a, b) => a.slide - b.slide);
|
|
5669
|
+
// HELD, not written: the rewrite is a candidate the review decides on,
|
|
5670
|
+
// slide by slide, like a quick fix (#907). Only a deck the review cannot
|
|
5671
|
+
// cut lands as it used to, as one edit the undo chord takes back.
|
|
5672
|
+
let candidate = null;
|
|
5673
|
+
if (next !== cur) {
|
|
5674
|
+
const h = fixReview.hold({ before: cur, after: next, what: KINDS[kind].what, kind: 'script', agent: cmd.name, left });
|
|
5675
|
+
if (h.ok) candidate = { id: h.id, units: h.units.length };
|
|
5676
|
+
else { console.log(` enhance: ${h.error} — written as one edit instead`); applyEdit(next, cur); }
|
|
5677
|
+
}
|
|
2901
5678
|
enhancing = null;
|
|
2902
|
-
broadcast('enhance', { state: 'done', ok: true, changed, failed, stale, kind });
|
|
2903
|
-
console.log(` enhance: done — ${changed.length} ${verb}${failed.length ? `, ${failed.length} left as they were` : ''}`);
|
|
5679
|
+
broadcast('enhance', { state: 'done', ok: true, changed, failed, stale, kind, candidate });
|
|
5680
|
+
console.log(` enhance: done — ${changed.length} ${verb}${failed.length ? `, ${failed.length} left as they were` : ''}${candidate ? ', held for review' : ''}`);
|
|
2904
5681
|
}).catch((e) => {
|
|
2905
5682
|
enhancing = null;
|
|
2906
5683
|
broadcast('enhance', { state: 'done', ok: false, error: oneline(e), kind });
|
|
2907
5684
|
});
|
|
2908
|
-
return json(200, { ok: true, of, agent: cmd.name, label: cmd.label, kind });
|
|
5685
|
+
return json(200, { ok: true, of, agent: cmd.name, label: cmd.label, kind, passage: !!passage });
|
|
2909
5686
|
}
|
|
2910
5687
|
|
|
2911
|
-
|
|
2912
|
-
|
|
2913
|
-
|
|
2914
|
-
|
|
2915
|
-
|
|
2916
|
-
|
|
2917
|
-
|
|
2918
|
-
|
|
5688
|
+
/**
|
|
5689
|
+
* The slide's own text, rewritten by a tool (cli/rewrite.mjs, SPEC
|
|
5690
|
+
* PRESENTING_WRITING): `{ slides, tool, instruction? }`. Runs like an
|
|
5691
|
+
* enhance, one ask per slide, and is HELD the same way: the passing slides
|
|
5692
|
+
* make the candidate, the review decides, nothing is written here.
|
|
5693
|
+
*/
|
|
5694
|
+
async function rewriteRoute({ body, json }) {
|
|
5695
|
+
const { slides, agent, tool, instruction = '' } = JSON.parse(body);
|
|
5696
|
+
const { rewriteDeck, applyRewritten, rewritable, TOOLS } = await import('./rewrite.mjs');
|
|
5697
|
+
if (!TOOLS[tool]) throw new Error('bad payload');
|
|
5698
|
+
if (tool === 'custom' && (typeof instruction !== 'string' || !instruction.trim())) return json(400, { ok: false, error: 'say what to change — the custom tool needs an instruction' });
|
|
5699
|
+
const which = slides === 'all' ? null
|
|
5700
|
+
: Array.isArray(slides) && slides.length && slides.every((n) => Number.isInteger(n) && n > 0) ? slides : undefined;
|
|
5701
|
+
if (which === undefined) throw new Error('bad payload');
|
|
5702
|
+
if (enhancing) return json(409, { ok: false, error: `already rewriting — ${enhancing.done} of ${enhancing.of} slides done` });
|
|
5703
|
+
if (reviewing) return json(409, { ok: false, error: 'the agent is reviewing the deck — wait for it to finish' });
|
|
5704
|
+
if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is editing the deck — wait for it to finish` });
|
|
2919
5705
|
const name = agent ?? agentPref ?? null;
|
|
2920
5706
|
const cmd = agentAsk(name, 'x');
|
|
2921
5707
|
if (!cmd) return json(400, { ok: false, error: agentUnavailable(name, agents) });
|
|
2922
|
-
const
|
|
2923
|
-
|
|
2924
|
-
|
|
2925
|
-
|
|
2926
|
-
|
|
2927
|
-
|
|
5708
|
+
const html = readDeck();
|
|
5709
|
+
const of = rewritable(html, which).length;
|
|
5710
|
+
if (!of) return json(422, { ok: false, error: which?.length === 1 ? `slide ${which[0]} has no text to rewrite` : 'no slide text to rewrite' });
|
|
5711
|
+
const stop = new AbortController();
|
|
5712
|
+
enhancing = { of, done: 0, stop: () => stop.abort() };
|
|
5713
|
+
broadcast('enhance', { state: 'start', of, agent: cmd.name, kind: tool });
|
|
5714
|
+
console.log(` rewrite: ${TOOLS[tool].label} on ${of} slide${of === 1 ? '' : 's'} ← ${cmd.name} (read-only)`);
|
|
5715
|
+
rewriteDeck(html, tool, which, {
|
|
5716
|
+
instruction: String(instruction).slice(0, 1000), agent: name, cwd: dirname(deckPath), signal: stop.signal,
|
|
5717
|
+
onSlide: (r) => {
|
|
5718
|
+
enhancing.done = r.done;
|
|
5719
|
+
broadcast('enhance', { state: 'slide', ...r, kind: tool });
|
|
5720
|
+
console.log(` rewrite: slide ${r.slide} ${r.ok ? (r.changed ? TOOLS[tool].done : 'unchanged') : `left as it was — ${r.why}`}`);
|
|
5721
|
+
},
|
|
5722
|
+
}).then(({ answers, results }) => {
|
|
5723
|
+
if (stop.signal.aborted) {
|
|
5724
|
+
enhancing = null;
|
|
5725
|
+
broadcast('enhance', { state: 'done', ok: false, stopped: true, kind: tool });
|
|
5726
|
+
console.log(' rewrite: stopped — nothing written');
|
|
5727
|
+
return;
|
|
5728
|
+
}
|
|
5729
|
+
const cur = readDeck();
|
|
5730
|
+
const { html: next, stale } = applyRewritten(cur, answers);
|
|
5731
|
+
const changed = results.filter((r) => r.changed && !stale.includes(r.slide)).map((r) => r.slide);
|
|
5732
|
+
const failed = results.filter((r) => !r.ok).map(({ slide, why }) => ({ slide, why }));
|
|
5733
|
+
const left = [...failed, ...stale.map((slide) => ({ slide, why: 'edited while the agent thought — kept as edited' }))].sort((a, b) => a.slide - b.slide);
|
|
5734
|
+
let candidate = null;
|
|
5735
|
+
if (next !== cur) {
|
|
5736
|
+
const what = tool === 'custom' ? `text: ${String(instruction).trim().slice(0, 60)}` : TOOLS[tool].what;
|
|
5737
|
+
const h = fixReview.hold({ before: cur, after: next, what, kind: 'text', agent: cmd.name, left });
|
|
5738
|
+
if (h.ok) candidate = { id: h.id, units: h.units.length };
|
|
5739
|
+
else { console.log(` rewrite: ${h.error} — written as one edit instead`); applyEdit(next, cur); }
|
|
5740
|
+
}
|
|
5741
|
+
enhancing = null;
|
|
5742
|
+
broadcast('enhance', { state: 'done', ok: true, changed, failed, stale, kind: tool, candidate });
|
|
5743
|
+
console.log(` rewrite: done — ${changed.length} ${TOOLS[tool].done}${failed.length ? `, ${failed.length} left as they were` : ''}${candidate ? ', held for review' : ''}`);
|
|
5744
|
+
}).catch((e) => {
|
|
5745
|
+
enhancing = null;
|
|
5746
|
+
broadcast('enhance', { state: 'done', ok: false, error: oneline(e), kind: tool });
|
|
5747
|
+
});
|
|
5748
|
+
return json(200, { ok: true, of, agent: cmd.name, label: cmd.label, kind: tool });
|
|
2928
5749
|
}
|
|
2929
5750
|
|
|
2930
5751
|
// The agent review (cli/agent-review.mjs): the agent reads the deck,
|
|
@@ -3032,15 +5853,44 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
3032
5853
|
return null;
|
|
3033
5854
|
}
|
|
3034
5855
|
|
|
5856
|
+
/**
|
|
5857
|
+
* `review: true` (a Check deck… quick fix, #907) holds what the agent
|
|
5858
|
+
* writes for the review view instead of landing it: `rule` names the
|
|
5859
|
+
* finding, for the commit the review drafts.
|
|
5860
|
+
*/
|
|
3035
5861
|
async function agentRoute({ body, json }) {
|
|
3036
|
-
const { prompt, agent, message, slide, offer, place = null } = JSON.parse(body);
|
|
5862
|
+
const { prompt, agent, message, slide, offer, place = null, review = false, rule = null, explain = false, follow = null } = JSON.parse(body);
|
|
3037
5863
|
if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('bad payload');
|
|
3038
5864
|
if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is already running` });
|
|
3039
5865
|
if (reviewing) return json(409, { ok: false, error: 'the agent is reviewing the deck — wait for it to finish' });
|
|
5866
|
+
if (explain) {
|
|
5867
|
+
// read-only: no skill offer (nothing is edited), no hold, no commit
|
|
5868
|
+
const ok = follow && typeof follow.prompt === 'string' && follow.prompt.trim();
|
|
5869
|
+
// that slide's source, fresh from the file: the question is about what is written there
|
|
5870
|
+
let source = '';
|
|
5871
|
+
if (Number.isInteger(slide) && slide > 0) {
|
|
5872
|
+
const { sectionBodies } = await import('../tools/deck-html.mjs');
|
|
5873
|
+
const body = sectionBodies(readDeck())[slide - 1];
|
|
5874
|
+
if (body) source = `\n\nSlide ${slide}'s source:\n\n${body}`;
|
|
5875
|
+
}
|
|
5876
|
+
const cmd = runAgent(prompt.trim() + source, agent, message, slide, { explain: { follow: ok
|
|
5877
|
+
? { prompt: follow.prompt, slide: follow.slide, message: follow.message, rule: follow.rule ?? null } : null } });
|
|
5878
|
+
if (!cmd) return json(400, { ok: false, error: agentUnavailable(agent ?? agentPref, agents) });
|
|
5879
|
+
return json(200, { ok: true, agent: cmd.name, label: cmd.label, readOnly: true });
|
|
5880
|
+
}
|
|
3040
5881
|
const gate = await skillGate(agent, { offer, place });
|
|
3041
5882
|
if (gate?.offer) return json(200, gate.offer);
|
|
3042
5883
|
if (gate?.error) return json(409, { ok: false, error: gate.error });
|
|
3043
|
-
const
|
|
5884
|
+
const what = typeof message === 'string' && message.trim() ? message.trim() : commitSubject(prompt, 'fix');
|
|
5885
|
+
const hold = review ? {
|
|
5886
|
+
done: (after, { ok = true } = {}) => {
|
|
5887
|
+
if (after === null) return null;
|
|
5888
|
+
const h = fixReview.hold({ before: readDeck(), after, what, rule: typeof rule === 'string' ? rule : null, slide, agent: agentJob?.agent ?? null });
|
|
5889
|
+
if (!h.ok) console.log(` fix: ${h.error}`);
|
|
5890
|
+
return h.ok ? { id: h.id, units: h.units.length, ok } : null;
|
|
5891
|
+
},
|
|
5892
|
+
} : null;
|
|
5893
|
+
const cmd = runAgent(prompt.trim(), agent, message, slide, hold ? { hold } : {});
|
|
3044
5894
|
if (!cmd) return json(400, { ok: false, error: agentUnavailable(agent ?? agentPref, agents) });
|
|
3045
5895
|
return json(200, { ok: true, agent: cmd.name, label: cmd.label });
|
|
3046
5896
|
}
|
|
@@ -3144,14 +5994,14 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
3144
5994
|
* quick fix Check deck… offers for one of `decklight check`'s findings
|
|
3145
5995
|
* (PRESENTING_EDITING, cli/check-fixes.mjs), applied by this server and
|
|
3146
5996
|
* recorded in the agent panel as an entry by *decklight*, beside the
|
|
3147
|
-
* agents' edits. One undo entry and one commit (`fix: <rule> on
|
|
5997
|
+
* agents' edits. One undo entry and one commit (`fix: <rule> on "Title"`,
|
|
3148
5998
|
* or `fix: <rule>` for the deck); `all` applies a batchable rule to every
|
|
3149
5999
|
* slide as one of each. `ds-behind` is Migrate (above), which keeps its
|
|
3150
6000
|
* own words. The judgement fixes never come here: the page hands those to
|
|
3151
6001
|
* the A agent as an ordinary ask.
|
|
3152
6002
|
*/
|
|
3153
6003
|
async function checkFixRoute({ body, json }) {
|
|
3154
|
-
const { rule, slide, all, ref, agent } = JSON.parse(body || '{}');
|
|
6004
|
+
const { rule, slide, all, ref, agent, review = false } = JSON.parse(body || '{}');
|
|
3155
6005
|
if (typeof rule !== 'string' || !/^[a-z][a-z-]*$/.test(rule)) throw new Error('bad payload');
|
|
3156
6006
|
if (slide != null && !(Number.isInteger(slide) && slide > 0)) throw new Error('bad payload');
|
|
3157
6007
|
if (agentJob) return json(409, { ok: false, error: `${agentJob.agent} is already running` });
|
|
@@ -3162,10 +6012,16 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
3162
6012
|
const { BATCH_RULES, fixSubject, offBrandTarget, renameRoles } = await import('./check-fixes.mjs');
|
|
3163
6013
|
const { setDeckTheme } = await import('./runtime-link.mjs');
|
|
3164
6014
|
const where = all && BATCH_RULES.includes(rule) ? null : slide ?? null;
|
|
3165
|
-
const subject = fixSubject(rule, where);
|
|
3166
6015
|
const before = readDeck();
|
|
6016
|
+
const subject = fixSubject(rule, where, before);
|
|
3167
6017
|
/** The deck rewritten in one step, committed as the fix, and said in the panel. */
|
|
3168
6018
|
const land = (next, { said, tail, prompt }) => {
|
|
6019
|
+
// reviewed first (#907): held, and nothing written until the author applies it
|
|
6020
|
+
if (review) {
|
|
6021
|
+
const h = fixReview.hold({ before, after: next, what: subject, rule, slide: where });
|
|
6022
|
+
if (!h.ok) return json(409, h);
|
|
6023
|
+
return json(200, { ok: true, changed: false, held: true, said, candidate: h });
|
|
6024
|
+
}
|
|
3169
6025
|
const ask = ownAsk({ kind: 'fix', title: subject, prompt, slide: where ?? undefined });
|
|
3170
6026
|
if (gitOn && shouldCommit(gitMode, { kind: 'bookend' }) && ownCommit(`decklight: save before fixing ${rule}`)) {
|
|
3171
6027
|
console.log(' git: committed your outstanding changes first');
|
|
@@ -3261,14 +6117,17 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
3261
6117
|
|
|
3262
6118
|
'POST /deck/edit/narration/record': recordRoute,
|
|
3263
6119
|
'GET /deck/edit/narration/tracks': tracksRoute,
|
|
6120
|
+
'POST /deck/edit/narration/lipsync': lipsyncRoute,
|
|
6121
|
+
'POST /deck/edit/narration/realign': realignRoute,
|
|
3264
6122
|
|
|
3265
6123
|
'POST /deck/edit/agent': agentRoute,
|
|
3266
6124
|
'POST /deck/edit/design-system/migrate': designSystemMigrateRoute,
|
|
3267
6125
|
'POST /deck/edit/check/fix': checkFixRoute,
|
|
3268
6126
|
'POST /deck/edit/agent/stop': agentStopRoute,
|
|
3269
6127
|
'POST /deck/edit/agent/prefer': agentPreferRoute,
|
|
6128
|
+
'POST /deck/edit/agent/model': agentModelRoute,
|
|
3270
6129
|
'POST /deck/edit/enhance': enhanceRoute,
|
|
3271
|
-
'POST /deck/edit/
|
|
6130
|
+
'POST /deck/edit/rewrite': rewriteRoute,
|
|
3272
6131
|
'POST /deck/edit/review': reviewRoute,
|
|
3273
6132
|
'GET /deck/edit/review': reviewFindingsRoute,
|
|
3274
6133
|
}));
|
|
@@ -3287,6 +6146,32 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
3287
6146
|
broadcast: (event, data) => clients.broadcast(event, data),
|
|
3288
6147
|
});
|
|
3289
6148
|
|
|
6149
|
+
// A quick fix reviewed before it lands (#907, cli/fix-review.mjs): the
|
|
6150
|
+
// candidate, its two sides as pages, and the apply that writes the slides
|
|
6151
|
+
// the author approved as one undo entry. An adjustment is the agent again,
|
|
6152
|
+
// held, working on the candidate rather than on the deck.
|
|
6153
|
+
fixReview = registerFixReviewRoutes(routes, {
|
|
6154
|
+
readDeck, applyEdit, broadcast,
|
|
6155
|
+
saveBefore: (what) => {
|
|
6156
|
+
if (gitOn && shouldCommit(gitMode, { kind: 'bookend' }) && ownCommit(`decklight: save before applying the reviewed ${what}`)) {
|
|
6157
|
+
console.log(' git: committed your outstanding changes first');
|
|
6158
|
+
}
|
|
6159
|
+
},
|
|
6160
|
+
adjust: async ({ candidate, unit, comment }) => {
|
|
6161
|
+
if (agentJob) return { ok: false, error: `${agentJob.agent} is already running` };
|
|
6162
|
+
if (reviewing) return { ok: false, error: 'the agent is reviewing the deck — wait for it to finish' };
|
|
6163
|
+
const cmd = runAgent(adjustPrompt(unit, comment, candidate.what), candidate.agent ?? undefined, null, unit.slide, {
|
|
6164
|
+
kind: 'fix', title: `adjust ${candidate.what} on slide ${unit.slide}`,
|
|
6165
|
+
hold: {
|
|
6166
|
+
start: candidate.after,
|
|
6167
|
+
done: (after) => { fixReview.adjusted(candidate.id, after, unit.key); return { id: candidate.id, adjusted: unit.key }; },
|
|
6168
|
+
},
|
|
6169
|
+
});
|
|
6170
|
+
if (!cmd) return { ok: false, code: 400, error: agentUnavailable(candidate.agent ?? agentPref, agents) };
|
|
6171
|
+
return { ok: true, agent: cmd.name };
|
|
6172
|
+
},
|
|
6173
|
+
});
|
|
6174
|
+
|
|
3290
6175
|
// The deck's look is a file of its own too (cli/edit-look.mjs): the theme
|
|
3291
6176
|
// pick and the brand-themes switch, and browsing and marking what the
|
|
3292
6177
|
// marketplaces offer a deck to wear — themes, design systems, fonts. They
|
|
@@ -3321,15 +6206,28 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
3321
6206
|
pendingAttr: () => pendingAttr,
|
|
3322
6207
|
clearPendingAttr: () => { pendingAttr = null; },
|
|
3323
6208
|
dismissNag: () => { nagDismissed = true; },
|
|
6209
|
+
followOutside,
|
|
6210
|
+
});
|
|
6211
|
+
|
|
6212
|
+
// And the way out to the author's own editor (cli/edit-open.mjs): a slide
|
|
6213
|
+
// or an element opened in it at its line. The command is the author's saved
|
|
6214
|
+
// choice, never the request's, and only this server's own page may ask.
|
|
6215
|
+
registerOpenRoutes(routes, {
|
|
6216
|
+
readDeck, deckPath,
|
|
6217
|
+
ownOrigin: (req) => isOwnOrigin(req, actualPort),
|
|
3324
6218
|
});
|
|
3325
6219
|
|
|
6220
|
+
// And its languages (cli/edit-translate.mjs, TRANSLATE_PANEL): what is
|
|
6221
|
+
// behind, and a run of decklight translate, as a child process
|
|
6222
|
+
registerTranslateRoutes(routes, { deckPath, broadcast });
|
|
6223
|
+
|
|
3326
6224
|
// The routes that run BEFORE the shared body read, and the only reason the
|
|
3327
6225
|
// dispatcher below has a sequence at all. `/deck/edit/narration/record`'s body is BINARY and
|
|
3328
6226
|
// megabytes of it — a slide of speech is ~48 kB a second — so the string
|
|
3329
6227
|
// concat and its 1 MB ceiling would both be wrong, and it reads the stream
|
|
3330
6228
|
// itself under its own 64 MB limit. `/deck/edit/asset` is the same case with a
|
|
3331
6229
|
// different payload — an image dropped on the stage, read under its own
|
|
3332
|
-
// 25 MB limit. The other three carry no body, and never had one read for them.
|
|
6230
|
+
// 25 MB limit, or a video put on a slide, streamed to disk under 200 MB. The other three carry no body, and never had one read for them.
|
|
3333
6231
|
const BEFORE_BODY = new Set([
|
|
3334
6232
|
'POST /deck/tts',
|
|
3335
6233
|
'POST /deck/edit/narration/record', 'POST /deck/edit/asset',
|
|
@@ -3392,8 +6290,9 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
3392
6290
|
|| pathname === '/deck/tts' || pathname.startsWith('/deck/tts/') || pathname.startsWith('/deck/lipsync/')
|
|
3393
6291
|
|| pathname === '/deck/review/incoming' || pathname === '/deck/review/at';
|
|
3394
6292
|
|
|
3395
|
-
// What a locked deck still answers: the lock, and the
|
|
3396
|
-
|
|
6293
|
+
// What a locked deck still answers: the lock, the stops, and opening the
|
|
6294
|
+
// deck in your editor, which writes nothing (cli/edit-open.mjs).
|
|
6295
|
+
const UNLOCKED_POSTS = new Set(['/deck/edit/lock', '/deck/edit/export/stop', '/deck/edit/agent/stop', '/deck/edit/open', '/deck/edit/editor']);
|
|
3397
6296
|
|
|
3398
6297
|
// Two static servers for one root, chosen per request by the mode. Write
|
|
3399
6298
|
// mode serves the cwd with the deck at "/" and an author's exotic asset as
|
|
@@ -3473,6 +6372,22 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
3473
6372
|
if (locked && req.method === 'POST' && url.pathname.startsWith('/deck/edit/') && !UNLOCKED_POSTS.has(url.pathname)) {
|
|
3474
6373
|
return json(423, { ok: false, locked: true, error: 'the deck is locked — unlock it from the palette or the lock chip' });
|
|
3475
6374
|
}
|
|
6375
|
+
// an agent is working on a fix held for review: the file is its until it
|
|
6376
|
+
// is put back, and a write made now would be undone by that (#907)
|
|
6377
|
+
if (holding && req.method === 'POST' && url.pathname.startsWith('/deck/edit/') && !UNLOCKED_POSTS.has(url.pathname)
|
|
6378
|
+
&& url.pathname !== '/deck/edit/candidate/discard') {
|
|
6379
|
+
return json(409, { ok: false, error: 'a fix is being prepared for review — wait for it, or stop the agent' });
|
|
6380
|
+
}
|
|
6381
|
+
// a translation takes its structure from its source (TRANSLATIONS):
|
|
6382
|
+
// the routes that change it are refused here, naming the file to use
|
|
6383
|
+
if (req.method === 'POST') {
|
|
6384
|
+
const refused = structureRefusal(deckPath, url.pathname);
|
|
6385
|
+
if (refused) {
|
|
6386
|
+
// said on the page however the write was sent: its one button opens the source
|
|
6387
|
+
broadcast('translate', { state: 'refused', ...refused });
|
|
6388
|
+
return json(409, { ok: false, translation: true, ...refused });
|
|
6389
|
+
}
|
|
6390
|
+
}
|
|
3476
6391
|
const key = `${req.method} ${url.pathname}`;
|
|
3477
6392
|
const prefixed = routes.has(key) ? null
|
|
3478
6393
|
: PREFIX_ROUTES.find((r) => r.method === req.method && url.pathname.startsWith(r.prefix));
|
|
@@ -3563,7 +6478,7 @@ export async function editMain(args, { onListen = null, client } = {}) {
|
|
|
3563
6478
|
url: `http://127.0.0.1:${actual}${deckUrl}`,
|
|
3564
6479
|
keys: 'Ctrl-C stops',
|
|
3565
6480
|
}));
|
|
3566
|
-
} else console.log(`decklight · ${basename(deckPath)} on http://127.0.0.1:${actual}${deckUrl} — editing on,
|
|
6481
|
+
} else console.log(`decklight · ${basename(deckPath)} on http://127.0.0.1:${actual}${deckUrl} — editing on, ${process.platform === 'darwin' ? '⌘Z' : 'Ctrl+Z'} undo, A agent, / everything else. Ctrl-C stops`);
|
|
3567
6482
|
if (token) {
|
|
3568
6483
|
console.log(` remote: listening on ${host} — http://${lanAddress() ?? host}:${actual}/deck/remote?t=${token}`);
|
|
3569
6484
|
console.log(' off this machine ONLY /deck/remote/* answers, with that token — the deck itself does not');
|