@lincyaw/workbench 0.2.0-rc.33 → 0.2.0-rc.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/package.json +4 -4
  2. package/src/context.tsx +2 -1
  3. package/src/diagnostics.ts +1 -1
  4. package/src/document-editing.ts +484 -0
  5. package/src/document-editor/ComponentPropertiesDialog.tsx +1 -1
  6. package/src/document-editor/DocumentBlockPreview.tsx +2 -2
  7. package/src/document-editor/DocumentStepNarration.tsx +8 -8
  8. package/src/document-production.ts +331 -0
  9. package/src/history.ts +1 -1
  10. package/src/index.ts +5 -2
  11. package/src/jobs.ts +1 -1
  12. package/src/panels/DocumentView.tsx +11 -11
  13. package/src/panels/DocumentVoiceDialog.tsx +2 -2
  14. package/src/panels/DocumentVoiceField.tsx +1 -1
  15. package/src/panels/HistoryPanel.tsx +1 -1
  16. package/src/panels/PageDeleteDialog.tsx +4 -4
  17. package/src/panels/PageRenameDialog.tsx +1 -1
  18. package/src/panels/ProductionCaptionSize.tsx +1 -1
  19. package/src/panels/ProductionCaptionTiming.tsx +5 -5
  20. package/src/panels/ProductionMediaClips.tsx +4 -4
  21. package/src/panels/ProductionPanel.tsx +2 -2
  22. package/src/panels/ProductionRecording.tsx +1 -1
  23. package/src/panels/ProductionRecordingRange.tsx +2 -2
  24. package/src/panels/ProductionTranscription.tsx +3 -3
  25. package/src/panels/SourceDocumentPanel.tsx +9 -9
  26. package/src/panels/TranscriptionAdoption.tsx +2 -2
  27. package/src/panels/VoiceoverDialog.tsx +1 -1
  28. package/src/preview-playback.ts +1 -1
  29. package/src/production-playback.ts +1 -1
  30. package/src/production-voice-playback.ts +3 -2
  31. package/src/use-recording-adoption.ts +2 -2
  32. package/src/voiceover-jobs.ts +1 -1
  33. package/src/workbench-state.ts +157 -0
  34. package/src/workbench.ts +56 -923
package/src/workbench.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { applyDocumentCaptionTiming, changeDocumentCaptionScale, randomUUID, replaceStepNarrations, validateDocument } from '@lincyaw/kernel'
2
- import type { DocumentCaptionTimingAction } from '@lincyaw/kernel'
3
- import { reconcileCaptionTiming } from './caption-timing.ts'
1
+ import { DocumentProduction } from './document-production.ts'
2
+ import { DocumentEditing } from './document-editing.ts'
3
+ import { isAgentChanging } from './workbench-state.ts'
4
+ import type { AgentAnswer, AgentDraft, AgentRequest, PlaybackKey, Pointer, PreviewSink, WebView, WorkbenchMode, WorkbenchState, WorkbenchStore } from './workbench-state.ts'
5
+ import { randomUUID } from '@lincyaw/kernel'
4
6
  import type { ProjectOperation, ProjectPlan } from '@lincyaw/kernel'
5
- import { undoDepth, redoDepth } from '@tiptap/pm/history'
6
- import { TextSelection } from '@tiptap/pm/state'
7
7
  import { CommentDraftBank } from './document-editor/comment-drafts.ts'
8
8
  import { ComponentPropertyDrafts } from './component-property-drafts.ts'
9
9
  import type { ComponentPropertyDraft } from './component-property-drafts.ts'
@@ -15,42 +15,25 @@ import { mutateCommentDrafts } from './document-editor/comment-draft-actions.ts'
15
15
  import { inspectComponentDrafts } from './component-draft-inspection.ts'
16
16
  import { mutateComponentDrafts } from './component-draft-actions.ts'
17
17
  import { DocumentSession } from './document-session.ts'
18
- import { sha256 } from './sha256.ts'
19
- import { reconcileRecordingAdoption } from './recording-adoption.ts'
20
18
  import { disposeTranscriptionSessions } from './transcription-session.ts'
21
19
  import { documentRecordingActive, disposeDocumentRecordings } from './audio-recording.ts'
22
- import { DOCUMENT_AUDIO_MAX_BYTES } from '@lincyaw/kernel'
23
20
  import type { DocumentSessionState } from './document-session.ts'
24
21
  import type { DocumentDraftReference } from './document-drafts.ts'
25
- import { DocumentReturnPoints, documentReturnStep, documentViewportOffset, restoreDocumentViewport } from './document-return-point.ts'
26
22
  import type { DocumentReturnPoint } from './document-return-point.ts'
27
- import type { DocumentRecordingAdoption, VerifiedDocumentRecordingAdoption, DocumentAudioImportAnswer, DocumentAudioInspectionAnswer, DocumentChangeAnswer, MediaClip, Narration, TeachingDocument, DocumentTranscriptionRequest, TranscriptionTask, TranscriptionAdoptionDraft, TranscriptionAdoptionApply, TranscriptionAdoptionPlan, TranscriptionAdoptionAnswer } from '@lincyaw/kernel'
28
- import type { NativeDocumentEditor } from './document-editor/schema.tsx'
29
- import type { DocumentEditorCommands } from './document-editor/DocumentEditor.tsx'
23
+ import type { DocumentChangeAnswer, TeachingDocument } from '@lincyaw/kernel'
30
24
  import type { DocumentInsertionPlace } from './document-editor/insertion-place.ts'
31
- import { nativeBlockText, nativeTextPoint, nativeTextPosition } from './document-editor/selection.ts'
32
- import type { NativeTextPoint } from './document-editor/selection.ts'
33
- import type { DocumentFieldBookmark, DocumentFieldRegistration, DocumentHistoryEditor } from './document-editor/focus.ts'
34
- import { duplicateDocumentPage, moveDocumentPage, pageDeletion, removeDocumentPage, renameDocumentPage } from '@lincyaw/kernel'
35
- import { changeStepTiming } from './step-production.ts'
36
- import { changeDocumentVoice } from './document-voices.ts'
37
- import type { DocumentVoiceOptions, DocumentVoiceScope } from './document-voices.ts'
38
- import type { CanonicalSource, VoiceoverJob, VoiceSource } from '@lincyaw/kernel'
39
- import type { StepDurationDraft, StepDurationKey, StepTimingPatch } from './step-production.ts'
40
- import { DocumentTimingDrafts } from './document-timing-drafts.ts'
41
- import { CaptionTimingDrafts } from './caption-timing-drafts.ts'
42
- import type { CaptionTimingDraft } from './caption-timing-drafts.ts'
25
+ import type { CanonicalSource, VoiceoverJob } from '@lincyaw/kernel'
43
26
  import { compileDocumentPreview, readPreviewWhenReady, waitForPreviewRequest } from './document-preview.ts'
44
27
  import { readDocumentSnapshot } from './document-preview.ts'
45
28
  import { errorMessage, sameProductionBinding, slideShape, stepKeys, stepTrail, trailStep } from '@lincyaw/kernel'
46
- import type { Diagnostic, DiagnosticSnapshot, DocumentOperation, DocumentsAnswer, Focus, FocusReport, IrAnswer, IrEvent, IRDocument, JobsAnswer, OperationAnswer, PreviewAnchor, PreviewAnswer, PreviewCommand, PreviewDiagnostics, PreviewPoint, PreviewPosition, PreviewRect, PreviewRenderer, PreviewReport, ReviewChange, ReviewSnapshot, RevisionsAnswer, UncommittedFile } from '@lincyaw/kernel'
29
+ import type { Diagnostic, Focus, FocusReport, IrAnswer, IrEvent, OperationAnswer, PreviewAnchor, PreviewCommand, PreviewDiagnostics, PreviewRenderer, PreviewReport, ReviewChange } from '@lincyaw/kernel'
47
30
  import { DocumentDiagnostics } from './diagnostics.ts'
48
31
  import { DocumentHistory } from './history.ts'
49
32
  import { DocumentJobs } from './jobs.ts'
50
33
  import { VoiceoverJobs } from './voiceover-jobs.ts'
51
- import { contentText, localeOf, MESSAGES } from './messages.ts'
34
+ import { localeOf, MESSAGES } from './messages.ts'
52
35
  import type { AgentPlace, Locale } from './messages.ts'
53
- import { changedPlaces, findPlaceAtLine, findPlaceSource } from './places.ts'
36
+ import { changedPlaces, findPlaceAtLine } from './places.ts'
54
37
  import { OperationLog } from './telemetry.ts'
55
38
  import type { OperationValue } from './telemetry.ts'
56
39
  import { PreviewPlayback } from './preview-playback.ts'
@@ -58,168 +41,15 @@ import { ProductionPlayback } from './production-playback.ts'
58
41
  import type { ProductionBinding, ProductionPlan, ProductionPlaybackCommand, ProductionPlaybackState } from '@lincyaw/kernel'
59
42
  import { workspaceClient, WorkspaceServerError } from './workspace-client.ts'
60
43
  import type { WorkspaceClient } from './workspace-client.ts'
61
- import type { PageDeletePlan } from '@lincyaw/kernel'
62
44
  import type { AuthoringClientAction, AuthoringClientActionResult, AuthoringClientSnapshot } from '@lincyaw/kernel'
63
45
  import { PRODUCTION_PLAYBACK_RATES } from '@lincyaw/kernel'
64
46
 
65
- /** `editing`: the canonical document is edited in the parent; `viewing`: a derived snapshot is presented. */
66
- export type WorkbenchMode = 'editing' | 'viewing'
67
-
68
- /**
69
- * How the web form is shown: as a page or as its presentation, whose controls can play a configured lecture.
70
- * Both share one preview page and switch in place with `go.view`.
71
- */
72
- export type WebView = 'document' | 'present'
73
-
74
- /** A playback key pressed in a preview that the workbench plays: Space, and the left and right arrows. */
75
- export type PlaybackKey = 'play-pause' | 'previous' | 'next'
76
-
77
- /** What the author points at in the document: a block (or a section), or a passage selected in it. */
78
- export interface Pointer {
79
- target: PreviewAnchor
80
- step?: number
81
- /** The selected passage. */
82
- quote?: string
83
- /** Its box in the preview's viewport; none while it is out of sight. */
84
- rect?: PreviewRect
85
- obstacles?: PreviewRect[]
86
- point?: PreviewPoint
87
- /** Its text can be edited in place. */
88
- isEditable: boolean
89
- }
90
-
91
- export type SaveState =
92
- | { kind: 'idle' }
93
- | { kind: 'saving' }
94
- | { kind: 'saved', at: string }
95
- | { kind: 'locked' }
96
- | { kind: 'failed', message: string }
97
-
98
- /** A request for the agent of the conversation: its text and what it is about. */
99
- export interface AgentRequest {
100
- text: string
101
- focus: FocusReport[]
102
- }
103
-
104
- /** A request for the author to finish and send in the conversation, and what it is about: the host only shows it. */
105
- export interface AgentDraft {
106
- text: string
107
- focus: FocusReport[]
108
- }
109
-
110
- /** Where the host put a request: the conversation's session and the request's id, which its user message carries. */
111
- export interface AgentAnswer {
112
- session: string
113
- request: string
114
- }
115
-
116
- export interface WorkbenchState {
117
- locale: Locale
118
- authoring?: DocumentSessionState
119
- /** Unaccepted numeric form input is retained separately from saved canonical timing. */
120
- hasDocumentTimingDrafts?: boolean
121
- documentTimingDraftStorageFailure?: boolean
122
- captionTimingDraftSteps?: string[]
123
- captionTimingDraftStorageFailure?: boolean
124
- isDark: boolean
125
- documents?: DocumentsAnswer
126
- documentsFailure?: string
127
- /** The workspace's routes answer 404: `@lincyaw/dsh` is turned off on the plugins page. */
128
- isBundleDisabled?: boolean
129
- document?: string
130
- ir?: IrAnswer
131
- mode: WorkbenchMode
132
- previewRenderer: PreviewRenderer
133
- /** In the web form: the page or the presentation, both in the same page, switched without loading it again. */
134
- webView: WebView
135
- previewReload: number
136
- preview?: PreviewAnswer
137
- previewFailure?: string
138
- /** The IR revision the preview shows. */
139
- previewIrRevision?: string
140
- isPreparingPresentation?: boolean
141
- presentationFailure?: string
142
- presentationSnapshot?: { version: string, fingerprint: string, revision: string, project: number }
143
- productionPlan?: ProductionPlan
144
- productionPlayback?: ProductionPlaybackState
145
- productionFailure?: string
146
- voiceoverJobs?: VoiceoverJob[]
147
- voiceoverJobsFailure?: string
148
- /** A cache refresh that actually changed the current production binding; it never starts playback. */
149
- voiceoverCacheRefresh?: { source: CanonicalSource, revision: string, sequence: number }
150
- /** Changes when an acknowledged preview connection is attached or detached, including same-revision reloads. */
151
- previewConnection: number
152
- /** Where the preview is: the section the author reads, or the slide and its step. */
153
- position?: PreviewPosition
154
- /** Changes on every position intent, including A → B → A, without changing the source. */
155
- documentPositionToken: string
156
- /** Explicit author navigation, distinct from the player's passive cursor and frame reload reports. */
157
- productionNavigationVersion: number
158
- documentPositionIntent: 'seek' | 'pause'
159
- /** An explicit source navigation request; scrolling updates position without issuing another request. */
160
- documentNavigation?: { section: string, block?: string, request: string }
161
- documentPositionFailure?: 'removed'
162
- isCreatingPage?: boolean
163
- isEditingPage?: boolean
164
- editorHistory?: EditorHistoryState
165
- isHistoryPreparing?: boolean
166
- pageEditFailure?: string
167
- diagnostics?: DiagnosticSnapshot
168
- isDiagnosticsUnavailable: boolean
169
- canRepairDiagnostics: boolean
170
- isRepairingDiagnostics: boolean
171
- diagnosticsRepairFailure?: string
172
- pointer?: Pointer
173
- save: SaveState
174
- /** What the conversation's agent is told the author points at. */
175
- focus: FocusReport[]
176
- isFocusPending: boolean
177
- focusFailure?: string
178
- review?: ReviewSnapshot
179
- history?: RevisionsAnswer
180
- /** Files changed elsewhere and not yet in the history. */
181
- outside?: UncommittedFile[]
182
- historyFailure?: string
183
- isHistoryBusy: boolean
184
- isAsking: boolean
185
- askFailure?: string
186
- /** What the document can be made into, and its builds and exports (the author's and the AI's). */
187
- jobs?: JobsAnswer
188
- jobsFailure?: string
189
- voiceServiceVersion?: number
190
- jobPreparing?: { target: string, canCancel: boolean }
191
- }
192
-
193
- export interface PreviewSink {
194
- readonly generation?: number
195
- readonly capabilities?: readonly PreviewCommand['type'][]
196
- send(command: PreviewCommand): void
197
- }
198
-
199
- export interface EditorHistoryState { section: string, undo: boolean, redo: boolean, field?: boolean }
200
-
201
47
  type Listener = () => void
202
48
  const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
203
49
 
204
- /** The workbench's state as its parts read and change it. */
205
- export interface WorkbenchStore {
206
- readonly state: WorkbenchState
207
- set(patch: Partial<WorkbenchState>): void
208
- }
209
-
210
50
  // The export of the lecture as a video (`@lincyaw/addon-lecture`).
211
51
  export const VIDEO_TARGET = 'video'
212
52
 
213
- /** The document the conversation works on: none when no document is open. */
214
- export function selectedDocument(state: WorkbenchState): string | null {
215
- return state.document ?? null
216
- }
217
-
218
- /** Whether the AI is changing the workspace now, or its change waits for the author. */
219
- export function isAgentChanging(state: WorkbenchState): boolean {
220
- return Boolean(state.review?.engine === 'git' && (state.review.running || state.review.changes.length > 0))
221
- }
222
-
223
53
  /** Whether the document has a slides form (no renderers listed: every form). */
224
54
  export function hasSlides(ir: IrAnswer | undefined): boolean {
225
55
  const renderers = ir?.doc.config.renderers
@@ -274,31 +104,9 @@ export function documentDirFor(title: string, taken: readonly string[]): string
274
104
  export class Workbench {
275
105
  readonly client: WorkspaceClient
276
106
  readonly #documentSession: DocumentSession
277
- readonly #audioImports = new WeakMap<File, { identity: string, version: string, id: string }>()
278
- readonly #audioFingerprints = new WeakMap<File, Promise<string>>()
279
- readonly #documentTimingDrafts = new DocumentTimingDrafts()
280
- readonly #captionTimingDrafts = new CaptionTimingDrafts()
281
- readonly #removedCueTimings = new Map<string, { pauseMs: number }>()
282
- readonly #removedNarrations = new Map<string, { narration: Narration, override?: { narrationStart: 'with-animation' | 'after-animation' } }>()
283
- #cueTimingScope?: string
284
- #documentEditor?: NativeDocumentEditor
285
- #documentEditorCommands?: DocumentEditorCommands
286
- #documentEditorBinding?: { identity: string, reset: number }
287
- readonly #documentReturnPoints = new DocumentReturnPoints()
288
- #documentViewport?: { element: HTMLElement, identity: string, returnScrollTop?: number, stop(): void }
289
- #stopDocumentReturnScroll?: () => void
290
- #openingDocument?: { directory: string, scope: number, generation: number, focus?: 'body', initial?: boolean, stop(): void,
291
- basis?: { identity: string, reset: number, version?: string, content: TeachingDocument }, point?: DocumentReturnPoint, fallback?: DocumentReturnPoint }
292
- #stopDocumentLayoutScroll?: () => void
293
- #activeDocumentHistory?: DocumentHistoryEditor
294
- #unsubscribeDocumentHistory?: () => void
295
- #unsubscribeDocumentSelection?: () => void
296
- #documentSelectionGeneration = 0
107
+ readonly production: DocumentProduction
297
108
  #removedDocumentPosition?: { identity: string, documentId: string, sectionId: string, stepId?: string, version: string, fingerprint: string, scope: number, generation: number, token: string }
298
- #pendingDocumentFocus?: { documentId: string, nodeId: string, generation: number, afterSave?: true }
299
- #pendingDocumentSelection?: { documentId: string, anchor: NativeTextPoint, head: NativeTextPoint, focused: boolean }
300
- readonly #documentFields = new Map<string, DocumentFieldRegistration>()
301
- #pendingDocumentField?: { field: Omit<DocumentFieldRegistration, 'focus' | 'editor'>, bookmark: DocumentFieldBookmark, reset: number, generation: number }
109
+ readonly editing: DocumentEditing
302
110
  #state: WorkbenchState
303
111
  readonly #listeners = new Set<Listener>()
304
112
  readonly #commentDrafts = new CommentDraftBank()
@@ -329,7 +137,7 @@ export class Workbench {
329
137
  #documentScope = 0
330
138
  #jobPreparation?: AbortController
331
139
  readonly #playback = new PreviewPlayback(() => ({ document: this.#state.document, scope: this.#documentScope, sinks: this.#previewSinks }))
332
- readonly #production = new ProductionPlayback(() => ({ document: this.#state.document, scope: this.#documentScope, sinks: this.#previewSinks,
140
+ readonly #productionPlayback = new ProductionPlayback(() => ({ document: this.#state.document, scope: this.#documentScope, sinks: this.#previewSinks,
333
141
  binding: this.#state.productionPlan?.binding, ready: this.#productionReady() }), state => this.#set({ productionPlayback: state }))
334
142
  /** A place to show that no preview could take yet (none was attached, e.g. the chat covered the document). */
335
143
  #pendingReveal?: PreviewAnchor
@@ -374,12 +182,7 @@ export class Workbench {
374
182
  }
375
183
  this.#documentSession = new DocumentSession(this.client, authoring => {
376
184
  if (this.#state.document !== authoring.directory) return
377
- const pendingField = this.#pendingDocumentField
378
- if (pendingField && (pendingField.field.identity !== authoring.identity || authoring.reset > pendingField.reset
379
- || pendingField.field.blockId !== undefined && !authoring.content?.blocks[pendingField.field.blockId]
380
- || !authoring.content?.steps[pendingField.field.stepId])) this.#pendingDocumentField = undefined
381
- const cueTimingScope = JSON.stringify([authoring.identity, authoring.reset])
382
- if (this.#cueTimingScope !== cueTimingScope) { this.#removedCueTimings.clear(); this.#removedNarrations.clear(); this.#cueTimingScope = cueTimingScope }
185
+ this.editing.sourceChanged(authoring)
383
186
  const previous = this.#state.authoring
384
187
  // A saved timestamp belongs to this client's acknowledged source version.
385
188
  // Remote adoption has no server modification time to display in its place.
@@ -394,34 +197,39 @@ export class Workbench {
394
197
  const removed = this.#state.webView === 'document' && position?.view !== 'present' && position && previous?.identity === authoring.identity
395
198
  && (selected ? !selectedStep || selectedIndex < 0 : !authoring.content?.sectionOrder.includes(position.section))
396
199
  const restoredPosition = !removed && this.#restoredDocumentPosition(authoring)
397
- const scope = this.#documentScope, generation = this.#documentSelectionGeneration
398
- if (removed && authoring.identity) this.#documentReturnPoints.forget(authoring.identity)
200
+ const scope = this.#documentScope, generation = this.editing.generation
201
+ if (removed && authoring.identity) this.editing.returnPoints.forget(authoring.identity)
399
202
  this.#set({ authoring,
400
203
  ...removed ? { position: undefined, documentNavigation: undefined, documentPositionFailure: 'removed' as const } : {},
401
204
  ...restoredPosition ? { documentPositionFailure: undefined } : {},
402
205
  ...moved ? { position: { ...position, section: selectedStep.sectionId, step: selectedIndex, trail: [] } } : {},
403
- hasDocumentTimingDrafts: Boolean(authoring.identity && authoring.content && this.#documentTimingDrafts.has(authoring.identity, authoring.content)),
404
- documentTimingDraftStorageFailure: this.#documentTimingDrafts.failed,
405
- captionTimingDraftSteps: authoring.identity && authoring.member?.id && authoring.content ? this.#captionTimingDrafts.steps({ identity: authoring.identity, memberId: authoring.member.id }, authoring.content) : [],
406
- captionTimingDraftStorageFailure: Boolean(authoring.identity && authoring.member?.id && this.#captionTimingDrafts.failed({ identity: authoring.identity, memberId: authoring.member.id })),
206
+ ...this.production.draftState(authoring),
407
207
  save: authoring.error ? { kind: 'failed', message: authoring.error } : authoring.saving ? { kind: 'saving' } : !authoring.dirty && (previous?.dirty || previous?.saving) ? { kind: 'saved', at: new Date().toISOString() } : adoptedCleanVersion || this.#state.save.kind === 'failed' ? { kind: 'idle' } : this.#state.save })
408
208
  // The deletion owns the token produced above; source restoration only retires its notice.
409
209
  if (removed && previous?.identity && previous.content && previous.version && previous.fingerprint
410
210
  && !previous.loading && !previous.dirty && !previous.saving && !previous.restored && !previous.composing && !previous.recovering && !previous.error
411
- && scope === this.#documentScope && generation === this.#documentSelectionGeneration && !this.#state.position && this.#state.documentPositionFailure === 'removed') {
211
+ && scope === this.#documentScope && generation === this.editing.generation && !this.#state.position && this.#state.documentPositionFailure === 'removed') {
412
212
  this.#removedDocumentPosition = { identity: previous.identity, documentId: previous.content.id, sectionId: position.section,
413
213
  ...selected ? { stepId: selected } : {}, version: previous.version, fingerprint: previous.fingerprint, scope, generation, token: this.#state.documentPositionToken }
414
214
  }
415
- this.#finishOpeningDocument()
215
+ this.editing.finishOpening()
416
216
  // Native insertion can select a page before the source actor receives that new entity.
417
217
  if (position && previous && previous.identity === authoring.identity && !previous.content?.sections[position.section]
418
- && authoring.content?.sections[position.section]) this.#saveDocumentReturnPoint()
419
- if (this.#production.changed()) void this.pausePlayback().catch(() => {})
218
+ && authoring.content?.sections[position.section]) this.editing.saveReturnPoint()
219
+ if (this.#productionPlayback.changed()) void this.pausePlayback().catch(() => {})
420
220
  const acknowledgedSourceChanged = !authoring.dirty && !authoring.loading && !authoring.error && !previous?.loading
421
221
  && previous?.identity === authoring.identity && Boolean(previous?.version && authoring.version)
422
222
  && (previous?.version !== authoring.version || previous?.fingerprint !== authoring.fingerprint)
423
223
  if (!authoring.dirty && previous?.dirty || acknowledgedSourceChanged) { void this.#history.read(authoring.directory); void this.loadDocuments() }
424
224
  })
225
+ this.production = new DocumentProduction({ store, session: this.#documentSession, client: this.client,
226
+ scope: () => this.#documentScope, document: identity => this.getDocument(identity), flush: signal => this.flushPendingEdits(signal),
227
+ pause: () => this.pausePlayback(), stopAuditions: () => this.stopAuditions(), stopPreviewOutputs: () => this.#playback.stopPreviewOutputs(),
228
+ sourceCurrent: binding => this.#productionSourceCurrent(binding) })
229
+ this.editing = new DocumentEditing({ store, session: this.#documentSession, scope: () => this.#documentScope,
230
+ flush: signal => this.flushPendingEdits(signal), goToSection: section => this.goToSection(section),
231
+ rememberStep: (directory, section, step) => { this.#selectedSteps.set(`${directory}\0${section}`, step) },
232
+ canAskAnimation: () => this.#drafters.size > 0, askAnimation: place => this.draftAnimation(place) })
425
233
  this.#diagnostics = new DocumentDiagnostics(this.client, store)
426
234
  this.#jobs = new DocumentJobs(this.client, store)
427
235
  this.#voiceover = new VoiceoverJobs(this.client, store, (job, signal) => this.#refreshVoiceover(job, signal))
@@ -516,7 +324,7 @@ export class Workbench {
516
324
  #restoredDocumentPosition(source: DocumentSessionState): boolean {
517
325
  const removed = this.#removedDocumentPosition
518
326
  if (!removed) return false
519
- if (removed.scope !== this.#documentScope || removed.generation !== this.#documentSelectionGeneration || removed.token !== this.#state.documentPositionToken
327
+ if (removed.scope !== this.#documentScope || removed.generation !== this.editing.generation || removed.token !== this.#state.documentPositionToken
520
328
  || removed.identity !== source.identity || this.#state.documentPositionFailure !== 'removed' || source.error) {
521
329
  this.#removedDocumentPosition = undefined
522
330
  return false
@@ -530,9 +338,9 @@ export class Workbench {
530
338
 
531
339
  #set(patch: Partial<WorkbenchState>): void {
532
340
  if (Object.hasOwn(patch, 'position') || Object.hasOwn(patch, 'documentPositionFailure')) this.#removedDocumentPosition = undefined
533
- if (Object.hasOwn(patch, 'position')) { this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.() }
341
+ if (Object.hasOwn(patch, 'position')) this.editing.beforePosition()
534
342
  this.#state = { ...this.#state, ...patch, ...Object.hasOwn(patch, 'position') ? { documentPositionToken: this.#nextDocumentPosition(), documentPositionIntent: patch.documentPositionIntent ?? 'seek' } : {} }
535
- if (Object.hasOwn(patch, 'position')) this.#saveDocumentReturnPoint()
343
+ if (Object.hasOwn(patch, 'position')) this.editing.saveReturnPoint()
536
344
  for (const listener of this.#listeners) listener()
537
345
  }
538
346
 
@@ -598,163 +406,28 @@ export class Workbench {
598
406
  await this.operateDocument({ op: 'retitle', dir, title })
599
407
  }
600
408
 
601
- #watchOpeningInteraction(cancel: () => void): () => void {
602
- if (typeof document === 'undefined') return () => {}
603
- const focused = document.activeElement, dialog = focused?.closest('[role="dialog"]')
604
- const interact = (event: Event) => {
605
- if (!event.isTrusted) return
606
- if (event.type === 'focusin' && (!(event.target instanceof Element) || event.target === focused || dialog?.contains(event.target))) return
607
- cancel()
608
- }
609
- const events = ['pointerdown', 'keydown', 'beforeinput', 'wheel', 'touchmove', 'focusin']
610
- for (const event of events) document.addEventListener(event, interact, true)
611
- return () => { for (const event of events) document.removeEventListener(event, interact, true) }
612
- }
613
-
614
- #cancelOpeningDocument(): void {
615
- const pending = this.#openingDocument
616
- this.#openingDocument = undefined
617
- pending?.stop()
618
- }
619
-
620
- #beginOpeningDocument(directory: string, focus?: 'body', fallback?: DocumentReturnPoint): void {
621
- this.#cancelOpeningDocument()
622
- this.#openingDocument = { directory, focus, fallback: fallback && { ...fallback }, scope: this.#documentScope, generation: this.#documentSelectionGeneration,
623
- stop: this.#watchOpeningInteraction(() => this.#cancelOpeningDocument()) }
624
- }
625
-
626
- #saveDocumentReturnPoint(): void {
627
- const source = this.#state.authoring, position = this.#state.position
628
- if (!source?.identity || !source.content || source.loading || !position || !source.content.sectionOrder.includes(position.section)) return
629
- const section = source.content.sections[position.section]
630
- let stepId = section?.stepOrder[position.step]
631
- if (this.#state.webView === 'present' || position.view === 'present') {
632
- const snapshot = this.#state.presentationSnapshot, ir = this.#state.ir
633
- if (!snapshot || !ir || source.dirty || source.saving || source.error || snapshot.version !== source.version || snapshot.fingerprint !== source.fingerprint
634
- || snapshot.project !== (source.projectRevision ?? 0) || snapshot.revision !== ir.revision || snapshot.revision !== this.#state.previewIrRevision) return
635
- const ids = ir.doc.sections.find(page => page.id === position.section)?.stepIds
636
- if (!ids || ids.length && !ids[position.step]) return
637
- stepId = ids[position.step]
638
- if (stepId && (!section?.stepOrder.includes(stepId) || source.content.steps[stepId]?.sectionId !== position.section)) return
639
- }
640
- if (!section || !stepId && section.stepOrder.length) return
641
- const viewport = this.#documentViewport, previous = this.#documentReturnPoints.read(source.identity)
642
- const measured = this.#state.webView === 'document' && viewport?.identity === source.identity ? documentViewportOffset(viewport.element, section.id) : undefined
643
- const offset = measured ?? (previous?.sectionId === section.id ? previous.offset : undefined)
644
- this.#documentReturnPoints.write(source.identity, { sectionId: section.id, ...stepId ? { stepId } : {}, ...offset !== undefined ? { offset } : {} })
645
- }
646
-
647
- #finishOpeningDocument(): void {
648
- const pending = this.#openingDocument, source = this.#state.authoring
649
- if (!pending || source?.loading || !source?.identity || !source.content) return
650
- if (source.error === 'document-identity-changed') { this.#cancelOpeningDocument(); return }
651
- if (pending.scope !== this.#documentScope || pending.directory !== this.#state.document || pending.generation !== this.#documentSelectionGeneration) { this.#cancelOpeningDocument(); return }
652
- if (!pending.basis) {
653
- pending.basis = { identity: source.identity, reset: source.reset, version: source.version, content: source.content }
654
- if (!pending.focus) {
655
- pending.point = this.#documentReturnPoints.read(source.identity) ?? pending.fallback
656
- if (!pending.point) {
657
- const section = source.content.sections[source.content.sectionOrder[0]!]
658
- if (!section) { this.#cancelOpeningDocument(); return }
659
- pending.point = { sectionId: section.id, ...section.stepOrder[0] ? { stepId: section.stepOrder[0] } : {} }
660
- pending.initial = true
661
- }
662
- if (documentReturnStep(source.content, pending.point) === undefined) {
663
- this.#documentReturnPoints.forget(source.identity); this.#cancelOpeningDocument()
664
- this.#set({ documentPositionFailure: 'removed' }); return
665
- }
666
- }
667
- }
668
- const basis = pending.basis
669
- if (source.identity !== basis.identity || source.reset !== basis.reset || source.version !== basis.version || source.content !== basis.content) { this.#cancelOpeningDocument(); return }
670
- const editor = this.#documentEditor, binding = this.#documentEditorBinding, viewport = this.#documentViewport
671
- if (!editor || editor.prosemirrorView.isDestroyed || binding?.identity !== source.identity || binding.reset !== source.reset || viewport?.identity !== source.identity) return
672
- // The editor can mount read-only while the source is still loading; a read-only body cannot take the caret yet.
673
- if (pending.focus && !editor.isEditable) return
674
- this.#cancelOpeningDocument()
675
- if (pending.focus) {
676
- const body = (blocks: typeof editor.document, sectionId?: string): { nodeId: string, sectionId: string } | undefined => {
677
- for (const block of blocks) {
678
- if (block.type === 'presmiumPage') sectionId = block.props.sectionId
679
- else if (sectionId && editor.schema.blockSchema[block.type].content === 'inline') return { nodeId: block.id, sectionId }
680
- const nested = body(block.children, sectionId)
681
- if (nested) return nested
682
- }
683
- }
684
- const target = body(editor.document)
685
- if (target && source.content.sections[target.sectionId]) {
686
- this.#set({ position: { section: target.sectionId, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: undefined })
687
- this.#focusDocumentNode(editor, target.nodeId)
688
- }
689
- return
690
- }
691
- const point = pending.point!, step = documentReturnStep(source.content, point)
692
- if (step === undefined) return
693
- this.#selectedSteps.set(`${pending.directory}\0${point.sectionId}`, step)
694
- this.#set({ position: { section: point.sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: undefined })
695
- if (pending.initial) return
696
- const current = () => this.#state.document === pending.directory && this.#state.authoring?.identity === basis.identity
697
- && this.#state.authoring.reset === basis.reset && this.#state.authoring.version === basis.version && this.#state.authoring.content === basis.content
698
- && this.#documentViewport === viewport && this.#state.position?.section === point.sectionId && this.#state.position.step === step
699
- const restore = () => {
700
- if (!current()) { stop(); return }
701
- const top = viewport.element.scrollTop
702
- restoreDocumentViewport(viewport.element, point)
703
- if (viewport.element.scrollTop !== top) viewport.returnScrollTop = viewport.element.scrollTop
704
- }
705
- const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(restore)
706
- let stopInteraction: () => void = () => {}
707
- const stop = () => { observer?.disconnect(); stopInteraction(); viewport.returnScrollTop = undefined; if (this.#stopDocumentReturnScroll === stop) this.#stopDocumentReturnScroll = undefined }
708
- this.#stopDocumentReturnScroll?.(); this.#stopDocumentReturnScroll = stop
709
- stopInteraction = this.#watchOpeningInteraction(stop)
710
- observer?.observe(viewport.element)
711
- observer?.observe(editor.prosemirrorView.dom)
712
- restore()
713
- }
714
-
715
- /** Consume only this viewport owner's actual programmatic destination; user gestures retire it. */
716
- consumeDocumentReturnScroll(element: HTMLElement): boolean {
717
- const viewport = this.#documentViewport, top = viewport?.returnScrollTop
718
- if (viewport?.element !== element || top === undefined) return false
719
- viewport.returnScrollTop = undefined
720
- return element.scrollTop === top
721
- }
722
-
723
- attachDocumentViewport(element: HTMLElement, identity: string): () => void {
724
- this.#documentViewport?.stop()
725
- const scroll = () => { if (!this.#openingDocument) this.#saveDocumentReturnPoint() }
726
- const viewport = { element, identity, stop: () => element.removeEventListener('scroll', scroll) }
727
- this.#documentViewport = viewport
728
- element.addEventListener('scroll', scroll, { passive: true })
729
- this.#finishOpeningDocument()
730
- return () => { if (this.#documentViewport === viewport) { this.#saveDocumentReturnPoint(); this.#stopDocumentReturnScroll?.(); this.#documentViewport = undefined }; viewport.stop() }
731
- }
732
-
733
- /** The body editor became editable: an opening that waits to put the caret in it can finish now. */
734
- documentEditorEditable(): void { this.#finishOpeningDocument() }
735
-
736
409
  async openDocument(dir: string, options: { focus?: 'body', expectedIdentity?: string, fallbackReturnPoint?: DocumentReturnPoint } = {}): Promise<void> {
737
410
  if (this.#state.document === dir) {
738
- if (options.focus) { this.#beginOpeningDocument(dir, options.focus); this.#finishOpeningDocument() }
411
+ if (options.focus) { this.editing.beginOpening(dir, options.focus); this.editing.finishOpening() }
739
412
  return
740
413
  }
741
- this.#saveDocumentReturnPoint()
414
+ this.editing.saveReturnPoint()
742
415
  this.#documentScope++
743
416
  const scope = this.#documentScope
744
417
  this.#stopSubscriptions()
745
418
  this.#history.subscribeReview(dir)
746
419
  this.#set({ ...DOCUMENT_RESET, document: dir, previewRenderer: 'web', webView: 'document' })
747
- this.#beginOpeningDocument(dir, options.focus, options.fallbackReturnPoint)
420
+ this.editing.beginOpening(dir, options.focus, options.fallbackReturnPoint)
748
421
  this.#record('document.open')
749
422
  this.#diagnostics.subscribe(dir)
750
423
  // Authoring is ready from source JSON; compilation and preview are independent.
751
424
  const [opened] = await Promise.all([this.#documentSession.open(dir, options.expectedIdentity), this.#readFocus(dir), this.#history.read(dir)])
752
425
  if (opened === 'identity-changed' && scope === this.#documentScope && this.#state.document === dir) { this.closeDocument(); return }
753
- this.#finishOpeningDocument()
426
+ this.editing.finishOpening()
754
427
  }
755
428
 
756
429
  closeDocument(): void {
757
- this.#saveDocumentReturnPoint()
430
+ this.editing.saveReturnPoint()
758
431
  this.#documentScope++
759
432
  if (this.#state.document !== undefined) this.#record('document.close')
760
433
  this.#stopSubscriptions()
@@ -1019,7 +692,7 @@ export class Workbench {
1019
692
  await this.pausePlayback()
1020
693
  signal.throwIfAborted()
1021
694
  if (!current()) return false
1022
- this.#production.reset()
695
+ this.#productionPlayback.reset()
1023
696
  this.#set({ productionPlan: plan, voiceoverCacheRefresh: { source: job.source, revision: job.revision, sequence: (this.#state.voiceoverCacheRefresh?.sequence ?? 0) + 1 } })
1024
697
  // The mounted production loader fetches this new binding in the existing frame.
1025
698
  // Replacing the iframe for every clip would interrupt progressive playback and its connection.
@@ -1204,7 +877,7 @@ export class Workbench {
1204
877
  signal.throwIfAborted()
1205
878
  if (scope !== this.#documentScope || this.#state.authoring?.identity !== identity || !this.#productionSourceCurrent(plan.binding)) throw new Error('production-source-changed')
1206
879
  this.#set({ productionPlan: plan })
1207
- if (this.#production.changed()) void this.pausePlayback().catch(() => {})
880
+ if (this.#productionPlayback.changed()) void this.pausePlayback().catch(() => {})
1208
881
  return plan
1209
882
  }
1210
883
 
@@ -1225,7 +898,7 @@ export class Workbench {
1225
898
  await this.pausePlayback()
1226
899
  signal?.throwIfAborted()
1227
900
  }
1228
- return await this.#production.control(control, signal)
901
+ return await this.#productionPlayback.control(control, signal)
1229
902
  } catch (error) {
1230
903
  const code = errorMessage(error), current = this.#state.productionPlan?.binding
1231
904
  if (scope === this.#documentScope && !signal?.aborted && current && sameProductionBinding(current, control.binding) && this.#productionReady()
@@ -1237,7 +910,7 @@ export class Workbench {
1237
910
 
1238
911
  closeProduction(): void {
1239
912
  this.#interruptProductionNavigation()
1240
- this.#production.reset()
913
+ this.#productionPlayback.reset()
1241
914
  this.#set({ productionPlan: undefined, productionFailure: undefined })
1242
915
  }
1243
916
 
@@ -1267,46 +940,6 @@ export class Workbench {
1267
940
  if (this.#state.document !== undefined) void this.#readPreview(this.#state.document)
1268
941
  }
1269
942
 
1270
- #pageEditMessage(reason: string): string {
1271
- const t = this.#messages
1272
- if (reason === 'native-unavailable') return t.nativeEditUnavailable
1273
- if (reason.startsWith('native-')) return t.nativeEditDraft
1274
- switch (reason) {
1275
- case 'page-multiple-files': return t.pageEditFiles
1276
- case 'page-boundary': return t.pageEditBoundary
1277
- case 'page-hierarchy': return t.pageEditHierarchy
1278
- case 'page-implicit-title': return t.pageEditImplicitTitle
1279
- case 'page-formatted-title': return t.pageEditFormattedTitle
1280
- case 'page-title': return t.pageEditInvalidTitle
1281
- case 'page-compiler': return t.pageEditCompiler
1282
- case 'page-referenced': return t.pageDeleteReferenced
1283
- case 'page-external-bindings': return t.pageDeleteExternalBindings
1284
- case 'page-references-unavailable': return t.pageDeleteReferencesUnavailable
1285
- case 'page-busy': return t.pageEditBusy
1286
- case 'preview-flush-unavailable': return t.pageEditPreview
1287
- case 'page-context-changed': return t.pageEditChanged
1288
- case 'save-timeout': return t.pageEditFlushTimeout
1289
- case 'source-draft': return t.pageEditSourceDraft
1290
- case 'source-refresh': return t.pageEditRefresh
1291
- case 'page-draft':
1292
- case 'source-conflict':
1293
- case 'narration-conflict':
1294
- case 'revision-conflict': return t.pageEditDraft
1295
- case 'save-locked': return t.saveLocked
1296
- default: return t.pageEditRequestFailed
1297
- }
1298
- }
1299
-
1300
- pageEditCapability(section: string): { rename: boolean, move: boolean, reason?: string } {
1301
- const exists = Boolean(this.#state.authoring?.content?.sections[section])
1302
- const capability = { rename: exists, move: exists }
1303
- if (isAgentChanging(this.#state)) return { rename: false, move: false, reason: this.#messages.saveLocked }
1304
- if (this.#state.isCreatingPage || this.#state.isEditingPage || this.#state.isHistoryBusy) return { rename: false, move: false, reason: this.#messages.pageEditBusy }
1305
- return capability
1306
- }
1307
-
1308
- clearPageEditFailure(): void { this.#set({ pageEditFailure: undefined }) }
1309
-
1310
943
  /** The preview acknowledges that all registered lecture playback has paused before audition audio starts. */
1311
944
  pausePlayback(interactive = false): Promise<void> { if (interactive) this.#interruptProductionNavigation(); return this.#playback.pause() }
1312
945
 
@@ -1338,175 +971,14 @@ export class Workbench {
1338
971
  if (!asset || asset.kind !== 'image' || asset.location !== answer.content.assets[answer.assetId]?.location) throw new Error('document-identity-changed')
1339
972
  return asset.location
1340
973
  }
1341
- #mediaSource(expected: { identity: string, version: string }): DocumentSessionState {
1342
- const source = this.#state.authoring
1343
- if (!source || !this.getDocument(expected.identity) || source.version !== expected.version || !source.fingerprint
1344
- || source.dirty || source.saving || source.composing || source.restored || source.error || isAgentChanging(this.#state)) throw new Error('production-source-changed')
1345
- return source
1346
- }
1347
- /** Inspects the saved declaration, including a local asset not yet attached to a step. */
1348
- async inspectDocumentAudio(assetId: string, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer> {
1349
- const source = this.#mediaSource(expected), scope = this.#documentScope
1350
- const answer = await this.client.readDocumentAudio(source.directory, assetId, expected.version, signal)
1351
- signal?.throwIfAborted()
1352
- if (scope !== this.#documentScope || answer.document !== source.directory || answer.version !== expected.version || answer.fingerprint !== source.fingerprint || answer.inspection.assetId !== assetId) throw new Error('production-source-changed')
1353
- this.#mediaSource(expected)
1354
- return answer
1355
- }
1356
- /** Recognition keeps its captured source even if subsequent author input moves to a newer version. */
1357
- async startDocumentTranscription(request: Omit<DocumentTranscriptionRequest, 'source'>, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionTask> {
1358
- const source = this.#mediaSource(expected)
1359
- if (!source.content || !source.fingerprint) throw new Error('production-source-changed')
1360
- const sent: DocumentTranscriptionRequest = { ...structuredClone(request), source: { documentId: source.content.id, version: expected.version, fingerprint: source.fingerprint } }
1361
- const answer = await this.client.startTranscription(source.directory, sent, signal)
1362
- signal?.throwIfAborted()
1363
- if (answer.document !== source.directory || answer.intent !== sent.intent || answer.source.documentId !== sent.source.documentId
1364
- || answer.source.version !== sent.source.version || answer.source.fingerprint !== sent.source.fingerprint || answer.audio.assetId !== sent.assetId || answer.audio.sha256 !== sent.audioSha256) throw new Error('transcription-response-changed')
1365
- return answer
1366
- }
1367
- async planDocumentTranscription(draft: TranscriptionAdoptionDraft, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionAdoptionPlan> {
1368
- const source = this.#mediaSource(expected), sent = structuredClone(draft)
1369
- if (sent.source.documentId !== source.content?.id || sent.source.version !== expected.version || sent.source.fingerprint !== source.fingerprint) throw new Error('production-source-changed')
1370
- const answer = await this.client.planTranscriptionAdoption(source.directory, sent, signal)
1371
- signal?.throwIfAborted()
1372
- this.#mediaSource(expected)
1373
- if (answer.document !== source.directory || answer.changeId !== sent.id || answer.source.documentId !== sent.source.documentId
1374
- || answer.source.version !== sent.source.version || answer.source.fingerprint !== sent.source.fingerprint || answer.candidate.id !== sent.candidate.id
1375
- || answer.candidate.revision !== sent.candidate.revision || answer.draftRevision !== sent.draftRevision) throw new Error('transcription-response-changed')
1376
- return answer
1377
- }
1378
- async adoptDocumentTranscription(request: TranscriptionAdoptionApply, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionAdoptionAnswer> {
1379
- const source = this.#mediaSource(expected), sent = structuredClone(request)
1380
- if (sent.source.documentId !== source.content?.id || sent.source.version !== expected.version || sent.source.fingerprint !== source.fingerprint) throw new Error('production-source-changed')
1381
- const answer = await this.#writeDocumentMedia(expected, directory => this.client.applyTranscriptionAdoption(directory, sent, signal), signal)
1382
- if (answer.adoption.planId !== sent.planId || answer.adoption.candidate.id !== sent.candidate.id || answer.adoption.candidate.revision !== sent.candidate.revision
1383
- || answer.adoption.draftRevision !== sent.draftRevision) throw new Error('transcription-response-changed')
1384
- return answer
1385
- }
1386
- async #writeDocumentMedia<T extends DocumentChangeAnswer>(expected: { identity: string, version: string }, write: (directory: string) => Promise<T>, signal?: AbortSignal): Promise<T> {
1387
- const scope = this.#documentScope, source = this.#mediaSource(expected)
1388
- this.stopAuditions()
1389
- await this.pausePlayback()
1390
- await this.flushPendingEdits(signal)
1391
- signal?.throwIfAborted()
1392
- if (scope !== this.#documentScope) throw new Error('production-source-changed')
1393
- this.#mediaSource(expected)
1394
- let answer: T
1395
- try { answer = await write(source.directory) }
1396
- finally { await this.#documentSession.refresh(source.directory) }
1397
- signal?.throwIfAborted()
1398
- if (scope !== this.#documentScope || answer.document !== source.directory || answer.content.id !== source.content?.id) throw new Error('production-source-changed')
1399
- this.#mediaSource({ identity: expected.identity, version: answer.version })
1400
- return answer
1401
- }
1402
- /** Import commits the original file and its declaration together, without creating a clip or narration. */
1403
- async importDocumentAudio(file: File, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioImportAnswer> {
1404
- let request: { identity: string, version: string, id: string } | undefined
1405
- const answer = await this.#writeDocumentMedia(expected, async directory => {
1406
- const existing = this.#audioImports.get(file), first = !existing || existing.identity !== expected.identity
1407
- request = first ? { identity: expected.identity, version: expected.version, id: randomUUID() } : existing!
1408
- this.#audioImports.set(file, request)
1409
- try { return await this.client.importDocumentAudio(directory, file, { id: request.id, baseDocumentVersion: request.version }, signal) }
1410
- catch (error) {
1411
- if (first && error instanceof WorkspaceServerError && error.status >= 400 && error.status < 500 && this.#audioImports.get(file) === request) this.#audioImports.delete(file)
1412
- throw error
1413
- }
1414
- }, signal)
1415
- if (answer.changeId !== request?.id || answer.inspection.assetId !== answer.assetId || !answer.content.assets[answer.assetId]) throw new Error('production-source-changed')
1416
- if (this.#audioImports.get(file) === request) this.#audioImports.delete(file)
1417
- return answer
1418
- }
1419
- /** Reconcile an ambiguous save against real asset bytes before admitting a new source-bound import. */
1420
- async ensureDocumentAudio(file: File, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer> {
1421
- const source = this.#mediaSource(expected)
1422
- if (!file.size || file.size > DOCUMENT_AUDIO_MAX_BYTES) throw new Error('production.asset-size')
1423
- let pending = this.#audioFingerprints.get(file)
1424
- if (!pending) {
1425
- pending = file.arrayBuffer().then(sha256)
1426
- this.#audioFingerprints.set(file, pending)
1427
- }
1428
- const hash = await pending
1429
- signal?.throwIfAborted(); this.#mediaSource(expected)
1430
- for (const asset of Object.values(source.content?.assets ?? {})) {
1431
- if (asset.kind !== 'audio' || asset.fingerprint !== `sha256:${hash}`) continue
1432
- try {
1433
- const answer = await this.inspectDocumentAudio(asset.id, expected, signal)
1434
- if (answer.inspection.sha256 === hash) return answer
1435
- } catch (error) {
1436
- if (!(error instanceof WorkspaceServerError) || ![404, 413, 422].includes(error.status)) throw error
1437
- }
1438
- }
1439
- signal?.throwIfAborted(); this.#mediaSource(expected)
1440
- const previous = this.#audioImports.get(file)
1441
- if (previous?.identity === expected.identity && previous.version !== expected.version) this.#audioImports.delete(file)
1442
- let imported: DocumentAudioImportAnswer
1443
- try { imported = await this.importDocumentAudio(file, expected, signal) }
1444
- catch (error) {
1445
- if (!previous || this.#audioImports.get(file) !== previous || !(error instanceof WorkspaceServerError)
1446
- || error.status !== 409 || error.message !== 'document-version-changed') throw error
1447
- signal?.throwIfAborted(); this.#mediaSource(expected)
1448
- this.#audioImports.delete(file)
1449
- imported = await this.importDocumentAudio(file, expected, signal)
1450
- }
1451
- return { document: imported.document, version: imported.version, fingerprint: imported.fingerprint, inspection: imported.inspection }
1452
- }
1453
- /** The source actor owns this external transaction; capture is independent from preview output. */
1454
- async adoptDocumentRecording(request: DocumentRecordingAdoption, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<VerifiedDocumentRecordingAdoption> {
1455
- const scope = this.#documentScope, source = this.#mediaSource(expected), sent = structuredClone(request)
1456
- if (sent.source.documentId !== source.content?.id || sent.source.version !== source.version || sent.source.fingerprint !== source.fingerprint
1457
- || !source.content.steps[sent.stepId] || !source.content.assets[sent.assetId]) throw new Error('production-source-changed')
1458
- this.#playback.stopPreviewOutputs()
1459
- await this.pausePlayback()
1460
- await this.flushPendingEdits(signal)
1461
- signal?.throwIfAborted()
1462
- if (scope !== this.#documentScope) throw new Error('production-source-changed')
1463
- this.#mediaSource(expected)
1464
- const answer = await this.#documentSession.commitExternal(expected, async (_before, ownedSignal) => {
1465
- const saved = await this.client.adoptRecording(source.directory, sent, ownedSignal)
1466
- if (saved.changeId !== sent.id || saved.verification.stepId !== sent.stepId || saved.verification.assetId !== sent.assetId || saved.verification.sha256 !== sent.sha256) throw new Error('document-confirmation')
1467
- return saved
1468
- }, (before, remote, current) => reconcileRecordingAdoption(sent, before, remote, current), signal)
1469
- signal?.throwIfAborted()
1470
- if (scope !== this.#documentScope || this.#state.authoring?.identity !== expected.identity) throw new Error('production-source-changed')
1471
- return answer
1472
- }
1473
- async applyDocumentMediaClip(clip: MediaClip, expected: { identity: string, version: string, binding: ProductionBinding }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
1474
- this.#mediaSource(expected)
1475
- if (!this.#state.productionPlan || !sameProductionBinding(this.#state.productionPlan.binding, expected.binding) || !this.#productionSourceCurrent(expected.binding)) throw new Error('production-source-changed')
1476
- const id = randomUUID(), value = structuredClone(clip)
1477
- const answer = await this.#writeDocumentMedia(expected, directory => this.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, binding: expected.binding, clip: value }, signal), signal)
1478
- if (answer.changeId !== id) throw new Error('production-source-changed')
1479
- return answer
1480
- }
1481
- async removeDocumentMediaClip(clipId: string, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
1482
- const id = randomUUID()
1483
- const answer = await this.#writeDocumentMedia(expected, directory => this.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, removeClipId: clipId }, signal), signal)
1484
- if (answer.changeId !== id) throw new Error('production-source-changed')
1485
- return answer
1486
- }
1487
- /** Applies a reviewed voice scope to the current source actor, without replacing body or narration. */
1488
- async applyDocumentVoice(scope: DocumentVoiceScope, value: VoiceSource | null, options: DocumentVoiceOptions, expected: { identity: string, version: string, fingerprint: string }): Promise<boolean> {
1489
- const source = this.#state.authoring, document = this.getDocument(expected.identity), context = this.#documentScope
1490
- if (!source || !document || source.version !== expected.version || source.fingerprint !== expected.fingerprint
1491
- || source.dirty || source.saving || source.composing || source.restored || source.error || isAgentChanging(this.#state)) throw new Error('voice-context-changed')
1492
- const next = changeDocumentVoice(document, scope, value, options)
1493
- if (next === document) return true
1494
- this.stopAuditions()
1495
- this.#documentSession.record(next)
1496
- await this.flushPendingEdits()
1497
- if (context !== this.#documentScope || this.#state.authoring?.identity !== expected.identity) return false
1498
- const saved = this.#state.authoring
1499
- if (!saved || saved.dirty || saved.saving || saved.composing || saved.restored || saved.error) throw new Error('voice-save-unconfirmed')
1500
- return true
1501
- }
1502
974
  /** Parameter planning is an authoring read; it does not compile, change modes or write the document. */
1503
975
  async planDocumentComponentAction(action: DocumentComponentAction, id: string, expected: { identity: string, version: string, fingerprint: string }, signal?: AbortSignal): Promise<DocumentAuthoringActionPlan> {
1504
- const source = this.#mediaSource(expected), scope = this.#documentScope
976
+ const source = this.production.source(expected), scope = this.#documentScope
1505
977
  if (!source.content || !source.fingerprint || source.fingerprint !== expected.fingerprint) throw new Error('component-source-changed')
1506
978
  const request = { id, source: componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint }), action: structuredClone(action) }
1507
979
  const answer = await this.client.planDocumentAction(source.directory, request, signal)
1508
980
  signal?.throwIfAborted()
1509
- const current = this.#mediaSource(expected)
981
+ const current = this.production.source(expected)
1510
982
  if (scope !== this.#documentScope || !current.content || !current.fingerprint || answer.document !== source.directory || answer.changeId !== id || answer.effect.kind !== 'component'
1511
983
  || !sameComponentSource(answer.source, request.source) || JSON.stringify(answer.action) !== JSON.stringify(request.action)) throw new Error('component-source-changed')
1512
984
  return answer
@@ -1514,13 +986,13 @@ export class Workbench {
1514
986
  /** The existing source actor owns adoption and ambiguous-response recovery, including later native input. */
1515
987
  async applyDocumentComponentPlan(plan: DocumentAuthoringActionPlan, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<{ answer: DocumentChangeAnswer, commitId?: string }> {
1516
988
  if (plan.effect.kind !== 'component' || !plan.action.type.startsWith('component.')) throw new Error('component-plan-invalid')
1517
- const source = this.#mediaSource(expected), action = plan.action as DocumentComponentAction, scope = this.#documentScope
989
+ const source = this.production.source(expected), action = plan.action as DocumentComponentAction, scope = this.#documentScope
1518
990
  if (!source.content || !source.fingerprint || !sameComponentSource(plan.source, componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint }))) throw new Error('component-source-changed')
1519
991
  this.#playback.stopPreviewOutputs()
1520
992
  await this.pausePlayback()
1521
993
  let receipt: AppliedDocumentAuthoringAction | undefined
1522
994
  const remember = (answer: DocumentChangeAnswer) => {
1523
- if (this.#documentEditorBinding?.identity === expected.identity) this.#documentEditorCommands?.rememberComponentConfiguration(answer.content)
995
+ this.editing.rememberComponent(answer.content, expected.identity)
1524
996
  return { answer, ...receipt?.commit ? { commitId: receipt.commit.id } : {} }
1525
997
  }
1526
998
  try {
@@ -1540,7 +1012,7 @@ export class Workbench {
1540
1012
  && file?.version === current.version && current.version !== plan.source.version) {
1541
1013
  // Canonical acceptance is already known even when later native input has
1542
1014
  // deleted the target. Undoing that deletion must restore its accepted configuration.
1543
- if (this.#documentEditorBinding?.identity === expected.identity) this.#documentEditorCommands?.rememberComponentConfiguration(plan.content)
1015
+ this.editing.rememberComponent(plan.content, expected.identity)
1544
1016
  try {
1545
1017
  if (!applyDocumentComponentAction(current.content, action).effect.changed) return remember({ document: source.directory, content: plan.content,
1546
1018
  version: current.version, fingerprint: current.fingerprint, issues: plan.issues, changeId: plan.changeId, files: plan.files.map(value => ({ path: value.path, version: value.version })) })
@@ -1549,118 +1021,6 @@ export class Workbench {
1549
1021
  throw error
1550
1022
  }
1551
1023
  }
1552
- /** Manual caption times reuse the canonical action plan, media preflight and original source actor. */
1553
- async applyDocumentCaptionTiming(action: DocumentCaptionTimingAction, id: string, expected: { identity: string, version: string, fingerprint: string }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
1554
- const source = this.#mediaSource(expected), scope = this.#documentScope
1555
- if (!source.content || source.fingerprint !== expected.fingerprint) throw new Error('caption-source-changed')
1556
- const request = { id, source: componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint! }), action }
1557
- const plan = await this.client.planDocumentAction(source.directory, request, signal)
1558
- signal?.throwIfAborted()
1559
- if (scope !== this.#documentScope || this.#state.authoring?.identity !== expected.identity || plan.effect.kind !== 'caption'
1560
- || plan.changeId !== id || JSON.stringify(plan.action) !== JSON.stringify(action) || !sameComponentSource(plan.source, request.source)) throw new Error('caption-source-changed')
1561
- this.#playback.stopPreviewOutputs()
1562
- await this.pausePlayback()
1563
- try {
1564
- return await this.#documentSession.commitExternal(expected, async (_before, ownedSignal) => {
1565
- const receipt = await this.client.applyDocumentAction(source.directory, { planId: plan.planId, digest: plan.digest, source: plan.source }, ownedSignal)
1566
- const actual = await this.client.readDocument(source.directory)
1567
- if (receipt.planId !== plan.planId || receipt.digest !== plan.digest || receipt.changeId !== id || !receipt.verification.saved || !receipt.verification.actionStateVerified
1568
- || !sameComponentSource(receipt.verification.source, componentSource(actual))) throw new Error('document-confirmation')
1569
- return { ...actual, changeId: id, files: receipt.files }
1570
- }, (before, answer, current) => reconcileCaptionTiming(action, before, answer, current), signal)
1571
- } catch (error) {
1572
- const current = this.#state.authoring, file = plan.files.find(file => file.path === (source.directory ? `${source.directory}/lecture.json` : 'lecture.json'))
1573
- // Lost ACK was independently read by commitExternal; only the exact predicted saved version can settle it.
1574
- if (scope === this.#documentScope && current?.identity === expected.identity && current.content && current.version === file?.version && current.fingerprint && !current.error) {
1575
- try {
1576
- if (!applyDocumentCaptionTiming(current.content, action).effect.changed) return { document: source.directory, content: plan.content, version: current.version!, fingerprint: current.fingerprint, changeId: id, issues: plan.issues, files: plan.files.map(({ path, version }) => ({ path, version })) }
1577
- } catch { /* A newer target stays pending with the actual request error. */ }
1578
- }
1579
- throw error
1580
- }
1581
- }
1582
- /** Uses the current actor revision so timing edits cannot replace later body or narration input. */
1583
- setDocumentStepProduction(stepId: string, patch: StepTimingPatch, identity?: string): void {
1584
- const document = this.getDocument(identity)
1585
- if (!document || isAgentChanging(this.#state)) return
1586
- const next = changeStepTiming(document, stepId, patch)
1587
- if (next === document) return
1588
- this.stopAuditions()
1589
- this.#documentSession.record(next)
1590
- }
1591
- /** The whole document's caption size (`production.captions.scale`), recorded like a step's timing. */
1592
- setDocumentCaptionScale(scale: number, identity?: string): void {
1593
- const document = this.getDocument(identity)
1594
- if (!document || isAgentChanging(this.#state)) return
1595
- const next = changeDocumentCaptionScale(document, scale)
1596
- if (next === document) return
1597
- this.#documentSession.record(next)
1598
- }
1599
- documentTimingDraft(stepId: string, key: StepDurationKey, identity: string, reset: number): StepDurationDraft | undefined {
1600
- const document = this.getDocument(identity)
1601
- return document && this.#state.authoring?.reset === reset ? this.#documentTimingDrafts.get(identity, document, stepId, key) : undefined
1602
- }
1603
- /** Retains unaccepted numeric input by stable target; it is not authoring content or a second timing source. */
1604
- setDocumentTimingDraft(stepId: string, key: StepDurationKey, draft: StepDurationDraft | undefined, identity: string, reset: number): void {
1605
- const source = this.#state.authoring, document = this.getDocument(identity)
1606
- if (!document?.steps[stepId] || source?.reset !== reset || isAgentChanging(this.#state)) return
1607
- if (!this.#documentTimingDrafts.set(identity, document, stepId, key, draft)) return
1608
- this.#set({ authoring: { ...source }, hasDocumentTimingDrafts: this.#documentTimingDrafts.has(identity, document), documentTimingDraftStorageFailure: this.#documentTimingDrafts.failed })
1609
- }
1610
- captionTimingDraft(stepId: string, identity: string): CaptionTimingDraft | undefined {
1611
- const source = this.#state.authoring
1612
- return source?.identity === identity && source.member?.id ? this.#captionTimingDrafts.get({ identity, memberId: source.member.id }, stepId) : undefined
1613
- }
1614
- setCaptionTimingDraft(stepId: string, draft: CaptionTimingDraft | undefined, identity: string): void {
1615
- const source = this.#state.authoring, document = this.getDocument(identity)
1616
- if (!document?.steps[stepId] || source?.identity !== identity || !source.member?.id) return
1617
- const scope = { identity, memberId: source.member.id }
1618
- this.#captionTimingDrafts.set(scope, stepId, draft)
1619
- this.#set({ captionTimingDraftSteps: this.#captionTimingDrafts.steps(scope, document), captionTimingDraftStorageFailure: this.#captionTimingDrafts.failed(scope) })
1620
- }
1621
- copyNarrationCueTiming(from: string, to: string, identity: string): void {
1622
- const document = this.getDocument(identity)
1623
- if (!document || isAgentChanging(this.#state)) return
1624
- const timing = document.production.cueTimings?.[from] ?? this.#removedCueTimings.get(from)
1625
- if (timing) this.#removedCueTimings.set(to, { ...timing })
1626
- }
1627
- /** Native block identity and order own the current step's complete script. */
1628
- setDocumentNarrations(stepId: string, narrations: Narration[], identity?: string): void {
1629
- const document = this.getDocument(identity)
1630
- if (!document || isAgentChanging(this.#state) || !Object.hasOwn(document.steps, stepId)) return
1631
- const step = document.steps[stepId]!
1632
- if (!document.sections[step.sectionId]?.stepOrder.includes(stepId)) return
1633
- const values = narrations.map(narration => {
1634
- const previous = document.narrations[narration.id] ?? this.#removedNarrations.get(narration.id)?.narration
1635
- return { ...previous, ...narration }
1636
- })
1637
- if (JSON.stringify(step.narrationIds.map(id => document.narrations[id])) === JSON.stringify(values)) return
1638
- const next = replaceStepNarrations(document, stepId, values)
1639
- for (const narration of values) {
1640
- const override = this.#removedNarrations.get(narration.id)?.override
1641
- if (override && !document.narrations[narration.id]) next.production.narrationOverrides = { ...next.production.narrationOverrides, [narration.id]: { ...override } }
1642
- }
1643
- const cueIds = new Set(values.flatMap(narration => narration.content.flatMap(node => node.type === 'cue' ? [node.id] : [])))
1644
- for (const cue of cueIds) {
1645
- const timing = this.#removedCueTimings.get(cue)
1646
- if (timing && !Object.hasOwn(next.production.cueTimings ?? {}, cue)) next.production.cueTimings = { ...next.production.cueTimings, [cue]: { ...timing } }
1647
- }
1648
- const references = (values: Narration[]) => JSON.stringify(values.map(narration => [narration.id, narration.provenance, narration.content.filter(node => node.type === 'cue')]))
1649
- if (references(step.narrationIds.map(id => document.narrations[id]!)) !== references(values)
1650
- && validateDocument(next).issues.some(issue => issue.severity === 'error')) throw new Error('document-narration-content')
1651
- for (const id of step.narrationIds) if (!next.steps[stepId]!.narrationIds.includes(id)) {
1652
- this.#removedNarrations.delete(id)
1653
- this.#removedNarrations.set(id, { narration: document.narrations[id]!, override: document.production.narrationOverrides?.[id] })
1654
- }
1655
- for (const [id, timing] of Object.entries(document.production.cueTimings ?? {})) if (!Object.hasOwn(next.production.cueTimings ?? {}, id)) {
1656
- this.#removedCueTimings.delete(id)
1657
- this.#removedCueTimings.set(id, { ...timing })
1658
- }
1659
- while (this.#removedNarrations.size > 512) this.#removedNarrations.delete(this.#removedNarrations.keys().next().value!)
1660
- while (this.#removedCueTimings.size > 512) this.#removedCueTimings.delete(this.#removedCueTimings.keys().next().value!)
1661
- this.stopAuditions()
1662
- this.#documentSession.record(next)
1663
- }
1664
1024
  recordDocument(content: TeachingDocument): void { if (!isAgentChanging(this.#state)) this.#documentSession.record(content) }
1665
1025
  documentComposition(composing: boolean, owner = 'body', identity?: string): void { this.#documentSession.composition(composing, owner, identity) }
1666
1026
  retryDocument(): Promise<void> { return this.#documentSession.retry() }
@@ -1672,232 +1032,10 @@ export class Workbench {
1672
1032
  if (this.#state.authoring?.identity === identity && !isAgentChanging(this.#state)) void this.#documentSession.forgetDraft(value)
1673
1033
  }
1674
1034
  documentError(error: Error): void { this.#set({ save: { kind: 'failed', message: error.message } }) }
1675
- documentInteraction(): void {
1676
- this.#documentSelectionGeneration++; this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.()
1677
- if (this.#state.documentPositionFailure) this.#set({ documentPositionFailure: undefined })
1678
- }
1679
- pendingDocumentField(blockId: string | undefined, identity?: string): Pick<DocumentFieldRegistration, 'stepId'> | undefined {
1680
- const pending = this.#pendingDocumentField, source = this.#state.authoring
1681
- return pending && pending.generation === this.#documentSelectionGeneration && pending.field.blockId === blockId
1682
- && pending.field.identity === (identity ?? source?.identity) && pending.reset === source?.reset ? pending.field : undefined
1683
- }
1684
- /** A live native field owns its target only while it still has focus in this source. */
1685
- focusedDocumentField(): Readonly<Pick<DocumentFieldRegistration, 'identity' | 'reset' | 'blockId' | 'stepId'>> & { readonly editor: DocumentHistoryEditor } | undefined {
1686
- const source = this.#state.authoring, editor = this.#activeDocumentHistory
1687
- if (!source?.identity || !source.content || !editor || editor === this.#documentEditor || editor.prosemirrorView.isDestroyed || !editor.prosemirrorView.hasFocus()) return
1688
- for (const field of this.#documentFields.values()) {
1689
- if (field.editor !== editor || field.identity !== source.identity || field.reset !== source.reset) continue
1690
- const step = source.content.steps[field.stepId], section = step && source.content.sections[step.sectionId]
1691
- if (!step || !section?.stepOrder.includes(field.stepId)) return
1692
- const { identity, reset, blockId, stepId } = field
1693
- return { identity, reset, blockId, stepId, editor }
1694
- }
1695
- return undefined
1696
- }
1697
- registerDocumentField(field: DocumentFieldRegistration): () => void {
1698
- if (field.identity !== this.#state.authoring?.identity || field.reset !== this.#state.authoring.reset) return () => {}
1699
- const key = JSON.stringify([field.identity, field.blockId, field.stepId])
1700
- this.#documentFields.set(key, field)
1701
- const pending = this.#pendingDocumentField
1702
- if (pending && pending.reset === field.reset && JSON.stringify([pending.field.identity, pending.field.blockId, pending.field.stepId]) === key) {
1703
- this.#pendingDocumentField = undefined
1704
- if (pending.generation === this.#documentSelectionGeneration && field.identity === this.#state.authoring?.identity && field.reset === this.#state.authoring.reset) field.focus.restore(pending.bookmark)
1705
- }
1706
- return () => {
1707
- if (this.#documentFields.get(key) !== field) return
1708
- this.#documentFields.delete(key)
1709
- if (field.editor && this.#activeDocumentHistory === field.editor) this.activateDocumentHistory(this.#documentEditor)
1710
- }
1711
- }
1712
- /** Toolbar commands use the focused native editor's own history, without replacing the body editor. */
1713
- activateDocumentHistory(editor: DocumentHistoryEditor | undefined): void {
1714
- if (editor && editor !== this.#documentEditor && ![...this.#documentFields.values()].some(field => field.editor === editor && field.identity === this.#state.authoring?.identity)) return
1715
- if (editor === this.#activeDocumentHistory) return
1716
- this.#unsubscribeDocumentHistory?.()
1717
- this.#activeDocumentHistory = editor
1718
- const update = () => this.#set({ editorHistory: editor ? { section: this.#state.position?.section ?? '', undo: undoDepth(editor.prosemirrorState) > 0, redo: redoDepth(editor.prosemirrorState) > 0, field: editor !== this.#documentEditor } : undefined })
1719
- this.#unsubscribeDocumentHistory = editor?.onChange(update)
1720
- update()
1721
- }
1722
- attachDocumentEditor(editor: NativeDocumentEditor | undefined, commands?: DocumentEditorCommands, binding?: { identity: string, reset: number }): void {
1723
- if (binding && (binding.identity !== this.#state.authoring?.identity || binding.reset !== this.#state.authoring.reset)) return
1724
- const wasBody = !this.#activeDocumentHistory || this.#activeDocumentHistory === this.#documentEditor
1725
- if (editor !== this.#documentEditor) this.#documentSession.composition(false, 'body')
1726
- this.#unsubscribeDocumentSelection?.(); this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
1727
- this.#documentEditor = editor; this.#documentEditorCommands = commands; this.#documentEditorBinding = editor ? binding : undefined
1728
- if (editor) {
1729
- const focus = this.#pendingDocumentFocus, selection = this.#pendingDocumentSelection
1730
- this.#pendingDocumentFocus = undefined; this.#pendingDocumentSelection = undefined
1731
- if (focus && focus.documentId === this.#state.authoring?.content?.id && focus.generation === this.#documentSelectionGeneration && editor.getBlock(focus.nodeId)) {
1732
- // A deferred page operation adopts its selection only after the source write is acknowledged.
1733
- if (!focus.afterSave) {
1734
- this.#focusDocumentNode(editor, focus.nodeId)
1735
- }
1736
- } else if (!this.#pendingDocumentField && selection && selection.documentId === this.#state.authoring?.content?.id) {
1737
- const anchor = nativeTextPosition(editor, selection.anchor), head = nativeTextPosition(editor, selection.head)
1738
- if (anchor !== undefined && head !== undefined) {
1739
- editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, anchor, head)))
1740
- if (selection.focused) editor.focus()
1741
- }
1742
- }
1743
- }
1744
- if (wasBody) this.activateDocumentHistory(editor)
1745
- if (editor) {
1746
- const focus = () => this.activateDocumentHistory(editor)
1747
- const element = editor.prosemirrorView.dom
1748
- element.addEventListener('focusin', focus)
1749
- if (editor.prosemirrorView.hasFocus()) focus()
1750
- const stopSelection = editor.onSelectionChange(() => { this.#documentSelectionGeneration++ })
1751
- this.#unsubscribeDocumentSelection = () => { this.#stopDocumentLayoutScroll?.(); stopSelection(); element.removeEventListener('focusin', focus) }
1752
- commands?.handleAnimationRequests({ available: () => this.#drafters.size > 0, request: place => this.draftAnimation(place) })
1753
- } else this.#unsubscribeDocumentSelection = undefined
1754
- this.#finishOpeningDocument()
1755
- }
1756
- /** `selectText`: the node's whole text is selected, so typing replaces it. */
1757
- #focusDocumentNode(editor: NativeDocumentEditor, nodeId: string, selectText = false): void {
1758
- this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
1759
- editor.setTextCursorPosition(nodeId, 'start')
1760
- const text = selectText ? nativeBlockText(editor, nodeId) : undefined
1761
- if (text) editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, text.from, text.to)))
1762
- editor.focus()
1763
- editor.prosemirrorView.dispatch(editor.prosemirrorState.tr.scrollIntoView())
1764
- // React node views can finish sizing after the native editor mounts.
1765
- // Keep only this untouched focus visible through those layout changes.
1766
- if (typeof ResizeObserver !== 'undefined') {
1767
- const view = editor.prosemirrorView, document = view.dom.ownerDocument
1768
- const source = this.#state.authoring!, identity = source.identity, reset = source.reset, documentId = source.content!.id
1769
- const request = this.#state.documentNavigation?.request, selected = editor.prosemirrorState.selection
1770
- let size = view.dom.getBoundingClientRect(), active = true
1771
- const events = ['pointerdown', 'wheel', 'touchmove', 'keydown', 'beforeinput']
1772
- const cancel = () => {
1773
- if (!active) return
1774
- active = false; observer.disconnect(); stopFocus(); stopSelection()
1775
- for (const event of events) document.removeEventListener(event, interact, true)
1776
- }
1777
- const interact = (event: Event) => { if (event.isTrusted) cancel() }
1778
- const stopFocus = editor.onFocusChange((_, { focused }) => { if (!focused) cancel() })
1779
- const stopSelection = editor.onSelectionChange(cancel)
1780
- const observer = new ResizeObserver(() => {
1781
- if (!active) return
1782
- const current = this.#state.authoring
1783
- if (this.#documentEditor !== editor || view.isDestroyed || !current || current.identity !== identity || current.reset !== reset
1784
- || current?.content?.id !== documentId || this.#state.documentNavigation?.request !== request
1785
- || !editor.isFocused() || !editor.prosemirrorState.selection.eq(selected) || editor.getTextCursorPosition().block.id !== nodeId) { cancel(); return }
1786
- const next = view.dom.getBoundingClientRect()
1787
- if (next.width === size.width && next.height === size.height) return
1788
- size = next
1789
- view.dispatch(editor.prosemirrorState.tr.scrollIntoView())
1790
- })
1791
- for (const event of events) document.addEventListener(event, interact, true)
1792
- observer.observe(view.dom)
1793
- this.#stopDocumentLayoutScroll = cancel
1794
- }
1795
- }
1796
1035
  async flushPendingEdits(signal?: AbortSignal): Promise<void> {
1797
1036
  if (isAgentChanging(this.#state)) throw new Error('save-locked')
1798
1037
  await this.#documentSession.flush(signal)
1799
1038
  }
1800
- async #changeDocumentPage(change: (document: TeachingDocument) => void): Promise<boolean> {
1801
- const source = this.#state.authoring, directory = this.#state.document
1802
- if (!source?.content || directory === undefined || isAgentChanging(this.#state)) return false
1803
- const scope = this.#documentScope, identity = source.identity, documentId = source.content.id
1804
- const current = () => scope === this.#documentScope && directory === this.#state.document && identity === this.#state.authoring?.identity && documentId === this.#state.authoring?.content?.id
1805
- this.#set({ isEditingPage: true, pageEditFailure: undefined })
1806
- try {
1807
- await this.flushPendingEdits()
1808
- if (!current()) throw new Error('page-context-changed')
1809
- const document = structuredClone(this.#state.authoring!.content!)
1810
- change(document)
1811
- const editor = this.#documentEditor
1812
- this.#pendingDocumentField = undefined
1813
- const plannedFocus = this.#pendingDocumentFocus
1814
- if (!plannedFocus || plannedFocus.generation !== this.#documentSelectionGeneration) for (const field of this.#documentFields.values()) {
1815
- if (field.identity !== source.identity || field.reset !== this.#state.authoring!.reset || field.blockId !== undefined && !document.blocks[field.blockId] || !document.steps[field.stepId]) continue
1816
- const bookmark = field.focus.capture()
1817
- if (bookmark) {
1818
- const { focus: _focus, editor: _editor, ...target } = field
1819
- this.#pendingDocumentField = { field: target, bookmark, reset: this.#state.authoring!.reset + 1, generation: this.#documentSelectionGeneration }
1820
- this.#pendingDocumentSelection = undefined
1821
- break
1822
- }
1823
- }
1824
- if (editor && !this.#pendingDocumentField) {
1825
- const state = editor.prosemirrorState, anchor = nativeTextPoint(editor, state.selection.anchor), head = nativeTextPoint(editor, state.selection.head)
1826
- if (anchor && head) this.#pendingDocumentSelection = { documentId: document.id, anchor, head, focused: editor.prosemirrorView.hasFocus() }
1827
- }
1828
- this.#documentSession.replace(document)
1829
- await this.#documentSession.flush()
1830
- return current()
1831
- } catch (error) { if (current()) this.#set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
1832
- finally { if (current()) this.#set({ isEditingPage: false }) }
1833
- }
1834
- renamePage(section: string, title: string): Promise<boolean> {
1835
- return this.#changeDocumentPage(document => { Object.assign(document, renameDocumentPage(document, section, title)) })
1836
- }
1837
- async duplicatePage(section: string): Promise<boolean> {
1838
- if (this.#state.isEditingPage || this.#state.isCreatingPage || this.#state.isHistoryBusy) return false
1839
- const scope = this.#documentScope, identity = this.#state.authoring?.identity, generation = this.#documentSelectionGeneration, navigation = this.#state.documentNavigation?.request
1840
- let copied: string | undefined
1841
- const saved = await this.#changeDocumentPage(document => {
1842
- if (scope !== this.#documentScope || identity !== this.#state.authoring?.identity) throw new Error('page-context-changed')
1843
- const page = document.sections[section]
1844
- if (!page) throw new Error('page-boundary')
1845
- const copy = duplicateDocumentPage(document, section, contentText(document.metadata.lang).copyTitle(page.title), () => randomUUID())
1846
- copied = copy.section
1847
- Object.assign(document, copy.document)
1848
- if (generation === this.#documentSelectionGeneration) this.#pendingDocumentFocus = { documentId: document.id, nodeId: `page:${copied}`, generation, afterSave: true }
1849
- })
1850
- // Source confirmation owns editing. A later author selection takes precedence over this response.
1851
- if (!saved || !copied || scope !== this.#documentScope || generation !== this.#documentSelectionGeneration || navigation !== this.#state.documentNavigation?.request || !this.#state.authoring?.content?.sections[copied]) return saved
1852
- this.goToSection(copied)
1853
- const editor = this.#documentEditor
1854
- if (editor) {
1855
- const blocks = editor.document, start = blocks.findIndex(block => block.id === `page:${copied}`)
1856
- const first = (nodes: typeof blocks): string | undefined => {
1857
- for (const node of nodes) { if (node.type === 'presmiumPage') break; if (node.content !== undefined) return node.id; const child = first(node.children); if (child) return child }
1858
- return undefined
1859
- }
1860
- const target = start < 0 ? undefined : first(blocks.slice(start + 1)) ?? blocks[start]!.id
1861
- if (target) { editor.setTextCursorPosition(target, 'start'); editor.focus() }
1862
- }
1863
- return true
1864
- }
1865
- movePage(section: string, before: string | null): Promise<boolean> {
1866
- return this.#changeDocumentPage(document => { Object.assign(document, moveDocumentPage(document, section, before)) })
1867
- }
1868
- pageDeleteMessage(reason: string): string { return this.#pageEditMessage(reason) }
1869
- async preparePageDeletion(section: string): Promise<PageDeletePlan> {
1870
- await this.flushPendingEdits()
1871
- const source = this.#state.authoring
1872
- if (!source?.content || !source.version || this.#state.document === undefined) throw new Error('document-unavailable')
1873
- return pageDeletion(source.content, this.#state.document, source.version, section)
1874
- }
1875
- async deletePage(plan: PageDeletePlan): Promise<boolean> {
1876
- if (!plan.allowed || plan.document !== this.#state.document) return false
1877
- return this.#changeDocumentPage(document => {
1878
- if (this.#state.authoring?.version !== plan.source.version) throw new Error('revision-conflict')
1879
- const current = pageDeletion(document, plan.document, plan.source.version, plan.section)
1880
- if (!current.allowed) throw new Error(current.reason)
1881
- Object.assign(document, removeDocumentPage(document, plan.section, () => randomUUID()))
1882
- this.#set({ position: { section: document.sectionOrder[0]!, step: 0, trail: [], view: 'document' }, documentNavigation: { section: document.sectionOrder[0]!, request: randomUUID() } })
1883
- })
1884
- }
1885
- createPage(after = this.#state.position?.section): boolean {
1886
- const source = this.#state.authoring, editor = this.#documentEditor, commands = this.#documentEditorCommands
1887
- if (!source?.content || source.loading || source.composing || source.restored || source.error || !editor || !commands
1888
- || editor.prosemirrorView.isDestroyed || isAgentChanging(this.#state) || this.#state.isEditingPage || this.#state.isCreatingPage
1889
- || this.#state.isHistoryBusy || this.#state.isHistoryPreparing) return false
1890
- try {
1891
- this.#set({ pageEditFailure: undefined })
1892
- const created = commands.insertPage(after, contentText(source.content.metadata.lang).newPage)
1893
- this.#pendingDocumentField = undefined; this.#pendingDocumentSelection = undefined; this.#pendingDocumentFocus = undefined
1894
- this.#set({ position: { section: created.sectionId, step: 0, trail: [], view: 'document' }, documentNavigation: { section: created.sectionId, request: randomUUID() } })
1895
- // The default title is selected: the author's first words name the page, and Enter goes on to its body.
1896
- this.#focusDocumentNode(editor, `page:${created.sectionId}`, true)
1897
- return true
1898
- } catch (error) { this.#set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
1899
- }
1900
-
1901
1039
  /** Points at a block or a passage (none: stops pointing): the preview outlines it and the conversation is told. */
1902
1040
  point(pointer: Pointer | undefined): void {
1903
1041
  const pointed = this.#state.pointer !== undefined || this.#state.focus.length > 0
@@ -2074,7 +1212,7 @@ export class Workbench {
2074
1212
  const plan = this.#state.productionPlan, range = plan?.pages.find(page => page.sectionId === sectionId)?.steps.find(step => step.stepId === stepId)
2075
1213
  if (plan?.canPreview && this.#productionReady() && range?.startMs !== undefined) {
2076
1214
  this.stopAuditions()
2077
- if (this.#production.selecting(sectionId, stepId)) return
1215
+ if (this.#productionPlayback.selecting(sectionId, stepId)) return
2078
1216
  this.#selectedSteps.set(`${this.#state.document}\0${sectionId}`, step)
2079
1217
  this.#set({ position: { section: sectionId, step, trail: [], view: 'present' } })
2080
1218
  return this.controlProduction({ binding: plan.binding, action: 'step', sectionId, stepId }).catch(() => undefined)
@@ -2129,8 +1267,8 @@ export class Workbench {
2129
1267
  return true
2130
1268
  }
2131
1269
 
2132
- undo(): Promise<boolean> { if (this.#state.mode !== 'editing') return Promise.resolve(false); if (this.#activeDocumentHistory && (this.#state.editorHistory?.undo || this.#state.editorHistory?.field)) { this.#activeDocumentHistory.focus(); return Promise.resolve(this.#activeDocumentHistory.undo()) } return this.#changeHistory('undo') }
2133
- redo(): Promise<boolean> { if (this.#state.mode !== 'editing') return Promise.resolve(false); if (this.#activeDocumentHistory && (this.#state.editorHistory?.redo || this.#state.editorHistory?.field)) { this.#activeDocumentHistory.focus(); return Promise.resolve(this.#activeDocumentHistory.redo()) } return this.#changeHistory('redo') }
1270
+ undo(): Promise<boolean> { const result = this.editing.nativeHistory('undo'); return result === undefined ? this.#changeHistory('undo') : Promise.resolve(result) }
1271
+ redo(): Promise<boolean> { const result = this.editing.nativeHistory('redo'); return result === undefined ? this.#changeHistory('redo') : Promise.resolve(result) }
2134
1272
 
2135
1273
  async #changeHistory(action: 'undo' | 'redo' | 'revert', revision?: string): Promise<boolean> {
2136
1274
  if (this.#state.mode !== 'editing' || this.#state.isCreatingPage || this.#state.isEditingPage || this.#state.isHistoryBusy || this.#state.isHistoryPreparing) return false
@@ -2231,7 +1369,7 @@ export class Workbench {
2231
1369
  sink.send({ type: 'highlight', target: reveal ?? this.#state.pointer?.target ?? null })
2232
1370
  return () => {
2233
1371
  this.#previewSinks.delete(sink)
2234
- this.#production.detach(sink)
1372
+ this.#productionPlayback.detach(sink)
2235
1373
  this.#set({ previewConnection: this.#state.previewConnection + 1 })
2236
1374
  this.#playback.detach(sink)
2237
1375
  }
@@ -2248,7 +1386,7 @@ export class Workbench {
2248
1386
  if (report.type === 'page-create') { origin?.send({ type: 'page-created', section: report.section, request: report.request, error: unsupported }); return }
2249
1387
  if (document !== this.#state.document || renderer !== this.#state.previewRenderer) return
2250
1388
  this.#playback.report(document, report, origin)
2251
- this.#production.report(document, report, origin)
1389
+ this.#productionPlayback.report(document, report, origin)
2252
1390
  switch (report.type) {
2253
1391
  case 'ready':
2254
1392
  case 'updated':
@@ -2283,7 +1421,7 @@ export class Workbench {
2283
1421
  if (snapshot && source && (source.dirty || source.loading || source.version !== snapshot.version || source.fingerprint !== snapshot.fingerprint)) break
2284
1422
  // An initial loader can report its old cursor while a newer stable selection is preparing.
2285
1423
  // Explicit native exits still reach the outer document workspace.
2286
- if (report.view !== 'document' && this.#production.selecting()) break
1424
+ if (report.view !== 'document' && this.#productionPlayback.selecting()) break
2287
1425
  // A fresh frame announces its document view before applying the queued
2288
1426
  // presentation command. Only the requested view completes that switch.
2289
1427
  if (renderer === 'web' && this.#awaitingView) {
@@ -2322,19 +1460,14 @@ export class Workbench {
2322
1460
 
2323
1461
  #stopSubscriptions(): void {
2324
1462
  this.#componentPropertyDrafts.stopAgentRead()
2325
- this.#saveDocumentReturnPoint(); this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.()
2326
- this.#documentViewport?.stop(); this.#documentViewport = undefined; this.#documentEditorBinding = undefined
1463
+ this.editing.reset()
2327
1464
  this.#presentationPreparation++
2328
1465
  this.#presentationController?.abort(new Error('client-document-changed'))
2329
1466
  this.#voiceover.stop()
2330
- this.#production.reset()
1467
+ this.#productionPlayback.reset()
2331
1468
  this.#set({ isPreparingPresentation: false, presentationFailure: undefined, presentationSnapshot: undefined, productionPlan: undefined, productionFailure: undefined })
2332
- this.#removedCueTimings.clear(); this.#removedNarrations.clear(); this.#cueTimingScope = undefined
1469
+ this.production.reset()
2333
1470
  this.#documentSession.close()
2334
- this.#unsubscribeDocumentHistory?.(); this.#unsubscribeDocumentHistory = undefined; this.#activeDocumentHistory = undefined; this.#documentEditor = undefined
2335
- this.#unsubscribeDocumentSelection?.(); this.#unsubscribeDocumentSelection = undefined
2336
- this.#pendingDocumentFocus = undefined; this.#pendingDocumentSelection = undefined; this.#documentSelectionGeneration++
2337
- this.#documentFields.clear(); this.#pendingDocumentField = undefined
2338
1471
  this.#playback.reset()
2339
1472
  this.#focusVersion++
2340
1473
  this.#pendingReveal = undefined
@@ -2357,7 +1490,7 @@ export class Workbench {
2357
1490
  this.#documentSession.dispose()
2358
1491
  this.#commentDrafts.close()
2359
1492
  this.#componentPropertyDrafts.close()
2360
- this.#captionTimingDrafts.close()
1493
+ this.production.dispose()
2361
1494
  disposeTranscriptionSessions(this.client)
2362
1495
  disposeDocumentRecordings(this)
2363
1496
  }