@lincyaw/workbench 0.2.0-rc.12 → 0.2.0-rc.120
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +5 -4
- package/src/AgentActivityBar.tsx +25 -0
- package/src/MediaClipEditor.tsx +7 -6
- package/src/StepProductionEditor.tsx +16 -7
- package/src/agent-activity-messages.ts +14 -0
- package/src/agent-activity.ts +38 -0
- package/src/approvals.tsx +6 -1
- package/src/audio-recording-messages.ts +5 -5
- package/src/audio-recording.ts +27 -5
- package/src/authoring-client.ts +10 -10
- package/src/authoring-draft-fragment.ts +3 -1
- package/src/authoring-window.ts +100 -0
- package/src/base-controls.tsx +28 -7
- package/src/body-draft-actions.ts +60 -0
- package/src/caption-timing-drafts.ts +20 -3
- package/src/caption-timing-messages.ts +2 -2
- package/src/caption-timing.ts +2 -2
- package/src/component-draft-actions.ts +1 -1
- package/src/component-properties.ts +3 -3
- package/src/component-property-drafts.ts +6 -6
- package/src/components.tsx +43 -38
- package/src/container-layout.ts +21 -0
- package/src/context.tsx +5 -3
- package/src/diagnostics.ts +1 -1
- package/src/document-draft-store.ts +45 -18
- package/src/document-drafts.ts +30 -21
- package/src/document-editing.ts +485 -0
- package/src/document-editor/BlockNoteSurface.tsx +40 -14
- package/src/document-editor/CommentComposer.tsx +24 -0
- package/src/document-editor/ComponentMaterials.tsx +4 -10
- package/src/document-editor/ComponentPropertiesDialog.tsx +12 -12
- package/src/document-editor/DocumentBlockFallback.tsx +4 -3
- package/src/document-editor/DocumentBlockPreview.tsx +11 -4
- package/src/document-editor/DocumentComments.tsx +87 -17
- package/src/document-editor/DocumentEditor.tsx +66 -14
- package/src/document-editor/DocumentStepNarration.tsx +39 -27
- package/src/document-editor/NarrationEditor.tsx +55 -21
- package/src/document-editor/NewCommentDrafts.tsx +120 -37
- package/src/document-editor/PlaceComment.tsx +252 -0
- package/src/document-editor/agent-targets.ts +34 -0
- package/src/document-editor/blocknote-messages.ts +2 -0
- package/src/document-editor/comment-draft-actions.ts +40 -20
- package/src/document-editor/comment-draft-inspection.ts +2 -2
- package/src/document-editor/comment-drafts.ts +75 -27
- package/src/document-editor/comments.ts +34 -14
- package/src/document-editor/component-label.ts +11 -0
- package/src/document-editor/file-input.ts +2 -2
- package/src/document-editor/focus.ts +0 -2
- package/src/document-editor/inline.ts +1 -0
- package/src/document-editor/insertion-place.ts +60 -0
- package/src/document-editor/messages.ts +3 -3
- package/src/document-editor/narration-schema.tsx +12 -6
- package/src/document-editor/narration.ts +19 -3
- package/src/document-editor/page-body.ts +60 -0
- package/src/document-editor/popover.tsx +4 -2
- package/src/document-editor/projection.ts +21 -19
- package/src/document-editor/rich-text.ts +3 -2
- package/src/document-editor/selection.ts +13 -0
- package/src/document-editor/style.css +8 -3
- package/src/document-editor/table-identities.ts +2 -1
- package/src/document-preview.ts +3 -2
- package/src/document-production.ts +492 -0
- package/src/document-return-point.ts +2 -2
- package/src/document-session.ts +216 -67
- package/src/document-timing-drafts.ts +26 -6
- package/src/effective-settings.ts +12 -0
- package/src/history.ts +5 -5
- package/src/import-messages.ts +40 -0
- package/src/index.ts +11 -5
- package/src/jobs.ts +1 -1
- package/src/mcp-settings-messages.ts +39 -0
- package/src/media-drafts.ts +43 -1
- package/src/messages.ts +39 -18
- package/src/outline.ts +5 -5
- package/src/panels/DocumentImportDialog.tsx +59 -0
- package/src/panels/DocumentNarrationPanel.tsx +2 -2
- package/src/panels/DocumentView.tsx +106 -77
- package/src/panels/DocumentVoiceDialog.tsx +29 -12
- package/src/panels/DocumentVoiceField.tsx +3 -2
- package/src/panels/ExportPanel.tsx +2 -10
- package/src/panels/HistoryPanel.tsx +36 -10
- package/src/panels/HomePanel.tsx +12 -1
- package/src/panels/McpSettingsPanel.tsx +86 -0
- package/src/panels/PageDeleteDialog.tsx +4 -4
- package/src/panels/PageRenameDialog.tsx +1 -1
- package/src/panels/PreviewPanel.tsx +4 -7
- package/src/panels/ProductionCaptionSize.tsx +20 -0
- package/src/panels/ProductionCaptionTiming.tsx +12 -9
- package/src/panels/ProductionMediaClips.tsx +25 -9
- package/src/panels/ProductionPanel.tsx +21 -17
- package/src/panels/ProductionRecording.tsx +86 -9
- package/src/panels/ProductionRecordingRange.tsx +26 -23
- package/src/panels/ProductionTimeline.tsx +6 -1
- package/src/panels/ProductionTranscription.tsx +8 -6
- package/src/panels/SourceDocumentPanel.tsx +24 -40
- package/src/panels/SpeechSettingsPanel.tsx +2 -2
- package/src/panels/TranscriptionAdoption.tsx +42 -36
- package/src/panels/VoiceCloneDialog.tsx +2 -1
- package/src/panels/VoicePreviewDialog.tsx +1 -1
- package/src/panels/VoiceScopeField.tsx +2 -2
- package/src/panels/VoiceoverDialog.tsx +11 -10
- package/src/places.ts +1 -36
- package/src/preview-playback.ts +1 -1
- package/src/production-draft-actions.ts +37 -0
- package/src/production-messages.ts +6 -0
- package/src/production-playback.ts +1 -1
- package/src/production-voice-playback.ts +3 -2
- package/src/recording-adoption.ts +4 -4
- package/src/sha256.ts +9 -0
- package/src/speech-settings-messages.ts +6 -6
- package/src/step-production.ts +4 -4
- package/src/styles.css +43 -92
- package/src/transcription-drafts.ts +124 -0
- package/src/use-recording-adoption.ts +5 -4
- package/src/voice-drafts.ts +32 -8
- package/src/voice-messages.ts +9 -9
- package/src/voiceover-jobs.ts +1 -1
- package/src/workbench-state.ts +159 -0
- package/src/workbench.ts +323 -956
- package/src/workspace-client.ts +41 -12
- package/src/assistant-mascot.ts +0 -62
- package/src/mascot-preference.ts +0 -37
- package/src/panels/ChangeTrail.tsx +0 -79
|
@@ -0,0 +1,485 @@
|
|
|
1
|
+
import { duplicateDocumentPage, errorMessage, moveDocumentPage, pageDeletion, randomUUID, removeDocumentPage, renameDocumentPage } from '@lincyaw/kernel'
|
|
2
|
+
import type { PageDeletePlan, PresmiumDocument } 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
|
+
import { effectiveOf } from './effective-settings.ts'
|
|
18
|
+
|
|
19
|
+
interface EditingOptions {
|
|
20
|
+
store: WorkbenchStore
|
|
21
|
+
session: DocumentSession
|
|
22
|
+
scope(): number
|
|
23
|
+
flush(signal?: AbortSignal): Promise<void>
|
|
24
|
+
goToSection(section: string): void
|
|
25
|
+
rememberStep(directory: string, section: string, step: number): void
|
|
26
|
+
canAskAnimation(): boolean
|
|
27
|
+
askAnimation(place: DocumentInsertionPlace): boolean
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Native editor selection, focus, page changes and viewport restoration share one document lifetime. */
|
|
31
|
+
export class DocumentEditing {
|
|
32
|
+
#documentEditor?: NativeDocumentEditor
|
|
33
|
+
#documentEditorCommands?: DocumentEditorCommands
|
|
34
|
+
#documentEditorBinding?: { identity: string, reset: number }
|
|
35
|
+
readonly #documentReturnPoints = new DocumentReturnPoints()
|
|
36
|
+
#documentViewport?: { element: HTMLElement, identity: string, returnScrollTop?: number, stop(): void }
|
|
37
|
+
#stopDocumentReturnScroll?: () => void
|
|
38
|
+
#openingDocument?: { directory: string, scope: number, generation: number, focus?: 'body', initial?: boolean, stop(): void,
|
|
39
|
+
basis?: { identity: string, reset: number, version?: string, content: PresmiumDocument }, point?: DocumentReturnPoint, fallback?: DocumentReturnPoint }
|
|
40
|
+
#stopDocumentLayoutScroll?: () => void
|
|
41
|
+
#activeDocumentHistory?: DocumentHistoryEditor
|
|
42
|
+
#unsubscribeDocumentHistory?: () => void
|
|
43
|
+
#unsubscribeDocumentSelection?: () => void
|
|
44
|
+
#generation = 0
|
|
45
|
+
#pendingDocumentFocus?: { documentId: string, nodeId: string, generation: number, afterSave?: true }
|
|
46
|
+
#pendingDocumentSelection?: { documentId: string, anchor: NativeTextPoint, head: NativeTextPoint, focused: boolean }
|
|
47
|
+
readonly #documentFields = new Map<string, DocumentFieldRegistration>()
|
|
48
|
+
#pendingDocumentField?: { field: Omit<DocumentFieldRegistration, 'focus' | 'editor'>, bookmark: DocumentFieldBookmark, reset: number, generation: number }
|
|
49
|
+
readonly #store: WorkbenchStore
|
|
50
|
+
readonly #session: DocumentSession
|
|
51
|
+
readonly #options: EditingOptions
|
|
52
|
+
|
|
53
|
+
constructor(options: EditingOptions) { this.#options = options; this.#store = options.store; this.#session = options.session }
|
|
54
|
+
get generation(): number { return this.#generation }
|
|
55
|
+
get returnPoints(): DocumentReturnPoints { return this.#documentReturnPoints }
|
|
56
|
+
sourceChanged(authoring: DocumentSessionState): void {
|
|
57
|
+
const pending = this.#pendingDocumentField
|
|
58
|
+
if (pending && (pending.field.identity !== authoring.identity || authoring.reset > pending.reset
|
|
59
|
+
|| pending.field.blockId !== undefined && !authoring.content?.blocks[pending.field.blockId]
|
|
60
|
+
|| !authoring.content?.steps[pending.field.stepId])) this.#pendingDocumentField = undefined
|
|
61
|
+
}
|
|
62
|
+
rememberComponent(content: PresmiumDocument, identity: string): void {
|
|
63
|
+
if (this.#documentEditorBinding?.identity === identity) this.#documentEditorCommands?.rememberComponentConfiguration(content)
|
|
64
|
+
}
|
|
65
|
+
beforePosition(): void { this.cancelOpening(); this.#stopDocumentReturnScroll?.() }
|
|
66
|
+
nativeHistory(action: 'undo' | 'redo'): boolean | undefined {
|
|
67
|
+
const state = this.#store.state
|
|
68
|
+
if (state.mode !== 'editing') return false
|
|
69
|
+
if (this.#activeDocumentHistory && (state.editorHistory?.[action] || state.editorHistory?.field)) {
|
|
70
|
+
this.#activeDocumentHistory.focus()
|
|
71
|
+
return this.#activeDocumentHistory[action]()
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
reset(): void {
|
|
75
|
+
this.saveReturnPoint(); this.cancelOpening(); this.#stopDocumentReturnScroll?.()
|
|
76
|
+
this.#documentViewport?.stop(); this.#documentViewport = undefined; this.#documentEditorBinding = undefined
|
|
77
|
+
this.#unsubscribeDocumentHistory?.(); this.#unsubscribeDocumentHistory = undefined; this.#activeDocumentHistory = undefined; this.#documentEditor = undefined
|
|
78
|
+
this.#unsubscribeDocumentSelection?.(); this.#unsubscribeDocumentSelection = undefined
|
|
79
|
+
this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
|
|
80
|
+
this.#pendingDocumentFocus = undefined; this.#pendingDocumentSelection = undefined; this.#generation++
|
|
81
|
+
this.#documentFields.clear(); this.#pendingDocumentField = undefined
|
|
82
|
+
this.#documentEditorCommands = undefined
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
#watchOpeningInteraction(cancel: () => void): () => void {
|
|
86
|
+
if (typeof document === 'undefined') return () => {}
|
|
87
|
+
const focused = document.activeElement, dialog = focused?.closest('[role="dialog"]')
|
|
88
|
+
const interact = (event: Event) => {
|
|
89
|
+
if (!event.isTrusted) return
|
|
90
|
+
if (event.type === 'focusin' && (!(event.target instanceof Element) || event.target === focused || dialog?.contains(event.target))) return
|
|
91
|
+
cancel()
|
|
92
|
+
}
|
|
93
|
+
const events = ['pointerdown', 'keydown', 'beforeinput', 'wheel', 'touchmove', 'focusin']
|
|
94
|
+
for (const event of events) document.addEventListener(event, interact, true)
|
|
95
|
+
return () => { for (const event of events) document.removeEventListener(event, interact, true) }
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
cancelOpening(): void {
|
|
99
|
+
const pending = this.#openingDocument
|
|
100
|
+
this.#openingDocument = undefined
|
|
101
|
+
pending?.stop()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
beginOpening(directory: string, focus?: 'body', fallback?: DocumentReturnPoint): void {
|
|
105
|
+
this.cancelOpening()
|
|
106
|
+
this.#openingDocument = { directory, focus, fallback: fallback && { ...fallback }, scope: this.#options.scope(), generation: this.#generation,
|
|
107
|
+
stop: this.#watchOpeningInteraction(() => this.cancelOpening()) }
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
saveReturnPoint(): void {
|
|
111
|
+
const source = this.#store.state.authoring, position = this.#store.state.position
|
|
112
|
+
if (!source?.identity || !source.content || source.loading || !position || !source.content.sectionOrder.includes(position.section)) return
|
|
113
|
+
const section = source.content.sections[position.section]
|
|
114
|
+
let stepId = section?.stepOrder[position.step]
|
|
115
|
+
if (this.#store.state.webView === 'present' || position.view === 'present') {
|
|
116
|
+
const snapshot = this.#store.state.presentationSnapshot, ir = this.#store.state.ir
|
|
117
|
+
if (!snapshot || !ir || source.dirty || source.saving || source.error || snapshot.version !== source.version || snapshot.fingerprint !== source.fingerprint
|
|
118
|
+
|| snapshot.project !== (source.projectRevision ?? 0) || snapshot.revision !== ir.revision || snapshot.revision !== this.#store.state.previewIrRevision) return
|
|
119
|
+
const ids = ir.doc.sections.find(page => page.id === position.section)?.stepIds
|
|
120
|
+
if (!ids || ids.length && !ids[position.step]) return
|
|
121
|
+
stepId = ids[position.step]
|
|
122
|
+
if (stepId && (!section?.stepOrder.includes(stepId) || source.content.steps[stepId]?.sectionId !== position.section)) return
|
|
123
|
+
}
|
|
124
|
+
if (!section || !stepId && section.stepOrder.length) return
|
|
125
|
+
const viewport = this.#documentViewport, previous = this.#documentReturnPoints.read(source.identity)
|
|
126
|
+
const measured = this.#store.state.webView === 'document' && viewport?.identity === source.identity ? documentViewportOffset(viewport.element, section.id) : undefined
|
|
127
|
+
const offset = measured ?? (previous?.sectionId === section.id ? previous.offset : undefined)
|
|
128
|
+
this.#documentReturnPoints.write(source.identity, { sectionId: section.id, ...stepId ? { stepId } : {}, ...offset !== undefined ? { offset } : {} })
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
finishOpening(): void {
|
|
132
|
+
const pending = this.#openingDocument, source = this.#store.state.authoring
|
|
133
|
+
if (!pending || source?.loading || !source?.identity || !source.content) return
|
|
134
|
+
if (source.error === 'document-identity-changed') { this.cancelOpening(); return }
|
|
135
|
+
if (pending.scope !== this.#options.scope() || pending.directory !== this.#store.state.document || pending.generation !== this.#generation) { this.cancelOpening(); return }
|
|
136
|
+
if (!pending.basis) {
|
|
137
|
+
pending.basis = { identity: source.identity, reset: source.reset, version: source.version, content: source.content }
|
|
138
|
+
if (!pending.focus) {
|
|
139
|
+
pending.point = this.#documentReturnPoints.read(source.identity) ?? pending.fallback
|
|
140
|
+
if (!pending.point) {
|
|
141
|
+
const section = source.content.sections[source.content.sectionOrder[0]!]
|
|
142
|
+
if (!section) { this.cancelOpening(); return }
|
|
143
|
+
pending.point = { sectionId: section.id, ...section.stepOrder[0] ? { stepId: section.stepOrder[0] } : {} }
|
|
144
|
+
pending.initial = true
|
|
145
|
+
}
|
|
146
|
+
if (documentReturnStep(source.content, pending.point) === undefined) {
|
|
147
|
+
this.#documentReturnPoints.forget(source.identity); this.cancelOpening()
|
|
148
|
+
this.#store.set({ documentPositionFailure: 'removed' }); return
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
const basis = pending.basis
|
|
153
|
+
if (source.identity !== basis.identity || source.reset !== basis.reset || source.version !== basis.version || source.content !== basis.content) { this.cancelOpening(); return }
|
|
154
|
+
const editor = this.#documentEditor, binding = this.#documentEditorBinding, viewport = this.#documentViewport
|
|
155
|
+
if (!editor || editor.prosemirrorView.isDestroyed || binding?.identity !== source.identity || binding.reset !== source.reset || viewport?.identity !== source.identity) return
|
|
156
|
+
// The editor can mount read-only while the source is still loading; a read-only body cannot take the caret yet.
|
|
157
|
+
if (pending.focus && !editor.isEditable) return
|
|
158
|
+
this.cancelOpening()
|
|
159
|
+
if (pending.focus) {
|
|
160
|
+
const body = (blocks: typeof editor.document, sectionId?: string): { nodeId: string, sectionId: string } | undefined => {
|
|
161
|
+
for (const block of blocks) {
|
|
162
|
+
if (block.type === 'presmiumPage') sectionId = block.props.sectionId
|
|
163
|
+
else if (sectionId && editor.schema.blockSchema[block.type].content === 'inline') return { nodeId: block.id, sectionId }
|
|
164
|
+
const nested = body(block.children, sectionId)
|
|
165
|
+
if (nested) return nested
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const target = body(editor.document)
|
|
169
|
+
if (target && source.content.sections[target.sectionId]) {
|
|
170
|
+
this.#store.set({ position: { section: target.sectionId, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: undefined })
|
|
171
|
+
this.#focusDocumentNode(editor, target.nodeId)
|
|
172
|
+
}
|
|
173
|
+
return
|
|
174
|
+
}
|
|
175
|
+
const point = pending.point!, step = documentReturnStep(source.content, point)
|
|
176
|
+
if (step === undefined) return
|
|
177
|
+
this.#options.rememberStep(pending.directory, point.sectionId, step)
|
|
178
|
+
this.#store.set({ position: { section: point.sectionId, step, trail: [], view: 'document' }, documentPositionFailure: undefined, documentNavigation: undefined })
|
|
179
|
+
if (pending.initial) return
|
|
180
|
+
const current = () => this.#store.state.document === pending.directory && this.#store.state.authoring?.identity === basis.identity
|
|
181
|
+
&& this.#store.state.authoring.reset === basis.reset && this.#store.state.authoring.version === basis.version && this.#store.state.authoring.content === basis.content
|
|
182
|
+
&& this.#documentViewport === viewport && this.#store.state.position?.section === point.sectionId && this.#store.state.position.step === step
|
|
183
|
+
const restore = () => {
|
|
184
|
+
if (!current()) { stop(); return }
|
|
185
|
+
const top = viewport.element.scrollTop
|
|
186
|
+
restoreDocumentViewport(viewport.element, point)
|
|
187
|
+
if (viewport.element.scrollTop !== top) viewport.returnScrollTop = viewport.element.scrollTop
|
|
188
|
+
}
|
|
189
|
+
const observer = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(restore)
|
|
190
|
+
let stopInteraction: () => void = () => {}
|
|
191
|
+
const stop = () => { observer?.disconnect(); stopInteraction(); viewport.returnScrollTop = undefined; if (this.#stopDocumentReturnScroll === stop) this.#stopDocumentReturnScroll = undefined }
|
|
192
|
+
this.#stopDocumentReturnScroll?.(); this.#stopDocumentReturnScroll = stop
|
|
193
|
+
stopInteraction = this.#watchOpeningInteraction(stop)
|
|
194
|
+
observer?.observe(viewport.element)
|
|
195
|
+
observer?.observe(editor.prosemirrorView.dom)
|
|
196
|
+
restore()
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Consume only this viewport owner's actual programmatic destination; user gestures retire it. */
|
|
200
|
+
consumeReturnScroll(element: HTMLElement): boolean {
|
|
201
|
+
const viewport = this.#documentViewport, top = viewport?.returnScrollTop
|
|
202
|
+
if (viewport?.element !== element || top === undefined) return false
|
|
203
|
+
viewport.returnScrollTop = undefined
|
|
204
|
+
return element.scrollTop === top
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
attachViewport(element: HTMLElement, identity: string): () => void {
|
|
208
|
+
this.#documentViewport?.stop()
|
|
209
|
+
const scroll = () => { if (!this.#openingDocument) this.saveReturnPoint() }
|
|
210
|
+
const viewport = { element, identity, stop: () => element.removeEventListener('scroll', scroll) }
|
|
211
|
+
this.#documentViewport = viewport
|
|
212
|
+
element.addEventListener('scroll', scroll, { passive: true })
|
|
213
|
+
this.finishOpening()
|
|
214
|
+
return () => { if (this.#documentViewport === viewport) { this.saveReturnPoint(); this.#stopDocumentReturnScroll?.(); this.#documentViewport = undefined }; viewport.stop() }
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/** The body editor became editable: an opening that waits to put the caret in it can finish now. */
|
|
218
|
+
editorEditable(): void { this.finishOpening() }
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
interact(): void {
|
|
222
|
+
this.#generation++; this.cancelOpening(); this.#stopDocumentReturnScroll?.()
|
|
223
|
+
if (this.#store.state.documentPositionFailure) this.#store.set({ documentPositionFailure: undefined })
|
|
224
|
+
}
|
|
225
|
+
pendingField(blockId: string | undefined, identity?: string): Pick<DocumentFieldRegistration, 'stepId'> | undefined {
|
|
226
|
+
const pending = this.#pendingDocumentField, source = this.#store.state.authoring
|
|
227
|
+
return pending && pending.generation === this.#generation && pending.field.blockId === blockId
|
|
228
|
+
&& pending.field.identity === (identity ?? source?.identity) && pending.reset === source?.reset ? pending.field : undefined
|
|
229
|
+
}
|
|
230
|
+
/** A live native field owns its target only while it still has focus in this source. */
|
|
231
|
+
focusedField(): Readonly<Pick<DocumentFieldRegistration, 'identity' | 'reset' | 'blockId' | 'stepId'>> & { readonly editor: DocumentHistoryEditor } | undefined {
|
|
232
|
+
const source = this.#store.state.authoring, editor = this.#activeDocumentHistory
|
|
233
|
+
if (!source?.identity || !source.content || !editor || editor === this.#documentEditor || editor.prosemirrorView.isDestroyed || !editor.prosemirrorView.hasFocus()) return
|
|
234
|
+
for (const field of this.#documentFields.values()) {
|
|
235
|
+
if (field.editor !== editor || field.identity !== source.identity || field.reset !== source.reset) continue
|
|
236
|
+
const step = source.content.steps[field.stepId], section = step && source.content.sections[step.sectionId]
|
|
237
|
+
if (!step || !section?.stepOrder.includes(field.stepId)) return
|
|
238
|
+
const { identity, reset, blockId, stepId } = field
|
|
239
|
+
return { identity, reset, blockId, stepId, editor }
|
|
240
|
+
}
|
|
241
|
+
return undefined
|
|
242
|
+
}
|
|
243
|
+
registerField(field: DocumentFieldRegistration): () => void {
|
|
244
|
+
if (field.identity !== this.#store.state.authoring?.identity || field.reset !== this.#store.state.authoring.reset) return () => {}
|
|
245
|
+
const key = JSON.stringify([field.identity, field.blockId, field.stepId])
|
|
246
|
+
this.#documentFields.set(key, field)
|
|
247
|
+
const pending = this.#pendingDocumentField
|
|
248
|
+
if (pending && pending.reset === field.reset && JSON.stringify([pending.field.identity, pending.field.blockId, pending.field.stepId]) === key) {
|
|
249
|
+
this.#pendingDocumentField = undefined
|
|
250
|
+
if (pending.generation === this.#generation && field.identity === this.#store.state.authoring?.identity && field.reset === this.#store.state.authoring.reset) field.focus.restore(pending.bookmark)
|
|
251
|
+
}
|
|
252
|
+
return () => {
|
|
253
|
+
if (this.#documentFields.get(key) !== field) return
|
|
254
|
+
this.#documentFields.delete(key)
|
|
255
|
+
if (field.editor && this.#activeDocumentHistory === field.editor) this.activateHistory(this.#documentEditor)
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
/** Toolbar commands use the focused native editor's own history, without replacing the body editor. */
|
|
259
|
+
activateHistory(editor: DocumentHistoryEditor | undefined): void {
|
|
260
|
+
if (editor && editor !== this.#documentEditor && ![...this.#documentFields.values()].some(field => field.editor === editor && field.identity === this.#store.state.authoring?.identity)) return
|
|
261
|
+
if (editor === this.#activeDocumentHistory) return
|
|
262
|
+
this.#unsubscribeDocumentHistory?.()
|
|
263
|
+
this.#activeDocumentHistory = editor
|
|
264
|
+
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 })
|
|
265
|
+
this.#unsubscribeDocumentHistory = editor?.onChange(update)
|
|
266
|
+
update()
|
|
267
|
+
}
|
|
268
|
+
attachEditor(editor: NativeDocumentEditor | undefined, commands?: DocumentEditorCommands, binding?: { identity: string, reset: number }): void {
|
|
269
|
+
if (binding && (binding.identity !== this.#store.state.authoring?.identity || binding.reset !== this.#store.state.authoring.reset)) return
|
|
270
|
+
const wasBody = !this.#activeDocumentHistory || this.#activeDocumentHistory === this.#documentEditor
|
|
271
|
+
if (editor !== this.#documentEditor) this.#session.composition(false, 'body')
|
|
272
|
+
this.#unsubscribeDocumentSelection?.(); this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
|
|
273
|
+
this.#documentEditor = editor; this.#documentEditorCommands = commands; this.#documentEditorBinding = editor ? binding : undefined
|
|
274
|
+
if (editor) {
|
|
275
|
+
const focus = this.#pendingDocumentFocus, selection = this.#pendingDocumentSelection
|
|
276
|
+
this.#pendingDocumentFocus = undefined; this.#pendingDocumentSelection = undefined
|
|
277
|
+
if (focus && focus.documentId === this.#store.state.authoring?.content?.id && focus.generation === this.#generation && editor.getBlock(focus.nodeId)) {
|
|
278
|
+
// A deferred page operation adopts its selection only after the source write is acknowledged.
|
|
279
|
+
if (!focus.afterSave) {
|
|
280
|
+
this.#focusDocumentNode(editor, focus.nodeId)
|
|
281
|
+
}
|
|
282
|
+
} else if (!this.#pendingDocumentField && selection && selection.documentId === this.#store.state.authoring?.content?.id) {
|
|
283
|
+
const anchor = nativeTextPosition(editor, selection.anchor), head = nativeTextPosition(editor, selection.head)
|
|
284
|
+
if (anchor !== undefined && head !== undefined) {
|
|
285
|
+
editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, anchor, head)))
|
|
286
|
+
if (selection.focused) editor.focus()
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
if (wasBody) this.activateHistory(editor)
|
|
291
|
+
if (editor) {
|
|
292
|
+
const focus = () => this.activateHistory(editor)
|
|
293
|
+
const element = editor.prosemirrorView.dom
|
|
294
|
+
element.addEventListener('focusin', focus)
|
|
295
|
+
if (editor.prosemirrorView.hasFocus()) focus()
|
|
296
|
+
const stopSelection = editor.onSelectionChange(() => { this.#generation++ })
|
|
297
|
+
this.#unsubscribeDocumentSelection = () => { this.#stopDocumentLayoutScroll?.(); stopSelection(); element.removeEventListener('focusin', focus) }
|
|
298
|
+
commands?.handleAnimationRequests({ available: () => this.#options.canAskAnimation(), request: place => this.#options.askAnimation(place) })
|
|
299
|
+
} else this.#unsubscribeDocumentSelection = undefined
|
|
300
|
+
this.finishOpening()
|
|
301
|
+
}
|
|
302
|
+
/** `selectText`: the node's whole text is selected, so typing replaces it. */
|
|
303
|
+
#focusDocumentNode(editor: NativeDocumentEditor, nodeId: string, selectText = false): void {
|
|
304
|
+
this.#stopDocumentLayoutScroll?.(); this.#stopDocumentLayoutScroll = undefined
|
|
305
|
+
editor.setTextCursorPosition(nodeId, 'start')
|
|
306
|
+
const text = selectText ? nativeBlockText(editor, nodeId) : undefined
|
|
307
|
+
if (text) editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, text.from, text.to)))
|
|
308
|
+
editor.focus()
|
|
309
|
+
editor.prosemirrorView.dispatch(editor.prosemirrorState.tr.scrollIntoView())
|
|
310
|
+
// React node views can finish sizing after the native editor mounts.
|
|
311
|
+
// Keep only this untouched focus visible through those layout changes.
|
|
312
|
+
if (typeof ResizeObserver !== 'undefined') {
|
|
313
|
+
const view = editor.prosemirrorView, document = view.dom.ownerDocument
|
|
314
|
+
const source = this.#store.state.authoring!, identity = source.identity, reset = source.reset, documentId = source.content!.id
|
|
315
|
+
const request = this.#store.state.documentNavigation?.request, selected = editor.prosemirrorState.selection
|
|
316
|
+
let size = view.dom.getBoundingClientRect(), active = true
|
|
317
|
+
const events = ['pointerdown', 'wheel', 'touchmove', 'keydown', 'beforeinput']
|
|
318
|
+
const cancel = () => {
|
|
319
|
+
if (!active) return
|
|
320
|
+
active = false; observer.disconnect(); stopFocus(); stopSelection()
|
|
321
|
+
for (const event of events) document.removeEventListener(event, interact, true)
|
|
322
|
+
}
|
|
323
|
+
const interact = (event: Event) => { if (event.isTrusted) cancel() }
|
|
324
|
+
const stopFocus = editor.onFocusChange((_, { focused }) => { if (!focused) cancel() })
|
|
325
|
+
const stopSelection = editor.onSelectionChange(cancel)
|
|
326
|
+
const observer = new ResizeObserver(() => {
|
|
327
|
+
if (!active) return
|
|
328
|
+
const current = this.#store.state.authoring
|
|
329
|
+
if (this.#documentEditor !== editor || view.isDestroyed || !current || current.identity !== identity || current.reset !== reset
|
|
330
|
+
|| current?.content?.id !== documentId || this.#store.state.documentNavigation?.request !== request
|
|
331
|
+
|| !editor.isFocused() || !editor.prosemirrorState.selection.eq(selected) || editor.getTextCursorPosition().block.id !== nodeId) { cancel(); return }
|
|
332
|
+
const next = view.dom.getBoundingClientRect()
|
|
333
|
+
if (next.width === size.width && next.height === size.height) return
|
|
334
|
+
size = next
|
|
335
|
+
view.dispatch(editor.prosemirrorState.tr.scrollIntoView())
|
|
336
|
+
})
|
|
337
|
+
for (const event of events) document.addEventListener(event, interact, true)
|
|
338
|
+
observer.observe(view.dom)
|
|
339
|
+
this.#stopDocumentLayoutScroll = cancel
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
async #changeDocumentPage(change: (document: PresmiumDocument) => void): Promise<boolean> {
|
|
344
|
+
const source = this.#store.state.authoring, directory = this.#store.state.document
|
|
345
|
+
if (!source?.content || directory === undefined || isAgentChanging(this.#store.state)) return false
|
|
346
|
+
const scope = this.#options.scope(), identity = source.identity, documentId = source.content.id
|
|
347
|
+
const current = () => scope === this.#options.scope() && directory === this.#store.state.document && identity === this.#store.state.authoring?.identity && documentId === this.#store.state.authoring?.content?.id
|
|
348
|
+
this.#store.set({ isEditingPage: true, pageEditFailure: undefined })
|
|
349
|
+
try {
|
|
350
|
+
await this.#options.flush()
|
|
351
|
+
if (!current()) throw new Error('page-context-changed')
|
|
352
|
+
const document = structuredClone(this.#store.state.authoring!.content!)
|
|
353
|
+
change(document)
|
|
354
|
+
const editor = this.#documentEditor
|
|
355
|
+
this.#pendingDocumentField = undefined
|
|
356
|
+
const plannedFocus = this.#pendingDocumentFocus
|
|
357
|
+
if (!plannedFocus || plannedFocus.generation !== this.#generation) for (const field of this.#documentFields.values()) {
|
|
358
|
+
if (field.identity !== source.identity || field.reset !== this.#store.state.authoring!.reset || field.blockId !== undefined && !document.blocks[field.blockId] || !document.steps[field.stepId]) continue
|
|
359
|
+
const bookmark = field.focus.capture()
|
|
360
|
+
if (bookmark) {
|
|
361
|
+
const { focus: _focus, editor: _editor, ...target } = field
|
|
362
|
+
this.#pendingDocumentField = { field: target, bookmark, reset: this.#store.state.authoring!.reset + 1, generation: this.#generation }
|
|
363
|
+
this.#pendingDocumentSelection = undefined
|
|
364
|
+
break
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
if (editor && !this.#pendingDocumentField) {
|
|
368
|
+
const state = editor.prosemirrorState, anchor = nativeTextPoint(editor, state.selection.anchor), head = nativeTextPoint(editor, state.selection.head)
|
|
369
|
+
if (anchor && head) this.#pendingDocumentSelection = { documentId: document.id, anchor, head, focused: editor.prosemirrorView.hasFocus() }
|
|
370
|
+
}
|
|
371
|
+
this.#session.replace(document)
|
|
372
|
+
await this.#session.flush()
|
|
373
|
+
return current()
|
|
374
|
+
} catch (error) { if (current()) this.#store.set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
|
|
375
|
+
finally { if (current()) this.#store.set({ isEditingPage: false }) }
|
|
376
|
+
}
|
|
377
|
+
renamePage(section: string, title: string): Promise<boolean> {
|
|
378
|
+
return this.#changeDocumentPage(document => { Object.assign(document, renameDocumentPage(document, section, title)) })
|
|
379
|
+
}
|
|
380
|
+
async duplicatePage(section: string): Promise<boolean> {
|
|
381
|
+
if (this.#store.state.isEditingPage || this.#store.state.isCreatingPage || this.#store.state.isHistoryBusy) return false
|
|
382
|
+
const scope = this.#options.scope(), identity = this.#store.state.authoring?.identity, generation = this.#generation, navigation = this.#store.state.documentNavigation?.request
|
|
383
|
+
let copied: string | undefined
|
|
384
|
+
const saved = await this.#changeDocumentPage(document => {
|
|
385
|
+
if (scope !== this.#options.scope() || identity !== this.#store.state.authoring?.identity) throw new Error('page-context-changed')
|
|
386
|
+
const page = document.sections[section]
|
|
387
|
+
if (!page) throw new Error('page-boundary')
|
|
388
|
+
const copy = duplicateDocumentPage(document, section, contentText(effectiveOf(document, this.#store.state.authoring?.inherited).metadata.lang).copyTitle(page.title), () => randomUUID())
|
|
389
|
+
copied = copy.section
|
|
390
|
+
Object.assign(document, copy.document)
|
|
391
|
+
if (generation === this.#generation) this.#pendingDocumentFocus = { documentId: document.id, nodeId: `page:${copied}`, generation, afterSave: true }
|
|
392
|
+
})
|
|
393
|
+
// Source confirmation owns editing. A later author selection takes precedence over this response.
|
|
394
|
+
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
|
|
395
|
+
this.#options.goToSection(copied)
|
|
396
|
+
const editor = this.#documentEditor
|
|
397
|
+
if (editor) {
|
|
398
|
+
const blocks = editor.document, start = blocks.findIndex(block => block.id === `page:${copied}`)
|
|
399
|
+
const first = (nodes: typeof blocks): string | undefined => {
|
|
400
|
+
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 }
|
|
401
|
+
return undefined
|
|
402
|
+
}
|
|
403
|
+
const target = start < 0 ? undefined : first(blocks.slice(start + 1)) ?? blocks[start]!.id
|
|
404
|
+
if (target) { editor.setTextCursorPosition(target, 'start'); editor.focus() }
|
|
405
|
+
}
|
|
406
|
+
return true
|
|
407
|
+
}
|
|
408
|
+
movePage(section: string, before: string | null): Promise<boolean> {
|
|
409
|
+
return this.#changeDocumentPage(document => { Object.assign(document, moveDocumentPage(document, section, before)) })
|
|
410
|
+
}
|
|
411
|
+
deletionMessage(reason: string): string { return this.#pageEditMessage(reason) }
|
|
412
|
+
async preparePageDeletion(section: string): Promise<PageDeletePlan> {
|
|
413
|
+
await this.#options.flush()
|
|
414
|
+
const source = this.#store.state.authoring
|
|
415
|
+
if (!source?.content || !source.version || this.#store.state.document === undefined) throw new Error('document-unavailable')
|
|
416
|
+
return pageDeletion(source.content, this.#store.state.document, source.version, section)
|
|
417
|
+
}
|
|
418
|
+
async deletePage(plan: PageDeletePlan): Promise<boolean> {
|
|
419
|
+
if (!plan.allowed || plan.document !== this.#store.state.document) return false
|
|
420
|
+
return this.#changeDocumentPage(document => {
|
|
421
|
+
if (this.#store.state.authoring?.version !== plan.source.version) throw new Error('revision-conflict')
|
|
422
|
+
const current = pageDeletion(document, plan.document, plan.source.version, plan.section)
|
|
423
|
+
if (!current.allowed) throw new Error(current.reason)
|
|
424
|
+
Object.assign(document, removeDocumentPage(document, plan.section, () => randomUUID()))
|
|
425
|
+
this.#store.set({ position: { section: document.sectionOrder[0]!, step: 0, trail: [], view: 'document' }, documentNavigation: { section: document.sectionOrder[0]!, request: randomUUID() } })
|
|
426
|
+
})
|
|
427
|
+
}
|
|
428
|
+
createPage(after = this.#store.state.position?.section): boolean {
|
|
429
|
+
const source = this.#store.state.authoring, editor = this.#documentEditor, commands = this.#documentEditorCommands
|
|
430
|
+
if (!source?.content || source.loading || source.composing || source.restored || source.error || !editor || !commands
|
|
431
|
+
|| editor.prosemirrorView.isDestroyed || isAgentChanging(this.#store.state) || this.#store.state.isEditingPage || this.#store.state.isCreatingPage
|
|
432
|
+
|| this.#store.state.isHistoryBusy || this.#store.state.isHistoryPreparing) return false
|
|
433
|
+
try {
|
|
434
|
+
this.#store.set({ pageEditFailure: undefined })
|
|
435
|
+
const created = commands.insertPage(after, contentText(effectiveOf(source.content, source.inherited).metadata.lang).newPage)
|
|
436
|
+
this.#pendingDocumentField = undefined; this.#pendingDocumentSelection = undefined; this.#pendingDocumentFocus = undefined
|
|
437
|
+
this.#store.set({ position: { section: created.sectionId, step: 0, trail: [], view: 'document' }, documentNavigation: { section: created.sectionId, request: randomUUID() } })
|
|
438
|
+
// The default title is selected: the author's first words name the page, and Enter goes on to its body.
|
|
439
|
+
this.#focusDocumentNode(editor, `page:${created.sectionId}`, true)
|
|
440
|
+
return true
|
|
441
|
+
} catch (error) { this.#store.set({ pageEditFailure: this.#pageEditMessage(errorMessage(error)) }); return false }
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
|
|
445
|
+
#pageEditMessage(reason: string): string {
|
|
446
|
+
const t = MESSAGES[this.#store.state.locale]
|
|
447
|
+
if (reason === 'native-unavailable') return t.nativeEditUnavailable
|
|
448
|
+
if (reason.startsWith('native-')) return t.nativeEditDraft
|
|
449
|
+
switch (reason) {
|
|
450
|
+
case 'page-multiple-files': return t.pageEditFiles
|
|
451
|
+
case 'page-boundary': return t.pageEditBoundary
|
|
452
|
+
case 'page-hierarchy': return t.pageEditHierarchy
|
|
453
|
+
case 'page-implicit-title': return t.pageEditImplicitTitle
|
|
454
|
+
case 'page-formatted-title': return t.pageEditFormattedTitle
|
|
455
|
+
case 'page-title': return t.pageEditInvalidTitle
|
|
456
|
+
case 'page-compiler': return t.pageEditCompiler
|
|
457
|
+
case 'page-referenced': return t.pageDeleteReferenced
|
|
458
|
+
case 'page-external-bindings': return t.pageDeleteExternalBindings
|
|
459
|
+
case 'page-references-unavailable': return t.pageDeleteReferencesUnavailable
|
|
460
|
+
case 'page-busy': return t.pageEditBusy
|
|
461
|
+
case 'preview-flush-unavailable': return t.pageEditPreview
|
|
462
|
+
case 'page-context-changed': return t.pageEditChanged
|
|
463
|
+
case 'save-timeout': return t.pageEditFlushTimeout
|
|
464
|
+
case 'source-draft': return t.pageEditSourceDraft
|
|
465
|
+
case 'source-refresh': return t.pageEditRefresh
|
|
466
|
+
case 'page-draft':
|
|
467
|
+
case 'source-conflict':
|
|
468
|
+
case 'narration-conflict':
|
|
469
|
+
case 'revision-conflict': return t.pageEditDraft
|
|
470
|
+
case 'save-locked': return t.saveLocked
|
|
471
|
+
default: return t.pageEditRequestFailed
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
pageCapability(section: string): { rename: boolean, move: boolean, reason?: string } {
|
|
476
|
+
const exists = Boolean(this.#store.state.authoring?.content?.sections[section])
|
|
477
|
+
const capability = { rename: exists, move: exists }
|
|
478
|
+
if (isAgentChanging(this.#store.state)) return { rename: false, move: false, reason: MESSAGES[this.#store.state.locale].saveLocked }
|
|
479
|
+
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 }
|
|
480
|
+
return capability
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
clearFailure(): void { this.#store.set({ pageEditFailure: undefined }) }
|
|
484
|
+
|
|
485
|
+
}
|
|
@@ -1,21 +1,23 @@
|
|
|
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
|
-
import { documentSelection } from './selection.ts'
|
|
13
|
+
import { documentSelection, nativeTextPoint } from './selection.ts'
|
|
13
14
|
import type { NativeDocumentSelection } from './selection.ts'
|
|
14
15
|
import { DOCUMENT_EDITOR_MESSAGES, IMAGE_IMPORT_MESSAGES, slashAliases } from './messages.ts'
|
|
15
16
|
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,17 +82,31 @@ 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
|
|
|
96
|
+
/** Text comments require a text range; opaque blocks use their preview's place-comment entry. */
|
|
97
|
+
function DocumentAddCommentButton() {
|
|
98
|
+
const editor = useBlockNoteEditor(documentEditorSchema)
|
|
99
|
+
const selectedText = useEditorState({ editor, selector: ({ editor }) => {
|
|
100
|
+
const { selection } = editor.prosemirrorState
|
|
101
|
+
return !selection.empty && Boolean(nativeTextPoint(editor, selection.from) && nativeTextPoint(editor, selection.to))
|
|
102
|
+
} })
|
|
103
|
+
return selectedText ? <AddCommentButton /> : null
|
|
104
|
+
}
|
|
105
|
+
|
|
90
106
|
function EditorToolbar(props: FormattingToolbarProps) {
|
|
91
107
|
const editor = useBlockNoteEditor(documentEditorSchema)
|
|
92
108
|
const title = useEditorState({ editor, selector: ({ editor }) => editor.getSelection()?.blocks.some(block => block.type === 'presmiumPage') ?? false })
|
|
93
|
-
if (title) return <FormattingToolbar {...props}><
|
|
109
|
+
if (title) return <FormattingToolbar {...props}><DocumentAddCommentButton /></FormattingToolbar>
|
|
94
110
|
return <FormattingToolbar {...props}>
|
|
95
111
|
<BlockTypeSelect items={props.blockTypeSelectItems} />
|
|
96
112
|
<BasicTextStyleButton basicTextStyle="bold" /><BasicTextStyleButton basicTextStyle="italic" />
|
|
@@ -98,7 +114,7 @@ function EditorToolbar(props: FormattingToolbarProps) {
|
|
|
98
114
|
<TextAlignButton textAlignment="left" /><TextAlignButton textAlignment="center" /><TextAlignButton textAlignment="right" />
|
|
99
115
|
<DocumentColorButton /><NestBlockButton /><UnnestBlockButton /><CreateLinkButton /><FormulaToolbarButton />
|
|
100
116
|
<TableCellMergeButton />
|
|
101
|
-
<
|
|
117
|
+
<DocumentAddCommentButton />
|
|
102
118
|
</FormattingToolbar>
|
|
103
119
|
}
|
|
104
120
|
|
|
@@ -110,13 +126,14 @@ function PlainContentComments({ editor }: { editor: NativeDocumentEditor }) {
|
|
|
110
126
|
return plain
|
|
111
127
|
} })
|
|
112
128
|
// BlockNote hides formatting controls over code; its own comment action still applies.
|
|
113
|
-
return show && editor.getExtension('comments') ? <div className="pm-document-editor__comment-tools"><FormattingToolbar><
|
|
129
|
+
return show && editor.getExtension('comments') ? <div className="pm-document-editor__comment-tools"><FormattingToolbar><DocumentAddCommentButton /></FormattingToolbar></div> : null
|
|
114
130
|
}
|
|
115
131
|
|
|
116
|
-
//
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
132
|
+
// Added items join the end of their group (formulas the one that holds tables, the animation request the one that holds
|
|
133
|
+
// pictures) so the menu keeps one heading per group.
|
|
134
|
+
function withGroupItems<Item extends { group?: string }>(items: Item[], added: Item[]): Item[] {
|
|
135
|
+
const index = items.findLastIndex(item => item.group === added[0]?.group)
|
|
136
|
+
return index < 0 ? [...items, ...added] : [...items.slice(0, index + 1), ...added, ...items.slice(index + 1)]
|
|
120
137
|
}
|
|
121
138
|
|
|
122
139
|
/** One native editor owns selection, transactions and history across the complete document. */
|
|
@@ -156,7 +173,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
|
|
|
156
173
|
dictionary, tables: { splitCells: true, cellBackgroundColor: true, cellTextColor: true, headers: true },
|
|
157
174
|
// The surface's own click handler opens links in editable and read-only states alike.
|
|
158
175
|
links: { onClick: () => true },
|
|
159
|
-
extensions: [nativeTextClipboard, documentBlockColors, imageFileInput({
|
|
176
|
+
extensions: [nativeTextClipboard, documentBlockColors, documentPageBodies(), imageFileInput({
|
|
160
177
|
onStart: () => { if (current.current.identity === props.identity) setFileErrors(undefined) },
|
|
161
178
|
onFailure: failure => { if (current.current.identity === props.identity) setFileErrors(value => ({ identity: props.identity, failures: [...(value?.identity === props.identity ? value.failures : []), failure] })) },
|
|
162
179
|
}), ...props.comments ? [nativeCommentSelection(), nativeComments(props.comments, t.author)] : []],
|
|
@@ -171,7 +188,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
|
|
|
171
188
|
stopCommentHistory?.(); current.current.onReady?.(undefined)
|
|
172
189
|
}
|
|
173
190
|
}, [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}>
|
|
191
|
+
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
192
|
<div className="pm-document-editor pm-ui-block-editor pm-ui" data-document-editor={props.identity}
|
|
176
193
|
onDragEnter={event => { if (event.dataTransfer.types.includes('Files')) event.stopPropagation() }}
|
|
177
194
|
onDragOver={event => { if (event.dataTransfer.types.includes('Files')) event.stopPropagation() }}
|
|
@@ -184,7 +201,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
|
|
|
184
201
|
}}
|
|
185
202
|
onCompositionStart={() => current.current.onComposition?.(true)}
|
|
186
203
|
onCompositionEnd={() => queueMicrotask(() => current.current.onComposition?.(false))}>
|
|
187
|
-
{fileErrors?.identity === props.identity && <PmNotice tone="danger"><
|
|
204
|
+
{fileErrors?.identity === props.identity && <PmNotice tone="danger" action={<PmIconButton small icon="close" label={fileMessages.dismiss} onClick={() => setFileErrors(undefined)} />}><ul className="pm-document-editor__file-errors">{fileErrors.failures.map((failure, index) => <li key={index}>{failure.name} · {fileMessages[failure.kind]}</li>)}</ul></PmNotice>}
|
|
188
205
|
<BlockNoteView editor={editor} editable={!props.readOnly} theme={DOCUMENT_EDITOR_THEME} formattingToolbar={false} slashMenu={false} linkToolbar={false} sideMenu={false} tableHandles={false} renderEditor={false} comments={false}
|
|
189
206
|
onChange={() => current.current.onChange(editor.document, editor)}
|
|
190
207
|
onSelectionChange={() => current.current.onSelection?.(documentSelection(editor))}>
|
|
@@ -196,14 +213,23 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
|
|
|
196
213
|
<LinkToolbarController linkToolbar={DocumentLinkToolbar} floatingUIOptions={linkToolbarOptions} />
|
|
197
214
|
<SideMenuController sideMenu={DocumentSideMenu} />
|
|
198
215
|
<TableHandlesController tableHandle={DocumentTableHandle} tableCellHandle={DocumentTableCellButton} />
|
|
199
|
-
<SuggestionMenuController triggerCharacter="/" getItems={async query => editor.getTextCursorPosition().block.type === 'presmiumPage' ? [] : filterSuggestionItems([...
|
|
216
|
+
<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() ? [{
|
|
217
|
+
title: t.animateWithAI, subtext: t.animateWithAIHint, group: dictionary.slash_menu.image.group, icon: <PmIcon name="sparkle" />, aliases: slashAliases('animateWithAIAliases'),
|
|
218
|
+
// The menu has already taken back the typed “/” and query; the AI is asked, the document stays as it was.
|
|
219
|
+
onItemClick: () => current.current.animationRequest?.request(editor),
|
|
220
|
+
}] : []), {
|
|
200
221
|
title: t.page, aliases: slashAliases('pageAliases'), group: t.document,
|
|
201
|
-
onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId:
|
|
222
|
+
onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId: randomUUID() }, content: t.untitledPage }], current, 'after') },
|
|
202
223
|
}], query)} />
|
|
203
224
|
{props.children}
|
|
204
225
|
</NewCommentDraftProvider></BlockNoteViewEditor>
|
|
205
226
|
</ComponentsContext.Provider>
|
|
206
227
|
</BlockNoteView>
|
|
228
|
+
<div className="pm-document-editor__end" aria-hidden="true" data-editable={props.readOnly ? undefined : ''} onMouseDown={event => {
|
|
229
|
+
if (event.button !== 0 || !editor.isEditable || editor.prosemirrorView.composing) return
|
|
230
|
+
event.preventDefault()
|
|
231
|
+
focusDocumentEnd(editor)
|
|
232
|
+
}} />
|
|
207
233
|
</div>
|
|
208
234
|
</COMMENT_EDITOR_CONTEXT.Provider></DOCUMENT_NODE_VIEWS.Provider></DOCUMENT_LINKS.Provider></DOCUMENT_EDITOR_LOCALE.Provider>
|
|
209
235
|
}
|