@lincyaw/workbench 0.2.0-rc.32 → 0.2.0-rc.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/package.json +4 -4
  2. package/src/context.tsx +2 -1
  3. package/src/diagnostics.ts +1 -1
  4. package/src/document-editing.ts +484 -0
  5. package/src/document-editor/ComponentPropertiesDialog.tsx +1 -1
  6. package/src/document-editor/DocumentBlockPreview.tsx +2 -2
  7. package/src/document-editor/DocumentStepNarration.tsx +10 -10
  8. package/src/document-production.ts +331 -0
  9. package/src/history.ts +1 -1
  10. package/src/index.ts +5 -2
  11. package/src/jobs.ts +1 -1
  12. package/src/panels/DocumentView.tsx +11 -11
  13. package/src/panels/DocumentVoiceDialog.tsx +2 -2
  14. package/src/panels/DocumentVoiceField.tsx +1 -1
  15. package/src/panels/HistoryPanel.tsx +1 -1
  16. package/src/panels/PageDeleteDialog.tsx +4 -4
  17. package/src/panels/PageRenameDialog.tsx +1 -1
  18. package/src/panels/ProductionCaptionSize.tsx +1 -1
  19. package/src/panels/ProductionCaptionTiming.tsx +5 -5
  20. package/src/panels/ProductionMediaClips.tsx +4 -4
  21. package/src/panels/ProductionPanel.tsx +2 -2
  22. package/src/panels/ProductionRecording.tsx +1 -1
  23. package/src/panels/ProductionRecordingRange.tsx +2 -2
  24. package/src/panels/ProductionTranscription.tsx +3 -3
  25. package/src/panels/SourceDocumentPanel.tsx +9 -9
  26. package/src/panels/TranscriptionAdoption.tsx +2 -2
  27. package/src/panels/VoiceoverDialog.tsx +1 -1
  28. package/src/preview-playback.ts +1 -1
  29. package/src/production-playback.ts +1 -1
  30. package/src/production-voice-playback.ts +3 -2
  31. package/src/use-recording-adoption.ts +2 -2
  32. package/src/voiceover-jobs.ts +1 -1
  33. package/src/workbench-state.ts +157 -0
  34. package/src/workbench.ts +56 -923
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.32",
3
+ "version": "0.2.0-rc.34",
4
4
  "description": "Presmium's workbench panels in React (the documents, a document edited on its rendered page with comments and version history) with the workspace service's client and the preview protocol's workbench side; @lincyaw/dsh places them in presmium studio (experimental)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -55,8 +55,8 @@
55
55
  "@tiptap/pm": "3.32.0",
56
56
  "katex": "0.18.10",
57
57
  "react-resizable-panels": "4.14.5",
58
- "@lincyaw/kernel": "1.0.0-rc.32",
59
- "@lincyaw/design": "1.0.0-rc.32"
58
+ "@lincyaw/kernel": "1.0.0-rc.34",
59
+ "@lincyaw/design": "1.0.0-rc.34"
60
60
  },
61
61
  "peerDependencies": {
62
62
  "react": "^18.3.1",
@@ -67,6 +67,6 @@
67
67
  "@types/react-dom": "18.3.7",
68
68
  "react": "^18.3.1",
69
69
  "react-dom": "^18.3.1",
70
- "@lincyaw/compiler": "1.0.0-rc.32"
70
+ "@lincyaw/compiler": "1.0.0-rc.34"
71
71
  }
72
72
  }
package/src/context.tsx CHANGED
@@ -2,7 +2,8 @@ import { createContext, useContext, useSyncExternalStore } from 'react'
2
2
  import type { ReactNode } from 'react'
3
3
  import { MESSAGES } from './messages.ts'
4
4
  import type { WorkbenchMessages } from './messages.ts'
5
- import type { Workbench, WorkbenchState } from './workbench.ts'
5
+ import type { Workbench } from './workbench.ts'
6
+ import type { WorkbenchState } from './workbench-state.ts'
6
7
 
7
8
  const WORKBENCH = createContext<Workbench | undefined>(undefined)
8
9
 
@@ -1,6 +1,6 @@
1
1
  import { errorMessage } from '@lincyaw/kernel'
2
2
  import type { Diagnostic, DiagnosticSnapshot, PreviewDiagnostics } from '@lincyaw/kernel'
3
- import type { WorkbenchStore } from './workbench.ts'
3
+ import type { WorkbenchStore } from './workbench-state.ts'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
5
 
6
6
  type Repairer = (diagnostics: readonly Diagnostic[]) => void | Promise<void>
@@ -0,0 +1,484 @@
1
+ import { duplicateDocumentPage, errorMessage, moveDocumentPage, pageDeletion, randomUUID, removeDocumentPage, renameDocumentPage } from '@lincyaw/kernel'
2
+ import type { PageDeletePlan, TeachingDocument } from '@lincyaw/kernel'
3
+ import { undoDepth, redoDepth } from '@tiptap/pm/history'
4
+ import { TextSelection } from '@tiptap/pm/state'
5
+ import { isAgentChanging } from './workbench-state.ts'
6
+ import type { WorkbenchStore } from './workbench-state.ts'
7
+ import type { DocumentSession, DocumentSessionState } from './document-session.ts'
8
+ import { DocumentReturnPoints, documentReturnStep, documentViewportOffset, restoreDocumentViewport } from './document-return-point.ts'
9
+ import type { DocumentReturnPoint } from './document-return-point.ts'
10
+ import type { NativeDocumentEditor } from './document-editor/schema.tsx'
11
+ import type { DocumentEditorCommands } from './document-editor/DocumentEditor.tsx'
12
+ import type { DocumentInsertionPlace } from './document-editor/insertion-place.ts'
13
+ import { nativeBlockText, nativeTextPoint, nativeTextPosition } from './document-editor/selection.ts'
14
+ import type { NativeTextPoint } from './document-editor/selection.ts'
15
+ import type { DocumentFieldBookmark, DocumentFieldRegistration, DocumentHistoryEditor } from './document-editor/focus.ts'
16
+ import { contentText, MESSAGES } from './messages.ts'
17
+
18
+ interface EditingOptions {
19
+ store: WorkbenchStore
20
+ session: DocumentSession
21
+ scope(): number
22
+ flush(signal?: AbortSignal): Promise<void>
23
+ goToSection(section: string): void
24
+ rememberStep(directory: string, section: string, step: number): void
25
+ canAskAnimation(): boolean
26
+ askAnimation(place: DocumentInsertionPlace): boolean
27
+ }
28
+
29
+ /** Native editor selection, focus, page changes and viewport restoration share one document lifetime. */
30
+ export class DocumentEditing {
31
+ #documentEditor?: NativeDocumentEditor
32
+ #documentEditorCommands?: DocumentEditorCommands
33
+ #documentEditorBinding?: { identity: string, reset: number }
34
+ readonly #documentReturnPoints = new DocumentReturnPoints()
35
+ #documentViewport?: { element: HTMLElement, identity: string, returnScrollTop?: number, stop(): void }
36
+ #stopDocumentReturnScroll?: () => void
37
+ #openingDocument?: { directory: string, scope: number, generation: number, focus?: 'body', initial?: boolean, stop(): void,
38
+ basis?: { identity: string, reset: number, version?: string, content: TeachingDocument }, point?: DocumentReturnPoint, fallback?: DocumentReturnPoint }
39
+ #stopDocumentLayoutScroll?: () => void
40
+ #activeDocumentHistory?: DocumentHistoryEditor
41
+ #unsubscribeDocumentHistory?: () => void
42
+ #unsubscribeDocumentSelection?: () => void
43
+ #generation = 0
44
+ #pendingDocumentFocus?: { documentId: string, nodeId: string, generation: number, afterSave?: true }
45
+ #pendingDocumentSelection?: { documentId: string, anchor: NativeTextPoint, head: NativeTextPoint, focused: boolean }
46
+ readonly #documentFields = new Map<string, DocumentFieldRegistration>()
47
+ #pendingDocumentField?: { field: Omit<DocumentFieldRegistration, 'focus' | 'editor'>, bookmark: DocumentFieldBookmark, reset: number, generation: number }
48
+ readonly #store: WorkbenchStore
49
+ readonly #session: DocumentSession
50
+ readonly #options: EditingOptions
51
+
52
+ constructor(options: EditingOptions) { this.#options = options; this.#store = options.store; this.#session = options.session }
53
+ get generation(): number { return this.#generation }
54
+ get returnPoints(): DocumentReturnPoints { return this.#documentReturnPoints }
55
+ sourceChanged(authoring: DocumentSessionState): void {
56
+ const pending = this.#pendingDocumentField
57
+ if (pending && (pending.field.identity !== authoring.identity || authoring.reset > pending.reset
58
+ || pending.field.blockId !== undefined && !authoring.content?.blocks[pending.field.blockId]
59
+ || !authoring.content?.steps[pending.field.stepId])) this.#pendingDocumentField = undefined
60
+ }
61
+ rememberComponent(content: TeachingDocument, identity: string): void {
62
+ if (this.#documentEditorBinding?.identity === identity) this.#documentEditorCommands?.rememberComponentConfiguration(content)
63
+ }
64
+ beforePosition(): void { this.cancelOpening(); this.#stopDocumentReturnScroll?.() }
65
+ nativeHistory(action: 'undo' | 'redo'): boolean | undefined {
66
+ const state = this.#store.state
67
+ if (state.mode !== 'editing') return false
68
+ if (this.#activeDocumentHistory && (state.editorHistory?.[action] || state.editorHistory?.field)) {
69
+ this.#activeDocumentHistory.focus()
70
+ return this.#activeDocumentHistory[action]()
71
+ }
72
+ }
73
+ reset(): void {
74
+ this.saveReturnPoint(); this.cancelOpening(); this.#stopDocumentReturnScroll?.()
75
+ this.#documentViewport?.stop(); this.#documentViewport = undefined; this.#documentEditorBinding = undefined
76
+ this.#unsubscribeDocumentHistory?.(); this.#unsubscribeDocumentHistory = undefined; this.#activeDocumentHistory = undefined; this.#documentEditor = undefined
77
+ this.#unsubscribeDocumentSelection?.(); this.#unsubscribeDocumentSelection = undefined
78
+ this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
79
+ this.#pendingDocumentFocus = undefined; this.#pendingDocumentSelection = undefined; this.#generation++
80
+ this.#documentFields.clear(); this.#pendingDocumentField = undefined
81
+ this.#documentEditorCommands = undefined
82
+ }
83
+
84
+ #watchOpeningInteraction(cancel: () => void): () => void {
85
+ if (typeof document === 'undefined') return () => {}
86
+ const focused = document.activeElement, dialog = focused?.closest('[role="dialog"]')
87
+ const interact = (event: Event) => {
88
+ if (!event.isTrusted) return
89
+ if (event.type === 'focusin' && (!(event.target instanceof Element) || event.target === focused || dialog?.contains(event.target))) return
90
+ cancel()
91
+ }
92
+ const events = ['pointerdown', 'keydown', 'beforeinput', 'wheel', 'touchmove', 'focusin']
93
+ for (const event of events) document.addEventListener(event, interact, true)
94
+ return () => { for (const event of events) document.removeEventListener(event, interact, true) }
95
+ }
96
+
97
+ cancelOpening(): void {
98
+ const pending = this.#openingDocument
99
+ this.#openingDocument = undefined
100
+ pending?.stop()
101
+ }
102
+
103
+ beginOpening(directory: string, focus?: 'body', fallback?: DocumentReturnPoint): void {
104
+ this.cancelOpening()
105
+ this.#openingDocument = { directory, focus, fallback: fallback && { ...fallback }, scope: this.#options.scope(), generation: this.#generation,
106
+ stop: this.#watchOpeningInteraction(() => this.cancelOpening()) }
107
+ }
108
+
109
+ saveReturnPoint(): void {
110
+ const source = this.#store.state.authoring, position = this.#store.state.position
111
+ if (!source?.identity || !source.content || source.loading || !position || !source.content.sectionOrder.includes(position.section)) return
112
+ const section = source.content.sections[position.section]
113
+ let stepId = section?.stepOrder[position.step]
114
+ if (this.#store.state.webView === 'present' || position.view === 'present') {
115
+ const snapshot = this.#store.state.presentationSnapshot, ir = this.#store.state.ir
116
+ if (!snapshot || !ir || source.dirty || source.saving || source.error || snapshot.version !== source.version || snapshot.fingerprint !== source.fingerprint
117
+ || snapshot.project !== (source.projectRevision ?? 0) || snapshot.revision !== ir.revision || snapshot.revision !== this.#store.state.previewIrRevision) return
118
+ const ids = ir.doc.sections.find(page => page.id === position.section)?.stepIds
119
+ if (!ids || ids.length && !ids[position.step]) return
120
+ stepId = ids[position.step]
121
+ if (stepId && (!section?.stepOrder.includes(stepId) || source.content.steps[stepId]?.sectionId !== position.section)) return
122
+ }
123
+ if (!section || !stepId && section.stepOrder.length) return
124
+ const viewport = this.#documentViewport, previous = this.#documentReturnPoints.read(source.identity)
125
+ const measured = this.#store.state.webView === 'document' && viewport?.identity === source.identity ? documentViewportOffset(viewport.element, section.id) : undefined
126
+ const offset = measured ?? (previous?.sectionId === section.id ? previous.offset : undefined)
127
+ this.#documentReturnPoints.write(source.identity, { sectionId: section.id, ...stepId ? { stepId } : {}, ...offset !== undefined ? { offset } : {} })
128
+ }
129
+
130
+ finishOpening(): void {
131
+ const pending = this.#openingDocument, source = this.#store.state.authoring
132
+ if (!pending || source?.loading || !source?.identity || !source.content) return
133
+ if (source.error === 'document-identity-changed') { this.cancelOpening(); return }
134
+ if (pending.scope !== this.#options.scope() || pending.directory !== this.#store.state.document || pending.generation !== this.#generation) { this.cancelOpening(); return }
135
+ if (!pending.basis) {
136
+ pending.basis = { identity: source.identity, reset: source.reset, version: source.version, content: source.content }
137
+ if (!pending.focus) {
138
+ pending.point = this.#documentReturnPoints.read(source.identity) ?? pending.fallback
139
+ if (!pending.point) {
140
+ const section = source.content.sections[source.content.sectionOrder[0]!]
141
+ if (!section) { this.cancelOpening(); return }
142
+ pending.point = { sectionId: section.id, ...section.stepOrder[0] ? { stepId: section.stepOrder[0] } : {} }
143
+ pending.initial = true
144
+ }
145
+ if (documentReturnStep(source.content, pending.point) === undefined) {
146
+ this.#documentReturnPoints.forget(source.identity); this.cancelOpening()
147
+ this.#store.set({ documentPositionFailure: 'removed' }); return
148
+ }
149
+ }
150
+ }
151
+ const basis = pending.basis
152
+ if (source.identity !== basis.identity || source.reset !== basis.reset || source.version !== basis.version || source.content !== basis.content) { this.cancelOpening(); return }
153
+ const editor = this.#documentEditor, binding = this.#documentEditorBinding, viewport = this.#documentViewport
154
+ if (!editor || editor.prosemirrorView.isDestroyed || binding?.identity !== source.identity || binding.reset !== source.reset || viewport?.identity !== source.identity) return
155
+ // The editor can mount read-only while the source is still loading; a read-only body cannot take the caret yet.
156
+ if (pending.focus && !editor.isEditable) return
157
+ this.cancelOpening()
158
+ if (pending.focus) {
159
+ const body = (blocks: typeof editor.document, sectionId?: string): { nodeId: string, sectionId: string } | undefined => {
160
+ for (const block of blocks) {
161
+ if (block.type === 'presmiumPage') sectionId = block.props.sectionId
162
+ else if (sectionId && editor.schema.blockSchema[block.type].content === 'inline') return { nodeId: block.id, sectionId }
163
+ const nested = body(block.children, sectionId)
164
+ if (nested) return nested
165
+ }
166
+ }
167
+ const target = body(editor.document)
168
+ if (target && source.content.sections[target.sectionId]) {
169
+ this.#store.set({ position: { section: target.sectionId, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: undefined })
170
+ this.#focusDocumentNode(editor, target.nodeId)
171
+ }
172
+ return
173
+ }
174
+ const point = pending.point!, step = documentReturnStep(source.content, point)
175
+ if (step === undefined) return
176
+ this.#options.rememberStep(pending.directory, point.sectionId, step)
177
+ this.#store.set({ position: { section: point.sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: undefined })
178
+ if (pending.initial) return
179
+ const current = () => this.#store.state.document === pending.directory && this.#store.state.authoring?.identity === basis.identity
180
+ && this.#store.state.authoring.reset === basis.reset && this.#store.state.authoring.version === basis.version && this.#store.state.authoring.content === basis.content
181
+ && this.#documentViewport === viewport && this.#store.state.position?.section === point.sectionId && this.#store.state.position.step === step
182
+ const restore = () => {
183
+ if (!current()) { stop(); return }
184
+ const top = viewport.element.scrollTop
185
+ restoreDocumentViewport(viewport.element, point)
186
+ if (viewport.element.scrollTop !== top) viewport.returnScrollTop = viewport.element.scrollTop
187
+ }
188
+ const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(restore)
189
+ let stopInteraction: () => void = () => {}
190
+ const stop = () => { observer?.disconnect(); stopInteraction(); viewport.returnScrollTop = undefined; if (this.#stopDocumentReturnScroll === stop) this.#stopDocumentReturnScroll = undefined }
191
+ this.#stopDocumentReturnScroll?.(); this.#stopDocumentReturnScroll = stop
192
+ stopInteraction = this.#watchOpeningInteraction(stop)
193
+ observer?.observe(viewport.element)
194
+ observer?.observe(editor.prosemirrorView.dom)
195
+ restore()
196
+ }
197
+
198
+ /** Consume only this viewport owner's actual programmatic destination; user gestures retire it. */
199
+ consumeReturnScroll(element: HTMLElement): boolean {
200
+ const viewport = this.#documentViewport, top = viewport?.returnScrollTop
201
+ if (viewport?.element !== element || top === undefined) return false
202
+ viewport.returnScrollTop = undefined
203
+ return element.scrollTop === top
204
+ }
205
+
206
+ attachViewport(element: HTMLElement, identity: string): () => void {
207
+ this.#documentViewport?.stop()
208
+ const scroll = () => { if (!this.#openingDocument) this.saveReturnPoint() }
209
+ const viewport = { element, identity, stop: () => element.removeEventListener('scroll', scroll) }
210
+ this.#documentViewport = viewport
211
+ element.addEventListener('scroll', scroll, { passive: true })
212
+ this.finishOpening()
213
+ return () => { if (this.#documentViewport === viewport) { this.saveReturnPoint(); this.#stopDocumentReturnScroll?.(); this.#documentViewport = undefined }; viewport.stop() }
214
+ }
215
+
216
+ /** The body editor became editable: an opening that waits to put the caret in it can finish now. */
217
+ editorEditable(): void { this.finishOpening() }
218
+
219
+
220
+ interact(): void {
221
+ this.#generation++; this.cancelOpening(); this.#stopDocumentReturnScroll?.()
222
+ if (this.#store.state.documentPositionFailure) this.#store.set({ documentPositionFailure: undefined })
223
+ }
224
+ pendingField(blockId: string | undefined, identity?: string): Pick<DocumentFieldRegistration, 'stepId'> | undefined {
225
+ const pending = this.#pendingDocumentField, source = this.#store.state.authoring
226
+ return pending && pending.generation === this.#generation && pending.field.blockId === blockId
227
+ && pending.field.identity === (identity ?? source?.identity) && pending.reset === source?.reset ? pending.field : undefined
228
+ }
229
+ /** A live native field owns its target only while it still has focus in this source. */
230
+ focusedField(): Readonly<Pick<DocumentFieldRegistration, 'identity' | 'reset' | 'blockId' | 'stepId'>> & { readonly editor: DocumentHistoryEditor } | undefined {
231
+ const source = this.#store.state.authoring, editor = this.#activeDocumentHistory
232
+ if (!source?.identity || !source.content || !editor || editor === this.#documentEditor || editor.prosemirrorView.isDestroyed || !editor.prosemirrorView.hasFocus()) return
233
+ for (const field of this.#documentFields.values()) {
234
+ if (field.editor !== editor || field.identity !== source.identity || field.reset !== source.reset) continue
235
+ const step = source.content.steps[field.stepId], section = step && source.content.sections[step.sectionId]
236
+ if (!step || !section?.stepOrder.includes(field.stepId)) return
237
+ const { identity, reset, blockId, stepId } = field
238
+ return { identity, reset, blockId, stepId, editor }
239
+ }
240
+ return undefined
241
+ }
242
+ registerField(field: DocumentFieldRegistration): () => void {
243
+ if (field.identity !== this.#store.state.authoring?.identity || field.reset !== this.#store.state.authoring.reset) return () => {}
244
+ const key = JSON.stringify([field.identity, field.blockId, field.stepId])
245
+ this.#documentFields.set(key, field)
246
+ const pending = this.#pendingDocumentField
247
+ if (pending && pending.reset === field.reset && JSON.stringify([pending.field.identity, pending.field.blockId, pending.field.stepId]) === key) {
248
+ this.#pendingDocumentField = undefined
249
+ if (pending.generation === this.#generation && field.identity === this.#store.state.authoring?.identity && field.reset === this.#store.state.authoring.reset) field.focus.restore(pending.bookmark)
250
+ }
251
+ return () => {
252
+ if (this.#documentFields.get(key) !== field) return
253
+ this.#documentFields.delete(key)
254
+ if (field.editor && this.#activeDocumentHistory === field.editor) this.activateHistory(this.#documentEditor)
255
+ }
256
+ }
257
+ /** Toolbar commands use the focused native editor's own history, without replacing the body editor. */
258
+ activateHistory(editor: DocumentHistoryEditor | undefined): void {
259
+ if (editor && editor !== this.#documentEditor && ![...this.#documentFields.values()].some(field => field.editor === editor && field.identity === this.#store.state.authoring?.identity)) return
260
+ if (editor === this.#activeDocumentHistory) return
261
+ this.#unsubscribeDocumentHistory?.()
262
+ this.#activeDocumentHistory = editor
263
+ const update = () => this.#store.set({ editorHistory: editor ? { section: this.#store.state.position?.section ?? '', undo: undoDepth(editor.prosemirrorState) > 0, redo: redoDepth(editor.prosemirrorState) > 0, field: editor !== this.#documentEditor } : undefined })
264
+ this.#unsubscribeDocumentHistory = editor?.onChange(update)
265
+ update()
266
+ }
267
+ attachEditor(editor: NativeDocumentEditor | undefined, commands?: DocumentEditorCommands, binding?: { identity: string, reset: number }): void {
268
+ if (binding && (binding.identity !== this.#store.state.authoring?.identity || binding.reset !== this.#store.state.authoring.reset)) return
269
+ const wasBody = !this.#activeDocumentHistory || this.#activeDocumentHistory === this.#documentEditor
270
+ if (editor !== this.#documentEditor) this.#session.composition(false, 'body')
271
+ this.#unsubscribeDocumentSelection?.(); this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
272
+ this.#documentEditor = editor; this.#documentEditorCommands = commands; this.#documentEditorBinding = editor ? binding : undefined
273
+ if (editor) {
274
+ const focus = this.#pendingDocumentFocus, selection = this.#pendingDocumentSelection
275
+ this.#pendingDocumentFocus = undefined; this.#pendingDocumentSelection = undefined
276
+ if (focus && focus.documentId === this.#store.state.authoring?.content?.id && focus.generation === this.#generation && editor.getBlock(focus.nodeId)) {
277
+ // A deferred page operation adopts its selection only after the source write is acknowledged.
278
+ if (!focus.afterSave) {
279
+ this.#focusDocumentNode(editor, focus.nodeId)
280
+ }
281
+ } else if (!this.#pendingDocumentField && selection && selection.documentId === this.#store.state.authoring?.content?.id) {
282
+ const anchor = nativeTextPosition(editor, selection.anchor), head = nativeTextPosition(editor, selection.head)
283
+ if (anchor !== undefined && head !== undefined) {
284
+ editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, anchor, head)))
285
+ if (selection.focused) editor.focus()
286
+ }
287
+ }
288
+ }
289
+ if (wasBody) this.activateHistory(editor)
290
+ if (editor) {
291
+ const focus = () => this.activateHistory(editor)
292
+ const element = editor.prosemirrorView.dom
293
+ element.addEventListener('focusin', focus)
294
+ if (editor.prosemirrorView.hasFocus()) focus()
295
+ const stopSelection = editor.onSelectionChange(() => { this.#generation++ })
296
+ this.#unsubscribeDocumentSelection = () => { this.#stopDocumentLayoutScroll?.(); stopSelection(); element.removeEventListener('focusin', focus) }
297
+ commands?.handleAnimationRequests({ available: () => this.#options.canAskAnimation(), request: place => this.#options.askAnimation(place) })
298
+ } else this.#unsubscribeDocumentSelection = undefined
299
+ this.finishOpening()
300
+ }
301
+ /** `selectText`: the node's whole text is selected, so typing replaces it. */
302
+ #focusDocumentNode(editor: NativeDocumentEditor, nodeId: string, selectText = false): void {
303
+ this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
304
+ editor.setTextCursorPosition(nodeId, 'start')
305
+ const text = selectText ? nativeBlockText(editor, nodeId) : undefined
306
+ if (text) editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, text.from, text.to)))
307
+ editor.focus()
308
+ editor.prosemirrorView.dispatch(editor.prosemirrorState.tr.scrollIntoView())
309
+ // React node views can finish sizing after the native editor mounts.
310
+ // Keep only this untouched focus visible through those layout changes.
311
+ if (typeof ResizeObserver !== 'undefined') {
312
+ const view = editor.prosemirrorView, document = view.dom.ownerDocument
313
+ const source = this.#store.state.authoring!, identity = source.identity, reset = source.reset, documentId = source.content!.id
314
+ const request = this.#store.state.documentNavigation?.request, selected = editor.prosemirrorState.selection
315
+ let size = view.dom.getBoundingClientRect(), active = true
316
+ const events = ['pointerdown', 'wheel', 'touchmove', 'keydown', 'beforeinput']
317
+ const cancel = () => {
318
+ if (!active) return
319
+ active = false; observer.disconnect(); stopFocus(); stopSelection()
320
+ for (const event of events) document.removeEventListener(event, interact, true)
321
+ }
322
+ const interact = (event: Event) => { if (event.isTrusted) cancel() }
323
+ const stopFocus = editor.onFocusChange((_, { focused }) => { if (!focused) cancel() })
324
+ const stopSelection = editor.onSelectionChange(cancel)
325
+ const observer = new ResizeObserver(() => {
326
+ if (!active) return
327
+ const current = this.#store.state.authoring
328
+ if (this.#documentEditor !== editor || view.isDestroyed || !current || current.identity !== identity || current.reset !== reset
329
+ || current?.content?.id !== documentId || this.#store.state.documentNavigation?.request !== request
330
+ || !editor.isFocused() || !editor.prosemirrorState.selection.eq(selected) || editor.getTextCursorPosition().block.id !== nodeId) { cancel(); return }
331
+ const next = view.dom.getBoundingClientRect()
332
+ if (next.width === size.width && next.height === size.height) return
333
+ size = next
334
+ view.dispatch(editor.prosemirrorState.tr.scrollIntoView())
335
+ })
336
+ for (const event of events) document.addEventListener(event, interact, true)
337
+ observer.observe(view.dom)
338
+ this.#stopDocumentLayoutScroll = cancel
339
+ }
340
+ }
341
+
342
+ async #changeDocumentPage(change: (document: TeachingDocument) => void): Promise<boolean> {
343
+ const source = this.#store.state.authoring, directory = this.#store.state.document
344
+ if (!source?.content || directory === undefined || isAgentChanging(this.#store.state)) return false
345
+ const scope = this.#options.scope(), identity = source.identity, documentId = source.content.id
346
+ const current = () => scope === this.#options.scope() && directory === this.#store.state.document && identity === this.#store.state.authoring?.identity && documentId === this.#store.state.authoring?.content?.id
347
+ this.#store.set({ isEditingPage: true, pageEditFailure: undefined })
348
+ try {
349
+ await this.#options.flush()
350
+ if (!current()) throw new Error('page-context-changed')
351
+ const document = structuredClone(this.#store.state.authoring!.content!)
352
+ change(document)
353
+ const editor = this.#documentEditor
354
+ this.#pendingDocumentField = undefined
355
+ const plannedFocus = this.#pendingDocumentFocus
356
+ if (!plannedFocus || plannedFocus.generation !== this.#generation) for (const field of this.#documentFields.values()) {
357
+ if (field.identity !== source.identity || field.reset !== this.#store.state.authoring!.reset || field.blockId !== undefined && !document.blocks[field.blockId] || !document.steps[field.stepId]) continue
358
+ const bookmark = field.focus.capture()
359
+ if (bookmark) {
360
+ const { focus: _focus, editor: _editor, ...target } = field
361
+ this.#pendingDocumentField = { field: target, bookmark, reset: this.#store.state.authoring!.reset + 1, generation: this.#generation }
362
+ this.#pendingDocumentSelection = undefined
363
+ break
364
+ }
365
+ }
366
+ if (editor && !this.#pendingDocumentField) {
367
+ const state = editor.prosemirrorState, anchor = nativeTextPoint(editor, state.selection.anchor), head = nativeTextPoint(editor, state.selection.head)
368
+ if (anchor && head) this.#pendingDocumentSelection = { documentId: document.id, anchor, head, focused: editor.prosemirrorView.hasFocus() }
369
+ }
370
+ this.#session.replace(document)
371
+ await this.#session.flush()
372
+ return current()
373
+ } catch (error) { if (current()) this.#store.set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
374
+ finally { if (current()) this.#store.set({ isEditingPage: false }) }
375
+ }
376
+ renamePage(section: string, title: string): Promise<boolean> {
377
+ return this.#changeDocumentPage(document => { Object.assign(document, renameDocumentPage(document, section, title)) })
378
+ }
379
+ async duplicatePage(section: string): Promise<boolean> {
380
+ if (this.#store.state.isEditingPage || this.#store.state.isCreatingPage || this.#store.state.isHistoryBusy) return false
381
+ const scope = this.#options.scope(), identity = this.#store.state.authoring?.identity, generation = this.#generation, navigation = this.#store.state.documentNavigation?.request
382
+ let copied: string | undefined
383
+ const saved = await this.#changeDocumentPage(document => {
384
+ if (scope !== this.#options.scope() || identity !== this.#store.state.authoring?.identity) throw new Error('page-context-changed')
385
+ const page = document.sections[section]
386
+ if (!page) throw new Error('page-boundary')
387
+ const copy = duplicateDocumentPage(document, section, contentText(document.metadata.lang).copyTitle(page.title), () => randomUUID())
388
+ copied = copy.section
389
+ Object.assign(document, copy.document)
390
+ if (generation === this.#generation) this.#pendingDocumentFocus = { documentId: document.id, nodeId: `page:${copied}`, generation, afterSave: true }
391
+ })
392
+ // Source confirmation owns editing. A later author selection takes precedence over this response.
393
+ if (!saved || !copied || scope !== this.#options.scope() || generation !== this.#generation || navigation !== this.#store.state.documentNavigation?.request || !this.#store.state.authoring?.content?.sections[copied]) return saved
394
+ this.#options.goToSection(copied)
395
+ const editor = this.#documentEditor
396
+ if (editor) {
397
+ const blocks = editor.document, start = blocks.findIndex(block => block.id === `page:${copied}`)
398
+ const first = (nodes: typeof blocks): string | undefined => {
399
+ 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 }
400
+ return undefined
401
+ }
402
+ const target = start < 0 ? undefined : first(blocks.slice(start + 1)) ?? blocks[start]!.id
403
+ if (target) { editor.setTextCursorPosition(target, 'start'); editor.focus() }
404
+ }
405
+ return true
406
+ }
407
+ movePage(section: string, before: string | null): Promise<boolean> {
408
+ return this.#changeDocumentPage(document => { Object.assign(document, moveDocumentPage(document, section, before)) })
409
+ }
410
+ deletionMessage(reason: string): string { return this.#pageEditMessage(reason) }
411
+ async preparePageDeletion(section: string): Promise<PageDeletePlan> {
412
+ await this.#options.flush()
413
+ const source = this.#store.state.authoring
414
+ if (!source?.content || !source.version || this.#store.state.document === undefined) throw new Error('document-unavailable')
415
+ return pageDeletion(source.content, this.#store.state.document, source.version, section)
416
+ }
417
+ async deletePage(plan: PageDeletePlan): Promise<boolean> {
418
+ if (!plan.allowed || plan.document !== this.#store.state.document) return false
419
+ return this.#changeDocumentPage(document => {
420
+ if (this.#store.state.authoring?.version !== plan.source.version) throw new Error('revision-conflict')
421
+ const current = pageDeletion(document, plan.document, plan.source.version, plan.section)
422
+ if (!current.allowed) throw new Error(current.reason)
423
+ Object.assign(document, removeDocumentPage(document, plan.section, () => randomUUID()))
424
+ this.#store.set({ position: { section: document.sectionOrder[0]!, step: 0, trail: [], view: 'document' }, documentNavigation: { section: document.sectionOrder[0]!, request: randomUUID() } })
425
+ })
426
+ }
427
+ createPage(after = this.#store.state.position?.section): boolean {
428
+ const source = this.#store.state.authoring, editor = this.#documentEditor, commands = this.#documentEditorCommands
429
+ if (!source?.content || source.loading || source.composing || source.restored || source.error || !editor || !commands
430
+ || editor.prosemirrorView.isDestroyed || isAgentChanging(this.#store.state) || this.#store.state.isEditingPage || this.#store.state.isCreatingPage
431
+ || this.#store.state.isHistoryBusy || this.#store.state.isHistoryPreparing) return false
432
+ try {
433
+ this.#store.set({ pageEditFailure: undefined })
434
+ const created = commands.insertPage(after, contentText(source.content.metadata.lang).newPage)
435
+ this.#pendingDocumentField = undefined; this.#pendingDocumentSelection = undefined; this.#pendingDocumentFocus = undefined
436
+ this.#store.set({ position: { section: created.sectionId, step: 0, trail: [], view: 'document' }, documentNavigation: { section: created.sectionId, request: randomUUID() } })
437
+ // The default title is selected: the author's first words name the page, and Enter goes on to its body.
438
+ this.#focusDocumentNode(editor, `page:${created.sectionId}`, true)
439
+ return true
440
+ } catch (error) { this.#store.set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
441
+ }
442
+
443
+
444
+ #pageEditMessage(reason: string): string {
445
+ const t = MESSAGES[this.#store.state.locale]
446
+ if (reason === 'native-unavailable') return t.nativeEditUnavailable
447
+ if (reason.startsWith('native-')) return t.nativeEditDraft
448
+ switch (reason) {
449
+ case 'page-multiple-files': return t.pageEditFiles
450
+ case 'page-boundary': return t.pageEditBoundary
451
+ case 'page-hierarchy': return t.pageEditHierarchy
452
+ case 'page-implicit-title': return t.pageEditImplicitTitle
453
+ case 'page-formatted-title': return t.pageEditFormattedTitle
454
+ case 'page-title': return t.pageEditInvalidTitle
455
+ case 'page-compiler': return t.pageEditCompiler
456
+ case 'page-referenced': return t.pageDeleteReferenced
457
+ case 'page-external-bindings': return t.pageDeleteExternalBindings
458
+ case 'page-references-unavailable': return t.pageDeleteReferencesUnavailable
459
+ case 'page-busy': return t.pageEditBusy
460
+ case 'preview-flush-unavailable': return t.pageEditPreview
461
+ case 'page-context-changed': return t.pageEditChanged
462
+ case 'save-timeout': return t.pageEditFlushTimeout
463
+ case 'source-draft': return t.pageEditSourceDraft
464
+ case 'source-refresh': return t.pageEditRefresh
465
+ case 'page-draft':
466
+ case 'source-conflict':
467
+ case 'narration-conflict':
468
+ case 'revision-conflict': return t.pageEditDraft
469
+ case 'save-locked': return t.saveLocked
470
+ default: return t.pageEditRequestFailed
471
+ }
472
+ }
473
+
474
+ pageCapability(section: string): { rename: boolean, move: boolean, reason?: string } {
475
+ const exists = Boolean(this.#store.state.authoring?.content?.sections[section])
476
+ const capability = { rename: exists, move: exists }
477
+ if (isAgentChanging(this.#store.state)) return { rename: false, move: false, reason: MESSAGES[this.#store.state.locale].saveLocked }
478
+ if (this.#store.state.isCreatingPage || this.#store.state.isEditingPage || this.#store.state.isHistoryBusy) return { rename: false, move: false, reason: MESSAGES[this.#store.state.locale].pageEditBusy }
479
+ return capability
480
+ }
481
+
482
+ clearFailure(): void { this.#store.set({ pageEditFailure: undefined }) }
483
+
484
+ }
@@ -3,7 +3,7 @@ import { applyDocumentComponentAction, effectiveComponentParameters, isRecord, r
3
3
  import type { CanonicalSource, DocumentComponentAction, DocumentParameterValidation, JsonObject, TeachingDocument } from '@lincyaw/kernel'
4
4
  import { PmButton, PmDialog, PmNotice, PmSelect } from '../components.tsx'
5
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
6
- import { isAgentChanging } from '../workbench.ts'
6
+ import { isAgentChanging } from '../workbench-state.ts'
7
7
  import { COMPONENT_PROPERTY_MESSAGES } from '../component-property-messages.ts'
8
8
  import type { ComponentPropertyMessages } from '../component-property-messages.ts'
9
9
  import { componentPropertyAction, componentSource, rebaseComponentPropertyDraft, sameComponentSource } from '../component-properties.ts'
@@ -30,8 +30,8 @@ export function DocumentBlockPreview({ blockId, fallback }: { blockId: string, f
30
30
  const sectionId = source?.content && documentBlockSection(source.content, blockId)
31
31
  const section = sectionId ? source?.content?.sections[sectionId] : undefined
32
32
  const stepId = section?.stepOrder[position && position.section === sectionId ? position.step : 0] ?? section?.stepOrder[0]
33
- const [narrationOpen, setNarrationOpen] = useState(() => Boolean(workbench.pendingDocumentField(blockId, source?.identity)
34
- || source?.identity && stepId && (workbench.documentTimingDraft(stepId, 'minimumHoldMs', source.identity, source.reset) || workbench.documentTimingDraft(stepId, 'trailingPauseMs', source.identity, source.reset)))), narrationPanel = useId()
33
+ const [narrationOpen, setNarrationOpen] = useState(() => Boolean(workbench.editing.pendingField(blockId, source?.identity)
34
+ || source?.identity && stepId && (workbench.production.timingDraft(stepId, 'minimumHoldMs', source.identity, source.reset) || workbench.production.timingDraft(stepId, 'trailingPauseMs', source.identity, source.reset)))), narrationPanel = useId()
35
35
  const root = useRef<HTMLElement>(null), viewport = useRef<HTMLDivElement>(null), frame = useRef<HTMLIFrameElement | null>(null)
36
36
  const mountFrame = useCallback((element: HTMLIFrameElement | null) => {
37
37
  frame.current = element
@@ -3,7 +3,7 @@ import type { Narration, NarrationNode, TeachingDocument } from '@lincyaw/kernel
3
3
  import { randomUUID } from '@lincyaw/kernel'
4
4
  import { PmIconButton } from '../components.tsx'
5
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
6
- import { isAgentChanging } from '../workbench.ts'
6
+ import { isAgentChanging } from '../workbench-state.ts'
7
7
  import { NarrationEditor } from './NarrationEditor.tsx'
8
8
  import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
9
9
  import { narrationFieldFocus, narrationsToNative, nativeToNarrations } from './narration.ts'
@@ -43,13 +43,13 @@ function NarrationField({ identity, reset, blockId, stepId, content, readOnly, a
43
43
  const retained = new Set(Object.values(document?.steps ?? {}).filter(step => step.id !== stepId).flatMap(step => step.narrationIds))
44
44
  return new Map([...retained].flatMap(id => document!.narrations[id]!.content.flatMap(node => node.type === 'cue' ? [[node.id, id] as const] : [])))
45
45
  }}
46
- onCueCopy={(from, to) => workbench.copyNarrationCueTiming(from, to, identity)}
46
+ onCueCopy={(from, to) => workbench.production.copyNarrationCueTiming(from, to, identity)}
47
47
  onReady={editor => {
48
48
  registration.current?.()
49
49
  fieldEditor.current = editor
50
- registration.current = editor ? workbench.registerDocumentField({ identity, reset, blockId, stepId, focus: narrationFieldFocus(editor), editor }) : undefined
50
+ registration.current = editor ? workbench.editing.registerField({ identity, reset, blockId, stepId, focus: narrationFieldFocus(editor), editor }) : undefined
51
51
  }}
52
- onFocus={() => { workbench.documentInteraction(); if (fieldEditor.current) workbench.activateDocumentHistory(fieldEditor.current); onPause() }} onChange={value => workbench.setDocumentNarrations(stepId, value, identity)}
52
+ onFocus={() => { workbench.editing.interact(); if (fieldEditor.current) workbench.editing.activateHistory(fieldEditor.current); onPause() }} onChange={value => workbench.production.setNarrations(stepId, value, identity)}
53
53
  onComposition={composing => workbench.documentComposition(composing, owner, identity)}
54
54
  onError={error => workbench.documentError(error)} />
55
55
  }
@@ -83,15 +83,15 @@ export function DocumentStepNarration({ blockId, sectionId, stepId, expanded, ad
83
83
  {!expanded && text && <p className="pm-ui-block-preview__caption" data-step-caption={stepId}>{text}</p>}
84
84
  {expanded && <div id={panelId} className="pm-ui-block-preview__narration-fields">
85
85
  {showLabel && <span className="pm-ui-block-preview__step-label">{fieldLabel}</span>}
86
- <NarrationField key={`${source.identity}:${source.reset}:${stepId}`}
86
+ <NarrationField key={`narration:${source.identity}:${source.reset}:${stepId}`}
87
87
  identity={source.identity!} reset={source.reset} blockId={blockId} stepId={stepId}
88
88
  content={ids.map(id => ({ id, content: document.narrations[id]!.content }))} readOnly={readOnly} advanced={advanced} onPause={onPause} />
89
- <StepProductionEditor key={`${source.identity}:${source.reset}:${stepId}`} document={document} stepId={stepId} locale={locale} readOnly={readOnly} advanced={advanced}
90
- onPause={onPause} onInteraction={() => workbench.documentInteraction()}
91
- onChange={patch => workbench.setDocumentStepProduction(stepId, patch, source.identity)}
92
- drafts={{ minimumHoldMs: workbench.documentTimingDraft(stepId, 'minimumHoldMs', source.identity, source.reset), trailingPauseMs: workbench.documentTimingDraft(stepId, 'trailingPauseMs', source.identity, source.reset) }}
89
+ <StepProductionEditor key={`timing:${source.identity}:${source.reset}:${stepId}`} document={document} stepId={stepId} locale={locale} readOnly={readOnly} advanced={advanced}
90
+ onPause={onPause} onInteraction={() => workbench.editing.interact()}
91
+ onChange={patch => workbench.production.setStepTiming(stepId, patch, source.identity)}
92
+ drafts={{ minimumHoldMs: workbench.production.timingDraft(stepId, 'minimumHoldMs', source.identity, source.reset), trailingPauseMs: workbench.production.timingDraft(stepId, 'trailingPauseMs', source.identity, source.reset) }}
93
93
  draftStorageFailure={timingStorageFailure}
94
- onDraft={(key, draft) => workbench.setDocumentTimingDraft(stepId, key, draft, source.identity!, source.reset)}
94
+ onDraft={(key, draft) => workbench.production.setTimingDraft(stepId, key, draft, source.identity!, source.reset)}
95
95
  onComposition={(key, composing) => workbench.documentComposition(composing, `production:${source.identity}:${source.reset}:${blockId}:${stepId}:${key}`, source.identity)} />
96
96
  </div>}
97
97
  </section>