@lincyaw/workbench 0.2.0-rc.10 → 0.2.0-rc.100

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 (100) hide show
  1. package/package.json +5 -4
  2. package/src/AgentActivityBar.tsx +25 -0
  3. package/src/MediaClipEditor.tsx +4 -3
  4. package/src/StepProductionEditor.tsx +13 -4
  5. package/src/agent-activity-messages.ts +14 -0
  6. package/src/agent-activity.ts +38 -0
  7. package/src/approvals.tsx +6 -1
  8. package/src/audio-recording.ts +27 -5
  9. package/src/authoring-client.ts +10 -10
  10. package/src/authoring-draft-fragment.ts +3 -1
  11. package/src/authoring-window.ts +100 -0
  12. package/src/body-draft-actions.ts +60 -0
  13. package/src/caption-timing-drafts.ts +18 -1
  14. package/src/component-property-drafts.ts +5 -5
  15. package/src/components.tsx +34 -36
  16. package/src/container-layout.ts +21 -0
  17. package/src/context.tsx +5 -3
  18. package/src/diagnostics.ts +1 -1
  19. package/src/document-draft-store.ts +45 -18
  20. package/src/document-drafts.ts +28 -19
  21. package/src/document-editing.ts +484 -0
  22. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  23. package/src/document-editor/CommentComposer.tsx +24 -0
  24. package/src/document-editor/ComponentMaterials.tsx +3 -9
  25. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  26. package/src/document-editor/DocumentBlockPreview.tsx +11 -4
  27. package/src/document-editor/DocumentComments.tsx +85 -14
  28. package/src/document-editor/DocumentEditor.tsx +56 -7
  29. package/src/document-editor/DocumentStepNarration.tsx +37 -26
  30. package/src/document-editor/NarrationEditor.tsx +54 -20
  31. package/src/document-editor/NewCommentDrafts.tsx +120 -37
  32. package/src/document-editor/PlaceComment.tsx +252 -0
  33. package/src/document-editor/agent-targets.ts +34 -0
  34. package/src/document-editor/blocknote-messages.ts +2 -0
  35. package/src/document-editor/comment-draft-actions.ts +40 -20
  36. package/src/document-editor/comment-draft-inspection.ts +2 -2
  37. package/src/document-editor/comment-drafts.ts +73 -25
  38. package/src/document-editor/comments.ts +30 -10
  39. package/src/document-editor/component-label.ts +11 -0
  40. package/src/document-editor/file-input.ts +2 -2
  41. package/src/document-editor/focus.ts +0 -2
  42. package/src/document-editor/insertion-place.ts +60 -0
  43. package/src/document-editor/messages.ts +3 -3
  44. package/src/document-editor/narration-schema.tsx +12 -6
  45. package/src/document-editor/narration.ts +19 -3
  46. package/src/document-editor/page-body.ts +60 -0
  47. package/src/document-editor/popover.tsx +4 -2
  48. package/src/document-editor/projection.ts +2 -2
  49. package/src/document-editor/rich-text.ts +3 -2
  50. package/src/document-editor/selection.ts +13 -0
  51. package/src/document-editor/style.css +7 -1
  52. package/src/document-editor/table-identities.ts +2 -1
  53. package/src/document-production.ts +491 -0
  54. package/src/document-session.ts +202 -56
  55. package/src/document-timing-drafts.ts +22 -2
  56. package/src/history.ts +5 -5
  57. package/src/index.ts +8 -5
  58. package/src/jobs.ts +1 -1
  59. package/src/media-drafts.ts +43 -1
  60. package/src/messages.ts +31 -14
  61. package/src/panels/DocumentNarrationPanel.tsx +2 -2
  62. package/src/panels/DocumentView.tsx +93 -61
  63. package/src/panels/DocumentVoiceDialog.tsx +25 -9
  64. package/src/panels/DocumentVoiceField.tsx +1 -1
  65. package/src/panels/ExportPanel.tsx +2 -10
  66. package/src/panels/HistoryPanel.tsx +34 -7
  67. package/src/panels/HomePanel.tsx +3 -1
  68. package/src/panels/PageDeleteDialog.tsx +4 -4
  69. package/src/panels/PageRenameDialog.tsx +1 -1
  70. package/src/panels/PreviewPanel.tsx +1 -4
  71. package/src/panels/ProductionCaptionSize.tsx +20 -0
  72. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  73. package/src/panels/ProductionMediaClips.tsx +23 -7
  74. package/src/panels/ProductionPanel.tsx +16 -13
  75. package/src/panels/ProductionRecording.tsx +86 -9
  76. package/src/panels/ProductionRecordingRange.tsx +21 -19
  77. package/src/panels/ProductionTimeline.tsx +6 -1
  78. package/src/panels/ProductionTranscription.tsx +5 -4
  79. package/src/panels/SourceDocumentPanel.tsx +18 -36
  80. package/src/panels/TranscriptionAdoption.tsx +40 -34
  81. package/src/panels/VoiceCloneDialog.tsx +2 -1
  82. package/src/panels/VoiceoverDialog.tsx +1 -1
  83. package/src/places.ts +1 -36
  84. package/src/preview-playback.ts +1 -1
  85. package/src/production-draft-actions.ts +37 -0
  86. package/src/production-messages.ts +6 -0
  87. package/src/production-playback.ts +1 -1
  88. package/src/production-voice-playback.ts +3 -2
  89. package/src/sha256.ts +9 -0
  90. package/src/styles.css +43 -79
  91. package/src/transcription-drafts.ts +124 -0
  92. package/src/use-recording-adoption.ts +2 -2
  93. package/src/voice-drafts.ts +32 -8
  94. package/src/voiceover-jobs.ts +1 -1
  95. package/src/workbench-state.ts +159 -0
  96. package/src/workbench.ts +294 -951
  97. package/src/workspace-client.ts +23 -11
  98. package/src/assistant-mascot.ts +0 -62
  99. package/src/mascot-preference.ts +0 -37
  100. package/src/panels/ChangeTrail.tsx +0 -79
@@ -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
+ }
@@ -1,12 +1,13 @@
1
1
  import { forwardRef, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
2
2
  import type { ForwardRefExoticComponent, ReactNode, RefAttributes } from 'react'
3
+ import { randomUUID } from '@lincyaw/kernel'
3
4
  import { filterSuggestionItems } from '@blocknote/core'
4
5
  import { BlockNoteView, components } from '@blocknote/mantine'
5
6
  import { AddCommentButton, BasicTextStyleButton, BlockNoteViewEditor, BlockTypeSelect, ComponentsContext, CreateLinkButton, FormattingToolbar, FormattingToolbarController, getDefaultReactSlashMenuItems, LinkToolbarController, NestBlockButton, RenderInPortalElement, SideMenuController, SuggestionMenuController, TableCellMergeButton, TableHandlesController, TextAlignButton, UnnestBlockButton, useBlockNoteEditor, useCreateBlockNote, useEditorState } from '@blocknote/react'
6
7
  import type { ComponentProps, FormattingToolbarProps } from '@blocknote/react'
7
8
  import { useMediaQuery } from '@mantine/hooks'
8
9
  import type { Locale } from '../messages.ts'
9
- import { PmIconButton, PmNotice, PmTooltip } from '../components.tsx'
10
+ import { PmIcon, PmIconButton, PmNotice, PmTooltip } from '../components.tsx'
10
11
  import { DOCUMENT_NODE_VIEWS, documentEditorSchema } from './schema.tsx'
11
12
  import type { DocumentEditorBlock, DocumentEditorInput, DocumentNodeViews, NativeDocumentEditor } from './schema.tsx'
12
13
  import { documentSelection } from './selection.ts'
@@ -16,6 +17,7 @@ import { blockNoteDictionary } from './blocknote-messages.ts'
16
17
  import { imageFileInput } from './file-input.ts'
17
18
  import type { ImageImportFailure } from './file-input.ts'
18
19
  import { nativeTextClipboard } from './clipboard.ts'
20
+ import { documentPageBodies, focusDocumentEnd } from './page-body.ts'
19
21
  import { documentBlockColors } from './colors.ts'
20
22
  import { DOCUMENT_EDITOR_LOCALE } from './math.tsx'
21
23
  import { DOCUMENT_LINKS, DocumentColorButton, DocumentLinkToolbar, DocumentSideMenu, DocumentTableCellButton, DocumentTableHandle, FormulaToolbarButton, formulaSlashItems, openDocumentLink } from './authoring.tsx'
@@ -80,10 +82,14 @@ export interface BlockNoteSurfaceProps {
80
82
  commentsPortal?: HTMLElement | null
81
83
  getPositionToken?(): string | undefined
82
84
  onCommentDraftRestore?(): void
85
+ /** The author asked to see the comments pane, e.g. after saving a place comment. */
86
+ onOpenComments?(): void
83
87
  onReady?(editor: NativeDocumentEditor | undefined): void
84
88
  onComposition?(composing: boolean): void
85
89
  /** Shows a page of this document from an in-document link; false when none matches. */
86
90
  onSectionLink?(sectionId: string): boolean
91
+ /** The slash menu's request to the AI for an animation where it was opened: it inserts nothing itself. */
92
+ animationRequest?: { available(): boolean, request(editor: NativeDocumentEditor): void }
87
93
  children?: ReactNode
88
94
  }
89
95
 
@@ -113,10 +119,11 @@ function PlainContentComments({ editor }: { editor: NativeDocumentEditor }) {
113
119
  return show && editor.getExtension('comments') ? <div className="pm-document-editor__comment-tools"><FormattingToolbar><AddCommentButton /></FormattingToolbar></div> : null
114
120
  }
115
121
 
116
- // Formulas join the group that holds tables so the menu keeps one heading per group.
117
- function withFormulas<Item extends { group?: string }>(items: Item[], formulas: Item[]): Item[] {
118
- const index = items.findLastIndex(item => item.group === formulas[0]?.group)
119
- return index < 0 ? [...items, ...formulas] : [...items.slice(0, index + 1), ...formulas, ...items.slice(index + 1)]
122
+ // Added items join the end of their group (formulas the one that holds tables, the animation request the one that holds
123
+ // pictures) so the menu keeps one heading per group.
124
+ function withGroupItems<Item extends { group?: string }>(items: Item[], added: Item[]): Item[] {
125
+ const index = items.findLastIndex(item => item.group === added[0]?.group)
126
+ return index < 0 ? [...items, ...added] : [...items.slice(0, index + 1), ...added, ...items.slice(index + 1)]
120
127
  }
121
128
 
122
129
  /** One native editor owns selection, transactions and history across the complete document. */
@@ -156,7 +163,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
156
163
  dictionary, tables: { splitCells: true, cellBackgroundColor: true, cellTextColor: true, headers: true },
157
164
  // The surface's own click handler opens links in editable and read-only states alike.
158
165
  links: { onClick: () => true },
159
- extensions: [nativeTextClipboard, documentBlockColors, imageFileInput({
166
+ extensions: [nativeTextClipboard, documentBlockColors, documentPageBodies(), imageFileInput({
160
167
  onStart: () => { if (current.current.identity === props.identity) setFileErrors(undefined) },
161
168
  onFailure: failure => { if (current.current.identity === props.identity) setFileErrors(value => ({ identity: props.identity, failures: [...(value?.identity === props.identity ? value.failures : []), failure] })) },
162
169
  }), ...props.comments ? [nativeCommentSelection(), nativeComments(props.comments, t.author)] : []],
@@ -171,7 +178,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
171
178
  stopCommentHistory?.(); current.current.onReady?.(undefined)
172
179
  }
173
180
  }, [editor])
174
- return <DOCUMENT_EDITOR_LOCALE.Provider value={props.locale}><DOCUMENT_LINKS.Provider value={links}><DOCUMENT_NODE_VIEWS.Provider value={props.nodeViews ?? {}}><COMMENT_EDITOR_CONTEXT.Provider value={props.comments ? { store: props.comments, locale: props.locale, sidebar: Boolean(props.commentsPortal), getPositionToken: () => current.current.getPositionToken?.(), onDraftRestore: () => current.current.onCommentDraftRestore?.() } : undefined}>
181
+ return <DOCUMENT_EDITOR_LOCALE.Provider value={props.locale}><DOCUMENT_LINKS.Provider value={links}><DOCUMENT_NODE_VIEWS.Provider value={props.nodeViews ?? {}}><COMMENT_EDITOR_CONTEXT.Provider value={props.comments ? { store: props.comments, locale: props.locale, sidebar: Boolean(props.commentsPortal), readOnly: Boolean(props.readOnly), getPositionToken: () => current.current.getPositionToken?.(), onDraftRestore: () => current.current.onCommentDraftRestore?.(), openComments: () => current.current.onOpenComments?.() } : undefined}>
175
182
  <div className="pm-document-editor pm-ui-block-editor pm-ui" data-document-editor={props.identity}
176
183
  onDragEnter={event => { if (event.dataTransfer.types.includes('Files')) event.stopPropagation() }}
177
184
  onDragOver={event => { if (event.dataTransfer.types.includes('Files')) event.stopPropagation() }}
@@ -196,14 +203,23 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
196
203
  <LinkToolbarController linkToolbar={DocumentLinkToolbar} floatingUIOptions={linkToolbarOptions} />
197
204
  <SideMenuController sideMenu={DocumentSideMenu} />
198
205
  <TableHandlesController tableHandle={DocumentTableHandle} tableCellHandle={DocumentTableCellButton} />
199
- <SuggestionMenuController triggerCharacter="/" getItems={async query => editor.getTextCursorPosition().block.type === 'presmiumPage' ? [] : filterSuggestionItems([...withFormulas(getDefaultReactSlashMenuItems(editor), formulaSlashItems(editor, props.locale, dictionary.slash_menu.table.group)), {
206
+ <SuggestionMenuController triggerCharacter="/" getItems={async query => editor.getTextCursorPosition().block.type === 'presmiumPage' ? [] : filterSuggestionItems([...withGroupItems(withGroupItems(getDefaultReactSlashMenuItems(editor), formulaSlashItems(editor, props.locale, dictionary.slash_menu.table.group)), current.current.animationRequest?.available() ? [{
207
+ title: t.animateWithAI, subtext: t.animateWithAIHint, group: dictionary.slash_menu.image.group, icon: <PmIcon name="sparkle" />, aliases: slashAliases('animateWithAIAliases'),
208
+ // The menu has already taken back the typed “/” and query; the AI is asked, the document stays as it was.
209
+ onItemClick: () => current.current.animationRequest?.request(editor),
210
+ }] : []), {
200
211
  title: t.page, aliases: slashAliases('pageAliases'), group: t.document,
201
- onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId: crypto.randomUUID() }, content: t.untitledPage }], current, 'after') },
212
+ onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId: randomUUID() }, content: t.untitledPage }], current, 'after') },
202
213
  }], query)} />
203
214
  {props.children}
204
215
  </NewCommentDraftProvider></BlockNoteViewEditor>
205
216
  </ComponentsContext.Provider>
206
217
  </BlockNoteView>
218
+ <div className="pm-document-editor__end" aria-hidden="true" data-editable={props.readOnly ? undefined : ''} onMouseDown={event => {
219
+ if (event.button !== 0 || !editor.isEditable || editor.prosemirrorView.composing) return
220
+ event.preventDefault()
221
+ focusDocumentEnd(editor)
222
+ }} />
207
223
  </div>
208
224
  </COMMENT_EDITOR_CONTEXT.Provider></DOCUMENT_NODE_VIEWS.Provider></DOCUMENT_LINKS.Provider></DOCUMENT_EDITOR_LOCALE.Provider>
209
225
  }
@@ -0,0 +1,24 @@
1
+ import { createContext, useContext, useMemo } from 'react'
2
+ import type { ComponentType, ReactNode } from 'react'
3
+ import { components } from '@blocknote/mantine'
4
+ import { ComponentsContext, FloatingComposer, useComponentsContext } from '@blocknote/react'
5
+ import type { ComponentProps } from '@blocknote/react'
6
+ import type { BlockNoteEditor } from '@blocknote/core'
7
+
8
+ const COMPOSER_CARD = createContext<{ Card: ComponentType<ComponentProps['Comments']['Card']>, header?: ReactNode } | undefined>(undefined)
9
+
10
+ function ComposerCard(props: ComponentProps['Comments']['Card']) {
11
+ const { Card, header } = useContext(COMPOSER_CARD)!
12
+ return <Card {...props}>{header && <div className="pm-ui-comment-target">{header}</div>}{props.children}</Card>
13
+ }
14
+
15
+ /** Text selections and block/step anchors share the native card, editor and Post action. */
16
+ export function CommentComposer({ editor, editorComponent = components.Comments.Editor, children }: {
17
+ editor: BlockNoteEditor<any, any, any>, editorComponent?: ComponentType<ComponentProps['Comments']['Editor']>, children?: ReactNode,
18
+ }) {
19
+ const native = useComponentsContext()!
20
+ const value = useMemo(() => ({ ...native, Comments: { ...native.Comments, Card: ComposerCard, Editor: editorComponent } }), [native, editorComponent])
21
+ return <COMPOSER_CARD.Provider value={{ Card: native.Comments.Card, header: children }}><ComponentsContext.Provider value={value}>
22
+ <FloatingComposer newCommentEditor={editor} />
23
+ </ComponentsContext.Provider></COMPOSER_CARD.Provider>
24
+ }
@@ -1,17 +1,11 @@
1
1
  import { useMemo } from 'react'
2
2
  import { applyDocumentComponentAction } from '@lincyaw/kernel'
3
- import type { Definition, TeachingDocument } from '@lincyaw/kernel'
3
+ import type { TeachingDocument } from '@lincyaw/kernel'
4
4
  import { PmButton, PmMenu, PmSearchList } from '../components.tsx'
5
5
  import type { ComponentPropertyMessages } from '../component-property-messages.ts'
6
+ import { componentDefinitionLabel } from './component-label.ts'
6
7
 
7
- export function componentDefinitionLabel(definition: Definition): string {
8
- const title = typeof definition.parameterSchema === 'object' && typeof definition.parameterSchema.title === 'string' ? definition.parameterSchema.title.trim() : ''
9
- if (title) return Array.from(title).slice(0, 80).join('')
10
- const implementation = definition.implementation
11
- const name = implementation.type === 'file' ? implementation.path.split('/').at(-1)?.replace(/\.(tsx?|jsx?|mjs|cjs)$/, '')
12
- : implementation.type === 'plugin' ? implementation.name : implementation.specifier.split('/').at(-1)
13
- return Array.from(name || definition.kind).slice(0, 80).join('')
14
- }
8
+ export { componentDefinitionLabel } from './component-label.ts'
15
9
 
16
10
  /** Selection is a proposal; only the caller's source-bound Apply changes a binding. */
17
11
  export function ComponentMaterials({ document, blockId, selected, onSelect, onLocate, disabled, messages: t }: {