@lincyaw/workbench 0.2.0-rc.8 → 0.2.0-rc.80

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 (90) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +4 -3
  3. package/src/StepProductionEditor.tsx +13 -4
  4. package/src/approvals.tsx +6 -1
  5. package/src/audio-recording.ts +27 -5
  6. package/src/authoring-client.ts +10 -10
  7. package/src/authoring-draft-fragment.ts +3 -1
  8. package/src/authoring-window.ts +100 -0
  9. package/src/body-draft-actions.ts +60 -0
  10. package/src/caption-timing-drafts.ts +18 -1
  11. package/src/component-property-drafts.ts +5 -5
  12. package/src/components.tsx +22 -31
  13. package/src/context.tsx +5 -3
  14. package/src/diagnostics.ts +1 -1
  15. package/src/document-draft-store.ts +45 -18
  16. package/src/document-drafts.ts +28 -19
  17. package/src/document-editing.ts +484 -0
  18. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  19. package/src/document-editor/ComponentMaterials.tsx +3 -9
  20. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  21. package/src/document-editor/DocumentBlockPreview.tsx +4 -2
  22. package/src/document-editor/DocumentComments.tsx +85 -14
  23. package/src/document-editor/DocumentEditor.tsx +44 -7
  24. package/src/document-editor/DocumentStepNarration.tsx +33 -25
  25. package/src/document-editor/NarrationEditor.tsx +54 -20
  26. package/src/document-editor/NewCommentDrafts.tsx +114 -31
  27. package/src/document-editor/PlaceComment.tsx +228 -0
  28. package/src/document-editor/comment-draft-actions.ts +40 -20
  29. package/src/document-editor/comment-draft-inspection.ts +2 -2
  30. package/src/document-editor/comment-drafts.ts +73 -25
  31. package/src/document-editor/comments.ts +30 -10
  32. package/src/document-editor/component-label.ts +11 -0
  33. package/src/document-editor/file-input.ts +2 -2
  34. package/src/document-editor/focus.ts +0 -2
  35. package/src/document-editor/insertion-place.ts +60 -0
  36. package/src/document-editor/messages.ts +3 -3
  37. package/src/document-editor/narration-schema.tsx +12 -6
  38. package/src/document-editor/narration.ts +19 -3
  39. package/src/document-editor/page-body.ts +60 -0
  40. package/src/document-editor/projection.ts +2 -2
  41. package/src/document-editor/rich-text.ts +3 -2
  42. package/src/document-editor/selection.ts +13 -0
  43. package/src/document-editor/style.css +12 -1
  44. package/src/document-editor/table-identities.ts +2 -1
  45. package/src/document-production.ts +491 -0
  46. package/src/document-session.ts +202 -56
  47. package/src/document-timing-drafts.ts +22 -2
  48. package/src/history.ts +5 -5
  49. package/src/index.ts +6 -5
  50. package/src/jobs.ts +1 -1
  51. package/src/media-drafts.ts +43 -1
  52. package/src/messages.ts +31 -14
  53. package/src/panels/DocumentView.tsx +71 -28
  54. package/src/panels/DocumentVoiceDialog.tsx +25 -9
  55. package/src/panels/DocumentVoiceField.tsx +1 -1
  56. package/src/panels/ExportPanel.tsx +1 -6
  57. package/src/panels/HistoryPanel.tsx +32 -2
  58. package/src/panels/PageDeleteDialog.tsx +4 -4
  59. package/src/panels/PageRenameDialog.tsx +1 -1
  60. package/src/panels/PreviewPanel.tsx +1 -4
  61. package/src/panels/ProductionCaptionSize.tsx +20 -0
  62. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  63. package/src/panels/ProductionMediaClips.tsx +23 -7
  64. package/src/panels/ProductionPanel.tsx +8 -4
  65. package/src/panels/ProductionRecording.tsx +86 -9
  66. package/src/panels/ProductionRecordingRange.tsx +21 -19
  67. package/src/panels/ProductionTimeline.tsx +6 -1
  68. package/src/panels/ProductionTranscription.tsx +5 -4
  69. package/src/panels/SourceDocumentPanel.tsx +16 -36
  70. package/src/panels/TranscriptionAdoption.tsx +40 -34
  71. package/src/panels/VoiceCloneDialog.tsx +2 -1
  72. package/src/panels/VoiceoverDialog.tsx +1 -1
  73. package/src/places.ts +1 -36
  74. package/src/preview-playback.ts +1 -1
  75. package/src/production-draft-actions.ts +37 -0
  76. package/src/production-messages.ts +6 -0
  77. package/src/production-playback.ts +1 -1
  78. package/src/production-voice-playback.ts +3 -2
  79. package/src/sha256.ts +9 -0
  80. package/src/styles.css +21 -43
  81. package/src/transcription-drafts.ts +124 -0
  82. package/src/use-recording-adoption.ts +2 -2
  83. package/src/voice-drafts.ts +32 -8
  84. package/src/voiceover-jobs.ts +1 -1
  85. package/src/workbench-state.ts +157 -0
  86. package/src/workbench.ts +258 -951
  87. package/src/workspace-client.ts +21 -11
  88. package/src/assistant-mascot.ts +0 -62
  89. package/src/mascot-preference.ts +0 -37
  90. package/src/panels/ChangeTrail.tsx +0 -79
@@ -10,6 +10,7 @@ import { BLOCK_PREVIEW_MESSAGES } from './block-preview-messages.ts'
10
10
  import { documentBlockSection, DocumentStepNarration } from './DocumentStepNarration.tsx'
11
11
  import { DocumentBlockPlayback } from './block-playback.ts'
12
12
  import { ComponentPropertiesDialog } from './ComponentPropertiesDialog.tsx'
13
+ import { PlaceCommentButton } from './PlaceComment.tsx'
13
14
  import { COMPONENT_PROPERTY_MESSAGES } from '../component-property-messages.ts'
14
15
 
15
16
  interface Snapshot { address: string, revision: string }
@@ -29,8 +30,8 @@ export function DocumentBlockPreview({ blockId, fallback }: { blockId: string, f
29
30
  const sectionId = source?.content && documentBlockSection(source.content, blockId)
30
31
  const section = sectionId ? source?.content?.sections[sectionId] : undefined
31
32
  const stepId = section?.stepOrder[position && position.section === sectionId ? position.step : 0] ?? section?.stepOrder[0]
32
- const [narrationOpen, setNarrationOpen] = useState(() => Boolean(workbench.pendingDocumentField(blockId, source?.identity)
33
- || source?.identity && stepId && (workbench.documentTimingDraft(stepId, 'minimumHoldMs', source.identity, source.reset) || workbench.documentTimingDraft(stepId, 'trailingPauseMs', source.identity, source.reset)))), narrationPanel = useId()
33
+ const [narrationOpen, setNarrationOpen] = useState(() => Boolean(workbench.editing.pendingField(blockId, source?.identity)
34
+ || source?.identity && stepId && (workbench.production.timingDraft(stepId, 'minimumHoldMs', source.identity, source.reset) || workbench.production.timingDraft(stepId, 'trailingPauseMs', source.identity, source.reset)))), narrationPanel = useId()
34
35
  const root = useRef<HTMLElement>(null), viewport = useRef<HTMLDivElement>(null), frame = useRef<HTMLIFrameElement | null>(null)
35
36
  const mountFrame = useCallback((element: HTMLIFrameElement | null) => {
36
37
  frame.current = element
@@ -216,6 +217,7 @@ export function DocumentBlockPreview({ blockId, fallback }: { blockId: string, f
216
217
  return <section ref={root} className="pm-ui-block-preview" data-block-preview={blockId} data-status={state.status} contentEditable={false}>
217
218
  <header className="pm-ui-block-preview__header"><span className="pm-ui-block-preview__label" role={state.status === 'failed' ? 'status' : undefined}><PmIcon name="slides" />{state.status === 'failed' ? t.previewFailure : old && state.snapshot ? t.previewPrevious : state.status === 'preparing' ? p.preparing : state.status === 'loading' ? t.previewLoading : t.previewSnapshot}</span>
218
219
  <span className="pm-ui-block-preview__actions">
220
+ {sectionId && stepId && <PlaceCommentButton blockId={blockId} sectionId={sectionId} stepId={stepId} stepIndex={section ? section.stepOrder.indexOf(stepId) + 1 : 1} onPause={pause} />}
219
221
  {source?.content?.blocks[blockId]?.type === 'component' && <PmIconButton small icon="sliders" label={COMPONENT_PROPERTY_MESSAGES[locale].properties}
220
222
  data-component-properties={blockId} disabled={!source.identity || workbench.client.capabilities?.readOnly} onClick={() => { if (source.identity && !workbench.client.capabilities?.readOnly) setProperties({ identity: source.identity, stepId }) }} />}
221
223
  {workbench.client.capabilities?.narration !== false && <PmIconButton small icon="captions" label={t.stepCaptions} aria-expanded={narrationOpen} aria-controls={narrationOpen ? narrationPanel : undefined} aria-pressed={narrationOpen} disabled={!stepId} onClick={() => {
@@ -1,22 +1,29 @@
1
1
  import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
2
  import type { FocusEvent, ReactNode } from 'react'
3
+ import { documentAnchorOrder, isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
4
+ import type { DocumentPlaceAnchor, TeachingDocument } from '@lincyaw/kernel'
3
5
  import { CommentEditorSubmitExtension, CommentsExtension } from '@blocknote/core/comments'
4
6
  import { components } from '@blocknote/mantine'
5
7
  import { FloatingThreadController, getReferenceText, Thread, useBlockNoteEditor, useCreateBlockNote, useEditorState, useExtension, useExtensionState, useThreads } from '@blocknote/react'
6
8
  import type { ComponentProps, ThreadProps } from '@blocknote/react'
7
9
  import type { Locale } from '../messages.ts'
8
10
  import { PmButton, PmEmpty, PmNotice, PmSelect } from '../components.tsx'
11
+ import { isApprovalTarget } from '../approvals.tsx'
12
+ import { useWorkbenchState } from '../context.tsx'
9
13
  import { enterSubmits } from './comments.ts'
10
14
  import type { DocumentCommentEditorHandle, DocumentThreadStore } from './comments.ts'
11
15
  import type { CommentDrafts, CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, CommentDraftOperation } from './comment-drafts.ts'
12
- import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
13
- import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
16
+ import { commentDraftBaseline, isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
17
+ import { discardNativeCommentDraft } from './comment-draft-actions.ts'
18
+ import { waitForDraft } from '../document-draft-store.ts'
19
+ import { createRichProjection, fallbackText, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
14
20
  import { commentEditorSchema } from './schema.tsx'
15
21
  import type { DocumentEditorBlock } from './schema.tsx'
16
22
  import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
23
+ import { componentDefinitionLabel } from './component-label.ts'
17
24
  import { commentFloating } from './popover.tsx'
18
25
 
19
- export const COMMENT_EDITOR_CONTEXT = createContext<{ store: DocumentThreadStore, locale: Locale, sidebar: boolean, getPositionToken?(): string | undefined, onDraftRestore?(): void } | undefined>(undefined)
26
+ export const COMMENT_EDITOR_CONTEXT = createContext<{ store: DocumentThreadStore, locale: Locale, sidebar: boolean, readOnly?: boolean, getPositionToken?(): string | undefined, onDraftRestore?(): void, openComments?(): void } | undefined>(undefined)
20
27
  const THREAD_CONTEXT = createContext<string | undefined>(undefined)
21
28
  const emptySubscribe = () => () => {}
22
29
  const emptyState = { candidates: [], pending: false, failed: false, reading: false } as const
@@ -32,12 +39,14 @@ export function DocumentCommentThread(props: ThreadProps) {
32
39
 
33
40
  /** Keep the native controller and reply editor while body selection owns the pointer. */
34
41
  export function DocumentFloatingThreadController() {
35
- const editor = useBlockNoteEditor(), { selectedThreadId } = useExtensionState(CommentsExtension)
42
+ const editor = useBlockNoteEditor(), { selectedThreadId, threadPositions } = useExtensionState(CommentsExtension)
36
43
  const empty = useEditorState({ editor, on: 'selection', selector: ({ editor }) => editor.prosemirrorState.selection.empty })
37
44
  const [selecting, setSelecting] = useState(false)
38
45
  const blocked = selecting || !empty
46
+ // A place thread has no text mark; it belongs to the sidebar only and must not open a floating card.
47
+ const positioned = Boolean(selectedThreadId && threadPositions.has(selectedThreadId))
39
48
  const shown = useRef(false), thread = useRef(selectedThreadId)
40
- shown.current = Boolean(selectedThreadId) && !blocked
49
+ shown.current = positioned && !blocked
41
50
  thread.current = selectedThreadId
42
51
  // The pointer that last pressed commented text, and the line of the thread chosen from it (the first line without one).
43
52
  const point = useRef<{ x: number, y: number }>(), line = useRef<{ thread: string, index: number }>()
@@ -101,26 +110,69 @@ export function DocumentFloatingThreadController() {
101
110
  return rects[Math.min(line.current.index, rects.length - 1)]
102
111
  }), [editor])
103
112
  return <FloatingThreadController floatingThread={DocumentCommentThread} floatingUIOptions={{
104
- useFloatingOptions: { ...floating, open: Boolean(selectedThreadId) && !blocked },
113
+ useFloatingOptions: { ...floating, open: positioned && !blocked },
105
114
  elementProps: { className: blocked ? 'pm-ui-comment-hidden' : undefined },
106
115
  }} />
107
116
  }
108
117
 
118
+ function placeReference(document: TeachingDocument | undefined, anchor: DocumentPlaceAnchor, t: typeof DOCUMENT_EDITOR_MESSAGES['zh-CN']): string {
119
+ if (!document) return ''
120
+ const block = document.blocks[anchor.blockId]
121
+ let label: string
122
+ if (block?.type === 'component') {
123
+ const definition = document.definitions[block.definitionId]
124
+ const author = typeof block.parameters.title === 'string' ? block.parameters.title.trim() : ''
125
+ const data = definition?.data && typeof definition.data.title === 'string' ? definition.data.title.trim() : ''
126
+ const schema = definition && typeof definition.parameterSchema === 'object' && typeof definition.parameterSchema.title === 'string' ? definition.parameterSchema.title.trim() : ''
127
+ const name = author || data || schema || (definition ? componentDefinitionLabel(definition) : block.definitionId)
128
+ label = definition?.kind === 'scene' ? t.animation(name) : t.component(name)
129
+ } else if (block?.type === 'code') label = t.codeReference(block.title ?? block.origin?.anchor ?? block.language)
130
+ else if (block?.type === 'image') label = block.alt || t.block
131
+ else if (block?.type === 'text') label = (block.content[0] ? Array.from(fallbackText(block.content[0]).replace(/\s+/g, ' ').trim()).slice(0, 40).join('') : '') || t.block
132
+ else if (block?.type === 'container') label = block.properties.title || t.block
133
+ else label = t.block
134
+ if (anchor.stepId === undefined) return t.placeCommentReference(label)
135
+ const step = document.steps[anchor.stepId], section = step ? document.sections[step.sectionId] : undefined
136
+ return t.placeCommentReference(label, step && section ? section.stepOrder.indexOf(step.id) + 1 : 0)
137
+ }
138
+
109
139
  /** Native Thread composition, with the same public focus/blur and position ordering as the sidebar. */
110
140
  export function DocumentThreadsSidebar({ children }: { children?: ReactNode }) {
111
141
  const editor = useBlockNoteEditor(), comments = useExtension(CommentsExtension), threads = useThreads()
112
142
  const { selectedThreadId, threadPositions } = useExtensionState(CommentsExtension)
113
- const ordered = [...threads.values()].sort((a, b) => (threadPositions.get(a.id)?.from ?? Number.MAX_VALUE) - (threadPositions.get(b.id)?.from ?? Number.MAX_VALUE))
143
+ const context = useContext(COMMENT_EDITOR_CONTEXT), t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
144
+ const document = useWorkbenchState(state => state.authoring?.content) ?? context?.store.document
145
+ const places = useMemo(() => document ? documentAnchorOrder(document) : new Map<string, number>(), [document])
146
+ const place = (threadId: string): number => {
147
+ const anchor = context?.store.anchorOf(threadId)
148
+ if (!anchor) return Number.MAX_VALUE
149
+ if (isDocumentPlaceAnchor(anchor)) {
150
+ const order = places.get(anchor.blockId)
151
+ const step = anchor.stepId === undefined ? undefined : document?.steps[anchor.stepId]
152
+ const section = step && document ? document.sections[step.sectionId] : undefined
153
+ return order === undefined ? Number.MAX_VALUE : order * 1_000_000 + (step && section ? section.stepOrder.indexOf(step.id) : 0)
154
+ }
155
+ const order = places.get(anchor.from.blockId)
156
+ return order === undefined ? Number.MAX_VALUE : order * 1_000_000 + Math.min(999_999, anchor.from.offset)
157
+ }
158
+ const reference = (threadId: string): string | undefined => {
159
+ const anchor = context?.store.anchorOf(threadId)
160
+ return anchor && isDocumentPlaceAnchor(anchor) ? placeReference(document, anchor, t) : getReferenceText(editor, threadPositions.get(threadId))
161
+ }
162
+ const orphaned = (threadId: string): boolean => {
163
+ const anchor = context?.store.anchorOf(threadId)
164
+ return !(anchor && isDocumentPlaceAnchor(anchor)) && !threadPositions.has(threadId)
165
+ }
166
+ const ordered = [...threads.values()].sort((a, b) => place(a.id) - place(b.id) || a.createdAt.getTime() - b.createdAt.getTime())
114
167
  const focus = (id: string, event: FocusEvent) => { if (!(event.target as HTMLElement).closest('.bn-action-toolbar')) comments.selectThread(id) }
115
168
  const blur = (event: FocusEvent) => {
116
169
  const next = event.relatedTarget
117
- if (!next || next.closest('.bn-action-toolbar')) return
170
+ if (!next || isApprovalTarget(next) || next.closest('.bn-action-toolbar')) return
118
171
  const parent = next.closest('.bn-thread')
119
172
  if (!parent || !(event.target instanceof Node) || !parent.contains(event.target)) comments.selectThread(undefined)
120
173
  }
121
- const context = useContext(COMMENT_EDITOR_CONTEXT), t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
122
174
  return <div className="bn-threads-sidebar">{children}<CommentDraftRetrieval />{!ordered.length && <PmEmpty icon="comment">{t.commentsEmpty}</PmEmpty>}{ordered.map(thread => <DocumentCommentThread key={thread.id} thread={thread}
123
- selected={selectedThreadId === thread.id} orphaned={!threadPositions.has(thread.id)} referenceText={getReferenceText(editor, threadPositions.get(thread.id))}
175
+ selected={selectedThreadId === thread.id} orphaned={orphaned(thread.id)} referenceText={reference(thread.id)}
124
176
  onFocus={event => focus(thread.id, event)} onBlur={blur} tabIndex={0} />)}</div>
125
177
  }
126
178
 
@@ -174,7 +226,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
174
226
  return value
175
227
  }, [props.editor, drafts])
176
228
  const rich = useMemo(() => ({ current: record.rich }), [record])
177
- const composerId = useRef(crypto.randomUUID())
229
+ const composerId = useRef(randomUUID())
178
230
  const state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState))
179
231
  useLayoutEffect(() => {
180
232
  if (!context || !threadId) return
@@ -242,7 +294,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
242
294
  || props.editor.prosemirrorState.selection !== native.selection || context.getPositionToken?.() !== position || record.current !== own
243
295
  || context.store.draftTargetState(target) === 'unavailable') throw new Error('client-comment-composer-changed')
244
296
  }
245
- if (own && !await drafts.confirm(own)) return
297
+ if (own && !await waitForDraft(drafts.confirm(own), operation?.signal)) return
246
298
  owns()
247
299
  const value = await drafts.recover(candidate, target, version, { signal: operation?.signal, guard: owns })
248
300
  if (!value) return
@@ -258,11 +310,30 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
258
310
  if (!operation) await drafts.discard(candidate)
259
311
  return value
260
312
  }
313
+ const discardActive = async (candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean> => {
314
+ const own = record.current, version = context?.store.version, before = input.current, native = props.editor.prosemirrorState, position = context?.getPositionToken?.()
315
+ if (!drafts || !context || !target || !version || !own || own.id !== candidate.id || own.revision !== candidate.revision) return false
316
+ const guard = () => {
317
+ context.store.beforeAction?.()
318
+ if (!active.current || !current.current.editable || context.store.version !== version || composing.current || submitting.current || input.current !== before || record.current !== own
319
+ || props.editor.prosemirrorView.isDestroyed || props.editor.prosemirrorView.composing || props.editor.prosemirrorState.doc !== native.doc
320
+ || props.editor.prosemirrorState.selection !== native.selection || context.getPositionToken?.() !== position) throw new Error('client-comment-composer-changed')
321
+ }
322
+ const saved = target.commentId ? context.store.threadSnapshot(target.threadId)?.comments.find(value => value.id === target.commentId && !value.deletedAt) : undefined
323
+ if (target.commentId && !saved?.content) return false
324
+ return discardNativeCommentDraft(drafts, candidate, operation, guard, () => {
325
+ suppress.current = true
326
+ try {
327
+ props.editor.replaceBlocks(props.editor.document, saved?.content ? productRichTextToNative(saved.content, rich.current) : [{ type: 'paragraph', content: [] }])
328
+ record.current = undefined; input.current++; handle?.restoreBaseline(saved ? commentDraftBaseline(saved) : undefined); setRevision(value => value + 1)
329
+ } finally { suppress.current = false }
330
+ })
331
+ }
261
332
  useLayoutEffect(() => {
262
333
  if (!drafts || !target || !props.editable) return
263
334
  return drafts.registerComposer({ id: composerId.current, target,
264
335
  snapshot: () => { const available = active.current && current.current.editable && !submitting.current && !props.editor.prosemirrorView.isDestroyed; return { record: record.current, composing: composing.current || available && props.editor.prosemirrorView.composing, available } },
265
- targetState: () => context?.store.draftTargetState(target) ?? 'unavailable', restore: recover })
336
+ targetState: () => context?.store.draftTargetState(target) ?? 'unavailable', restore: recover, discard: discardActive })
266
337
  }, [drafts, handle, props.editor, props.editable])
267
338
  const composition = (value: boolean) => {
268
339
  composing.current = value
@@ -276,7 +347,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
276
347
  <MantineCommentEditor {...props} />
277
348
  {recoveryFailure && <PmNotice tone="warn">{t.commentRecoveryChanged}</PmNotice>}
278
349
  {failure && <PmNotice tone="danger">{failure === 'changed' ? t.commentChanged : t.commentUnavailable}</PmNotice>}
279
- {drafts && props.editable && <DraftChoices candidates={candidates} disabled={composing.current || submitting.current} onRecover={async candidate => { const captured = handle, owner = recoveryOwner.current; setRecoveryFailure(false); try { await recover(candidate) } catch { if (active.current && current.current.editable && currentHandle.current === captured && recoveryOwner.current === owner) setRecoveryFailure(true) } }} onDiscard={async candidate => { await drafts.discard(candidate) }} />}
350
+ {drafts && props.editable && <DraftChoices candidates={candidates} disabled={composing.current || submitting.current} onRecover={async candidate => { const captured = handle, owner = recoveryOwner.current; setRecoveryFailure(false); try { await recover(candidate) } catch { if (active.current && current.current.editable && currentHandle.current === captured && recoveryOwner.current === owner) setRecoveryFailure(true) } }} onDiscard={async candidate => { await drafts.discardProposal(candidate) }} />}
280
351
  {drafts && props.editable && state.failed && !context?.sidebar && <PmNotice tone="warn">{t.commentBackupFailed}</PmNotice>}
281
352
  </div>
282
353
  }
@@ -1,7 +1,8 @@
1
1
  import { useEffect, useMemo, useRef } from 'react'
2
2
  import type { Transaction } from '@tiptap/pm/state'
3
+ import { TextSelection } from '@tiptap/pm/state'
3
4
  import { closeHistory } from '@tiptap/pm/history'
4
- import { allocateDocumentPage } from '@lincyaw/kernel'
5
+ import { allocateDocumentPage, randomUUID } from '@lincyaw/kernel'
5
6
  import type { Member, TeachingDocument } from '@lincyaw/kernel'
6
7
  import type { Locale } from '../messages.ts'
7
8
  import { BlockNoteSurface } from './BlockNoteSurface.tsx'
@@ -12,17 +13,25 @@ import type { NativePageCreation } from './projection.ts'
12
13
  import { captureRichBaseline } from './rich-text.ts'
13
14
  import { captureTableIdentities, seedTableIdentities } from './table-identities.ts'
14
15
  import type { DocumentNodeViews, NativeDocumentEditor } from './schema.tsx'
15
- import { nativeEditingCursor } from './selection.ts'
16
- import type { NativeDocumentSelection } from './selection.ts'
16
+ import { nativeEditingCursor, nativeTextPoint, nativeTextPosition } from './selection.ts'
17
+ import type { NativeDocumentSelection, NativeTextPoint } from './selection.ts'
18
+ import { documentInsertionPlace } from './insertion-place.ts'
19
+ import type { DocumentInsertionPlace } from './insertion-place.ts'
17
20
 
18
21
  export interface DocumentEditingPosition {
19
22
  nativeBlockId: string
20
23
  sectionId: string
21
24
  position: number
22
25
  }
26
+ /** Who takes the slash menu's request for an animation where it was opened; while none is available the menu has no such item. */
27
+ export interface DocumentAnimationRequests {
28
+ available(): boolean
29
+ request(place: DocumentInsertionPlace): void
30
+ }
23
31
  export interface DocumentEditorCommands {
24
32
  insertPage(after: string | undefined, title: string): NativePageCreation
25
33
  rememberComponentConfiguration(document: TeachingDocument): void
34
+ handleAnimationRequests(requests: DocumentAnimationRequests | undefined): void
26
35
  }
27
36
 
28
37
  export interface DocumentEditorProps {
@@ -56,6 +65,7 @@ export interface DocumentEditorProps {
56
65
  onError?(error: Error): void
57
66
  commentsPortal?: HTMLElement | null
58
67
  onCommentDraftRestore?(): void
68
+ onOpenComments?(): void
59
69
  }
60
70
 
61
71
  /** A source version reset replaces the editor; its own save receipts never replace it. */
@@ -73,11 +83,19 @@ export function DocumentEditor(props: DocumentEditorProps) {
73
83
  return () => comments.close()
74
84
  }, [comments])
75
85
  const current = useRef(props), editor = useRef<NativeDocumentEditor>(), unsubscribe = useRef<() => void>()
86
+ const animationRequests = useRef<DocumentAnimationRequests>()
76
87
  const projectedDocument = useRef<NativeDocumentEditor['prosemirrorState']['doc']>()
77
88
  const pendingTransaction = useRef<Transaction>()
78
89
  const focusFrame = useRef<number>()
79
90
  const binding = useRef(projection)
80
91
  const active = useRef(projection)
92
+ const editorIdentity = useRef(props.identity)
93
+ const retainedSelection = useRef<{ from: NativeTextPoint, to: NativeTextPoint }>()
94
+ const previous = editor.current
95
+ if (binding.current !== projection && editorIdentity.current === props.identity && previous?.isFocused() && !previous.prosemirrorView.composing) {
96
+ const from = nativeTextPoint(previous, previous.prosemirrorState.selection.anchor), to = nativeTextPoint(previous, previous.prosemirrorState.selection.head)
97
+ if (from && to) retainedSelection.current = { from, to }
98
+ }
81
99
  active.current = projection
82
100
  current.current = props
83
101
  const cancelFocus = () => { if (focusFrame.current !== undefined) cancelAnimationFrame(focusFrame.current); focusFrame.current = undefined }
@@ -113,7 +131,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
113
131
  if (!latest || current.current.getDocumentVersion && current.current.getDocumentVersion() === undefined) return
114
132
  syncComments()
115
133
  const document = nativeDocumentToProduct(editor.current.document, projection, latest)
116
- const threads = comments.snapshot(editor.current)
134
+ const threads = comments.snapshot(editor.current, document)
117
135
  if (Object.keys(threads).length) document.comments = threads
118
136
  else delete document.comments
119
137
  current.current.onChange(document)
@@ -125,7 +143,16 @@ export function DocumentEditor(props: DocumentEditorProps) {
125
143
  }
126
144
  return <BlockNoteSurface identity={props.identity} reset={props.reset} initialContent={projection.content} locale={props.locale} contentLang={props.document.metadata.lang || 'zh-CN'} readOnly={props.readOnly}
127
145
  resolveAssetURL={props.resolveAssetURL} uploadImage={props.uploadImage}
128
- comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection} onSectionLink={sectionId => {
146
+ comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} onOpenComments={() => current.current.onOpenComments?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection}
147
+ animationRequest={{
148
+ available: () => !current.current.readOnly && binding.current === projection && active.current === projection && Boolean(animationRequests.current?.available()),
149
+ request: value => {
150
+ if (value !== editor.current || binding.current !== projection || active.current !== projection) return
151
+ const place = documentInsertionPlace(value, projection)
152
+ if (place) animationRequests.current?.request(place)
153
+ },
154
+ }}
155
+ onSectionLink={sectionId => {
129
156
  if (!current.current.onSectionLink?.(sectionId)) return false
130
157
  // The click placed the caret in the link; it follows the reader to the page they asked for.
131
158
  const value = editor.current
@@ -147,7 +174,17 @@ export function DocumentEditor(props: DocumentEditorProps) {
147
174
  comments.restoreAnchors(value)
148
175
  binding.current = projection
149
176
  editor.current = value
177
+ editorIdentity.current = props.identity
150
178
  projectedDocument.current = value.prosemirrorState.doc
179
+ const selection = retainedSelection.current
180
+ retainedSelection.current = undefined
181
+ if (selection) {
182
+ const from = nativeTextPosition(value, selection.from), to = nativeTextPosition(value, selection.to)
183
+ if (from !== undefined && to !== undefined) {
184
+ value.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, from, to)).setMeta('addToHistory', false))
185
+ value.focus()
186
+ }
187
+ }
151
188
  const stopBefore = value.onBeforeChange(({ tr }) => { if (!comments.synchronizing && tr.docChanged) pendingTransaction.current = tr })
152
189
  const stopComments = comments.subscribe(emit)
153
190
  const stopSelection = value.onSelectionChange(() => { cancelFocus(); reportPosition() })
@@ -162,7 +199,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
162
199
  })
163
200
  unsubscribe.current = () => { stopBefore(); stopComments(); stopSelection(); stopFocus(); cancelFocus() }
164
201
  }
165
- const commands: DocumentEditorCommands | undefined = value ? { rememberComponentConfiguration: document => {
202
+ const commands: DocumentEditorCommands | undefined = value ? { handleAnimationRequests: requests => { animationRequests.current = requests }, rememberComponentConfiguration: document => {
166
203
  if (editor.current === value && active.current === projection && binding.current === projection && !value.prosemirrorView.isDestroyed) rememberComponentConfiguration(projection, document)
167
204
  }, insertPage: (after, title) => {
168
205
  if (current.current.readOnly || editor.current !== value || active.current !== projection || binding.current !== projection || value.prosemirrorView.isDestroyed) throw new Error('page-context-changed')
@@ -171,7 +208,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
171
208
  const next = after ? blocks.slice(index + 1).find(block => block.type === 'presmiumPage') : undefined
172
209
  const latest = current.current.getDocument ? current.current.getDocument() : current.current.document
173
210
  if (!latest) throw new Error('page-context-changed')
174
- const creation = allocateDocumentPage(latest, () => crypto.randomUUID())
211
+ const creation = allocateDocumentPage(latest, () => randomUUID())
175
212
  projection.createdPages.set(creation.sectionId, creation)
176
213
  try {
177
214
  value.transact(transaction => {
@@ -1,11 +1,12 @@
1
1
  import { useRef, useState } from 'react'
2
- import type { NarrationNode, TeachingDocument } from '@lincyaw/kernel'
2
+ import type { Narration, NarrationNode, TeachingDocument } from '@lincyaw/kernel'
3
+ import { randomUUID } from '@lincyaw/kernel'
3
4
  import { PmIconButton } from '../components.tsx'
4
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
5
- import { isAgentChanging } from '../workbench.ts'
6
+ import { isAgentChanging } from '../workbench-state.ts'
6
7
  import { NarrationEditor } from './NarrationEditor.tsx'
7
8
  import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
8
- import { narrationFieldFocus } from './narration.ts'
9
+ import { narrationFieldFocus, narrationsToNative, nativeToNarrations } from './narration.ts'
9
10
  import type { NativeNarrationEditor } from './narration-schema.tsx'
10
11
  import { StepProductionEditor } from '../StepProductionEditor.tsx'
11
12
 
@@ -23,28 +24,32 @@ export function narrationDisplay(content: readonly NarrationNode[]): string {
23
24
  return content.map(node => node.type === 'text' ? node.text : node.type === 'pronunciation' ? node.display : '').join('')
24
25
  }
25
26
 
26
- function NarrationField({ identity, reset, blockId, stepId, slot, narrationId, content, readOnly, advanced, onPause }: {
27
- identity: string, reset: number, blockId?: string, stepId: string, slot: number, narrationId?: string, content: NarrationNode[], readOnly: boolean, advanced: boolean, onPause(): void,
27
+ function NarrationField({ identity, reset, blockId, stepId, content, readOnly, advanced, onPause }: {
28
+ identity: string, reset: number, blockId?: string, stepId: string, content: Narration[], readOnly: boolean, advanced: boolean, onPause(): void,
28
29
  }) {
29
30
  const workbench = useWorkbench(), locale = useWorkbenchState(state => state.locale)
30
- // Reserving an identity does not create an entity. The first actual input commits it.
31
- const [reservedId] = useState(() => {
32
- const pending = workbench.pendingDocumentField(blockId, identity)
33
- return narrationId ?? (pending?.stepId === stepId ? pending.narrationId : undefined) ?? crypto.randomUUID()
34
- })
35
- const id = narrationId ?? reservedId
36
- const target = () => narrationId ?? workbench.getDocument(identity)?.steps[stepId]?.narrationIds[slot] ?? id
31
+ const [emptyId] = useState(() => randomUUID())
32
+ const read = () => {
33
+ const document = workbench.getDocument(identity), step = document?.steps[stepId]
34
+ return step ? step.narrationIds.map(id => ({ id, content: document!.narrations[id]!.content })) : undefined
35
+ }
37
36
  const registration = useRef<() => void>()
38
37
  const fieldEditor = useRef<NativeNarrationEditor>()
39
- const owner = `narration:${identity}:${reset}:${JSON.stringify(blockId ?? null)}:${stepId}:${slot}:${id}`
40
- return <NarrationEditor identity={identity} reset={reset} narrationId={id} content={content} locale={locale} readOnly={readOnly} advanced={advanced}
41
- getContent={() => { const document = workbench.getDocument(identity); return document ? document.narrations[target()]?.content ?? [] : undefined }}
38
+ const owner = `narration:${identity}:${reset}:${JSON.stringify(blockId ?? null)}:${stepId}`
39
+ return <NarrationEditor identity={identity} reset={reset} fieldId={stepId} content={content} locale={locale} readOnly={readOnly} advanced={advanced} blockMenu
40
+ getContent={read} toNative={value => narrationsToNative(value, emptyId)} fromNative={nativeToNarrations}
41
+ cueOwners={() => {
42
+ const document = workbench.getDocument(identity)
43
+ const retained = new Set(Object.values(document?.steps ?? {}).filter(step => step.id !== stepId).flatMap(step => step.narrationIds))
44
+ return new Map([...retained].flatMap(id => document!.narrations[id]!.content.flatMap(node => node.type === 'cue' ? [[node.id, id] as const] : [])))
45
+ }}
46
+ onCueCopy={(from, to) => workbench.production.copyNarrationCueTiming(from, to, identity)}
42
47
  onReady={editor => {
43
48
  registration.current?.()
44
49
  fieldEditor.current = editor
45
- registration.current = editor ? workbench.registerDocumentField({ identity, reset, blockId, stepId, narrationId: id, slot, focus: narrationFieldFocus(editor), editor }) : undefined
50
+ registration.current = editor ? workbench.editing.registerField({ identity, reset, blockId, stepId, focus: narrationFieldFocus(editor), editor }) : undefined
46
51
  }}
47
- onFocus={() => { workbench.documentInteraction(); if (fieldEditor.current) workbench.activateDocumentHistory(fieldEditor.current); onPause() }} onChange={value => workbench.setDocumentNarration(stepId, target(), value, identity)}
52
+ onFocus={() => { workbench.editing.interact(); if (fieldEditor.current) workbench.editing.activateHistory(fieldEditor.current); onPause() }} onChange={value => workbench.production.setNarrations(stepId, value, identity)}
48
53
  onComposition={composing => workbench.documentComposition(composing, owner, identity)}
49
54
  onError={error => workbench.documentError(error)} />
50
55
  }
@@ -78,15 +83,18 @@ export function DocumentStepNarration({ blockId, sectionId, stepId, expanded, ad
78
83
  {!expanded && text && <p className="pm-ui-block-preview__caption" data-step-caption={stepId}>{text}</p>}
79
84
  {expanded && <div id={panelId} className="pm-ui-block-preview__narration-fields">
80
85
  {showLabel && <span className="pm-ui-block-preview__step-label">{fieldLabel}</span>}
81
- {(ids.length ? ids : [undefined]).map((id, slot) => <NarrationField key={`${source.identity}:${source.reset}:${stepId}:${slot}`}
82
- identity={source.identity!} reset={source.reset} blockId={blockId} stepId={stepId} slot={slot} narrationId={id}
83
- content={id ? document.narrations[id]?.content ?? [] : []} readOnly={readOnly} advanced={advanced} onPause={onPause} />)}
84
- <StepProductionEditor key={`${source.identity}:${source.reset}:${stepId}`} document={document} stepId={stepId} locale={locale} readOnly={readOnly} advanced={advanced}
85
- onPause={onPause} onInteraction={() => workbench.documentInteraction()}
86
- onChange={patch => workbench.setDocumentStepProduction(stepId, patch, source.identity)}
87
- drafts={{ minimumHoldMs: workbench.documentTimingDraft(stepId, 'minimumHoldMs', source.identity, source.reset), trailingPauseMs: workbench.documentTimingDraft(stepId, 'trailingPauseMs', source.identity, source.reset) }}
86
+ <NarrationField key={`narration:${source.identity}:${source.reset}:${stepId}`}
87
+ identity={source.identity!} reset={source.reset} blockId={blockId} stepId={stepId}
88
+ content={ids.map(id => ({ id, content: document.narrations[id]!.content }))} readOnly={readOnly} advanced={advanced} onPause={onPause} />
89
+ <StepProductionEditor key={`timing:${source.identity}:${source.reset}:${stepId}`} document={document} stepId={stepId} locale={locale} readOnly={readOnly} advanced={advanced}
90
+ onPause={onPause} onInteraction={() => workbench.editing.interact()}
91
+ onChange={patch => workbench.production.setStepTiming(stepId, patch, source.identity)}
92
+ drafts={{ minimumHoldMs: workbench.production.timingDraft(stepId, 'minimumHoldMs', source.identity, source.reset), trailingPauseMs: workbench.production.timingDraft(stepId, 'trailingPauseMs', source.identity, source.reset) }}
88
93
  draftStorageFailure={timingStorageFailure}
89
- onDraft={(key, draft) => workbench.setDocumentTimingDraft(stepId, key, draft, source.identity!, source.reset)}
94
+ onDraft={(key, draft) => workbench.production.setTimingDraft(stepId, key, draft, source.identity!, source.reset)}
95
+ draftControlKey={JSON.stringify([source.identity, source.reset, stepId])}
96
+ registerDraftControl={(key, control) => workbench.production.registerDraftView({ identity: source.identity!, kind: 'step-timing',
97
+ has: target => target === JSON.stringify([stepId, key]), blocked: () => control.composing(), clear: () => control.clear() })}
90
98
  onComposition={(key, composing) => workbench.documentComposition(composing, `production:${source.identity}:${source.reset}:${blockId}:${stepId}:${key}`, source.identity)} />
91
99
  </div>}
92
100
  </section>
@@ -1,26 +1,31 @@
1
1
  import { useEffect, useMemo, useRef, useState } from 'react'
2
2
  import { createRoot } from 'react-dom/client'
3
- import type { NarrationNode } from '@lincyaw/kernel'
4
3
  import { blockNoteDictionary } from './blocknote-messages.ts'
5
4
  import { BlockNoteView } from '@blocknote/mantine'
6
- import { useCreateBlockNote } from '@blocknote/react'
7
- import { PmButton, PmDialog, PmInput } from '../components.tsx'
5
+ import { SideMenuExtension } from '@blocknote/core/extensions'
6
+ import { DragHandleMenu, RemoveBlockItem, SideMenu, SideMenuController, useBlockNoteEditor, useComponentsContext, useCreateBlockNote, useDictionary, useExtension, useExtensionState, usePortalElement } from '@blocknote/react'
7
+ import type { SideMenuProps } from '@blocknote/react'
8
+ import { PmButton, PmDialog, PmIcon, PmInput } from '../components.tsx'
8
9
  import type { Locale } from '../messages.ts'
9
10
  import { DOCUMENT_EDITOR_THEME } from './BlockNoteSurface.tsx'
10
- import { narrationToNative, nativeToNarration } from './narration.ts'
11
- import { NARRATION_CONTEXT, NARRATION_MESSAGES, narrationExtensions, narrationSchema } from './narration-schema.tsx'
12
- import type { NativeNarrationEditor } from './narration-schema.tsx'
11
+ import { NARRATION_CONTEXT, NARRATION_MESSAGES, createNarrationExtensions, narrationSchema } from './narration-schema.tsx'
12
+ import type { NativeNarrationBlock, NativeNarrationEditor, NativeNarrationInput } from './narration-schema.tsx'
13
13
 
14
- export interface NarrationEditorProps {
14
+ export interface NarrationEditorProps<T> {
15
15
  identity: string
16
- narrationId: string
17
- content: NarrationNode[]
18
- getContent?(): NarrationNode[] | undefined
16
+ fieldId: string
17
+ content: T
18
+ getContent?(): T | undefined
19
+ toNative(content: T): NativeNarrationInput[]
20
+ fromNative(blocks: readonly NativeNarrationBlock[]): T
21
+ blockMenu?: boolean
22
+ cueOwners?(): ReadonlyMap<string, string>
23
+ onCueCopy?(from: string, to: string): void
19
24
  locale: Locale
20
25
  reset?: number
21
26
  readOnly?: boolean
22
27
  advanced?: boolean
23
- onChange(content: NarrationNode[]): void
28
+ onChange(content: T): void
24
29
  onComposition?(composing: boolean): void
25
30
  onFocus?(): void
26
31
  onError?(error: Error): void
@@ -28,7 +33,7 @@ export interface NarrationEditorProps {
28
33
  }
29
34
 
30
35
  /** A native field can live inside an opaque body node without sharing its DOM event root. */
31
- export function NarrationEditor(props: NarrationEditorProps) {
36
+ export function NarrationEditor<T>(props: NarrationEditorProps<T>) {
32
37
  const mount = useRef<HTMLDivElement>(null), root = useRef<ReturnType<typeof createRoot>>(), current = useRef(props)
33
38
  current.current = props
34
39
  useEffect(() => {
@@ -50,14 +55,40 @@ export function NarrationEditor(props: NarrationEditorProps) {
50
55
  }
51
56
  }, [])
52
57
  useEffect(() => { root.current?.render(<NarrationSurface {...props} />) })
53
- return <div ref={mount} contentEditable={false} data-narration-editor={props.narrationId} />
58
+ return <div ref={mount} contentEditable={false} data-narration-editor={props.fieldId} />
54
59
  }
55
60
 
56
- function NarrationSurface(props: NarrationEditorProps) {
61
+ function NarrationBlockMenu() {
62
+ const components = useComponentsContext()!, dictionary = useDictionary(), portalElement = usePortalElement()
63
+ const sideMenu = useExtension(SideMenuExtension)
64
+ return <components.Generic.Menu.Root position="left" portalElement={portalElement} onOpenChange={open => {
65
+ if (open) sideMenu.freezeMenu()
66
+ else sideMenu.unfreezeMenu()
67
+ }}>
68
+ <components.Generic.Menu.Trigger><components.SideMenu.Button label={dictionary.side_menu.drag_handle_label} icon={<PmIcon name="more" />} /></components.Generic.Menu.Trigger>
69
+ <DragHandleMenu><RemoveBlockItem>{dictionary.drag_handle.delete_menuitem}</RemoveBlockItem></DragHandleMenu>
70
+ </components.Generic.Menu.Root>
71
+ }
72
+
73
+ function InsertNarrationBlock() {
74
+ const editor = useBlockNoteEditor(), components = useComponentsContext()!, dictionary = useDictionary()
75
+ const block = useExtensionState(SideMenuExtension, { selector: state => state?.block })
76
+ if (!block) return null
77
+ return <components.SideMenu.Button label={dictionary.side_menu.add_block_label} icon={<PmIcon name="plus" />} onClick={() => {
78
+ const [inserted] = editor.insertBlocks([{ type: 'paragraph' }], block, 'after')
79
+ editor.setTextCursorPosition(inserted!, 'start'); editor.focus()
80
+ }} />
81
+ }
82
+
83
+ function NarrationSideMenu(props: SideMenuProps) {
84
+ return <SideMenu {...props}><InsertNarrationBlock /><NarrationBlockMenu /></SideMenu>
85
+ }
86
+
87
+ function NarrationSurface<T>(props: NarrationEditorProps<T>) {
57
88
  const current = useRef(props), pending = useRef<string[]>([])
58
89
  current.current = props
59
90
  const canonical = props.getContent?.() ?? props.content
60
- const incoming = JSON.stringify(canonical), sourceKey = JSON.stringify([props.identity, props.narrationId, props.reset])
91
+ const incoming = JSON.stringify(canonical), sourceKey = JSON.stringify([props.identity, props.fieldId, props.reset])
61
92
  const version = useRef({ key: sourceKey, incoming, epoch: 0 })
62
93
  if (version.current.key !== sourceKey) {
63
94
  version.current.epoch++; version.current.key = sourceKey; pending.current = []
@@ -70,10 +101,11 @@ function NarrationSurface(props: NarrationEditorProps) {
70
101
  const instance = useMemo(() => ({ content: structuredClone(canonical), emitted: incoming }), [sourceKey, version.current.epoch])
71
102
  const active = useRef(instance); active.current = instance
72
103
  const t = NARRATION_MESSAGES[props.locale]
73
- const editor = useCreateBlockNote({ schema: narrationSchema, initialContent: narrationToNative(props.narrationId, instance.content),
104
+ const editor = useCreateBlockNote({ schema: narrationSchema, initialContent: props.toNative(instance.content),
74
105
  trailingBlock: false,
75
106
  dictionary: { ...blockNoteDictionary(props.locale), placeholders: { ...blockNoteDictionary(props.locale).placeholders, default: props.advanced === false ? t.emptyCaptions : t.empty } },
76
- extensions: narrationExtensions, domAttributes: { editor: { 'aria-label': props.advanced === false ? t.captions : t.field } },
107
+ extensions: createNarrationExtensions(() => current.current.cueOwners?.() ?? new Map(), (from, to) => current.current.onCueCopy?.(from, to)),
108
+ domAttributes: { editor: { 'aria-label': props.advanced === false ? t.captions : t.field } },
77
109
  }, [instance, props.advanced])
78
110
  const baseline = useMemo(() => JSON.stringify(editor.document), [editor])
79
111
  const [open, setOpen] = useState(false), [display, setDisplay] = useState(''), [spoken, setSpoken] = useState('')
@@ -85,7 +117,7 @@ function NarrationSurface(props: NarrationEditorProps) {
85
117
  if (active.current !== instance) return
86
118
  if (current.current.getContent && current.current.getContent() === undefined) return
87
119
  try {
88
- const content = JSON.stringify(editor.document) === baseline ? structuredClone(instance.content) : nativeToNarration(editor.document)
120
+ const content = JSON.stringify(editor.document) === baseline ? structuredClone(instance.content) : current.current.fromNative(editor.document)
89
121
  const serialized = JSON.stringify(content)
90
122
  if (serialized === instance.emitted) return
91
123
  instance.emitted = serialized; pending.current.push(serialized)
@@ -93,10 +125,12 @@ function NarrationSurface(props: NarrationEditorProps) {
93
125
  } catch (error) { current.current.onError?.(error instanceof Error ? error : new Error(String(error))) }
94
126
  }
95
127
  return <NARRATION_CONTEXT.Provider value={{ locale: props.locale, readOnly: props.readOnly, advanced: props.advanced }}>
96
- <div className="pm-ui-narration-editor pm-ui-block-editor pm-ui" onFocus={() => current.current.onFocus?.()}
128
+ <div className="pm-ui-narration-editor pm-ui-block-editor pm-ui" data-block-menu={props.blockMenu || undefined} onFocus={() => current.current.onFocus?.()}
97
129
  onCompositionStart={() => current.current.onComposition?.(true)}
98
130
  onCompositionEnd={() => queueMicrotask(() => { if (active.current === instance) current.current.onComposition?.(false) })}>
99
- <BlockNoteView editor={editor} editable={!props.readOnly} theme={DOCUMENT_EDITOR_THEME} formattingToolbar={false} sideMenu={false} slashMenu={false} linkToolbar={false} comments={false} onChange={change} />
131
+ <BlockNoteView editor={editor} editable={!props.readOnly} theme={DOCUMENT_EDITOR_THEME} formattingToolbar={false} sideMenu={false} slashMenu={false} linkToolbar={false} comments={false} onChange={change}>
132
+ {props.blockMenu && <SideMenuController sideMenu={NarrationSideMenu} />}
133
+ </BlockNoteView>
100
134
  {props.advanced !== false && <div className="pm-ui-narration-editor__actions"><PmButton small variant="ghost" disabled={props.readOnly} onClick={() => { setDisplay(editor.getSelectedText()); setSpoken(''); setOpen(true) }}>{t.pronunciation}</PmButton></div>}
101
135
  <PmDialog open={open} label={t.pronunciation} closeLabel={t.cancel} onClose={() => setOpen(false)} actions={<>
102
136
  <PmButton small onClick={() => setOpen(false)}>{t.cancel}</PmButton>