@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.
Files changed (124) hide show
  1. package/README.md +1 -1
  2. package/package.json +5 -4
  3. package/src/AgentActivityBar.tsx +25 -0
  4. package/src/MediaClipEditor.tsx +7 -6
  5. package/src/StepProductionEditor.tsx +16 -7
  6. package/src/agent-activity-messages.ts +14 -0
  7. package/src/agent-activity.ts +38 -0
  8. package/src/approvals.tsx +6 -1
  9. package/src/audio-recording-messages.ts +5 -5
  10. package/src/audio-recording.ts +27 -5
  11. package/src/authoring-client.ts +10 -10
  12. package/src/authoring-draft-fragment.ts +3 -1
  13. package/src/authoring-window.ts +100 -0
  14. package/src/base-controls.tsx +28 -7
  15. package/src/body-draft-actions.ts +60 -0
  16. package/src/caption-timing-drafts.ts +20 -3
  17. package/src/caption-timing-messages.ts +2 -2
  18. package/src/caption-timing.ts +2 -2
  19. package/src/component-draft-actions.ts +1 -1
  20. package/src/component-properties.ts +3 -3
  21. package/src/component-property-drafts.ts +6 -6
  22. package/src/components.tsx +43 -38
  23. package/src/container-layout.ts +21 -0
  24. package/src/context.tsx +5 -3
  25. package/src/diagnostics.ts +1 -1
  26. package/src/document-draft-store.ts +45 -18
  27. package/src/document-drafts.ts +30 -21
  28. package/src/document-editing.ts +485 -0
  29. package/src/document-editor/BlockNoteSurface.tsx +40 -14
  30. package/src/document-editor/CommentComposer.tsx +24 -0
  31. package/src/document-editor/ComponentMaterials.tsx +4 -10
  32. package/src/document-editor/ComponentPropertiesDialog.tsx +12 -12
  33. package/src/document-editor/DocumentBlockFallback.tsx +4 -3
  34. package/src/document-editor/DocumentBlockPreview.tsx +11 -4
  35. package/src/document-editor/DocumentComments.tsx +87 -17
  36. package/src/document-editor/DocumentEditor.tsx +66 -14
  37. package/src/document-editor/DocumentStepNarration.tsx +39 -27
  38. package/src/document-editor/NarrationEditor.tsx +55 -21
  39. package/src/document-editor/NewCommentDrafts.tsx +120 -37
  40. package/src/document-editor/PlaceComment.tsx +252 -0
  41. package/src/document-editor/agent-targets.ts +34 -0
  42. package/src/document-editor/blocknote-messages.ts +2 -0
  43. package/src/document-editor/comment-draft-actions.ts +40 -20
  44. package/src/document-editor/comment-draft-inspection.ts +2 -2
  45. package/src/document-editor/comment-drafts.ts +75 -27
  46. package/src/document-editor/comments.ts +34 -14
  47. package/src/document-editor/component-label.ts +11 -0
  48. package/src/document-editor/file-input.ts +2 -2
  49. package/src/document-editor/focus.ts +0 -2
  50. package/src/document-editor/inline.ts +1 -0
  51. package/src/document-editor/insertion-place.ts +60 -0
  52. package/src/document-editor/messages.ts +3 -3
  53. package/src/document-editor/narration-schema.tsx +12 -6
  54. package/src/document-editor/narration.ts +19 -3
  55. package/src/document-editor/page-body.ts +60 -0
  56. package/src/document-editor/popover.tsx +4 -2
  57. package/src/document-editor/projection.ts +21 -19
  58. package/src/document-editor/rich-text.ts +3 -2
  59. package/src/document-editor/selection.ts +13 -0
  60. package/src/document-editor/style.css +8 -3
  61. package/src/document-editor/table-identities.ts +2 -1
  62. package/src/document-preview.ts +3 -2
  63. package/src/document-production.ts +492 -0
  64. package/src/document-return-point.ts +2 -2
  65. package/src/document-session.ts +216 -67
  66. package/src/document-timing-drafts.ts +26 -6
  67. package/src/effective-settings.ts +12 -0
  68. package/src/history.ts +5 -5
  69. package/src/import-messages.ts +40 -0
  70. package/src/index.ts +11 -5
  71. package/src/jobs.ts +1 -1
  72. package/src/mcp-settings-messages.ts +39 -0
  73. package/src/media-drafts.ts +43 -1
  74. package/src/messages.ts +39 -18
  75. package/src/outline.ts +5 -5
  76. package/src/panels/DocumentImportDialog.tsx +59 -0
  77. package/src/panels/DocumentNarrationPanel.tsx +2 -2
  78. package/src/panels/DocumentView.tsx +106 -77
  79. package/src/panels/DocumentVoiceDialog.tsx +29 -12
  80. package/src/panels/DocumentVoiceField.tsx +3 -2
  81. package/src/panels/ExportPanel.tsx +2 -10
  82. package/src/panels/HistoryPanel.tsx +36 -10
  83. package/src/panels/HomePanel.tsx +12 -1
  84. package/src/panels/McpSettingsPanel.tsx +86 -0
  85. package/src/panels/PageDeleteDialog.tsx +4 -4
  86. package/src/panels/PageRenameDialog.tsx +1 -1
  87. package/src/panels/PreviewPanel.tsx +4 -7
  88. package/src/panels/ProductionCaptionSize.tsx +20 -0
  89. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  90. package/src/panels/ProductionMediaClips.tsx +25 -9
  91. package/src/panels/ProductionPanel.tsx +21 -17
  92. package/src/panels/ProductionRecording.tsx +86 -9
  93. package/src/panels/ProductionRecordingRange.tsx +26 -23
  94. package/src/panels/ProductionTimeline.tsx +6 -1
  95. package/src/panels/ProductionTranscription.tsx +8 -6
  96. package/src/panels/SourceDocumentPanel.tsx +24 -40
  97. package/src/panels/SpeechSettingsPanel.tsx +2 -2
  98. package/src/panels/TranscriptionAdoption.tsx +42 -36
  99. package/src/panels/VoiceCloneDialog.tsx +2 -1
  100. package/src/panels/VoicePreviewDialog.tsx +1 -1
  101. package/src/panels/VoiceScopeField.tsx +2 -2
  102. package/src/panels/VoiceoverDialog.tsx +11 -10
  103. package/src/places.ts +1 -36
  104. package/src/preview-playback.ts +1 -1
  105. package/src/production-draft-actions.ts +37 -0
  106. package/src/production-messages.ts +6 -0
  107. package/src/production-playback.ts +1 -1
  108. package/src/production-voice-playback.ts +3 -2
  109. package/src/recording-adoption.ts +4 -4
  110. package/src/sha256.ts +9 -0
  111. package/src/speech-settings-messages.ts +6 -6
  112. package/src/step-production.ts +4 -4
  113. package/src/styles.css +43 -92
  114. package/src/transcription-drafts.ts +124 -0
  115. package/src/use-recording-adoption.ts +5 -4
  116. package/src/voice-drafts.ts +32 -8
  117. package/src/voice-messages.ts +9 -9
  118. package/src/voiceover-jobs.ts +1 -1
  119. package/src/workbench-state.ts +159 -0
  120. package/src/workbench.ts +323 -956
  121. package/src/workspace-client.ts +41 -12
  122. package/src/assistant-mascot.ts +0 -62
  123. package/src/mascot-preference.ts +0 -37
  124. package/src/panels/ChangeTrail.tsx +0 -79
@@ -1,16 +1,19 @@
1
1
  import { useRef, useState } from 'react'
2
- import type { NarrationNode, TeachingDocument } from '@lincyaw/kernel'
2
+ import type { Narration, NarrationNode, PresmiumDocument } 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'
7
+ import { latestAgentActivity } from '../agent-activity.ts'
6
8
  import { NarrationEditor } from './NarrationEditor.tsx'
7
9
  import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
8
- import { narrationFieldFocus } from './narration.ts'
10
+ import { narrationFieldFocus, narrationsToNative, nativeToNarrations } from './narration.ts'
9
11
  import type { NativeNarrationEditor } from './narration-schema.tsx'
10
12
  import { StepProductionEditor } from '../StepProductionEditor.tsx'
13
+ import { effectiveOf } from '../effective-settings.ts'
11
14
 
12
15
  /** Content ownership determines the page, even when the author is reading another page. */
13
- export function documentBlockSection(document: TeachingDocument, blockId: string): string | undefined {
16
+ export function documentBlockSection(document: PresmiumDocument, blockId: string): string | undefined {
14
17
  const contains = (id: string): boolean => {
15
18
  if (id === blockId) return true
16
19
  const block = document.blocks[id]
@@ -23,28 +26,32 @@ export function narrationDisplay(content: readonly NarrationNode[]): string {
23
26
  return content.map(node => node.type === 'text' ? node.text : node.type === 'pronunciation' ? node.display : '').join('')
24
27
  }
25
28
 
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,
29
+ function NarrationField({ identity, reset, blockId, stepId, content, readOnly, advanced, onPause }: {
30
+ identity: string, reset: number, blockId?: string, stepId: string, content: Narration[], readOnly: boolean, advanced: boolean, onPause(): void,
28
31
  }) {
29
32
  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
33
+ const [emptyId] = useState(() => randomUUID())
34
+ const read = () => {
35
+ const document = workbench.getDocument(identity), step = document?.steps[stepId]
36
+ return step ? step.narrationIds.map(id => ({ id, content: document!.narrations[id]!.content })) : undefined
37
+ }
37
38
  const registration = useRef<() => void>()
38
39
  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 }}
40
+ const owner = `narration:${identity}:${reset}:${JSON.stringify(blockId ?? null)}:${stepId}`
41
+ return <NarrationEditor identity={identity} reset={reset} fieldId={stepId} content={content} locale={locale} readOnly={readOnly} advanced={advanced} blockMenu
42
+ getContent={read} toNative={value => narrationsToNative(value, emptyId)} fromNative={nativeToNarrations}
43
+ cueOwners={() => {
44
+ const document = workbench.getDocument(identity)
45
+ const retained = new Set(Object.values(document?.steps ?? {}).filter(step => step.id !== stepId).flatMap(step => step.narrationIds))
46
+ return new Map([...retained].flatMap(id => document!.narrations[id]!.content.flatMap(node => node.type === 'cue' ? [[node.id, id] as const] : [])))
47
+ }}
48
+ onCueCopy={(from, to) => workbench.production.copyNarrationCueTiming(from, to, identity)}
42
49
  onReady={editor => {
43
50
  registration.current?.()
44
51
  fieldEditor.current = editor
45
- registration.current = editor ? workbench.registerDocumentField({ identity, reset, blockId, stepId, narrationId: id, slot, focus: narrationFieldFocus(editor), editor }) : undefined
52
+ registration.current = editor ? workbench.editing.registerField({ identity, reset, blockId, stepId, focus: narrationFieldFocus(editor), editor }) : undefined
46
53
  }}
47
- onFocus={() => { workbench.documentInteraction(); if (fieldEditor.current) workbench.activateDocumentHistory(fieldEditor.current); onPause() }} onChange={value => workbench.setDocumentNarration(stepId, target(), value, identity)}
54
+ onFocus={() => { workbench.editing.interact(); if (fieldEditor.current) workbench.editing.activateHistory(fieldEditor.current); onPause() }} onChange={value => workbench.production.setNarrations(stepId, value, identity)}
48
55
  onComposition={composing => workbench.documentComposition(composing, owner, identity)}
49
56
  onError={error => workbench.documentError(error)} />
50
57
  }
@@ -57,6 +64,8 @@ export function DocumentStepNarration({ blockId, sectionId, stepId, expanded, ad
57
64
  const locale = useWorkbenchState(state => state.locale), t = DOCUMENT_EDITOR_MESSAGES[locale]
58
65
  const readOnly = useWorkbenchState(state => workbench.client.capabilities?.readOnly === true || Boolean(state.authoring?.loading) || isAgentChanging(state))
59
66
  const timingStorageFailure = useWorkbenchState(state => state.documentTimingDraftStorageFailure)
67
+ const activities = useWorkbenchState(state => state.agentActivities)
68
+ const activity = latestAgentActivity(activities?.filter(value => value.document === source?.directory && value.targets.some(target => target.step === stepId)))
60
69
  if (workbench.client.capabilities?.narration === false) return null
61
70
  const document = source?.content, section = document?.sections[sectionId], step = document?.steps[stepId]
62
71
  if (!source?.identity || !document || !section || !step) return null
@@ -67,7 +76,7 @@ export function DocumentStepNarration({ blockId, sectionId, stepId, expanded, ad
67
76
  const id = section.stepOrder[index + offset]
68
77
  if (id) { onPause(); workbench.selectDocumentStep(sectionId, id) }
69
78
  }
70
- return <section className="pm-ui-block-preview__narration" aria-label={fieldLabel} data-step-narration={stepId}>
79
+ return <section className="pm-ui-block-preview__narration" aria-label={fieldLabel} data-step-narration={stepId} data-pm-agent-target={activity?.state}>
71
80
  <header className="pm-ui-block-preview__narration-header">
72
81
  <span className="pm-ui-block-preview__step-label">{label}</span>
73
82
  <span className="pm-ui-block-preview__actions">
@@ -78,15 +87,18 @@ export function DocumentStepNarration({ blockId, sectionId, stepId, expanded, ad
78
87
  {!expanded && text && <p className="pm-ui-block-preview__caption" data-step-caption={stepId}>{text}</p>}
79
88
  {expanded && <div id={panelId} className="pm-ui-block-preview__narration-fields">
80
89
  {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) }}
90
+ <NarrationField key={`narration:${source.identity}:${source.reset}:${stepId}`}
91
+ identity={source.identity!} reset={source.reset} blockId={blockId} stepId={stepId}
92
+ content={ids.map(id => ({ id, content: document.narrations[id]!.content }))} readOnly={readOnly} advanced={advanced} onPause={onPause} />
93
+ <StepProductionEditor key={`timing:${source.identity}:${source.reset}:${stepId}`} document={effectiveOf(document, source.inherited)} stepId={stepId} locale={locale} readOnly={readOnly} advanced={advanced}
94
+ onPause={onPause} onInteraction={() => workbench.editing.interact()}
95
+ onChange={patch => workbench.production.setStepTiming(stepId, patch, source.identity)}
96
+ drafts={{ minimumHoldMs: workbench.production.timingDraft(stepId, 'minimumHoldMs', source.identity, source.reset), trailingPauseMs: workbench.production.timingDraft(stepId, 'trailingPauseMs', source.identity, source.reset) }}
88
97
  draftStorageFailure={timingStorageFailure}
89
- onDraft={(key, draft) => workbench.setDocumentTimingDraft(stepId, key, draft, source.identity!, source.reset)}
98
+ onDraft={(key, draft) => workbench.production.setTimingDraft(stepId, key, draft, source.identity!, source.reset)}
99
+ draftControlKey={JSON.stringify([source.identity, source.reset, stepId])}
100
+ registerDraftControl={(key, control) => workbench.production.registerDraftView({ identity: source.identity!, kind: 'step-timing',
101
+ has: target => target === JSON.stringify([stepId, key]), blocked: () => control.composing(), clear: () => control.clear() })}
90
102
  onComposition={(key, composing) => workbench.documentComposition(composing, `production:${source.identity}:${source.reset}:${blockId}:${stepId}:${key}`, source.identity)} />
91
103
  </div>}
92
104
  </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,11 +125,13 @@ 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} />
100
- {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>}
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>
134
+ {props.advanced !== false && <div className="pm-ui-narration-editor__actions"><PmButton small variant="text" 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>
103
137
  <PmButton small variant="primary" disabled={!display} onClick={() => { editor.insertInlineContent([{ type: 'narrationAtom', props: { kind: 'pronunciation', display, spoken, cueId: '', payload: '' } }], { updateSelection: true }); setOpen(false); editor.focus() }}>{t.done}</PmButton>
@@ -2,19 +2,24 @@ import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef,
2
2
  import type { ReactNode } from 'react'
3
3
  import { CommentEditorSubmitExtension, CommentsExtension } from '@blocknote/core/comments'
4
4
  import { components } from '@blocknote/mantine'
5
- import { ComponentsContext, FloatingComposer, PositionPopover, useBlockNoteEditor, useComponentsContext, useCreateBlockNote, useDictionary, useEditorState, useExtension, useExtensionState } from '@blocknote/react'
5
+ import { PositionPopover, useBlockNoteEditor, useCreateBlockNote, useDictionary, useEditorState, useExtension, useExtensionState } from '@blocknote/react'
6
6
  import type { ComponentProps } from '@blocknote/react'
7
7
  import type { BlockNoteEditor } from '@blocknote/core'
8
+ import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
8
9
  import { TextSelection } from '@tiptap/pm/state'
9
10
  import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
10
11
  import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
12
+ import { discardNativeCommentDraft } from './comment-draft-actions.ts'
13
+ import { waitForDraft } from '../document-draft-store.ts'
14
+ import { isApprovalTarget } from '../approvals.tsx'
11
15
  import { enterSubmits } from './comments.ts'
12
- import type { CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, NewCommentDraftTarget } from './comment-drafts.ts'
16
+ import type { CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, CommentDraftOperation, NewCommentDraftTarget } from './comment-drafts.ts'
13
17
  import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
14
18
  import type { DocumentEditorBlock, NativeDocumentEditor } from './schema.tsx'
15
19
  import { PmNotice } from '../components.tsx'
16
20
  import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
17
21
  import { commentFloating } from './popover.tsx'
22
+ import { CommentComposer } from './CommentComposer.tsx'
18
23
 
19
24
  type CommentEditor = BlockNoteEditor<any, any, any>
20
25
  interface ComposerBinding {
@@ -25,13 +30,18 @@ interface ComposerBinding {
25
30
  input: number
26
31
  composing: boolean
27
32
  active: boolean
33
+ submitting: boolean
34
+ adopting?: boolean
35
+ previous?: ComposerBinding
36
+ adoption?: { guard(): void, finish(record?: CommentDraftRecord): void }
28
37
  }
29
- interface PreparedDraft { record: CommentDraftRecord, origin: CommentDraftReference, doc: NativeDocumentEditor['prosemirrorState']['doc'], selection: NativeDocumentEditor['prosemirrorState']['selection'], version: string }
38
+ interface PreparedDraft { record: CommentDraftRecord, origin?: CommentDraftReference, previous?: ComposerBinding, doc: NativeDocumentEditor['prosemirrorState']['doc'], selection: NativeDocumentEditor['prosemirrorState']['selection'], version: string, adoption?: ComposerBinding['adoption'], canUse(editor: CommentEditor): boolean }
30
39
  interface NewDraftOwner {
31
40
  editor: NativeDocumentEditor
32
41
  latest: { current: ComposerBinding | undefined }
33
42
  prepared: { current: PreparedDraft | undefined }
34
- restore(candidate: CommentDraftCandidate, current?: () => boolean): Promise<void>
43
+ generation: number
44
+ restore(candidate: CommentDraftCandidate, current?: () => boolean, operation?: CommentDraftOperation): Promise<CommentDraftRecord | undefined>
35
45
  failure?: boolean
36
46
  }
37
47
  const NEW_DRAFT_OWNER = createContext<NewDraftOwner | undefined>(undefined)
@@ -42,27 +52,33 @@ const emptyState = { candidates: [], pending: false, failed: false, reading: fal
42
52
  export function NewCommentDraftProvider({ children }: { children?: ReactNode }) {
43
53
  const context = useContext(COMMENT_EDITOR_CONTEXT), editor = useBlockNoteEditor() as NativeDocumentEditor, comments = useExtension(CommentsExtension)
44
54
  const latest = useRef<ComposerBinding>(), prepared = useRef<PreparedDraft>(), active = useRef(true), operation = useRef(0)
45
- const [failure, setFailure] = useState(false)
46
- useEffect(() => { active.current = true; return () => { active.current = false; ++operation.current; prepared.current = undefined; latest.current = undefined } }, [editor])
47
- const restore = async (candidate: CommentDraftCandidate, current = () => true) => {
55
+ const composerId = useRef(randomUUID()), handoff = useRef<() => void>()
56
+ const [failure, setFailure] = useState(false), [generation, setGeneration] = useState(0)
57
+ useEffect(() => { active.current = true; return () => { active.current = false; ++operation.current; handoff.current?.(); prepared.current = undefined; latest.current = undefined } }, [editor])
58
+ const restore = async (candidate: CommentDraftCandidate, current = () => true, action?: CommentDraftOperation): Promise<CommentDraftRecord | undefined> => {
48
59
  const store = context?.store, drafts = store?.drafts, target = candidate.target
49
60
  if (!store || !drafts || !isNewCommentDraft(target) || candidate.storage !== 'durable' || editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing) return
50
- const binding = latest.current
61
+ const binding = latest.current?.active ? latest.current : undefined
51
62
  if (binding?.record && !drafts.owns(binding.record)) binding.record = undefined
63
+ handoff.current?.()
52
64
  const request = ++operation.current, input = binding?.input, record = binding?.record
53
65
  try {
54
66
  store.beforeAction?.()
55
67
  if (!store.auth.canCreateThread() || store.draftTargetState(target) !== 'current' || !store.newDraftPositions(target, editor)) { setFailure(true); return }
56
- const version = store.version, native = editor.prosemirrorState, extensionState = comments.store.state, position = context.getPositionToken?.()
57
- if (!version || binding?.composing || binding?.editor.prosemirrorView.composing) return
68
+ const version = store.version, native = editor.prosemirrorState, extensionState = comments.store.state, position = context.getPositionToken?.(), form = binding?.editor.prosemirrorState
69
+ if (!version || binding?.composing || binding?.submitting || binding?.editor.prosemirrorView.composing) return
58
70
  const owns = () => active.current && current() && request === operation.current && !editor.prosemirrorView.isDestroyed && !editor.prosemirrorView.composing && store.version === version
59
71
  && context.getPositionToken?.() === position
60
72
  && editor.prosemirrorState.doc === native.doc && editor.prosemirrorState.selection === native.selection && comments.store.state === extensionState
61
73
  && (!binding || latest.current === binding && binding.input === input && binding.record === record && !binding.composing)
62
- if (record && !await drafts.confirm(record) || !owns()) return
63
- const nextTarget = { ...target, intentId: crypto.randomUUID() }, next = await drafts.recover(candidate, nextTarget, version)
74
+ const guard = () => { action?.signal?.throwIfAborted(); action?.guard?.(); if (!owns()) throw new Error('client-comment-composer-changed') }
75
+ guard()
76
+ if (record && !await waitForDraft(drafts.confirm(record), action?.signal)) return
77
+ guard()
78
+ const nextTarget = { ...target, intentId: randomUUID() }, next = await drafts.recover(candidate, nextTarget, version, { signal: action?.signal, guard })
64
79
  store.beforeAction?.()
65
- if (!next || !owns()) return
80
+ if (!next) return
81
+ guard()
66
82
  const positions = store.newDraftPositions(nextTarget, editor)
67
83
  if (!positions) { setFailure(true); return }
68
84
  comments.stopPendingComment()
@@ -70,14 +86,46 @@ export function NewCommentDraftProvider({ children }: { children?: ReactNode })
70
86
  editor.focus()
71
87
  editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, positions.from, positions.to)).scrollIntoView())
72
88
  // The public controller creates the actual editor; this is only its strictly committed handoff.
73
- prepared.current = { record: next, origin: candidate, doc: editor.prosemirrorState.doc, selection: editor.prosemirrorState.selection, version }
89
+ let finish!: (record?: CommentDraftRecord) => void
90
+ const adopted = new Promise<CommentDraftRecord | undefined>(resolve => { finish = resolve })
91
+ const pending: PreparedDraft = { record: next, previous: binding, ...!action ? { origin: candidate } : {}, doc: editor.prosemirrorState.doc, selection: editor.prosemirrorState.selection, version,
92
+ canUse: actual => (!binding || binding.input === input && binding.record === record && !binding.composing && !binding.submitting)
93
+ && (actual === binding?.editor ? !actual.prosemirrorView.isDestroyed && actual.prosemirrorState.doc === form?.doc && actual.prosemirrorState.selection === form?.selection : actual.isEmpty) }
94
+ if (action) {
95
+ let settled = false
96
+ const complete = (value?: CommentDraftRecord) => { if (settled) return; settled = true; if (handoff.current === cancel) handoff.current = undefined; finish(value) }
97
+ const cancel = () => complete()
98
+ handoff.current = cancel
99
+ pending.adoption = { finish: complete, guard: () => {
100
+ action.signal?.throwIfAborted(); store.beforeAction?.()
101
+ const actual = latest.current
102
+ if (!active.current || !current() || request !== operation.current || store.version !== version || editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing
103
+ || editor.prosemirrorState.doc !== pending.doc || editor.prosemirrorState.selection !== pending.selection || !actual?.active || actual.record !== next || actual.input !== 0
104
+ || actual.composing || actual.submitting || !store.newDraftPositions(nextTarget, editor)) throw new Error('client-comment-composer-changed')
105
+ } }
106
+ }
107
+ prepared.current = pending
74
108
  comments.startPendingComment()
75
- prepared.current.selection = editor.prosemirrorState.selection
109
+ pending.selection = editor.prosemirrorState.selection
110
+ setGeneration(value => value + 1)
76
111
  setFailure(false)
77
112
  context.onDraftRestore?.()
78
- } catch { if (active.current && request === operation.current) setFailure(true) }
113
+ if (action) return await waitForDraft(adopted, action.signal)
114
+ } catch (error) { if (active.current && request === operation.current) setFailure(true); if (action) throw error }
115
+ finally { if (request === operation.current) handoff.current?.() }
79
116
  }
80
- return <NEW_DRAFT_OWNER.Provider value={{ editor, latest, prepared, restore, failure }}>{children}</NEW_DRAFT_OWNER.Provider>
117
+ useLayoutEffect(() => {
118
+ const store = context?.store, drafts = store?.drafts
119
+ if (!store || !drafts) return
120
+ return drafts.registerComposer({ id: composerId.current, target: { kind: 'create', intentId: composerId.current, documentId: store.document.id },
121
+ accepts: target => isNewCommentDraft(target) && Boolean(store.newDraftPositions(target, editor)),
122
+ snapshot: () => { const binding = latest.current?.active ? latest.current : undefined; return { record: binding?.record,
123
+ composing: editor.prosemirrorView.composing || Boolean(binding?.composing || binding?.editor.prosemirrorView.composing),
124
+ available: active.current && !context.readOnly && !editor.prosemirrorView.isDestroyed && !binding?.submitting && store.auth.canCreateThread() } },
125
+ targetState: target => target && isNewCommentDraft(target) && store.newDraftPositions(target, editor) ? 'current' : 'unavailable',
126
+ restore: (candidate, action) => restore(candidate, () => active.current, action) })
127
+ }, [context?.store, context?.readOnly, editor])
128
+ return <NEW_DRAFT_OWNER.Provider value={{ editor, latest, prepared, generation, restore, failure }}>{children}</NEW_DRAFT_OWNER.Provider>
81
129
  }
82
130
 
83
131
  /**
@@ -106,7 +154,8 @@ export function DocumentNewCommentController() {
106
154
  const position = useEditorState({ editor, selector: ({ editor }) => pendingComment ? { from: editor.prosemirrorState.selection.from, to: editor.prosemirrorState.selection.to } : undefined })
107
155
  const floating = useMemo(() => commentFloating(), [])
108
156
  return <PositionPopover position={position} focusManagerProps={{ disabled: true }} elementProps={{ style: { zIndex: COMPOSER_LAYER } }}
109
- useFloatingOptions={{ placement: 'bottom', ...floating, open: pendingComment, onOpenChange(open) {
157
+ useFloatingOptions={{ placement: 'bottom', ...floating, open: pendingComment, onOpenChange(open, event?: Event) {
158
+ if (!open && isApprovalTarget(event?.target ?? document.activeElement)) return
110
159
  if (open || !owner || owner.latest.current?.composing || owner.latest.current?.editor.prosemirrorView.composing) return
111
160
  try { context?.store.beforeAction?.() } catch { return }
112
161
  comments.stopPendingComment()
@@ -119,26 +168,30 @@ export function DocumentNewCommentController() {
119
168
  const COMPOSER_LAYER = 60
120
169
 
121
170
  function DocumentNewCommentComposer({ newCommentEditor }: { newCommentEditor: CommentEditor }) {
122
- const owner = useContext(NEW_DRAFT_OWNER), context = useContext(COMMENT_EDITOR_CONTEXT), nativeComponents = useComponentsContext()!
171
+ const owner = useContext(NEW_DRAFT_OWNER), context = useContext(COMMENT_EDITOR_CONTEXT)
123
172
  const [binding, setBinding] = useState<ComposerBinding>(), [, render] = useState(0)
124
173
  useLayoutEffect(() => {
125
174
  if (!owner || !context) return
126
175
  try {
127
176
  context.store.beforeAction?.()
128
177
  const restored = owner.prepared.current, prepared = restored && restored.version === context.store.version
129
- && restored.doc === owner.editor.prosemirrorState.doc && restored.selection === owner.editor.prosemirrorState.selection && newCommentEditor.isEmpty
178
+ && restored.doc === owner.editor.prosemirrorState.doc && restored.selection === owner.editor.prosemirrorState.selection && restored.canUse(newCommentEditor)
130
179
  && isNewCommentDraft(restored.record.target) && context.store.newDraftPositions(restored.record.target, owner.editor) ? restored : undefined
180
+ if (restored && !prepared && owner.latest.current?.editor === newCommentEditor) {
181
+ const retained = owner.latest.current
182
+ retained.active = true; owner.prepared.current = undefined; restored.adoption?.finish(); setBinding(retained)
183
+ return () => { retained.active = false }
184
+ }
131
185
  const target = prepared && isNewCommentDraft(prepared.record.target) ? prepared.record.target : context.store.newDraftTarget(owner.editor)
132
- const value: ComposerBinding = { target, editor: newCommentEditor, record: prepared?.record, origin: prepared?.origin, input: 0, composing: false, active: true }
133
- if (prepared) owner.prepared.current = undefined
186
+ const value: ComposerBinding = { target, editor: newCommentEditor, record: prepared?.record, origin: prepared?.origin, adoption: prepared?.adoption, previous: prepared?.previous, adopting: Boolean(prepared), input: 0, composing: false, active: true, submitting: false }
187
+ if (restored) { if (!prepared) restored.adoption?.finish(); owner.prepared.current = undefined }
134
188
  owner.latest.current = value; setBinding(value)
135
189
  return () => { value.active = false }
136
190
  } catch { /* The unchanged native form remains available when no authoritative target can be confirmed. */ }
137
- }, [newCommentEditor, context?.store, owner?.editor])
138
- const value = useMemo(() => ({ ...nativeComponents, Comments: { ...nativeComponents.Comments, Editor: NewCommentEditor } }), [nativeComponents])
139
- return <NEW_COMPOSER_BINDING.Provider value={{ binding, ready: () => render(value => value + 1) }}><ComponentsContext.Provider value={value}>
140
- <FloatingComposer newCommentEditor={newCommentEditor} />
141
- </ComponentsContext.Provider></NEW_COMPOSER_BINDING.Provider>
191
+ }, [newCommentEditor, context?.store, owner?.editor, owner?.generation])
192
+ return <NEW_COMPOSER_BINDING.Provider value={{ binding, ready: () => render(value => value + 1) }}>
193
+ <CommentComposer editor={newCommentEditor} editorComponent={NewCommentEditor} />
194
+ </NEW_COMPOSER_BINDING.Provider>
142
195
  }
143
196
  const NEW_COMPOSER_BINDING = createContext<{ binding?: ComposerBinding, ready(): void } | undefined>(undefined)
144
197
 
@@ -149,9 +202,24 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
149
202
  const drafts = context?.store.drafts, state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState))
150
203
  useLayoutEffect(() => {
151
204
  if (!binding || !drafts || !context || !owner) return
152
- if (binding.record && props.editor.isEmpty) {
153
- props.editor.replaceBlocks(props.editor.document, productRichTextToNative(binding.record.content, rich))
154
- if (binding.origin) { void drafts.discard(binding.origin); binding.origin = undefined }
205
+ if (binding.record && (props.editor.isEmpty || binding.adopting)) {
206
+ let replaced = false
207
+ try {
208
+ binding.adoption?.guard()
209
+ props.editor.replaceBlocks(props.editor.document, productRichTextToNative(binding.record.content, rich))
210
+ replaced = true
211
+ if (JSON.stringify(nativeRichTextToProduct(props.editor.document as DocumentEditorBlock[], rich)) !== JSON.stringify(binding.record.content)) throw new Error('client-comment-native-unverified')
212
+ binding.adoption?.finish(binding.record); binding.adoption = undefined; binding.adopting = false
213
+ if (binding.origin) { void drafts.discard(binding.origin); binding.origin = undefined }
214
+ } catch {
215
+ binding.adoption?.finish(); binding.adoption = undefined; binding.adopting = false
216
+ const previous = binding.previous
217
+ if (!replaced && previous?.editor === props.editor) {
218
+ binding.target = previous.target; binding.record = previous.record; binding.origin = previous.origin; binding.input = previous.input
219
+ } else binding.record = undefined
220
+ setFailure(true)
221
+ }
222
+ binding.previous = undefined
155
223
  }
156
224
  const original = props.editor.getExtension(CommentEditorSubmitExtension)
157
225
  let guarded: typeof original, stopEnter = () => {}
@@ -163,13 +231,13 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
163
231
  const positions = context.store.newDraftPositions(binding.target, owner.editor), selection = owner.editor.prosemirrorState.selection
164
232
  if (!context.store.auth.canCreateThread() || !positions || selection.from !== positions.from || selection.to !== positions.to) { setFailure(true); return }
165
233
  const before = new Set(context.store.getThreads().keys()), record = binding.record
166
- submitting.current = true
234
+ submitting.current = true; binding.submitting = true
167
235
  try {
168
236
  const result = original.submit(), thread = [...context.store.getThreads().values()].find(thread => !before.has(thread.id))
169
237
  const actual = thread && context.store.threadSnapshot(thread.id)
170
238
  if (actual) { drafts.submitted(record, actual.comments[0], actual); binding.record = undefined }
171
239
  await result
172
- } finally { submitting.current = false }
240
+ } finally { submitting.current = false; binding.submitting = false }
173
241
  } catch { setFailure(true) }
174
242
  } }))
175
243
  guarded = props.editor.getExtension(CommentEditorSubmitExtension); composer.ready()
@@ -185,12 +253,27 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
185
253
  })
186
254
  return () => { stop(); stopEnter(); if (original && guarded && !props.editor.prosemirrorView.isDestroyed && props.editor.getExtension(CommentEditorSubmitExtension) === guarded) props.editor.replaceExtension(guarded, original) }
187
255
  }, [binding, drafts, props.editor])
188
- const composerId = useRef(crypto.randomUUID())
256
+ const composerId = useRef(randomUUID())
257
+ const discardActive = async (candidate: CommentDraftCandidate, action?: CommentDraftOperation): Promise<boolean> => {
258
+ if (!binding || !drafts || !context || !owner || !binding.record || binding.record.id !== candidate.id || binding.record.revision !== candidate.revision) return false
259
+ const record = binding.record, input = binding.input, native = props.editor.prosemirrorState, version = context.store.version, position = context.getPositionToken?.()
260
+ const guard = () => {
261
+ context.store.beforeAction?.()
262
+ if (!binding.active || owner.latest.current !== binding || binding.record !== record || binding.input !== input || context.store.version !== version
263
+ || context.getPositionToken?.() !== position || binding.composing || submitting.current || props.editor.prosemirrorView.isDestroyed
264
+ || props.editor.prosemirrorView.composing || props.editor.prosemirrorState.doc !== native.doc || props.editor.prosemirrorState.selection !== native.selection) throw new Error('client-comment-composer-changed')
265
+ }
266
+ return discardNativeCommentDraft(drafts, candidate, action, guard, () => {
267
+ suppress.current = true
268
+ try { props.editor.replaceBlocks(props.editor.document, [{ type: 'paragraph', content: [] }]); binding.record = undefined; binding.origin = undefined; binding.input++ }
269
+ finally { suppress.current = false }
270
+ })
271
+ }
189
272
  useLayoutEffect(() => {
190
273
  if (!binding || !drafts || !context) return
191
274
  return drafts.registerComposer({ id: composerId.current, target: binding.target,
192
275
  snapshot: () => { const available = binding.active && !submitting.current && !props.editor.prosemirrorView.isDestroyed; return { record: binding.record, composing: binding.composing || available && props.editor.prosemirrorView.composing, available } },
193
- targetState: () => context.store.draftTargetState(binding.target) })
276
+ targetState: () => context.store.draftTargetState(binding.target), discard: discardActive })
194
277
  }, [binding, drafts, props.editor])
195
278
  const t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
196
279
  const composition = (value: boolean) => {
@@ -211,14 +294,14 @@ export function DocumentNewCommentRecovery() {
211
294
  const active = useRef(true)
212
295
  useLayoutEffect(() => { active.current = true; return () => { active.current = false } }, [owner?.editor])
213
296
  const state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState)), t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
214
- const candidates = state.candidates.filter(value => isNewCommentDraft(value.target))
297
+ const candidates = state.candidates.filter(value => isNewCommentDraft(value.target) && !(value.target.anchor && isDocumentPlaceAnchor(value.target.anchor)))
215
298
  if (!drafts || !owner) return null
216
299
  return <>{owner.failure && <PmNotice tone="warn">{t.commentTargetUnavailable}</PmNotice>}<DraftChoices candidates={candidates} preview
217
300
  canRecover={candidate => isNewCommentDraft(candidate.target) && Boolean(context?.store.newDraftPositions(candidate.target, owner.editor))}
218
- unavailableMessage={t.commentTargetUnavailable} onRecover={candidate => owner.restore(candidate, () => active.current)} onDiscard={async candidate => {
301
+ unavailableMessage={t.commentTargetUnavailable} onRecover={async candidate => { await owner.restore(candidate, () => active.current) }} onDiscard={async candidate => {
219
302
  const binding = owner.latest.current, record = binding?.record, input = binding?.input
220
303
  const { token, storage, ...value } = candidate
221
- if (await drafts.discard(candidate) && binding && owner.latest.current === binding && binding.input === input && binding.record === record
304
+ if (await drafts.discardProposal(candidate) && binding && owner.latest.current === binding && binding.input === input && binding.record === record
222
305
  && record && JSON.stringify(record) === JSON.stringify(value)) binding.record = undefined
223
306
  }} /></>
224
307
  }