@lincyaw/workbench 0.2.0-rc.5 → 0.2.0-rc.50

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 (79) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +1 -1
  3. package/src/audio-recording.ts +27 -5
  4. package/src/authoring-client.ts +10 -10
  5. package/src/authoring-draft-fragment.ts +3 -1
  6. package/src/body-draft-actions.ts +60 -0
  7. package/src/component-property-drafts.ts +5 -5
  8. package/src/components.tsx +10 -28
  9. package/src/context.tsx +2 -1
  10. package/src/diagnostics.ts +1 -1
  11. package/src/document-draft-store.ts +45 -18
  12. package/src/document-drafts.ts +28 -19
  13. package/src/document-editing.ts +484 -0
  14. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  15. package/src/document-editor/ComponentMaterials.tsx +3 -9
  16. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  17. package/src/document-editor/DocumentBlockPreview.tsx +4 -2
  18. package/src/document-editor/DocumentComments.tsx +58 -9
  19. package/src/document-editor/DocumentEditor.tsx +44 -7
  20. package/src/document-editor/DocumentStepNarration.tsx +30 -25
  21. package/src/document-editor/NarrationEditor.tsx +54 -20
  22. package/src/document-editor/NewCommentDrafts.tsx +4 -3
  23. package/src/document-editor/PlaceComment.tsx +150 -0
  24. package/src/document-editor/comment-drafts.ts +16 -14
  25. package/src/document-editor/comments.ts +30 -10
  26. package/src/document-editor/component-label.ts +11 -0
  27. package/src/document-editor/file-input.ts +2 -2
  28. package/src/document-editor/focus.ts +0 -2
  29. package/src/document-editor/insertion-place.ts +60 -0
  30. package/src/document-editor/messages.ts +3 -3
  31. package/src/document-editor/narration-schema.tsx +12 -6
  32. package/src/document-editor/narration.ts +19 -3
  33. package/src/document-editor/page-body.ts +60 -0
  34. package/src/document-editor/projection.ts +2 -2
  35. package/src/document-editor/rich-text.ts +3 -2
  36. package/src/document-editor/selection.ts +13 -0
  37. package/src/document-editor/style.css +12 -1
  38. package/src/document-editor/table-identities.ts +2 -1
  39. package/src/document-production.ts +331 -0
  40. package/src/document-session.ts +190 -51
  41. package/src/history.ts +3 -3
  42. package/src/index.ts +5 -5
  43. package/src/jobs.ts +1 -1
  44. package/src/messages.ts +19 -4
  45. package/src/panels/DocumentView.tsx +66 -26
  46. package/src/panels/DocumentVoiceDialog.tsx +2 -2
  47. package/src/panels/DocumentVoiceField.tsx +1 -1
  48. package/src/panels/ExportPanel.tsx +1 -6
  49. package/src/panels/HistoryPanel.tsx +1 -1
  50. package/src/panels/PageDeleteDialog.tsx +4 -4
  51. package/src/panels/PageRenameDialog.tsx +1 -1
  52. package/src/panels/PreviewPanel.tsx +1 -4
  53. package/src/panels/ProductionCaptionSize.tsx +20 -0
  54. package/src/panels/ProductionCaptionTiming.tsx +7 -7
  55. package/src/panels/ProductionMediaClips.tsx +6 -5
  56. package/src/panels/ProductionPanel.tsx +8 -4
  57. package/src/panels/ProductionRecording.tsx +86 -9
  58. package/src/panels/ProductionRecordingRange.tsx +4 -4
  59. package/src/panels/ProductionTimeline.tsx +6 -1
  60. package/src/panels/ProductionTranscription.tsx +5 -4
  61. package/src/panels/SourceDocumentPanel.tsx +12 -15
  62. package/src/panels/TranscriptionAdoption.tsx +9 -8
  63. package/src/panels/VoiceCloneDialog.tsx +2 -1
  64. package/src/panels/VoiceoverDialog.tsx +1 -1
  65. package/src/places.ts +1 -36
  66. package/src/preview-playback.ts +1 -1
  67. package/src/production-messages.ts +6 -0
  68. package/src/production-playback.ts +1 -1
  69. package/src/production-voice-playback.ts +3 -2
  70. package/src/sha256.ts +9 -0
  71. package/src/styles.css +16 -41
  72. package/src/use-recording-adoption.ts +2 -2
  73. package/src/voiceover-jobs.ts +1 -1
  74. package/src/workbench-state.ts +157 -0
  75. package/src/workbench.ts +177 -943
  76. package/src/workspace-client.ts +6 -5
  77. package/src/assistant-mascot.ts +0 -62
  78. package/src/mascot-preference.ts +0 -37
  79. package/src/panels/ChangeTrail.tsx +0 -79
@@ -1,7 +1,8 @@
1
- import { isRecord, validateDocument } from '@lincyaw/kernel'
1
+ import { isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
2
  import type { TeachingDocument } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from './document-draft-store.ts'
4
- import type { DraftStoreCommit } from './document-draft-store.ts'
4
+ import { sha256 as tokenOf } from './sha256.ts'
5
+ import type { DraftStoreCommit, DraftStoreOperation } from './document-draft-store.ts'
5
6
 
6
7
  export interface DocumentDraftReference { id: string, revision: number, token: string }
7
8
  export interface DocumentDraft {
@@ -45,36 +46,36 @@ function documentDraft(value: unknown, documentId: string): DocumentDraft | unde
45
46
  return { content: checked.document, baseVersion: value.baseVersion, baseHash: value.baseHash, input: value.input,
46
47
  pendingHash: value.pendingHash, composing: value.composing, origins: value.origins }
47
48
  }
48
- async function tokenOf(raw: string): Promise<string> {
49
- const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw))
50
- return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
51
- }
52
49
 
53
50
  /** Strictly committed document backups, with old localStorage copies identified as unconfirmed rescue material. */
54
51
  export class DocumentDrafts {
55
- readonly #owner = crypto.randomUUID()
52
+ readonly #owner = randomUUID()
56
53
  readonly #owned = new Map<string, { identity: string, revision: number, raw: string }>()
57
54
  #store?: DocumentDraftStore
58
55
  #identity?: string
59
56
  #closed = false
57
+ #revision = 0
58
+ get revision(): number { return this.#revision }
59
+ #touch(): void { if (!this.#closed) { this.#revision++; this.#changed?.() } }
60
60
  readonly #changed?: () => void
61
61
  constructor(changed?: () => void) { this.#changed = changed }
62
62
 
63
63
  #storage(identity: string): DocumentDraftStore | undefined {
64
64
  if (this.#closed || this.#identity !== undefined && this.#identity !== identity) return
65
65
  this.#identity = identity
66
- return this.#store ??= new DocumentDraftStore(identity, this.#changed)
66
+ return this.#store ??= new DocumentDraftStore(identity, () => this.#touch())
67
67
  }
68
68
  matches(identity: string, key: string | null): boolean { return key === null || key.startsWith(prefix(identity)) || key.startsWith(markerPrefix(identity)) }
69
69
 
70
- async read(identity: string, documentId: string): Promise<{ records: RecoverableDocumentDraft[], failed: boolean }> {
70
+ async read(identity: string, documentId: string, signal?: AbortSignal): Promise<{ records: RecoverableDocumentDraft[], failed: boolean }> {
71
+ signal?.throwIfAborted()
71
72
  const store = this.#storage(identity), values: { key: string, raw: unknown, source: 'durable' | 'rescue' }[] = []
72
73
  let failed = false, durable = new Map<string, unknown>()
73
74
  if (!store) return { records: [], failed: true }
74
75
  try {
75
- durable = await store.read([prefix(identity), markerPrefix(identity)])
76
+ durable = await store.read([prefix(identity), markerPrefix(identity)], signal, signal ? 2048 : undefined)
76
77
  for (const [key, raw] of durable) if (key.startsWith(prefix(identity))) values.push({ key, raw, source: 'durable' })
77
- } catch { failed = true }
78
+ } catch { signal?.throwIfAborted(); failed = true }
78
79
  // Existing localStorage input is never removed or silently treated as a strict commit.
79
80
  try {
80
81
  const keys: string[] = []
@@ -86,9 +87,10 @@ export class DocumentDrafts {
86
87
  const raw = localStorage.getItem(key)
87
88
  if (raw !== null) values.push({ key, raw, source: 'rescue' })
88
89
  }
89
- } catch { failed = true }
90
+ } catch { signal?.throwIfAborted(); failed = true }
90
91
  const records = new Map<string, RecoverableDocumentDraft>()
91
92
  for (const { key, raw, source } of values) {
93
+ signal?.throwIfAborted()
92
94
  try {
93
95
  if (typeof raw !== 'string' || raw.length > MAX_CHARS) throw new Error('document-draft-size')
94
96
  const value: unknown = JSON.parse(raw)
@@ -96,14 +98,17 @@ export class DocumentDrafts {
96
98
  || typeof value.owner !== 'string' || !value.owner || value.owner.length > 200 || typeof value.updatedAt !== 'number' || !Number.isSafeInteger(value.updatedAt) || value.updatedAt < 0 || Number.isNaN(new Date(value.updatedAt).getTime())) throw new Error('document-draft-data')
97
99
  const draft = documentDraft(value, documentId)
98
100
  if (!draft) throw new Error('document-draft-document')
101
+ if (draft.baseHash.startsWith('json:')) draft.baseHash = await tokenOf(draft.baseHash.slice(5))
102
+ if (draft.pendingHash?.startsWith('json:')) draft.pendingHash = await tokenOf(draft.pendingHash.slice(5))
99
103
  const token = await tokenOf(raw), marker = settledKey(identity, { id: value.id, revision: value.revision, token })
100
104
  if (durable.get(marker) === token) continue
101
105
  if (source === 'rescue' && localStorage.getItem(marker) === token) continue
102
106
  const id = JSON.stringify([value.id, value.revision, token])
103
107
  if (!records.has(id)) records.set(id, { ...draft, format: 2, identity, id: value.id, owner: value.owner, revision: value.revision, updatedAt: value.updatedAt, token, source,
104
108
  owned: source === 'durable' && value.owner === this.#owner && (this.#owned.get(value.id)?.raw === raw || store.owns(key, raw)) })
105
- } catch { failed = true }
109
+ } catch { signal?.throwIfAborted(); failed = true }
106
110
  }
111
+ signal?.throwIfAborted()
107
112
  return { records: [...records.values()], failed }
108
113
  }
109
114
 
@@ -113,7 +118,7 @@ export class DocumentDrafts {
113
118
  const owned = previous && this.#owned.get(previous.id)
114
119
  if (previous && (!owned || owned.identity !== identity || previous.owner !== this.#owner || previous.revision !== owned.revision)) return
115
120
  const changed = previous && store.conflicted(keyOf(identity, previous.id))
116
- const record: StoredDocumentDraft = { ...draft, format: 2, identity, id: !changed && previous ? previous.id : crypto.randomUUID(), owner: this.#owner, revision: changed ? 1 : (owned?.revision ?? 0) + 1, updatedAt: Date.now() }
121
+ const record: StoredDocumentDraft = { ...draft, format: 2, identity, id: !changed && previous ? previous.id : randomUUID(), owner: this.#owner, revision: changed ? 1 : (owned?.revision ?? 0) + 1, updatedAt: Date.now() }
117
122
  if (!Number.isSafeInteger(record.revision)) return
118
123
  try { const raw = JSON.stringify(record); return raw.length <= MAX_CHARS ? { record, raw } : undefined }
119
124
  catch { return }
@@ -126,21 +131,25 @@ export class DocumentDrafts {
126
131
  const commit = this.#store!.put(keyOf(identity, next.record.id), next.raw)
127
132
  if (!commit) return
128
133
  this.#owned.set(next.record.id, { identity, revision: next.record.revision, raw: next.raw })
134
+ void commit.done.then(() => this.#touch())
129
135
  if (previous && previous.id !== next.record.id) this.archive(previous)
130
136
  return { ...commit, record: next.record, clearing: false }
131
137
  }
132
138
 
133
- async fork(identity: string, draft: DocumentDraft): Promise<StoredDocumentDraft | undefined> {
139
+ async fork(identity: string, draft: DocumentDraft, operation?: DraftStoreOperation): Promise<StoredDocumentDraft | undefined> {
134
140
  const next = this.#record(identity, draft)
135
- if (!next || !await this.#store!.create(keyOf(identity, next.record.id), next.raw)) return
141
+ if (!next || !await this.#store!.create(keyOf(identity, next.record.id), next.raw, operation)) return
136
142
  this.#owned.set(next.record.id, { identity, revision: next.record.revision, raw: next.raw })
143
+ this.#touch()
137
144
  return next.record
138
145
  }
139
146
 
140
147
  /** Immutable, revision-specific markers never delete another tab's newer record. */
141
- async settle(identity: string, values: readonly DocumentDraftReference[]): Promise<boolean> {
148
+ async settle(identity: string, values: readonly DocumentDraftReference[], operation?: DraftStoreOperation): Promise<boolean> {
142
149
  const store = this.#storage(identity)
143
- return Boolean(store && await store.mark(values.map(value => [settledKey(identity, value), value.token])))
150
+ const done = Boolean(store && await store.mark(values.map(value => [settledKey(identity, value), value.token]), operation))
151
+ if (done) this.#touch()
152
+ return done
144
153
  }
145
154
 
146
155
  remove(identity: string, record: StoredDocumentDraft, origins: readonly DocumentDraftReference[]): DocumentDraftCommit | undefined {
@@ -148,7 +157,7 @@ export class DocumentDrafts {
148
157
  if (!store || !owned || owned.identity !== identity || record.owner !== this.#owner || owned.revision !== record.revision) return
149
158
  const commit = store.remove(keyOf(identity, record.id), origins.map(value => [settledKey(identity, value), value.token]))
150
159
  if (!commit) return
151
- void commit.done.then(result => { if (result === 'committed' && this.#owned.get(record.id)?.revision === record.revision) this.#owned.delete(record.id) })
160
+ void commit.done.then(result => { if (result === 'committed' && this.#owned.get(record.id)?.revision === record.revision) this.#owned.delete(record.id); this.#touch() })
152
161
  return { ...commit, record, clearing: true }
153
162
  }
154
163
 
@@ -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
+ }