@lincyaw/workbench 0.2.0-rc.4 → 0.2.0-rc.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +5 -4
- package/src/MediaClipEditor.tsx +1 -1
- package/src/authoring-client.ts +3 -3
- package/src/authoring-draft-fragment.ts +3 -1
- package/src/component-property-drafts.ts +5 -5
- package/src/components.tsx +10 -28
- package/src/context.tsx +2 -1
- package/src/diagnostics.ts +1 -1
- package/src/document-drafts.ts +6 -7
- package/src/document-editing.ts +484 -0
- package/src/document-editor/BlockNoteSurface.tsx +25 -9
- package/src/document-editor/ComponentMaterials.tsx +3 -9
- package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
- package/src/document-editor/DocumentBlockPreview.tsx +4 -2
- package/src/document-editor/DocumentComments.tsx +58 -9
- package/src/document-editor/DocumentEditor.tsx +44 -7
- package/src/document-editor/DocumentStepNarration.tsx +30 -25
- package/src/document-editor/NarrationEditor.tsx +54 -20
- package/src/document-editor/NewCommentDrafts.tsx +4 -3
- package/src/document-editor/PlaceComment.tsx +150 -0
- package/src/document-editor/comment-drafts.ts +16 -14
- package/src/document-editor/comments.ts +30 -10
- package/src/document-editor/component-label.ts +11 -0
- package/src/document-editor/file-input.ts +2 -2
- package/src/document-editor/focus.ts +0 -2
- package/src/document-editor/insertion-place.ts +60 -0
- package/src/document-editor/messages.ts +3 -3
- package/src/document-editor/narration-schema.tsx +12 -6
- package/src/document-editor/narration.ts +19 -3
- package/src/document-editor/page-body.ts +60 -0
- package/src/document-editor/projection.ts +2 -2
- package/src/document-editor/rich-text.ts +3 -2
- package/src/document-editor/selection.ts +13 -0
- package/src/document-editor/style.css +12 -1
- package/src/document-editor/table-identities.ts +2 -1
- package/src/document-production.ts +331 -0
- package/src/document-session.ts +50 -16
- package/src/history.ts +3 -3
- package/src/index.ts +5 -5
- package/src/jobs.ts +1 -1
- package/src/messages.ts +19 -4
- package/src/panels/DocumentView.tsx +21 -21
- package/src/panels/DocumentVoiceDialog.tsx +2 -2
- package/src/panels/DocumentVoiceField.tsx +1 -1
- package/src/panels/ExportPanel.tsx +1 -6
- package/src/panels/HistoryPanel.tsx +1 -1
- package/src/panels/PageDeleteDialog.tsx +4 -4
- package/src/panels/PageRenameDialog.tsx +1 -1
- package/src/panels/PreviewPanel.tsx +1 -4
- package/src/panels/ProductionCaptionSize.tsx +20 -0
- package/src/panels/ProductionCaptionTiming.tsx +7 -7
- package/src/panels/ProductionMediaClips.tsx +6 -5
- package/src/panels/ProductionPanel.tsx +7 -3
- package/src/panels/ProductionRecording.tsx +1 -1
- package/src/panels/ProductionRecordingRange.tsx +4 -4
- package/src/panels/ProductionTimeline.tsx +6 -1
- package/src/panels/ProductionTranscription.tsx +5 -4
- package/src/panels/SourceDocumentPanel.tsx +12 -15
- package/src/panels/TranscriptionAdoption.tsx +9 -8
- package/src/panels/VoiceoverDialog.tsx +1 -1
- package/src/places.ts +1 -36
- package/src/preview-playback.ts +1 -1
- package/src/production-messages.ts +6 -0
- package/src/production-playback.ts +1 -1
- package/src/production-voice-playback.ts +3 -2
- package/src/sha256.ts +9 -0
- package/src/styles.css +16 -41
- package/src/use-recording-adoption.ts +2 -2
- package/src/voiceover-jobs.ts +1 -1
- package/src/workbench-state.ts +157 -0
- package/src/workbench.ts +101 -932
- package/src/workspace-client.ts +2 -1
- package/src/assistant-mascot.ts +0 -62
- package/src/mascot-preference.ts +0 -37
- package/src/panels/ChangeTrail.tsx +0 -79
package/src/workbench.ts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
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,40 +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 { reconcileRecordingAdoption } from './recording-adoption.ts'
|
|
19
18
|
import { disposeTranscriptionSessions } from './transcription-session.ts'
|
|
20
19
|
import { documentRecordingActive, disposeDocumentRecordings } from './audio-recording.ts'
|
|
21
|
-
import { DOCUMENT_AUDIO_MAX_BYTES } from '@lincyaw/kernel'
|
|
22
20
|
import type { DocumentSessionState } from './document-session.ts'
|
|
23
21
|
import type { DocumentDraftReference } from './document-drafts.ts'
|
|
24
|
-
import { DocumentReturnPoints, documentReturnStep, documentViewportOffset, restoreDocumentViewport } from './document-return-point.ts'
|
|
25
22
|
import type { DocumentReturnPoint } from './document-return-point.ts'
|
|
26
|
-
import type {
|
|
27
|
-
import type {
|
|
28
|
-
import type {
|
|
29
|
-
import { nativeTextPoint, nativeTextPosition } from './document-editor/selection.ts'
|
|
30
|
-
import type { NativeTextPoint } from './document-editor/selection.ts'
|
|
31
|
-
import type { DocumentFieldBookmark, DocumentFieldRegistration, DocumentHistoryEditor } from './document-editor/focus.ts'
|
|
32
|
-
import { duplicateDocumentPage, moveDocumentPage, pageDeletion, removeDocumentPage, renameDocumentPage } from '@lincyaw/kernel'
|
|
33
|
-
import { changeStepTiming } from './step-production.ts'
|
|
34
|
-
import { changeDocumentVoice } from './document-voices.ts'
|
|
35
|
-
import type { DocumentVoiceOptions, DocumentVoiceScope } from './document-voices.ts'
|
|
36
|
-
import type { CanonicalSource, VoiceoverJob, VoiceSource } from '@lincyaw/kernel'
|
|
37
|
-
import type { StepDurationDraft, StepDurationKey, StepTimingPatch } from './step-production.ts'
|
|
38
|
-
import { DocumentTimingDrafts } from './document-timing-drafts.ts'
|
|
39
|
-
import { CaptionTimingDrafts } from './caption-timing-drafts.ts'
|
|
40
|
-
import type { CaptionTimingDraft } from './caption-timing-drafts.ts'
|
|
23
|
+
import type { DocumentChangeAnswer, TeachingDocument } from '@lincyaw/kernel'
|
|
24
|
+
import type { DocumentInsertionPlace } from './document-editor/insertion-place.ts'
|
|
25
|
+
import type { CanonicalSource, VoiceoverJob } from '@lincyaw/kernel'
|
|
41
26
|
import { compileDocumentPreview, readPreviewWhenReady, waitForPreviewRequest } from './document-preview.ts'
|
|
42
27
|
import { readDocumentSnapshot } from './document-preview.ts'
|
|
43
28
|
import { errorMessage, sameProductionBinding, slideShape, stepKeys, stepTrail, trailStep } from '@lincyaw/kernel'
|
|
44
|
-
import type { Diagnostic,
|
|
29
|
+
import type { Diagnostic, Focus, FocusReport, IrAnswer, IrEvent, OperationAnswer, PreviewAnchor, PreviewCommand, PreviewDiagnostics, PreviewRenderer, PreviewReport, ReviewChange } from '@lincyaw/kernel'
|
|
45
30
|
import { DocumentDiagnostics } from './diagnostics.ts'
|
|
46
31
|
import { DocumentHistory } from './history.ts'
|
|
47
32
|
import { DocumentJobs } from './jobs.ts'
|
|
48
33
|
import { VoiceoverJobs } from './voiceover-jobs.ts'
|
|
49
|
-
import {
|
|
34
|
+
import { localeOf, MESSAGES } from './messages.ts'
|
|
50
35
|
import type { AgentPlace, Locale } from './messages.ts'
|
|
51
|
-
import {
|
|
36
|
+
import { changedPlaces, findPlaceAtLine } from './places.ts'
|
|
52
37
|
import { OperationLog } from './telemetry.ts'
|
|
53
38
|
import type { OperationValue } from './telemetry.ts'
|
|
54
39
|
import { PreviewPlayback } from './preview-playback.ts'
|
|
@@ -56,166 +41,15 @@ import { ProductionPlayback } from './production-playback.ts'
|
|
|
56
41
|
import type { ProductionBinding, ProductionPlan, ProductionPlaybackCommand, ProductionPlaybackState } from '@lincyaw/kernel'
|
|
57
42
|
import { workspaceClient, WorkspaceServerError } from './workspace-client.ts'
|
|
58
43
|
import type { WorkspaceClient } from './workspace-client.ts'
|
|
59
|
-
import type { PageDeletePlan } from '@lincyaw/kernel'
|
|
60
44
|
import type { AuthoringClientAction, AuthoringClientActionResult, AuthoringClientSnapshot } from '@lincyaw/kernel'
|
|
61
45
|
import { PRODUCTION_PLAYBACK_RATES } from '@lincyaw/kernel'
|
|
62
46
|
|
|
63
|
-
/** `editing`: the canonical document is edited in the parent; `viewing`: a derived snapshot is presented. */
|
|
64
|
-
export type WorkbenchMode = 'editing' | 'viewing'
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* How the web form is shown: as a page or as its presentation, whose controls can play a configured lecture.
|
|
68
|
-
* Both share one preview page and switch in place with `go.view`.
|
|
69
|
-
*/
|
|
70
|
-
export type WebView = 'document' | 'present'
|
|
71
|
-
|
|
72
|
-
/** A playback key pressed in a preview that the workbench plays: Space, and the left and right arrows. */
|
|
73
|
-
export type PlaybackKey = 'play-pause' | 'previous' | 'next'
|
|
74
|
-
|
|
75
|
-
/** What the author points at in the document: a block (or a section), or a passage selected in it. */
|
|
76
|
-
export interface Pointer {
|
|
77
|
-
target: PreviewAnchor
|
|
78
|
-
step?: number
|
|
79
|
-
/** The selected passage. */
|
|
80
|
-
quote?: string
|
|
81
|
-
/** Its box in the preview's viewport; none while it is out of sight. */
|
|
82
|
-
rect?: PreviewRect
|
|
83
|
-
obstacles?: PreviewRect[]
|
|
84
|
-
point?: PreviewPoint
|
|
85
|
-
/** Its text can be edited in place. */
|
|
86
|
-
isEditable: boolean
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export type SaveState =
|
|
90
|
-
| { kind: 'idle' }
|
|
91
|
-
| { kind: 'saving' }
|
|
92
|
-
| { kind: 'saved', at: string }
|
|
93
|
-
| { kind: 'locked' }
|
|
94
|
-
| { kind: 'failed', message: string }
|
|
95
|
-
|
|
96
|
-
/** A request for the agent of the conversation: its text and what it is about. */
|
|
97
|
-
export interface AgentRequest {
|
|
98
|
-
text: string
|
|
99
|
-
focus: FocusReport[]
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/** Where the host put a request: the conversation's session and the request's id, which its user message carries. */
|
|
103
|
-
export interface AgentAnswer {
|
|
104
|
-
session: string
|
|
105
|
-
request: string
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
export interface WorkbenchState {
|
|
109
|
-
locale: Locale
|
|
110
|
-
authoring?: DocumentSessionState
|
|
111
|
-
/** Unaccepted numeric form input is retained separately from saved canonical timing. */
|
|
112
|
-
hasDocumentTimingDrafts?: boolean
|
|
113
|
-
documentTimingDraftStorageFailure?: boolean
|
|
114
|
-
captionTimingDraftSteps?: string[]
|
|
115
|
-
captionTimingDraftStorageFailure?: boolean
|
|
116
|
-
isDark: boolean
|
|
117
|
-
documents?: DocumentsAnswer
|
|
118
|
-
documentsFailure?: string
|
|
119
|
-
/** The workspace's routes answer 404: `@lincyaw/dsh` is turned off on the plugins page. */
|
|
120
|
-
isBundleDisabled?: boolean
|
|
121
|
-
document?: string
|
|
122
|
-
ir?: IrAnswer
|
|
123
|
-
mode: WorkbenchMode
|
|
124
|
-
previewRenderer: PreviewRenderer
|
|
125
|
-
/** In the web form: the page or the presentation, both in the same page, switched without loading it again. */
|
|
126
|
-
webView: WebView
|
|
127
|
-
previewReload: number
|
|
128
|
-
preview?: PreviewAnswer
|
|
129
|
-
previewFailure?: string
|
|
130
|
-
/** The IR revision the preview shows. */
|
|
131
|
-
previewIrRevision?: string
|
|
132
|
-
isPreparingPresentation?: boolean
|
|
133
|
-
presentationFailure?: string
|
|
134
|
-
presentationSnapshot?: { version: string, fingerprint: string, revision: string, project: number }
|
|
135
|
-
productionPlan?: ProductionPlan
|
|
136
|
-
productionPlayback?: ProductionPlaybackState
|
|
137
|
-
productionFailure?: string
|
|
138
|
-
voiceoverJobs?: VoiceoverJob[]
|
|
139
|
-
voiceoverJobsFailure?: string
|
|
140
|
-
/** A cache refresh that actually changed the current production binding; it never starts playback. */
|
|
141
|
-
voiceoverCacheRefresh?: { source: CanonicalSource, revision: string, sequence: number }
|
|
142
|
-
/** Changes when an acknowledged preview connection is attached or detached, including same-revision reloads. */
|
|
143
|
-
previewConnection: number
|
|
144
|
-
/** Where the preview is: the section the author reads, or the slide and its step. */
|
|
145
|
-
position?: PreviewPosition
|
|
146
|
-
/** Changes on every position intent, including A → B → A, without changing the source. */
|
|
147
|
-
documentPositionToken: string
|
|
148
|
-
/** Explicit author navigation, distinct from the player's passive cursor and frame reload reports. */
|
|
149
|
-
productionNavigationVersion: number
|
|
150
|
-
documentPositionIntent: 'seek' | 'pause'
|
|
151
|
-
/** An explicit source navigation request; scrolling updates position without issuing another request. */
|
|
152
|
-
documentNavigation?: { section: string, block?: string, request: string }
|
|
153
|
-
documentPositionFailure?: 'removed'
|
|
154
|
-
isCreatingPage?: boolean
|
|
155
|
-
isEditingPage?: boolean
|
|
156
|
-
editorHistory?: EditorHistoryState
|
|
157
|
-
isHistoryPreparing?: boolean
|
|
158
|
-
pageEditFailure?: string
|
|
159
|
-
diagnostics?: DiagnosticSnapshot
|
|
160
|
-
isDiagnosticsUnavailable: boolean
|
|
161
|
-
canRepairDiagnostics: boolean
|
|
162
|
-
isRepairingDiagnostics: boolean
|
|
163
|
-
diagnosticsRepairFailure?: string
|
|
164
|
-
pointer?: Pointer
|
|
165
|
-
/** Where the blocks the AI just changed are in the preview, for the kitten to walk to; `id` is new for each change. */
|
|
166
|
-
changeTrail?: { id: number, rects: PreviewRect[] }
|
|
167
|
-
/** The places the AI just changed, for the kitten in the editor to walk to; `id` is new for each change. */
|
|
168
|
-
changedPlaces?: { id: number, targets: PreviewAnchor[] }
|
|
169
|
-
save: SaveState
|
|
170
|
-
/** What the conversation's agent is told the author points at. */
|
|
171
|
-
focus: FocusReport[]
|
|
172
|
-
isFocusPending: boolean
|
|
173
|
-
focusFailure?: string
|
|
174
|
-
review?: ReviewSnapshot
|
|
175
|
-
history?: RevisionsAnswer
|
|
176
|
-
/** Files changed elsewhere and not yet in the history. */
|
|
177
|
-
outside?: UncommittedFile[]
|
|
178
|
-
historyFailure?: string
|
|
179
|
-
isHistoryBusy: boolean
|
|
180
|
-
isAsking: boolean
|
|
181
|
-
askFailure?: string
|
|
182
|
-
/** What the document can be made into, and its builds and exports (the author's and the AI's). */
|
|
183
|
-
jobs?: JobsAnswer
|
|
184
|
-
jobsFailure?: string
|
|
185
|
-
voiceServiceVersion?: number
|
|
186
|
-
jobPreparing?: { target: string, canCancel: boolean }
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
export interface PreviewSink {
|
|
190
|
-
readonly generation?: number
|
|
191
|
-
readonly capabilities?: readonly PreviewCommand['type'][]
|
|
192
|
-
send(command: PreviewCommand): void
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
export interface EditorHistoryState { section: string, undo: boolean, redo: boolean, field?: boolean }
|
|
196
|
-
|
|
197
47
|
type Listener = () => void
|
|
198
48
|
const sameSource = (a: CanonicalSource, b: CanonicalSource) => a.documentId === b.documentId && a.version === b.version && a.fingerprint === b.fingerprint
|
|
199
49
|
|
|
200
|
-
/** The workbench's state as its parts read and change it. */
|
|
201
|
-
export interface WorkbenchStore {
|
|
202
|
-
readonly state: WorkbenchState
|
|
203
|
-
set(patch: Partial<WorkbenchState>): void
|
|
204
|
-
}
|
|
205
|
-
|
|
206
50
|
// The export of the lecture as a video (`@lincyaw/addon-lecture`).
|
|
207
51
|
export const VIDEO_TARGET = 'video'
|
|
208
52
|
|
|
209
|
-
/** The document the conversation works on: none when no document is open. */
|
|
210
|
-
export function selectedDocument(state: WorkbenchState): string | null {
|
|
211
|
-
return state.document ?? null
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/** Whether the AI is changing the workspace now, or its change waits for the author. */
|
|
215
|
-
export function isAgentChanging(state: WorkbenchState): boolean {
|
|
216
|
-
return Boolean(state.review && (state.review.running || state.review.changes.length > 0))
|
|
217
|
-
}
|
|
218
|
-
|
|
219
53
|
/** Whether the document has a slides form (no renderers listed: every form). */
|
|
220
54
|
export function hasSlides(ir: IrAnswer | undefined): boolean {
|
|
221
55
|
const renderers = ir?.doc.config.renderers
|
|
@@ -270,30 +104,9 @@ export function documentDirFor(title: string, taken: readonly string[]): string
|
|
|
270
104
|
export class Workbench {
|
|
271
105
|
readonly client: WorkspaceClient
|
|
272
106
|
readonly #documentSession: DocumentSession
|
|
273
|
-
readonly
|
|
274
|
-
readonly #audioFingerprints = new WeakMap<File, Promise<string>>()
|
|
275
|
-
readonly #documentTimingDrafts = new DocumentTimingDrafts()
|
|
276
|
-
readonly #captionTimingDrafts = new CaptionTimingDrafts()
|
|
277
|
-
readonly #removedCueTimings = new Map<string, { pauseMs: number }>()
|
|
278
|
-
#cueTimingScope?: string
|
|
279
|
-
#documentEditor?: NativeDocumentEditor
|
|
280
|
-
#documentEditorCommands?: DocumentEditorCommands
|
|
281
|
-
#documentEditorBinding?: { identity: string, reset: number }
|
|
282
|
-
readonly #documentReturnPoints = new DocumentReturnPoints()
|
|
283
|
-
#documentViewport?: { element: HTMLElement, identity: string, returnScrollTop?: number, stop(): void }
|
|
284
|
-
#stopDocumentReturnScroll?: () => void
|
|
285
|
-
#openingDocument?: { directory: string, scope: number, generation: number, focus?: 'body', initial?: boolean, stop(): void,
|
|
286
|
-
basis?: { identity: string, reset: number, version?: string, content: TeachingDocument }, point?: DocumentReturnPoint, fallback?: DocumentReturnPoint }
|
|
287
|
-
#stopDocumentLayoutScroll?: () => void
|
|
288
|
-
#activeDocumentHistory?: DocumentHistoryEditor
|
|
289
|
-
#unsubscribeDocumentHistory?: () => void
|
|
290
|
-
#unsubscribeDocumentSelection?: () => void
|
|
291
|
-
#documentSelectionGeneration = 0
|
|
107
|
+
readonly production: DocumentProduction
|
|
292
108
|
#removedDocumentPosition?: { identity: string, documentId: string, sectionId: string, stepId?: string, version: string, fingerprint: string, scope: number, generation: number, token: string }
|
|
293
|
-
|
|
294
|
-
#pendingDocumentSelection?: { documentId: string, anchor: NativeTextPoint, head: NativeTextPoint, focused: boolean }
|
|
295
|
-
readonly #documentFields = new Map<string, DocumentFieldRegistration>()
|
|
296
|
-
#pendingDocumentField?: { field: Omit<DocumentFieldRegistration, 'focus' | 'editor'>, bookmark: DocumentFieldBookmark, reset: number, generation: number }
|
|
109
|
+
readonly editing: DocumentEditing
|
|
297
110
|
#state: WorkbenchState
|
|
298
111
|
readonly #listeners = new Set<Listener>()
|
|
299
112
|
readonly #commentDrafts = new CommentDraftBank()
|
|
@@ -307,6 +120,7 @@ export class Workbench {
|
|
|
307
120
|
readonly #jobs: DocumentJobs
|
|
308
121
|
readonly #voiceover: VoiceoverJobs
|
|
309
122
|
readonly #askers = new Set<(request: AgentRequest) => Promise<AgentAnswer | void>>()
|
|
123
|
+
readonly #drafters = new Set<(draft: AgentDraft) => void | Promise<void>>()
|
|
310
124
|
readonly #previewSinks = new Set<PreviewSink>()
|
|
311
125
|
readonly #playbackKeys = new Set<(command: PlaybackKey) => void>()
|
|
312
126
|
#unsubscribeIr?: () => void
|
|
@@ -323,13 +137,12 @@ export class Workbench {
|
|
|
323
137
|
#documentScope = 0
|
|
324
138
|
#jobPreparation?: AbortController
|
|
325
139
|
readonly #playback = new PreviewPlayback(() => ({ document: this.#state.document, scope: this.#documentScope, sinks: this.#previewSinks }))
|
|
326
|
-
readonly #
|
|
140
|
+
readonly #productionPlayback = new ProductionPlayback(() => ({ document: this.#state.document, scope: this.#documentScope, sinks: this.#previewSinks,
|
|
327
141
|
binding: this.#state.productionPlan?.binding, ready: this.#productionReady() }), state => this.#set({ productionPlayback: state }))
|
|
328
142
|
/** A place to show that no preview could take yet (none was attached, e.g. the chat covered the document). */
|
|
329
143
|
#pendingReveal?: PreviewAnchor
|
|
330
144
|
/** The AI's changes to show on the document once the preview has them. */
|
|
331
145
|
#pendingFlash?: ReviewChange[]
|
|
332
|
-
#trail = 0
|
|
333
146
|
#lastPosition?: string
|
|
334
147
|
#awaitingView?: WebView
|
|
335
148
|
/** The forms asked for ahead of the author (`web:<dir>`, `slides:<dir>`), and the wait before asking for the slides. */
|
|
@@ -369,12 +182,7 @@ export class Workbench {
|
|
|
369
182
|
}
|
|
370
183
|
this.#documentSession = new DocumentSession(this.client, authoring => {
|
|
371
184
|
if (this.#state.document !== authoring.directory) return
|
|
372
|
-
|
|
373
|
-
if (pendingField && (pendingField.field.identity !== authoring.identity || authoring.reset > pendingField.reset
|
|
374
|
-
|| pendingField.field.blockId !== undefined && !authoring.content?.blocks[pendingField.field.blockId]
|
|
375
|
-
|| !authoring.content?.steps[pendingField.field.stepId])) this.#pendingDocumentField = undefined
|
|
376
|
-
const cueTimingScope = JSON.stringify([authoring.identity, authoring.reset])
|
|
377
|
-
if (this.#cueTimingScope !== cueTimingScope) { this.#removedCueTimings.clear(); this.#cueTimingScope = cueTimingScope }
|
|
185
|
+
this.editing.sourceChanged(authoring)
|
|
378
186
|
const previous = this.#state.authoring
|
|
379
187
|
// A saved timestamp belongs to this client's acknowledged source version.
|
|
380
188
|
// Remote adoption has no server modification time to display in its place.
|
|
@@ -389,40 +197,39 @@ export class Workbench {
|
|
|
389
197
|
const removed = this.#state.webView === 'document' && position?.view !== 'present' && position && previous?.identity === authoring.identity
|
|
390
198
|
&& (selected ? !selectedStep || selectedIndex < 0 : !authoring.content?.sectionOrder.includes(position.section))
|
|
391
199
|
const restoredPosition = !removed && this.#restoredDocumentPosition(authoring)
|
|
392
|
-
const scope = this.#documentScope, generation = this
|
|
393
|
-
if (removed && authoring.identity) this
|
|
200
|
+
const scope = this.#documentScope, generation = this.editing.generation
|
|
201
|
+
if (removed && authoring.identity) this.editing.returnPoints.forget(authoring.identity)
|
|
394
202
|
this.#set({ authoring,
|
|
395
203
|
...removed ? { position: undefined, documentNavigation: undefined, documentPositionFailure: 'removed' as const } : {},
|
|
396
204
|
...restoredPosition ? { documentPositionFailure: undefined } : {},
|
|
397
205
|
...moved ? { position: { ...position, section: selectedStep.sectionId, step: selectedIndex, trail: [] } } : {},
|
|
398
|
-
|
|
399
|
-
documentTimingDraftStorageFailure: this.#documentTimingDrafts.failed,
|
|
400
|
-
captionTimingDraftSteps: authoring.identity && authoring.member?.id && authoring.content ? this.#captionTimingDrafts.steps({ identity: authoring.identity, memberId: authoring.member.id }, authoring.content) : [],
|
|
401
|
-
captionTimingDraftStorageFailure: Boolean(authoring.identity && authoring.member?.id && this.#captionTimingDrafts.failed({ identity: authoring.identity, memberId: authoring.member.id })),
|
|
206
|
+
...this.production.draftState(authoring),
|
|
402
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 })
|
|
403
208
|
// The deletion owns the token produced above; source restoration only retires its notice.
|
|
404
209
|
if (removed && previous?.identity && previous.content && previous.version && previous.fingerprint
|
|
405
210
|
&& !previous.loading && !previous.dirty && !previous.saving && !previous.restored && !previous.composing && !previous.recovering && !previous.error
|
|
406
|
-
&& scope === this.#documentScope && generation === this
|
|
211
|
+
&& scope === this.#documentScope && generation === this.editing.generation && !this.#state.position && this.#state.documentPositionFailure === 'removed') {
|
|
407
212
|
this.#removedDocumentPosition = { identity: previous.identity, documentId: previous.content.id, sectionId: position.section,
|
|
408
213
|
...selected ? { stepId: selected } : {}, version: previous.version, fingerprint: previous.fingerprint, scope, generation, token: this.#state.documentPositionToken }
|
|
409
214
|
}
|
|
410
|
-
this
|
|
215
|
+
this.editing.finishOpening()
|
|
411
216
|
// Native insertion can select a page before the source actor receives that new entity.
|
|
412
217
|
if (position && previous && previous.identity === authoring.identity && !previous.content?.sections[position.section]
|
|
413
|
-
&& authoring.content?.sections[position.section]) this
|
|
414
|
-
if (this.#
|
|
218
|
+
&& authoring.content?.sections[position.section]) this.editing.saveReturnPoint()
|
|
219
|
+
if (this.#productionPlayback.changed()) void this.pausePlayback().catch(() => {})
|
|
415
220
|
const acknowledgedSourceChanged = !authoring.dirty && !authoring.loading && !authoring.error && !previous?.loading
|
|
416
221
|
&& previous?.identity === authoring.identity && Boolean(previous?.version && authoring.version)
|
|
417
222
|
&& (previous?.version !== authoring.version || previous?.fingerprint !== authoring.fingerprint)
|
|
418
223
|
if (!authoring.dirty && previous?.dirty || acknowledgedSourceChanged) { void this.#history.read(authoring.directory); void this.loadDocuments() }
|
|
419
|
-
// The source changed under an author with nothing unsaved while the AI holds a review: the AI changed it. The
|
|
420
|
-
// editor's kitten walks to the blocks whose content differs.
|
|
421
|
-
if (acknowledgedSourceChanged && !previous?.dirty && !previous?.saving && this.#state.review && previous?.content && authoring.content) {
|
|
422
|
-
const targets = changedBlocks(previous.content, authoring.content)
|
|
423
|
-
if (targets.length) this.#set({ changedPlaces: { id: ++this.#trail, targets } })
|
|
424
|
-
}
|
|
425
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) })
|
|
426
233
|
this.#diagnostics = new DocumentDiagnostics(this.client, store)
|
|
427
234
|
this.#jobs = new DocumentJobs(this.client, store)
|
|
428
235
|
this.#voiceover = new VoiceoverJobs(this.client, store, (job, signal) => this.#refreshVoiceover(job, signal))
|
|
@@ -506,12 +313,18 @@ export class Workbench {
|
|
|
506
313
|
return () => this.#askers.delete(asker)
|
|
507
314
|
}
|
|
508
315
|
|
|
316
|
+
/** The host's way to put a request in the conversation's composer for the author to finish; nothing is sent. */
|
|
317
|
+
onAgentDraft = (drafter: (draft: AgentDraft) => void | Promise<void>): (() => void) => {
|
|
318
|
+
this.#drafters.add(drafter)
|
|
319
|
+
return () => this.#drafters.delete(drafter)
|
|
320
|
+
}
|
|
321
|
+
|
|
509
322
|
#nextDocumentPosition(): string { return `${this.#positionSeed}:${++this.#positionSequence}` }
|
|
510
323
|
|
|
511
324
|
#restoredDocumentPosition(source: DocumentSessionState): boolean {
|
|
512
325
|
const removed = this.#removedDocumentPosition
|
|
513
326
|
if (!removed) return false
|
|
514
|
-
if (removed.scope !== this.#documentScope || removed.generation !== this
|
|
327
|
+
if (removed.scope !== this.#documentScope || removed.generation !== this.editing.generation || removed.token !== this.#state.documentPositionToken
|
|
515
328
|
|| removed.identity !== source.identity || this.#state.documentPositionFailure !== 'removed' || source.error) {
|
|
516
329
|
this.#removedDocumentPosition = undefined
|
|
517
330
|
return false
|
|
@@ -525,9 +338,9 @@ export class Workbench {
|
|
|
525
338
|
|
|
526
339
|
#set(patch: Partial<WorkbenchState>): void {
|
|
527
340
|
if (Object.hasOwn(patch, 'position') || Object.hasOwn(patch, 'documentPositionFailure')) this.#removedDocumentPosition = undefined
|
|
528
|
-
if (Object.hasOwn(patch, 'position'))
|
|
341
|
+
if (Object.hasOwn(patch, 'position')) this.editing.beforePosition()
|
|
529
342
|
this.#state = { ...this.#state, ...patch, ...Object.hasOwn(patch, 'position') ? { documentPositionToken: this.#nextDocumentPosition(), documentPositionIntent: patch.documentPositionIntent ?? 'seek' } : {} }
|
|
530
|
-
if (Object.hasOwn(patch, 'position')) this
|
|
343
|
+
if (Object.hasOwn(patch, 'position')) this.editing.saveReturnPoint()
|
|
531
344
|
for (const listener of this.#listeners) listener()
|
|
532
345
|
}
|
|
533
346
|
|
|
@@ -557,7 +370,7 @@ export class Workbench {
|
|
|
557
370
|
}
|
|
558
371
|
|
|
559
372
|
planDocumentOperation(operation: ProjectOperation): Promise<ProjectPlan> {
|
|
560
|
-
return this.client.planProjectChange({ id:
|
|
373
|
+
return this.client.planProjectChange({ id: randomUUID(), operation })
|
|
561
374
|
}
|
|
562
375
|
|
|
563
376
|
operateDocument(operation: ProjectOperation, planned?: ProjectPlan): Promise<OperationAnswer> {
|
|
@@ -593,163 +406,28 @@ export class Workbench {
|
|
|
593
406
|
await this.operateDocument({ op: 'retitle', dir, title })
|
|
594
407
|
}
|
|
595
408
|
|
|
596
|
-
#watchOpeningInteraction(cancel: () => void): () => void {
|
|
597
|
-
if (typeof document === 'undefined') return () => {}
|
|
598
|
-
const focused = document.activeElement, dialog = focused?.closest('[role="dialog"]')
|
|
599
|
-
const interact = (event: Event) => {
|
|
600
|
-
if (!event.isTrusted) return
|
|
601
|
-
if (event.type === 'focusin' && (!(event.target instanceof Element) || event.target === focused || dialog?.contains(event.target))) return
|
|
602
|
-
cancel()
|
|
603
|
-
}
|
|
604
|
-
const events = ['pointerdown', 'keydown', 'beforeinput', 'wheel', 'touchmove', 'focusin']
|
|
605
|
-
for (const event of events) document.addEventListener(event, interact, true)
|
|
606
|
-
return () => { for (const event of events) document.removeEventListener(event, interact, true) }
|
|
607
|
-
}
|
|
608
|
-
|
|
609
|
-
#cancelOpeningDocument(): void {
|
|
610
|
-
const pending = this.#openingDocument
|
|
611
|
-
this.#openingDocument = undefined
|
|
612
|
-
pending?.stop()
|
|
613
|
-
}
|
|
614
|
-
|
|
615
|
-
#beginOpeningDocument(directory: string, focus?: 'body', fallback?: DocumentReturnPoint): void {
|
|
616
|
-
this.#cancelOpeningDocument()
|
|
617
|
-
this.#openingDocument = { directory, focus, fallback: fallback && { ...fallback }, scope: this.#documentScope, generation: this.#documentSelectionGeneration,
|
|
618
|
-
stop: this.#watchOpeningInteraction(() => this.#cancelOpeningDocument()) }
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
#saveDocumentReturnPoint(): void {
|
|
622
|
-
const source = this.#state.authoring, position = this.#state.position
|
|
623
|
-
if (!source?.identity || !source.content || source.loading || !position || !source.content.sectionOrder.includes(position.section)) return
|
|
624
|
-
const section = source.content.sections[position.section]
|
|
625
|
-
let stepId = section?.stepOrder[position.step]
|
|
626
|
-
if (this.#state.webView === 'present' || position.view === 'present') {
|
|
627
|
-
const snapshot = this.#state.presentationSnapshot, ir = this.#state.ir
|
|
628
|
-
if (!snapshot || !ir || source.dirty || source.saving || source.error || snapshot.version !== source.version || snapshot.fingerprint !== source.fingerprint
|
|
629
|
-
|| snapshot.project !== (source.projectRevision ?? 0) || snapshot.revision !== ir.revision || snapshot.revision !== this.#state.previewIrRevision) return
|
|
630
|
-
const ids = ir.doc.sections.find(page => page.id === position.section)?.stepIds
|
|
631
|
-
if (!ids || ids.length && !ids[position.step]) return
|
|
632
|
-
stepId = ids[position.step]
|
|
633
|
-
if (stepId && (!section?.stepOrder.includes(stepId) || source.content.steps[stepId]?.sectionId !== position.section)) return
|
|
634
|
-
}
|
|
635
|
-
if (!section || !stepId && section.stepOrder.length) return
|
|
636
|
-
const viewport = this.#documentViewport, previous = this.#documentReturnPoints.read(source.identity)
|
|
637
|
-
const measured = this.#state.webView === 'document' && viewport?.identity === source.identity ? documentViewportOffset(viewport.element, section.id) : undefined
|
|
638
|
-
const offset = measured ?? (previous?.sectionId === section.id ? previous.offset : undefined)
|
|
639
|
-
this.#documentReturnPoints.write(source.identity, { sectionId: section.id, ...stepId ? { stepId } : {}, ...offset !== undefined ? { offset } : {} })
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
#finishOpeningDocument(): void {
|
|
643
|
-
const pending = this.#openingDocument, source = this.#state.authoring
|
|
644
|
-
if (!pending || source?.loading || !source?.identity || !source.content) return
|
|
645
|
-
if (source.error === 'document-identity-changed') { this.#cancelOpeningDocument(); return }
|
|
646
|
-
if (pending.scope !== this.#documentScope || pending.directory !== this.#state.document || pending.generation !== this.#documentSelectionGeneration) { this.#cancelOpeningDocument(); return }
|
|
647
|
-
if (!pending.basis) {
|
|
648
|
-
pending.basis = { identity: source.identity, reset: source.reset, version: source.version, content: source.content }
|
|
649
|
-
if (!pending.focus) {
|
|
650
|
-
pending.point = this.#documentReturnPoints.read(source.identity) ?? pending.fallback
|
|
651
|
-
if (!pending.point) {
|
|
652
|
-
const section = source.content.sections[source.content.sectionOrder[0]!]
|
|
653
|
-
if (!section) { this.#cancelOpeningDocument(); return }
|
|
654
|
-
pending.point = { sectionId: section.id, ...section.stepOrder[0] ? { stepId: section.stepOrder[0] } : {} }
|
|
655
|
-
pending.initial = true
|
|
656
|
-
}
|
|
657
|
-
if (documentReturnStep(source.content, pending.point) === undefined) {
|
|
658
|
-
this.#documentReturnPoints.forget(source.identity); this.#cancelOpeningDocument()
|
|
659
|
-
this.#set({ documentPositionFailure: 'removed' }); return
|
|
660
|
-
}
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
const basis = pending.basis
|
|
664
|
-
if (source.identity !== basis.identity || source.reset !== basis.reset || source.version !== basis.version || source.content !== basis.content) { this.#cancelOpeningDocument(); return }
|
|
665
|
-
const editor = this.#documentEditor, binding = this.#documentEditorBinding, viewport = this.#documentViewport
|
|
666
|
-
if (!editor || editor.prosemirrorView.isDestroyed || binding?.identity !== source.identity || binding.reset !== source.reset || viewport?.identity !== source.identity) return
|
|
667
|
-
// The editor can mount read-only while the source is still loading; a read-only body cannot take the caret yet.
|
|
668
|
-
if (pending.focus && !editor.isEditable) return
|
|
669
|
-
this.#cancelOpeningDocument()
|
|
670
|
-
if (pending.focus) {
|
|
671
|
-
const body = (blocks: typeof editor.document, sectionId?: string): { nodeId: string, sectionId: string } | undefined => {
|
|
672
|
-
for (const block of blocks) {
|
|
673
|
-
if (block.type === 'presmiumPage') sectionId = block.props.sectionId
|
|
674
|
-
else if (sectionId && editor.schema.blockSchema[block.type].content === 'inline') return { nodeId: block.id, sectionId }
|
|
675
|
-
const nested = body(block.children, sectionId)
|
|
676
|
-
if (nested) return nested
|
|
677
|
-
}
|
|
678
|
-
}
|
|
679
|
-
const target = body(editor.document)
|
|
680
|
-
if (target && source.content.sections[target.sectionId]) {
|
|
681
|
-
this.#set({ position: { section: target.sectionId, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: undefined })
|
|
682
|
-
this.#focusDocumentNode(editor, target.nodeId)
|
|
683
|
-
}
|
|
684
|
-
return
|
|
685
|
-
}
|
|
686
|
-
const point = pending.point!, step = documentReturnStep(source.content, point)
|
|
687
|
-
if (step === undefined) return
|
|
688
|
-
this.#selectedSteps.set(`${pending.directory}\0${point.sectionId}`, step)
|
|
689
|
-
this.#set({ position: { section: point.sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: undefined })
|
|
690
|
-
if (pending.initial) return
|
|
691
|
-
const current = () => this.#state.document === pending.directory && this.#state.authoring?.identity === basis.identity
|
|
692
|
-
&& this.#state.authoring.reset === basis.reset && this.#state.authoring.version === basis.version && this.#state.authoring.content === basis.content
|
|
693
|
-
&& this.#documentViewport === viewport && this.#state.position?.section === point.sectionId && this.#state.position.step === step
|
|
694
|
-
const restore = () => {
|
|
695
|
-
if (!current()) { stop(); return }
|
|
696
|
-
const top = viewport.element.scrollTop
|
|
697
|
-
restoreDocumentViewport(viewport.element, point)
|
|
698
|
-
if (viewport.element.scrollTop !== top) viewport.returnScrollTop = viewport.element.scrollTop
|
|
699
|
-
}
|
|
700
|
-
const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(restore)
|
|
701
|
-
let stopInteraction: () => void = () => {}
|
|
702
|
-
const stop = () => { observer?.disconnect(); stopInteraction(); viewport.returnScrollTop = undefined; if (this.#stopDocumentReturnScroll === stop) this.#stopDocumentReturnScroll = undefined }
|
|
703
|
-
this.#stopDocumentReturnScroll?.(); this.#stopDocumentReturnScroll = stop
|
|
704
|
-
stopInteraction = this.#watchOpeningInteraction(stop)
|
|
705
|
-
observer?.observe(viewport.element)
|
|
706
|
-
observer?.observe(editor.prosemirrorView.dom)
|
|
707
|
-
restore()
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
/** Consume only this viewport owner's actual programmatic destination; user gestures retire it. */
|
|
711
|
-
consumeDocumentReturnScroll(element: HTMLElement): boolean {
|
|
712
|
-
const viewport = this.#documentViewport, top = viewport?.returnScrollTop
|
|
713
|
-
if (viewport?.element !== element || top === undefined) return false
|
|
714
|
-
viewport.returnScrollTop = undefined
|
|
715
|
-
return element.scrollTop === top
|
|
716
|
-
}
|
|
717
|
-
|
|
718
|
-
attachDocumentViewport(element: HTMLElement, identity: string): () => void {
|
|
719
|
-
this.#documentViewport?.stop()
|
|
720
|
-
const scroll = () => { if (!this.#openingDocument) this.#saveDocumentReturnPoint() }
|
|
721
|
-
const viewport = { element, identity, stop: () => element.removeEventListener('scroll', scroll) }
|
|
722
|
-
this.#documentViewport = viewport
|
|
723
|
-
element.addEventListener('scroll', scroll, { passive: true })
|
|
724
|
-
this.#finishOpeningDocument()
|
|
725
|
-
return () => { if (this.#documentViewport === viewport) { this.#saveDocumentReturnPoint(); this.#stopDocumentReturnScroll?.(); this.#documentViewport = undefined }; viewport.stop() }
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
/** The body editor became editable: an opening that waits to put the caret in it can finish now. */
|
|
729
|
-
documentEditorEditable(): void { this.#finishOpeningDocument() }
|
|
730
|
-
|
|
731
409
|
async openDocument(dir: string, options: { focus?: 'body', expectedIdentity?: string, fallbackReturnPoint?: DocumentReturnPoint } = {}): Promise<void> {
|
|
732
410
|
if (this.#state.document === dir) {
|
|
733
|
-
if (options.focus) { this
|
|
411
|
+
if (options.focus) { this.editing.beginOpening(dir, options.focus); this.editing.finishOpening() }
|
|
734
412
|
return
|
|
735
413
|
}
|
|
736
|
-
this
|
|
414
|
+
this.editing.saveReturnPoint()
|
|
737
415
|
this.#documentScope++
|
|
738
416
|
const scope = this.#documentScope
|
|
739
417
|
this.#stopSubscriptions()
|
|
740
418
|
this.#history.subscribeReview(dir)
|
|
741
419
|
this.#set({ ...DOCUMENT_RESET, document: dir, previewRenderer: 'web', webView: 'document' })
|
|
742
|
-
this
|
|
420
|
+
this.editing.beginOpening(dir, options.focus, options.fallbackReturnPoint)
|
|
743
421
|
this.#record('document.open')
|
|
744
422
|
this.#diagnostics.subscribe(dir)
|
|
745
423
|
// Authoring is ready from source JSON; compilation and preview are independent.
|
|
746
424
|
const [opened] = await Promise.all([this.#documentSession.open(dir, options.expectedIdentity), this.#readFocus(dir), this.#history.read(dir)])
|
|
747
425
|
if (opened === 'identity-changed' && scope === this.#documentScope && this.#state.document === dir) { this.closeDocument(); return }
|
|
748
|
-
this
|
|
426
|
+
this.editing.finishOpening()
|
|
749
427
|
}
|
|
750
428
|
|
|
751
429
|
closeDocument(): void {
|
|
752
|
-
this
|
|
430
|
+
this.editing.saveReturnPoint()
|
|
753
431
|
this.#documentScope++
|
|
754
432
|
if (this.#state.document !== undefined) this.#record('document.close')
|
|
755
433
|
this.#stopSubscriptions()
|
|
@@ -790,7 +468,6 @@ export class Workbench {
|
|
|
790
468
|
this.#pendingFlash = undefined
|
|
791
469
|
const targets = changedPlaces(ir.doc, changes)
|
|
792
470
|
if (targets.length === 0) return
|
|
793
|
-
this.#trail++
|
|
794
471
|
this.#broadcast({ type: 'flash', targets })
|
|
795
472
|
this.#record('ai.change.shown', { 'presmium.places': targets.map(target => [target.section, target.block].filter(Boolean).join(':')).join('\n') })
|
|
796
473
|
}
|
|
@@ -1015,7 +692,7 @@ export class Workbench {
|
|
|
1015
692
|
await this.pausePlayback()
|
|
1016
693
|
signal.throwIfAborted()
|
|
1017
694
|
if (!current()) return false
|
|
1018
|
-
this.#
|
|
695
|
+
this.#productionPlayback.reset()
|
|
1019
696
|
this.#set({ productionPlan: plan, voiceoverCacheRefresh: { source: job.source, revision: job.revision, sequence: (this.#state.voiceoverCacheRefresh?.sequence ?? 0) + 1 } })
|
|
1020
697
|
// The mounted production loader fetches this new binding in the existing frame.
|
|
1021
698
|
// Replacing the iframe for every clip would interrupt progressive playback and its connection.
|
|
@@ -1200,7 +877,7 @@ export class Workbench {
|
|
|
1200
877
|
signal.throwIfAborted()
|
|
1201
878
|
if (scope !== this.#documentScope || this.#state.authoring?.identity !== identity || !this.#productionSourceCurrent(plan.binding)) throw new Error('production-source-changed')
|
|
1202
879
|
this.#set({ productionPlan: plan })
|
|
1203
|
-
if (this.#
|
|
880
|
+
if (this.#productionPlayback.changed()) void this.pausePlayback().catch(() => {})
|
|
1204
881
|
return plan
|
|
1205
882
|
}
|
|
1206
883
|
|
|
@@ -1221,7 +898,7 @@ export class Workbench {
|
|
|
1221
898
|
await this.pausePlayback()
|
|
1222
899
|
signal?.throwIfAborted()
|
|
1223
900
|
}
|
|
1224
|
-
return await this.#
|
|
901
|
+
return await this.#productionPlayback.control(control, signal)
|
|
1225
902
|
} catch (error) {
|
|
1226
903
|
const code = errorMessage(error), current = this.#state.productionPlan?.binding
|
|
1227
904
|
if (scope === this.#documentScope && !signal?.aborted && current && sameProductionBinding(current, control.binding) && this.#productionReady()
|
|
@@ -1233,7 +910,7 @@ export class Workbench {
|
|
|
1233
910
|
|
|
1234
911
|
closeProduction(): void {
|
|
1235
912
|
this.#interruptProductionNavigation()
|
|
1236
|
-
this.#
|
|
913
|
+
this.#productionPlayback.reset()
|
|
1237
914
|
this.#set({ productionPlan: undefined, productionFailure: undefined })
|
|
1238
915
|
}
|
|
1239
916
|
|
|
@@ -1263,46 +940,6 @@ export class Workbench {
|
|
|
1263
940
|
if (this.#state.document !== undefined) void this.#readPreview(this.#state.document)
|
|
1264
941
|
}
|
|
1265
942
|
|
|
1266
|
-
#pageEditMessage(reason: string): string {
|
|
1267
|
-
const t = this.#messages
|
|
1268
|
-
if (reason === 'native-unavailable') return t.nativeEditUnavailable
|
|
1269
|
-
if (reason.startsWith('native-')) return t.nativeEditDraft
|
|
1270
|
-
switch (reason) {
|
|
1271
|
-
case 'page-multiple-files': return t.pageEditFiles
|
|
1272
|
-
case 'page-boundary': return t.pageEditBoundary
|
|
1273
|
-
case 'page-hierarchy': return t.pageEditHierarchy
|
|
1274
|
-
case 'page-implicit-title': return t.pageEditImplicitTitle
|
|
1275
|
-
case 'page-formatted-title': return t.pageEditFormattedTitle
|
|
1276
|
-
case 'page-title': return t.pageEditInvalidTitle
|
|
1277
|
-
case 'page-compiler': return t.pageEditCompiler
|
|
1278
|
-
case 'page-referenced': return t.pageDeleteReferenced
|
|
1279
|
-
case 'page-external-bindings': return t.pageDeleteExternalBindings
|
|
1280
|
-
case 'page-references-unavailable': return t.pageDeleteReferencesUnavailable
|
|
1281
|
-
case 'page-busy': return t.pageEditBusy
|
|
1282
|
-
case 'preview-flush-unavailable': return t.pageEditPreview
|
|
1283
|
-
case 'page-context-changed': return t.pageEditChanged
|
|
1284
|
-
case 'save-timeout': return t.pageEditFlushTimeout
|
|
1285
|
-
case 'source-draft': return t.pageEditSourceDraft
|
|
1286
|
-
case 'source-refresh': return t.pageEditRefresh
|
|
1287
|
-
case 'page-draft':
|
|
1288
|
-
case 'source-conflict':
|
|
1289
|
-
case 'narration-conflict':
|
|
1290
|
-
case 'revision-conflict': return t.pageEditDraft
|
|
1291
|
-
case 'save-locked': return t.saveLocked
|
|
1292
|
-
default: return t.pageEditRequestFailed
|
|
1293
|
-
}
|
|
1294
|
-
}
|
|
1295
|
-
|
|
1296
|
-
pageEditCapability(section: string): { rename: boolean, move: boolean, reason?: string } {
|
|
1297
|
-
const exists = Boolean(this.#state.authoring?.content?.sections[section])
|
|
1298
|
-
const capability = { rename: exists, move: exists }
|
|
1299
|
-
if (isAgentChanging(this.#state)) return { rename: false, move: false, reason: this.#messages.saveLocked }
|
|
1300
|
-
if (this.#state.isCreatingPage || this.#state.isEditingPage || this.#state.isHistoryBusy) return { rename: false, move: false, reason: this.#messages.pageEditBusy }
|
|
1301
|
-
return capability
|
|
1302
|
-
}
|
|
1303
|
-
|
|
1304
|
-
clearPageEditFailure(): void { this.#set({ pageEditFailure: undefined }) }
|
|
1305
|
-
|
|
1306
943
|
/** The preview acknowledges that all registered lecture playback has paused before audition audio starts. */
|
|
1307
944
|
pausePlayback(interactive = false): Promise<void> { if (interactive) this.#interruptProductionNavigation(); return this.#playback.pause() }
|
|
1308
945
|
|
|
@@ -1334,175 +971,14 @@ export class Workbench {
|
|
|
1334
971
|
if (!asset || asset.kind !== 'image' || asset.location !== answer.content.assets[answer.assetId]?.location) throw new Error('document-identity-changed')
|
|
1335
972
|
return asset.location
|
|
1336
973
|
}
|
|
1337
|
-
#mediaSource(expected: { identity: string, version: string }): DocumentSessionState {
|
|
1338
|
-
const source = this.#state.authoring
|
|
1339
|
-
if (!source || !this.getDocument(expected.identity) || source.version !== expected.version || !source.fingerprint
|
|
1340
|
-
|| source.dirty || source.saving || source.composing || source.restored || source.error || isAgentChanging(this.#state)) throw new Error('production-source-changed')
|
|
1341
|
-
return source
|
|
1342
|
-
}
|
|
1343
|
-
/** Inspects the saved declaration, including a local asset not yet attached to a step. */
|
|
1344
|
-
async inspectDocumentAudio(assetId: string, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer> {
|
|
1345
|
-
const source = this.#mediaSource(expected), scope = this.#documentScope
|
|
1346
|
-
const answer = await this.client.readDocumentAudio(source.directory, assetId, expected.version, signal)
|
|
1347
|
-
signal?.throwIfAborted()
|
|
1348
|
-
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')
|
|
1349
|
-
this.#mediaSource(expected)
|
|
1350
|
-
return answer
|
|
1351
|
-
}
|
|
1352
|
-
/** Recognition keeps its captured source even if subsequent author input moves to a newer version. */
|
|
1353
|
-
async startDocumentTranscription(request: Omit<DocumentTranscriptionRequest, 'source'>, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionTask> {
|
|
1354
|
-
const source = this.#mediaSource(expected)
|
|
1355
|
-
if (!source.content || !source.fingerprint) throw new Error('production-source-changed')
|
|
1356
|
-
const sent: DocumentTranscriptionRequest = { ...structuredClone(request), source: { documentId: source.content.id, version: expected.version, fingerprint: source.fingerprint } }
|
|
1357
|
-
const answer = await this.client.startTranscription(source.directory, sent, signal)
|
|
1358
|
-
signal?.throwIfAborted()
|
|
1359
|
-
if (answer.document !== source.directory || answer.intent !== sent.intent || answer.source.documentId !== sent.source.documentId
|
|
1360
|
-
|| 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')
|
|
1361
|
-
return answer
|
|
1362
|
-
}
|
|
1363
|
-
async planDocumentTranscription(draft: TranscriptionAdoptionDraft, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionAdoptionPlan> {
|
|
1364
|
-
const source = this.#mediaSource(expected), sent = structuredClone(draft)
|
|
1365
|
-
if (sent.source.documentId !== source.content?.id || sent.source.version !== expected.version || sent.source.fingerprint !== source.fingerprint) throw new Error('production-source-changed')
|
|
1366
|
-
const answer = await this.client.planTranscriptionAdoption(source.directory, sent, signal)
|
|
1367
|
-
signal?.throwIfAborted()
|
|
1368
|
-
this.#mediaSource(expected)
|
|
1369
|
-
if (answer.document !== source.directory || answer.changeId !== sent.id || answer.source.documentId !== sent.source.documentId
|
|
1370
|
-
|| answer.source.version !== sent.source.version || answer.source.fingerprint !== sent.source.fingerprint || answer.candidate.id !== sent.candidate.id
|
|
1371
|
-
|| answer.candidate.revision !== sent.candidate.revision || answer.draftRevision !== sent.draftRevision) throw new Error('transcription-response-changed')
|
|
1372
|
-
return answer
|
|
1373
|
-
}
|
|
1374
|
-
async adoptDocumentTranscription(request: TranscriptionAdoptionApply, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<TranscriptionAdoptionAnswer> {
|
|
1375
|
-
const source = this.#mediaSource(expected), sent = structuredClone(request)
|
|
1376
|
-
if (sent.source.documentId !== source.content?.id || sent.source.version !== expected.version || sent.source.fingerprint !== source.fingerprint) throw new Error('production-source-changed')
|
|
1377
|
-
const answer = await this.#writeDocumentMedia(expected, directory => this.client.applyTranscriptionAdoption(directory, sent, signal), signal)
|
|
1378
|
-
if (answer.adoption.planId !== sent.planId || answer.adoption.candidate.id !== sent.candidate.id || answer.adoption.candidate.revision !== sent.candidate.revision
|
|
1379
|
-
|| answer.adoption.draftRevision !== sent.draftRevision) throw new Error('transcription-response-changed')
|
|
1380
|
-
return answer
|
|
1381
|
-
}
|
|
1382
|
-
async #writeDocumentMedia<T extends DocumentChangeAnswer>(expected: { identity: string, version: string }, write: (directory: string) => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
1383
|
-
const scope = this.#documentScope, source = this.#mediaSource(expected)
|
|
1384
|
-
this.stopAuditions()
|
|
1385
|
-
await this.pausePlayback()
|
|
1386
|
-
await this.flushPendingEdits(signal)
|
|
1387
|
-
signal?.throwIfAborted()
|
|
1388
|
-
if (scope !== this.#documentScope) throw new Error('production-source-changed')
|
|
1389
|
-
this.#mediaSource(expected)
|
|
1390
|
-
let answer: T
|
|
1391
|
-
try { answer = await write(source.directory) }
|
|
1392
|
-
finally { await this.#documentSession.refresh(source.directory) }
|
|
1393
|
-
signal?.throwIfAborted()
|
|
1394
|
-
if (scope !== this.#documentScope || answer.document !== source.directory || answer.content.id !== source.content?.id) throw new Error('production-source-changed')
|
|
1395
|
-
this.#mediaSource({ identity: expected.identity, version: answer.version })
|
|
1396
|
-
return answer
|
|
1397
|
-
}
|
|
1398
|
-
/** Import commits the original file and its declaration together, without creating a clip or narration. */
|
|
1399
|
-
async importDocumentAudio(file: File, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioImportAnswer> {
|
|
1400
|
-
let request: { identity: string, version: string, id: string } | undefined
|
|
1401
|
-
const answer = await this.#writeDocumentMedia(expected, async directory => {
|
|
1402
|
-
const existing = this.#audioImports.get(file), first = !existing || existing.identity !== expected.identity
|
|
1403
|
-
request = first ? { identity: expected.identity, version: expected.version, id: crypto.randomUUID() } : existing!
|
|
1404
|
-
this.#audioImports.set(file, request)
|
|
1405
|
-
try { return await this.client.importDocumentAudio(directory, file, { id: request.id, baseDocumentVersion: request.version }, signal) }
|
|
1406
|
-
catch (error) {
|
|
1407
|
-
if (first && error instanceof WorkspaceServerError && error.status >= 400 && error.status < 500 && this.#audioImports.get(file) === request) this.#audioImports.delete(file)
|
|
1408
|
-
throw error
|
|
1409
|
-
}
|
|
1410
|
-
}, signal)
|
|
1411
|
-
if (answer.changeId !== request?.id || answer.inspection.assetId !== answer.assetId || !answer.content.assets[answer.assetId]) throw new Error('production-source-changed')
|
|
1412
|
-
if (this.#audioImports.get(file) === request) this.#audioImports.delete(file)
|
|
1413
|
-
return answer
|
|
1414
|
-
}
|
|
1415
|
-
/** Reconcile an ambiguous save against real asset bytes before admitting a new source-bound import. */
|
|
1416
|
-
async ensureDocumentAudio(file: File, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentAudioInspectionAnswer> {
|
|
1417
|
-
const source = this.#mediaSource(expected)
|
|
1418
|
-
if (!file.size || file.size > DOCUMENT_AUDIO_MAX_BYTES) throw new Error('production.asset-size')
|
|
1419
|
-
let pending = this.#audioFingerprints.get(file)
|
|
1420
|
-
if (!pending) {
|
|
1421
|
-
pending = file.arrayBuffer().then(bytes => crypto.subtle.digest('SHA-256', bytes)).then(bytes => [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join(''))
|
|
1422
|
-
this.#audioFingerprints.set(file, pending)
|
|
1423
|
-
}
|
|
1424
|
-
const hash = await pending
|
|
1425
|
-
signal?.throwIfAborted(); this.#mediaSource(expected)
|
|
1426
|
-
for (const asset of Object.values(source.content?.assets ?? {})) {
|
|
1427
|
-
if (asset.kind !== 'audio' || asset.fingerprint !== `sha256:${hash}`) continue
|
|
1428
|
-
try {
|
|
1429
|
-
const answer = await this.inspectDocumentAudio(asset.id, expected, signal)
|
|
1430
|
-
if (answer.inspection.sha256 === hash) return answer
|
|
1431
|
-
} catch (error) {
|
|
1432
|
-
if (!(error instanceof WorkspaceServerError) || ![404, 413, 422].includes(error.status)) throw error
|
|
1433
|
-
}
|
|
1434
|
-
}
|
|
1435
|
-
signal?.throwIfAborted(); this.#mediaSource(expected)
|
|
1436
|
-
const previous = this.#audioImports.get(file)
|
|
1437
|
-
if (previous?.identity === expected.identity && previous.version !== expected.version) this.#audioImports.delete(file)
|
|
1438
|
-
let imported: DocumentAudioImportAnswer
|
|
1439
|
-
try { imported = await this.importDocumentAudio(file, expected, signal) }
|
|
1440
|
-
catch (error) {
|
|
1441
|
-
if (!previous || this.#audioImports.get(file) !== previous || !(error instanceof WorkspaceServerError)
|
|
1442
|
-
|| error.status !== 409 || error.message !== 'document-version-changed') throw error
|
|
1443
|
-
signal?.throwIfAborted(); this.#mediaSource(expected)
|
|
1444
|
-
this.#audioImports.delete(file)
|
|
1445
|
-
imported = await this.importDocumentAudio(file, expected, signal)
|
|
1446
|
-
}
|
|
1447
|
-
return { document: imported.document, version: imported.version, fingerprint: imported.fingerprint, inspection: imported.inspection }
|
|
1448
|
-
}
|
|
1449
|
-
/** The source actor owns this external transaction; capture is independent from preview output. */
|
|
1450
|
-
async adoptDocumentRecording(request: DocumentRecordingAdoption, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<VerifiedDocumentRecordingAdoption> {
|
|
1451
|
-
const scope = this.#documentScope, source = this.#mediaSource(expected), sent = structuredClone(request)
|
|
1452
|
-
if (sent.source.documentId !== source.content?.id || sent.source.version !== source.version || sent.source.fingerprint !== source.fingerprint
|
|
1453
|
-
|| !source.content.steps[sent.stepId] || !source.content.assets[sent.assetId]) throw new Error('production-source-changed')
|
|
1454
|
-
this.#playback.stopPreviewOutputs()
|
|
1455
|
-
await this.pausePlayback()
|
|
1456
|
-
await this.flushPendingEdits(signal)
|
|
1457
|
-
signal?.throwIfAborted()
|
|
1458
|
-
if (scope !== this.#documentScope) throw new Error('production-source-changed')
|
|
1459
|
-
this.#mediaSource(expected)
|
|
1460
|
-
const answer = await this.#documentSession.commitExternal(expected, async (_before, ownedSignal) => {
|
|
1461
|
-
const saved = await this.client.adoptRecording(source.directory, sent, ownedSignal)
|
|
1462
|
-
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')
|
|
1463
|
-
return saved
|
|
1464
|
-
}, (before, remote, current) => reconcileRecordingAdoption(sent, before, remote, current), signal)
|
|
1465
|
-
signal?.throwIfAborted()
|
|
1466
|
-
if (scope !== this.#documentScope || this.#state.authoring?.identity !== expected.identity) throw new Error('production-source-changed')
|
|
1467
|
-
return answer
|
|
1468
|
-
}
|
|
1469
|
-
async applyDocumentMediaClip(clip: MediaClip, expected: { identity: string, version: string, binding: ProductionBinding }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
|
|
1470
|
-
this.#mediaSource(expected)
|
|
1471
|
-
if (!this.#state.productionPlan || !sameProductionBinding(this.#state.productionPlan.binding, expected.binding) || !this.#productionSourceCurrent(expected.binding)) throw new Error('production-source-changed')
|
|
1472
|
-
const id = crypto.randomUUID(), value = structuredClone(clip)
|
|
1473
|
-
const answer = await this.#writeDocumentMedia(expected, directory => this.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, binding: expected.binding, clip: value }, signal), signal)
|
|
1474
|
-
if (answer.changeId !== id) throw new Error('production-source-changed')
|
|
1475
|
-
return answer
|
|
1476
|
-
}
|
|
1477
|
-
async removeDocumentMediaClip(clipId: string, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
|
|
1478
|
-
const id = crypto.randomUUID()
|
|
1479
|
-
const answer = await this.#writeDocumentMedia(expected, directory => this.client.changeDocumentMediaClip(directory, { id, baseDocumentVersion: expected.version, removeClipId: clipId }, signal), signal)
|
|
1480
|
-
if (answer.changeId !== id) throw new Error('production-source-changed')
|
|
1481
|
-
return answer
|
|
1482
|
-
}
|
|
1483
|
-
/** Applies a reviewed voice scope to the current source actor, without replacing body or narration. */
|
|
1484
|
-
async applyDocumentVoice(scope: DocumentVoiceScope, value: VoiceSource | null, options: DocumentVoiceOptions, expected: { identity: string, version: string, fingerprint: string }): Promise<boolean> {
|
|
1485
|
-
const source = this.#state.authoring, document = this.getDocument(expected.identity), context = this.#documentScope
|
|
1486
|
-
if (!source || !document || source.version !== expected.version || source.fingerprint !== expected.fingerprint
|
|
1487
|
-
|| source.dirty || source.saving || source.composing || source.restored || source.error || isAgentChanging(this.#state)) throw new Error('voice-context-changed')
|
|
1488
|
-
const next = changeDocumentVoice(document, scope, value, options)
|
|
1489
|
-
if (next === document) return true
|
|
1490
|
-
this.stopAuditions()
|
|
1491
|
-
this.#documentSession.record(next)
|
|
1492
|
-
await this.flushPendingEdits()
|
|
1493
|
-
if (context !== this.#documentScope || this.#state.authoring?.identity !== expected.identity) return false
|
|
1494
|
-
const saved = this.#state.authoring
|
|
1495
|
-
if (!saved || saved.dirty || saved.saving || saved.composing || saved.restored || saved.error) throw new Error('voice-save-unconfirmed')
|
|
1496
|
-
return true
|
|
1497
|
-
}
|
|
1498
974
|
/** Parameter planning is an authoring read; it does not compile, change modes or write the document. */
|
|
1499
975
|
async planDocumentComponentAction(action: DocumentComponentAction, id: string, expected: { identity: string, version: string, fingerprint: string }, signal?: AbortSignal): Promise<DocumentAuthoringActionPlan> {
|
|
1500
|
-
const source = this
|
|
976
|
+
const source = this.production.source(expected), scope = this.#documentScope
|
|
1501
977
|
if (!source.content || !source.fingerprint || source.fingerprint !== expected.fingerprint) throw new Error('component-source-changed')
|
|
1502
978
|
const request = { id, source: componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint }), action: structuredClone(action) }
|
|
1503
979
|
const answer = await this.client.planDocumentAction(source.directory, request, signal)
|
|
1504
980
|
signal?.throwIfAborted()
|
|
1505
|
-
const current = this
|
|
981
|
+
const current = this.production.source(expected)
|
|
1506
982
|
if (scope !== this.#documentScope || !current.content || !current.fingerprint || answer.document !== source.directory || answer.changeId !== id || answer.effect.kind !== 'component'
|
|
1507
983
|
|| !sameComponentSource(answer.source, request.source) || JSON.stringify(answer.action) !== JSON.stringify(request.action)) throw new Error('component-source-changed')
|
|
1508
984
|
return answer
|
|
@@ -1510,13 +986,13 @@ export class Workbench {
|
|
|
1510
986
|
/** The existing source actor owns adoption and ambiguous-response recovery, including later native input. */
|
|
1511
987
|
async applyDocumentComponentPlan(plan: DocumentAuthoringActionPlan, expected: { identity: string, version: string }, signal?: AbortSignal): Promise<{ answer: DocumentChangeAnswer, commitId?: string }> {
|
|
1512
988
|
if (plan.effect.kind !== 'component' || !plan.action.type.startsWith('component.')) throw new Error('component-plan-invalid')
|
|
1513
|
-
const source = this
|
|
989
|
+
const source = this.production.source(expected), action = plan.action as DocumentComponentAction, scope = this.#documentScope
|
|
1514
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')
|
|
1515
991
|
this.#playback.stopPreviewOutputs()
|
|
1516
992
|
await this.pausePlayback()
|
|
1517
993
|
let receipt: AppliedDocumentAuthoringAction | undefined
|
|
1518
994
|
const remember = (answer: DocumentChangeAnswer) => {
|
|
1519
|
-
|
|
995
|
+
this.editing.rememberComponent(answer.content, expected.identity)
|
|
1520
996
|
return { answer, ...receipt?.commit ? { commitId: receipt.commit.id } : {} }
|
|
1521
997
|
}
|
|
1522
998
|
try {
|
|
@@ -1536,7 +1012,7 @@ export class Workbench {
|
|
|
1536
1012
|
&& file?.version === current.version && current.version !== plan.source.version) {
|
|
1537
1013
|
// Canonical acceptance is already known even when later native input has
|
|
1538
1014
|
// deleted the target. Undoing that deletion must restore its accepted configuration.
|
|
1539
|
-
|
|
1015
|
+
this.editing.rememberComponent(plan.content, expected.identity)
|
|
1540
1016
|
try {
|
|
1541
1017
|
if (!applyDocumentComponentAction(current.content, action).effect.changed) return remember({ document: source.directory, content: plan.content,
|
|
1542
1018
|
version: current.version, fingerprint: current.fingerprint, issues: plan.issues, changeId: plan.changeId, files: plan.files.map(value => ({ path: value.path, version: value.version })) })
|
|
@@ -1545,121 +1021,6 @@ export class Workbench {
|
|
|
1545
1021
|
throw error
|
|
1546
1022
|
}
|
|
1547
1023
|
}
|
|
1548
|
-
/** Manual caption times reuse the canonical action plan, media preflight and original source actor. */
|
|
1549
|
-
async applyDocumentCaptionTiming(action: DocumentCaptionTimingAction, id: string, expected: { identity: string, version: string, fingerprint: string }, signal?: AbortSignal): Promise<DocumentChangeAnswer> {
|
|
1550
|
-
const source = this.#mediaSource(expected), scope = this.#documentScope
|
|
1551
|
-
if (!source.content || source.fingerprint !== expected.fingerprint) throw new Error('caption-source-changed')
|
|
1552
|
-
const request = { id, source: componentSource({ content: source.content, version: source.version!, fingerprint: source.fingerprint! }), action }
|
|
1553
|
-
const plan = await this.client.planDocumentAction(source.directory, request, signal)
|
|
1554
|
-
signal?.throwIfAborted()
|
|
1555
|
-
if (scope !== this.#documentScope || this.#state.authoring?.identity !== expected.identity || plan.effect.kind !== 'caption'
|
|
1556
|
-
|| plan.changeId !== id || JSON.stringify(plan.action) !== JSON.stringify(action) || !sameComponentSource(plan.source, request.source)) throw new Error('caption-source-changed')
|
|
1557
|
-
this.#playback.stopPreviewOutputs()
|
|
1558
|
-
await this.pausePlayback()
|
|
1559
|
-
try {
|
|
1560
|
-
return await this.#documentSession.commitExternal(expected, async (_before, ownedSignal) => {
|
|
1561
|
-
const receipt = await this.client.applyDocumentAction(source.directory, { planId: plan.planId, digest: plan.digest, source: plan.source }, ownedSignal)
|
|
1562
|
-
const actual = await this.client.readDocument(source.directory)
|
|
1563
|
-
if (receipt.planId !== plan.planId || receipt.digest !== plan.digest || receipt.changeId !== id || !receipt.verification.saved || !receipt.verification.actionStateVerified
|
|
1564
|
-
|| !sameComponentSource(receipt.verification.source, componentSource(actual))) throw new Error('document-confirmation')
|
|
1565
|
-
return { ...actual, changeId: id, files: receipt.files }
|
|
1566
|
-
}, (before, answer, current) => reconcileCaptionTiming(action, before, answer, current), signal)
|
|
1567
|
-
} catch (error) {
|
|
1568
|
-
const current = this.#state.authoring, file = plan.files.find(file => file.path === (source.directory ? `${source.directory}/lecture.json` : 'lecture.json'))
|
|
1569
|
-
// Lost ACK was independently read by commitExternal; only the exact predicted saved version can settle it.
|
|
1570
|
-
if (scope === this.#documentScope && current?.identity === expected.identity && current.content && current.version === file?.version && current.fingerprint && !current.error) {
|
|
1571
|
-
try {
|
|
1572
|
-
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 })) }
|
|
1573
|
-
} catch { /* A newer target stays pending with the actual request error. */ }
|
|
1574
|
-
}
|
|
1575
|
-
throw error
|
|
1576
|
-
}
|
|
1577
|
-
}
|
|
1578
|
-
/** Uses the current actor revision so timing edits cannot replace later body or narration input. */
|
|
1579
|
-
setDocumentStepProduction(stepId: string, patch: StepTimingPatch, identity?: string): void {
|
|
1580
|
-
const document = this.getDocument(identity)
|
|
1581
|
-
if (!document || isAgentChanging(this.#state)) return
|
|
1582
|
-
const next = changeStepTiming(document, stepId, patch)
|
|
1583
|
-
if (next === document) return
|
|
1584
|
-
this.stopAuditions()
|
|
1585
|
-
this.#documentSession.record(next)
|
|
1586
|
-
}
|
|
1587
|
-
documentTimingDraft(stepId: string, key: StepDurationKey, identity: string, reset: number): StepDurationDraft | undefined {
|
|
1588
|
-
const document = this.getDocument(identity)
|
|
1589
|
-
return document && this.#state.authoring?.reset === reset ? this.#documentTimingDrafts.get(identity, document, stepId, key) : undefined
|
|
1590
|
-
}
|
|
1591
|
-
/** Retains unaccepted numeric input by stable target; it is not authoring content or a second timing source. */
|
|
1592
|
-
setDocumentTimingDraft(stepId: string, key: StepDurationKey, draft: StepDurationDraft | undefined, identity: string, reset: number): void {
|
|
1593
|
-
const source = this.#state.authoring, document = this.getDocument(identity)
|
|
1594
|
-
if (!document?.steps[stepId] || source?.reset !== reset || isAgentChanging(this.#state)) return
|
|
1595
|
-
if (!this.#documentTimingDrafts.set(identity, document, stepId, key, draft)) return
|
|
1596
|
-
this.#set({ authoring: { ...source }, hasDocumentTimingDrafts: this.#documentTimingDrafts.has(identity, document), documentTimingDraftStorageFailure: this.#documentTimingDrafts.failed })
|
|
1597
|
-
}
|
|
1598
|
-
captionTimingDraft(stepId: string, identity: string): CaptionTimingDraft | undefined {
|
|
1599
|
-
const source = this.#state.authoring
|
|
1600
|
-
return source?.identity === identity && source.member?.id ? this.#captionTimingDrafts.get({ identity, memberId: source.member.id }, stepId) : undefined
|
|
1601
|
-
}
|
|
1602
|
-
setCaptionTimingDraft(stepId: string, draft: CaptionTimingDraft | undefined, identity: string): void {
|
|
1603
|
-
const source = this.#state.authoring, document = this.getDocument(identity)
|
|
1604
|
-
if (!document?.steps[stepId] || source?.identity !== identity || !source.member?.id) return
|
|
1605
|
-
const scope = { identity, memberId: source.member.id }
|
|
1606
|
-
this.#captionTimingDrafts.set(scope, stepId, draft)
|
|
1607
|
-
this.#set({ captionTimingDraftSteps: this.#captionTimingDrafts.steps(scope, document), captionTimingDraftStorageFailure: this.#captionTimingDrafts.failed(scope) })
|
|
1608
|
-
}
|
|
1609
|
-
/** Changes one stable narration target without replacing the body editor or derived captions. */
|
|
1610
|
-
setDocumentNarration(stepId: string, narrationId: string | undefined, content: NarrationNode[], identity?: string): string | undefined {
|
|
1611
|
-
const document = this.getDocument(identity)
|
|
1612
|
-
if (!document || isAgentChanging(this.#state) || !Object.hasOwn(document.steps, stepId)) return undefined
|
|
1613
|
-
const step = document.steps[stepId]!
|
|
1614
|
-
if (!document.sections[step.sectionId]?.stepOrder.includes(stepId)) return undefined
|
|
1615
|
-
if (!Array.isArray(content)) throw new Error('document-narration-content')
|
|
1616
|
-
let meaningful = false
|
|
1617
|
-
for (const node of content) {
|
|
1618
|
-
if (!node || typeof node !== 'object') throw new Error('document-narration-content')
|
|
1619
|
-
if (node.type === 'text' && typeof node.text === 'string') meaningful ||= Boolean(node.text.trim())
|
|
1620
|
-
else if (node.type === 'pronunciation' && typeof node.display === 'string' && typeof node.spoken === 'string') meaningful ||= Boolean(node.display.trim() || node.spoken.trim())
|
|
1621
|
-
else if (node.type === 'cue' && typeof node.id === 'string' && node.id && typeof node.action === 'string' && node.action) meaningful = true
|
|
1622
|
-
else throw new Error('document-narration-content')
|
|
1623
|
-
}
|
|
1624
|
-
const target = narrationId ?? step.narrationIds[0]
|
|
1625
|
-
const existing = target !== undefined && Object.hasOwn(document.narrations, target) ? document.narrations[target] : undefined
|
|
1626
|
-
if (existing && !step.narrationIds.includes(existing.id)) throw new Error('document-narration-target')
|
|
1627
|
-
if (!existing && !meaningful) return undefined
|
|
1628
|
-
const id = target ?? crypto.randomUUID()
|
|
1629
|
-
if (!id || id.length > 200 || /[\u0000-\u001f]/.test(id) || ['__proto__', 'constructor', 'prototype'].includes(id)) throw new Error('document-narration-target')
|
|
1630
|
-
if (!existing && (document.id === id || [document.sections, document.blocks, document.steps, document.assets, document.definitions].some(map => Object.hasOwn(map, id)))) throw new Error('document-narration-target')
|
|
1631
|
-
if (existing && JSON.stringify(existing.content) === JSON.stringify(content)) return id
|
|
1632
|
-
const next: TeachingDocument = { ...document,
|
|
1633
|
-
narrations: { ...document.narrations, [id]: { ...existing, id, content: structuredClone(content) } },
|
|
1634
|
-
...step.narrationIds.includes(id) ? {} : { steps: { ...document.steps, [stepId]: { ...step, narrationIds: [...step.narrationIds, id] } } },
|
|
1635
|
-
}
|
|
1636
|
-
const cueIds = new Set(content.flatMap(node => node.type === 'cue' ? [node.id] : []))
|
|
1637
|
-
const previousCues = new Set(existing?.content.flatMap(node => node.type === 'cue' ? [node.id] : []) ?? [])
|
|
1638
|
-
if (document.production.cueTimings) {
|
|
1639
|
-
const removed = [...previousCues].filter(cue => !cueIds.has(cue) && Object.hasOwn(document.production.cueTimings!, cue)
|
|
1640
|
-
&& !Object.values(next.narrations).some(narration => narration.content.some(node => node.type === 'cue' && node.id === cue)))
|
|
1641
|
-
if (removed.length) {
|
|
1642
|
-
const cueTimings = { ...document.production.cueTimings }
|
|
1643
|
-
for (const cue of removed) {
|
|
1644
|
-
this.#removedCueTimings.delete(cue)
|
|
1645
|
-
this.#removedCueTimings.set(cue, { ...cueTimings[cue]! })
|
|
1646
|
-
delete cueTimings[cue]
|
|
1647
|
-
}
|
|
1648
|
-
while (this.#removedCueTimings.size > 512) this.#removedCueTimings.delete(this.#removedCueTimings.keys().next().value!)
|
|
1649
|
-
next.production = { ...document.production, cueTimings }
|
|
1650
|
-
}
|
|
1651
|
-
}
|
|
1652
|
-
for (const cue of cueIds) {
|
|
1653
|
-
const timing = this.#removedCueTimings.get(cue)
|
|
1654
|
-
if (!previousCues.has(cue) && timing && !Object.hasOwn(next.production.cueTimings ?? {}, cue)) {
|
|
1655
|
-
next.production = { ...next.production, cueTimings: { ...next.production.cueTimings, [cue]: { ...timing } } }
|
|
1656
|
-
this.#removedCueTimings.delete(cue)
|
|
1657
|
-
}
|
|
1658
|
-
}
|
|
1659
|
-
this.stopAuditions()
|
|
1660
|
-
this.#documentSession.record(next)
|
|
1661
|
-
return id
|
|
1662
|
-
}
|
|
1663
1024
|
recordDocument(content: TeachingDocument): void { if (!isAgentChanging(this.#state)) this.#documentSession.record(content) }
|
|
1664
1025
|
documentComposition(composing: boolean, owner = 'body', identity?: string): void { this.#documentSession.composition(composing, owner, identity) }
|
|
1665
1026
|
retryDocument(): Promise<void> { return this.#documentSession.retry() }
|
|
@@ -1671,228 +1032,10 @@ export class Workbench {
|
|
|
1671
1032
|
if (this.#state.authoring?.identity === identity && !isAgentChanging(this.#state)) void this.#documentSession.forgetDraft(value)
|
|
1672
1033
|
}
|
|
1673
1034
|
documentError(error: Error): void { this.#set({ save: { kind: 'failed', message: error.message } }) }
|
|
1674
|
-
documentInteraction(): void {
|
|
1675
|
-
this.#documentSelectionGeneration++; this.#cancelOpeningDocument(); this.#stopDocumentReturnScroll?.()
|
|
1676
|
-
if (this.#state.documentPositionFailure) this.#set({ documentPositionFailure: undefined })
|
|
1677
|
-
}
|
|
1678
|
-
pendingDocumentField(blockId: string | undefined, identity?: string): Pick<DocumentFieldRegistration, 'stepId' | 'narrationId' | 'slot'> | undefined {
|
|
1679
|
-
const pending = this.#pendingDocumentField, source = this.#state.authoring
|
|
1680
|
-
return pending && pending.generation === this.#documentSelectionGeneration && pending.field.blockId === blockId
|
|
1681
|
-
&& pending.field.identity === (identity ?? source?.identity) && pending.reset === source?.reset ? pending.field : undefined
|
|
1682
|
-
}
|
|
1683
|
-
/** A live native field owns its target only while it still has focus in this source. */
|
|
1684
|
-
focusedDocumentField(): Readonly<Pick<DocumentFieldRegistration, 'identity' | 'reset' | 'blockId' | 'stepId' | 'narrationId' | 'slot'>> & { readonly editor: DocumentHistoryEditor } | undefined {
|
|
1685
|
-
const source = this.#state.authoring, editor = this.#activeDocumentHistory
|
|
1686
|
-
if (!source?.identity || !source.content || !editor || editor === this.#documentEditor || editor.prosemirrorView.isDestroyed || !editor.prosemirrorView.hasFocus()) return
|
|
1687
|
-
for (const field of this.#documentFields.values()) {
|
|
1688
|
-
if (field.editor !== editor || field.identity !== source.identity || field.reset !== source.reset) continue
|
|
1689
|
-
const step = source.content.steps[field.stepId], section = step && source.content.sections[step.sectionId]
|
|
1690
|
-
if (!step || !section?.stepOrder.includes(field.stepId) || field.slot < 0 || field.slot >= Math.max(1, step.narrationIds.length)
|
|
1691
|
-
|| step.narrationIds[field.slot] !== undefined && step.narrationIds[field.slot] !== field.narrationId) return
|
|
1692
|
-
const { identity, reset, blockId, stepId, narrationId, slot } = field
|
|
1693
|
-
return { identity, reset, blockId, stepId, narrationId, slot, 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, field.slot, field.narrationId])
|
|
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, pending.field.slot, pending.field.narrationId]) === 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
|
-
} else this.#unsubscribeDocumentSelection = undefined
|
|
1753
|
-
this.#finishOpeningDocument()
|
|
1754
|
-
}
|
|
1755
|
-
#focusDocumentNode(editor: NativeDocumentEditor, nodeId: string): void {
|
|
1756
|
-
this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
|
|
1757
|
-
editor.setTextCursorPosition(nodeId, 'start')
|
|
1758
|
-
editor.focus()
|
|
1759
|
-
editor.prosemirrorView.dispatch(editor.prosemirrorState.tr.scrollIntoView())
|
|
1760
|
-
// React node views can finish sizing after the native editor mounts.
|
|
1761
|
-
// Keep only this untouched focus visible through those layout changes.
|
|
1762
|
-
if (typeof ResizeObserver !== 'undefined') {
|
|
1763
|
-
const view = editor.prosemirrorView, document = view.dom.ownerDocument
|
|
1764
|
-
const source = this.#state.authoring!, identity = source.identity, reset = source.reset, documentId = source.content!.id
|
|
1765
|
-
const request = this.#state.documentNavigation?.request, selected = editor.prosemirrorState.selection
|
|
1766
|
-
let size = view.dom.getBoundingClientRect(), active = true
|
|
1767
|
-
const events = ['pointerdown', 'wheel', 'touchmove', 'keydown', 'beforeinput']
|
|
1768
|
-
const cancel = () => {
|
|
1769
|
-
if (!active) return
|
|
1770
|
-
active = false; observer.disconnect(); stopFocus(); stopSelection()
|
|
1771
|
-
for (const event of events) document.removeEventListener(event, interact, true)
|
|
1772
|
-
}
|
|
1773
|
-
const interact = (event: Event) => { if (event.isTrusted) cancel() }
|
|
1774
|
-
const stopFocus = editor.onFocusChange((_, { focused }) => { if (!focused) cancel() })
|
|
1775
|
-
const stopSelection = editor.onSelectionChange(cancel)
|
|
1776
|
-
const observer = new ResizeObserver(() => {
|
|
1777
|
-
if (!active) return
|
|
1778
|
-
const current = this.#state.authoring
|
|
1779
|
-
if (this.#documentEditor !== editor || view.isDestroyed || !current || current.identity !== identity || current.reset !== reset
|
|
1780
|
-
|| current?.content?.id !== documentId || this.#state.documentNavigation?.request !== request
|
|
1781
|
-
|| !editor.isFocused() || !editor.prosemirrorState.selection.eq(selected) || editor.getTextCursorPosition().block.id !== nodeId) { cancel(); return }
|
|
1782
|
-
const next = view.dom.getBoundingClientRect()
|
|
1783
|
-
if (next.width === size.width && next.height === size.height) return
|
|
1784
|
-
size = next
|
|
1785
|
-
view.dispatch(editor.prosemirrorState.tr.scrollIntoView())
|
|
1786
|
-
})
|
|
1787
|
-
for (const event of events) document.addEventListener(event, interact, true)
|
|
1788
|
-
observer.observe(view.dom)
|
|
1789
|
-
this.#stopDocumentLayoutScroll = cancel
|
|
1790
|
-
}
|
|
1791
|
-
}
|
|
1792
1035
|
async flushPendingEdits(signal?: AbortSignal): Promise<void> {
|
|
1793
1036
|
if (isAgentChanging(this.#state)) throw new Error('save-locked')
|
|
1794
1037
|
await this.#documentSession.flush(signal)
|
|
1795
1038
|
}
|
|
1796
|
-
async #changeDocumentPage(change: (document: TeachingDocument) => void): Promise<boolean> {
|
|
1797
|
-
const source = this.#state.authoring, directory = this.#state.document
|
|
1798
|
-
if (!source?.content || directory === undefined || isAgentChanging(this.#state)) return false
|
|
1799
|
-
const scope = this.#documentScope, identity = source.identity, documentId = source.content.id
|
|
1800
|
-
const current = () => scope === this.#documentScope && directory === this.#state.document && identity === this.#state.authoring?.identity && documentId === this.#state.authoring?.content?.id
|
|
1801
|
-
this.#set({ isEditingPage: true, pageEditFailure: undefined })
|
|
1802
|
-
try {
|
|
1803
|
-
await this.flushPendingEdits()
|
|
1804
|
-
if (!current()) throw new Error('page-context-changed')
|
|
1805
|
-
const document = structuredClone(this.#state.authoring!.content!)
|
|
1806
|
-
change(document)
|
|
1807
|
-
const editor = this.#documentEditor
|
|
1808
|
-
this.#pendingDocumentField = undefined
|
|
1809
|
-
const plannedFocus = this.#pendingDocumentFocus
|
|
1810
|
-
if (!plannedFocus || plannedFocus.generation !== this.#documentSelectionGeneration) for (const field of this.#documentFields.values()) {
|
|
1811
|
-
if (field.identity !== source.identity || field.reset !== this.#state.authoring!.reset || field.blockId !== undefined && !document.blocks[field.blockId] || !document.steps[field.stepId]) continue
|
|
1812
|
-
const bookmark = field.focus.capture()
|
|
1813
|
-
if (bookmark) {
|
|
1814
|
-
const { focus: _focus, editor: _editor, ...target } = field
|
|
1815
|
-
this.#pendingDocumentField = { field: target, bookmark, reset: this.#state.authoring!.reset + 1, generation: this.#documentSelectionGeneration }
|
|
1816
|
-
this.#pendingDocumentSelection = undefined
|
|
1817
|
-
break
|
|
1818
|
-
}
|
|
1819
|
-
}
|
|
1820
|
-
if (editor && !this.#pendingDocumentField) {
|
|
1821
|
-
const state = editor.prosemirrorState, anchor = nativeTextPoint(editor, state.selection.anchor), head = nativeTextPoint(editor, state.selection.head)
|
|
1822
|
-
if (anchor && head) this.#pendingDocumentSelection = { documentId: document.id, anchor, head, focused: editor.prosemirrorView.hasFocus() }
|
|
1823
|
-
}
|
|
1824
|
-
this.#documentSession.replace(document)
|
|
1825
|
-
await this.#documentSession.flush()
|
|
1826
|
-
return current()
|
|
1827
|
-
} catch (error) { if (current()) this.#set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
|
|
1828
|
-
finally { if (current()) this.#set({ isEditingPage: false }) }
|
|
1829
|
-
}
|
|
1830
|
-
renamePage(section: string, title: string): Promise<boolean> {
|
|
1831
|
-
return this.#changeDocumentPage(document => { Object.assign(document, renameDocumentPage(document, section, title)) })
|
|
1832
|
-
}
|
|
1833
|
-
async duplicatePage(section: string): Promise<boolean> {
|
|
1834
|
-
if (this.#state.isEditingPage || this.#state.isCreatingPage || this.#state.isHistoryBusy) return false
|
|
1835
|
-
const scope = this.#documentScope, identity = this.#state.authoring?.identity, generation = this.#documentSelectionGeneration, navigation = this.#state.documentNavigation?.request
|
|
1836
|
-
let copied: string | undefined
|
|
1837
|
-
const saved = await this.#changeDocumentPage(document => {
|
|
1838
|
-
if (scope !== this.#documentScope || identity !== this.#state.authoring?.identity) throw new Error('page-context-changed')
|
|
1839
|
-
const page = document.sections[section]
|
|
1840
|
-
if (!page) throw new Error('page-boundary')
|
|
1841
|
-
const copy = duplicateDocumentPage(document, section, contentText(document.metadata.lang).copyTitle(page.title), () => crypto.randomUUID())
|
|
1842
|
-
copied = copy.section
|
|
1843
|
-
Object.assign(document, copy.document)
|
|
1844
|
-
if (generation === this.#documentSelectionGeneration) this.#pendingDocumentFocus = { documentId: document.id, nodeId: `page:${copied}`, generation, afterSave: true }
|
|
1845
|
-
})
|
|
1846
|
-
// Source confirmation owns editing. A later author selection takes precedence over this response.
|
|
1847
|
-
if (!saved || !copied || scope !== this.#documentScope || generation !== this.#documentSelectionGeneration || navigation !== this.#state.documentNavigation?.request || !this.#state.authoring?.content?.sections[copied]) return saved
|
|
1848
|
-
this.goToSection(copied)
|
|
1849
|
-
const editor = this.#documentEditor
|
|
1850
|
-
if (editor) {
|
|
1851
|
-
const blocks = editor.document, start = blocks.findIndex(block => block.id === `page:${copied}`)
|
|
1852
|
-
const first = (nodes: typeof blocks): string | undefined => {
|
|
1853
|
-
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 }
|
|
1854
|
-
return undefined
|
|
1855
|
-
}
|
|
1856
|
-
const target = start < 0 ? undefined : first(blocks.slice(start + 1)) ?? blocks[start]!.id
|
|
1857
|
-
if (target) { editor.setTextCursorPosition(target, 'start'); editor.focus() }
|
|
1858
|
-
}
|
|
1859
|
-
return true
|
|
1860
|
-
}
|
|
1861
|
-
movePage(section: string, before: string | null): Promise<boolean> {
|
|
1862
|
-
return this.#changeDocumentPage(document => { Object.assign(document, moveDocumentPage(document, section, before)) })
|
|
1863
|
-
}
|
|
1864
|
-
pageDeleteMessage(reason: string): string { return this.#pageEditMessage(reason) }
|
|
1865
|
-
async preparePageDeletion(section: string): Promise<PageDeletePlan> {
|
|
1866
|
-
await this.flushPendingEdits()
|
|
1867
|
-
const source = this.#state.authoring
|
|
1868
|
-
if (!source?.content || !source.version || this.#state.document === undefined) throw new Error('document-unavailable')
|
|
1869
|
-
return pageDeletion(source.content, this.#state.document, source.version, section)
|
|
1870
|
-
}
|
|
1871
|
-
async deletePage(plan: PageDeletePlan): Promise<boolean> {
|
|
1872
|
-
if (!plan.allowed || plan.document !== this.#state.document) return false
|
|
1873
|
-
return this.#changeDocumentPage(document => {
|
|
1874
|
-
if (this.#state.authoring?.version !== plan.source.version) throw new Error('revision-conflict')
|
|
1875
|
-
const current = pageDeletion(document, plan.document, plan.source.version, plan.section)
|
|
1876
|
-
if (!current.allowed) throw new Error(current.reason)
|
|
1877
|
-
Object.assign(document, removeDocumentPage(document, plan.section, () => crypto.randomUUID()))
|
|
1878
|
-
this.#set({ position: { section: document.sectionOrder[0]!, step: 0, trail: [], view: 'document' }, documentNavigation: { section: document.sectionOrder[0]!, request: crypto.randomUUID() } })
|
|
1879
|
-
})
|
|
1880
|
-
}
|
|
1881
|
-
createPage(after = this.#state.position?.section): boolean {
|
|
1882
|
-
const source = this.#state.authoring, editor = this.#documentEditor, commands = this.#documentEditorCommands
|
|
1883
|
-
if (!source?.content || source.loading || source.composing || source.restored || source.error || !editor || !commands
|
|
1884
|
-
|| editor.prosemirrorView.isDestroyed || isAgentChanging(this.#state) || this.#state.isEditingPage || this.#state.isCreatingPage
|
|
1885
|
-
|| this.#state.isHistoryBusy || this.#state.isHistoryPreparing) return false
|
|
1886
|
-
try {
|
|
1887
|
-
this.#set({ pageEditFailure: undefined })
|
|
1888
|
-
const created = commands.insertPage(after, contentText(source.content.metadata.lang).newPage)
|
|
1889
|
-
this.#pendingDocumentField = undefined; this.#pendingDocumentSelection = undefined; this.#pendingDocumentFocus = undefined
|
|
1890
|
-
this.#set({ position: { section: created.sectionId, step: 0, trail: [], view: 'document' }, documentNavigation: { section: created.sectionId, request: crypto.randomUUID() } })
|
|
1891
|
-
this.#focusDocumentNode(editor, created.nodeId)
|
|
1892
|
-
return true
|
|
1893
|
-
} catch (error) { this.#set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
|
|
1894
|
-
}
|
|
1895
|
-
|
|
1896
1039
|
/** Points at a block or a passage (none: stops pointing): the preview outlines it and the conversation is told. */
|
|
1897
1040
|
point(pointer: Pointer | undefined): void {
|
|
1898
1041
|
const pointed = this.#state.pointer !== undefined || this.#state.focus.length > 0
|
|
@@ -1966,6 +1109,40 @@ export class Workbench {
|
|
|
1966
1109
|
}
|
|
1967
1110
|
}
|
|
1968
1111
|
|
|
1112
|
+
/**
|
|
1113
|
+
* Opens the conversation with a request, for the author to describe and send, to add an animation at `place` of the
|
|
1114
|
+
* open document; the document's focus points the AI at the place's block. Nothing is inserted or sent.
|
|
1115
|
+
*/
|
|
1116
|
+
draftAnimation(place: DocumentInsertionPlace): boolean {
|
|
1117
|
+
const document = this.#state.document, content = this.#state.authoring?.content, drafter = [...this.#drafters][0]
|
|
1118
|
+
const section = content?.sections[place.sectionId]
|
|
1119
|
+
if (document === undefined || !content || !section || !drafter) return false
|
|
1120
|
+
const report = (block?: string): FocusReport => ({ id: 'insertion', from: this.#state.previewRenderer, section: place.sectionId, ...block ? { block } : {}, ...place.text ? { quote: place.text.slice(0, 2000) } : {} })
|
|
1121
|
+
const text = this.#messages.animationRequest(content.sectionOrder.indexOf(place.sectionId) + 1, section.title, place)
|
|
1122
|
+
const focus = [report(place.blocks[0])]
|
|
1123
|
+
void this.#focusFirst(document, [...place.blocks.map(block => [report(block)]), [report()], []])
|
|
1124
|
+
const drafted = (attributes: Record<string, OperationValue>) => this.#record('agent.draft', { 'presmium.ask.kind': 'animation', 'presmium.ask.text': text, 'presmium.section': place.sectionId, 'presmium.block': place.blocks[0], ...attributes })
|
|
1125
|
+
this.#set({ askFailure: undefined })
|
|
1126
|
+
void (async () => drafter({ text, focus }))().then(() => drafted({ 'presmium.outcome': 'drafted' }), (error: unknown) => {
|
|
1127
|
+
drafted({ 'presmium.outcome': 'failed', 'presmium.error': errorMessage(error) })
|
|
1128
|
+
if (this.#state.document === document) this.#set({ askFailure: errorMessage(error) })
|
|
1129
|
+
})
|
|
1130
|
+
return true
|
|
1131
|
+
}
|
|
1132
|
+
|
|
1133
|
+
/**
|
|
1134
|
+
* Sets the first of `choices` the service can locate as the document's focus. Its runtime snapshot is compiled from the
|
|
1135
|
+
* saved source, which may not have a block or page created moments ago yet; the last choice leaves no stale focus.
|
|
1136
|
+
*/
|
|
1137
|
+
async #focusFirst(document: string, choices: FocusReport[][]): Promise<void> {
|
|
1138
|
+
for (const focus of choices) {
|
|
1139
|
+
this.setFocus(focus)
|
|
1140
|
+
const version = this.#focusVersion
|
|
1141
|
+
await this.#focusWriting
|
|
1142
|
+
if (version !== this.#focusVersion || this.#state.document !== document || !this.#state.focusFailure) return
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
|
|
1969
1146
|
/** A place as the author sees it: the section's title and the passage. */
|
|
1970
1147
|
#describe(item: FocusReport & Partial<Focus>): AgentPlace {
|
|
1971
1148
|
const doc = this.#state.ir?.doc
|
|
@@ -1989,7 +1166,7 @@ export class Workbench {
|
|
|
1989
1166
|
/** Shows a section in the preview: from the navigation pane, the section to read or the slide to show. */
|
|
1990
1167
|
goToSection(section: string): void {
|
|
1991
1168
|
if (this.#state.webView === 'document' && this.#state.authoring?.content?.sections[section]) {
|
|
1992
|
-
this.#set({ position: { section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: { section, request:
|
|
1169
|
+
this.#set({ position: { section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: { section, request: randomUUID() } }); return
|
|
1993
1170
|
}
|
|
1994
1171
|
this.goToStep(section, this.#selectedSteps.get(`${this.#state.document}\0${section}`) ?? 0)
|
|
1995
1172
|
}
|
|
@@ -2003,7 +1180,7 @@ export class Workbench {
|
|
|
2003
1180
|
const visible = (index: number) => Boolean(section.stepOrder[index] && effectiveComponentParameters(document, blockId, section.stepOrder[index]).visual?.visible)
|
|
2004
1181
|
const step = visible(current) ? current : Math.max(0, section.stepOrder.findIndex((_, index) => visible(index)))
|
|
2005
1182
|
this.#set({ position: { section: sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined,
|
|
2006
|
-
documentNavigation: { section: sectionId, block: blockId, request:
|
|
1183
|
+
documentNavigation: { section: sectionId, block: blockId, request: randomUUID() } })
|
|
2007
1184
|
}
|
|
2008
1185
|
|
|
2009
1186
|
observeDocumentSection(section: string): void {
|
|
@@ -2035,7 +1212,7 @@ export class Workbench {
|
|
|
2035
1212
|
const plan = this.#state.productionPlan, range = plan?.pages.find(page => page.sectionId === sectionId)?.steps.find(step => step.stepId === stepId)
|
|
2036
1213
|
if (plan?.canPreview && this.#productionReady() && range?.startMs !== undefined) {
|
|
2037
1214
|
this.stopAuditions()
|
|
2038
|
-
if (this.#
|
|
1215
|
+
if (this.#productionPlayback.selecting(sectionId, stepId)) return
|
|
2039
1216
|
this.#selectedSteps.set(`${this.#state.document}\0${sectionId}`, step)
|
|
2040
1217
|
this.#set({ position: { section: sectionId, step, trail: [], view: 'present' } })
|
|
2041
1218
|
return this.controlProduction({ binding: plan.binding, action: 'step', sectionId, stepId }).catch(() => undefined)
|
|
@@ -2090,8 +1267,8 @@ export class Workbench {
|
|
|
2090
1267
|
return true
|
|
2091
1268
|
}
|
|
2092
1269
|
|
|
2093
|
-
undo(): Promise<boolean> {
|
|
2094
|
-
redo(): Promise<boolean> {
|
|
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) }
|
|
2095
1272
|
|
|
2096
1273
|
async #changeHistory(action: 'undo' | 'redo' | 'revert', revision?: string): Promise<boolean> {
|
|
2097
1274
|
if (this.#state.mode !== 'editing' || this.#state.isCreatingPage || this.#state.isEditingPage || this.#state.isHistoryBusy || this.#state.isHistoryPreparing) return false
|
|
@@ -2192,7 +1369,7 @@ export class Workbench {
|
|
|
2192
1369
|
sink.send({ type: 'highlight', target: reveal ?? this.#state.pointer?.target ?? null })
|
|
2193
1370
|
return () => {
|
|
2194
1371
|
this.#previewSinks.delete(sink)
|
|
2195
|
-
this.#
|
|
1372
|
+
this.#productionPlayback.detach(sink)
|
|
2196
1373
|
this.#set({ previewConnection: this.#state.previewConnection + 1 })
|
|
2197
1374
|
this.#playback.detach(sink)
|
|
2198
1375
|
}
|
|
@@ -2209,7 +1386,7 @@ export class Workbench {
|
|
|
2209
1386
|
if (report.type === 'page-create') { origin?.send({ type: 'page-created', section: report.section, request: report.request, error: unsupported }); return }
|
|
2210
1387
|
if (document !== this.#state.document || renderer !== this.#state.previewRenderer) return
|
|
2211
1388
|
this.#playback.report(document, report, origin)
|
|
2212
|
-
this.#
|
|
1389
|
+
this.#productionPlayback.report(document, report, origin)
|
|
2213
1390
|
switch (report.type) {
|
|
2214
1391
|
case 'ready':
|
|
2215
1392
|
case 'updated':
|
|
@@ -2236,9 +1413,6 @@ export class Workbench {
|
|
|
2236
1413
|
} else if (this.#state.pointer?.quote) this.point(undefined)
|
|
2237
1414
|
break
|
|
2238
1415
|
}
|
|
2239
|
-
case 'flashed':
|
|
2240
|
-
if (this.#trail) this.#set({ changeTrail: { id: this.#trail, rects: report.rects } })
|
|
2241
|
-
break
|
|
2242
1416
|
case 'rect':
|
|
2243
1417
|
if (this.#state.pointer) this.#set({ pointer: { ...this.#state.pointer, rect: report.rect ?? undefined, obstacles: report.obstacles } })
|
|
2244
1418
|
break
|
|
@@ -2247,7 +1421,7 @@ export class Workbench {
|
|
|
2247
1421
|
if (snapshot && source && (source.dirty || source.loading || source.version !== snapshot.version || source.fingerprint !== snapshot.fingerprint)) break
|
|
2248
1422
|
// An initial loader can report its old cursor while a newer stable selection is preparing.
|
|
2249
1423
|
// Explicit native exits still reach the outer document workspace.
|
|
2250
|
-
if (report.view !== 'document' && this.#
|
|
1424
|
+
if (report.view !== 'document' && this.#productionPlayback.selecting()) break
|
|
2251
1425
|
// A fresh frame announces its document view before applying the queued
|
|
2252
1426
|
// presentation command. Only the requested view completes that switch.
|
|
2253
1427
|
if (renderer === 'web' && this.#awaitingView) {
|
|
@@ -2286,19 +1460,14 @@ export class Workbench {
|
|
|
2286
1460
|
|
|
2287
1461
|
#stopSubscriptions(): void {
|
|
2288
1462
|
this.#componentPropertyDrafts.stopAgentRead()
|
|
2289
|
-
this
|
|
2290
|
-
this.#documentViewport?.stop(); this.#documentViewport = undefined; this.#documentEditorBinding = undefined
|
|
1463
|
+
this.editing.reset()
|
|
2291
1464
|
this.#presentationPreparation++
|
|
2292
1465
|
this.#presentationController?.abort(new Error('client-document-changed'))
|
|
2293
1466
|
this.#voiceover.stop()
|
|
2294
|
-
this.#
|
|
1467
|
+
this.#productionPlayback.reset()
|
|
2295
1468
|
this.#set({ isPreparingPresentation: false, presentationFailure: undefined, presentationSnapshot: undefined, productionPlan: undefined, productionFailure: undefined })
|
|
2296
|
-
this
|
|
1469
|
+
this.production.reset()
|
|
2297
1470
|
this.#documentSession.close()
|
|
2298
|
-
this.#unsubscribeDocumentHistory?.(); this.#unsubscribeDocumentHistory = undefined; this.#activeDocumentHistory = undefined; this.#documentEditor = undefined
|
|
2299
|
-
this.#unsubscribeDocumentSelection?.(); this.#unsubscribeDocumentSelection = undefined
|
|
2300
|
-
this.#pendingDocumentFocus = undefined; this.#pendingDocumentSelection = undefined; this.#documentSelectionGeneration++
|
|
2301
|
-
this.#documentFields.clear(); this.#pendingDocumentField = undefined
|
|
2302
1471
|
this.#playback.reset()
|
|
2303
1472
|
this.#focusVersion++
|
|
2304
1473
|
this.#pendingReveal = undefined
|
|
@@ -2321,7 +1490,7 @@ export class Workbench {
|
|
|
2321
1490
|
this.#documentSession.dispose()
|
|
2322
1491
|
this.#commentDrafts.close()
|
|
2323
1492
|
this.#componentPropertyDrafts.close()
|
|
2324
|
-
this
|
|
1493
|
+
this.production.dispose()
|
|
2325
1494
|
disposeTranscriptionSessions(this.client)
|
|
2326
1495
|
disposeDocumentRecordings(this)
|
|
2327
1496
|
}
|