@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.
- package/package.json +5 -4
- package/src/MediaClipEditor.tsx +4 -3
- package/src/StepProductionEditor.tsx +13 -4
- package/src/approvals.tsx +6 -1
- package/src/audio-recording.ts +27 -5
- package/src/authoring-client.ts +10 -10
- package/src/authoring-draft-fragment.ts +3 -1
- package/src/authoring-window.ts +100 -0
- package/src/body-draft-actions.ts +60 -0
- package/src/caption-timing-drafts.ts +18 -1
- package/src/component-property-drafts.ts +5 -5
- package/src/components.tsx +22 -31
- package/src/context.tsx +5 -3
- package/src/diagnostics.ts +1 -1
- package/src/document-draft-store.ts +45 -18
- package/src/document-drafts.ts +28 -19
- package/src/document-editing.ts +484 -0
- package/src/document-editor/BlockNoteSurface.tsx +25 -9
- package/src/document-editor/ComponentMaterials.tsx +3 -9
- package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
- package/src/document-editor/DocumentBlockPreview.tsx +4 -2
- package/src/document-editor/DocumentComments.tsx +85 -14
- package/src/document-editor/DocumentEditor.tsx +44 -7
- package/src/document-editor/DocumentStepNarration.tsx +33 -25
- package/src/document-editor/NarrationEditor.tsx +54 -20
- package/src/document-editor/NewCommentDrafts.tsx +114 -31
- package/src/document-editor/PlaceComment.tsx +228 -0
- package/src/document-editor/comment-draft-actions.ts +40 -20
- package/src/document-editor/comment-draft-inspection.ts +2 -2
- package/src/document-editor/comment-drafts.ts +73 -25
- package/src/document-editor/comments.ts +30 -10
- package/src/document-editor/component-label.ts +11 -0
- package/src/document-editor/file-input.ts +2 -2
- package/src/document-editor/focus.ts +0 -2
- package/src/document-editor/insertion-place.ts +60 -0
- package/src/document-editor/messages.ts +3 -3
- package/src/document-editor/narration-schema.tsx +12 -6
- package/src/document-editor/narration.ts +19 -3
- package/src/document-editor/page-body.ts +60 -0
- package/src/document-editor/projection.ts +2 -2
- package/src/document-editor/rich-text.ts +3 -2
- package/src/document-editor/selection.ts +13 -0
- package/src/document-editor/style.css +12 -1
- package/src/document-editor/table-identities.ts +2 -1
- package/src/document-production.ts +491 -0
- package/src/document-session.ts +202 -56
- package/src/document-timing-drafts.ts +22 -2
- package/src/history.ts +5 -5
- package/src/index.ts +6 -5
- package/src/jobs.ts +1 -1
- package/src/media-drafts.ts +43 -1
- package/src/messages.ts +31 -14
- package/src/panels/DocumentView.tsx +71 -28
- package/src/panels/DocumentVoiceDialog.tsx +25 -9
- package/src/panels/DocumentVoiceField.tsx +1 -1
- package/src/panels/ExportPanel.tsx +1 -6
- package/src/panels/HistoryPanel.tsx +32 -2
- package/src/panels/PageDeleteDialog.tsx +4 -4
- package/src/panels/PageRenameDialog.tsx +1 -1
- package/src/panels/PreviewPanel.tsx +1 -4
- package/src/panels/ProductionCaptionSize.tsx +20 -0
- package/src/panels/ProductionCaptionTiming.tsx +12 -9
- package/src/panels/ProductionMediaClips.tsx +23 -7
- package/src/panels/ProductionPanel.tsx +8 -4
- package/src/panels/ProductionRecording.tsx +86 -9
- package/src/panels/ProductionRecordingRange.tsx +21 -19
- package/src/panels/ProductionTimeline.tsx +6 -1
- package/src/panels/ProductionTranscription.tsx +5 -4
- package/src/panels/SourceDocumentPanel.tsx +16 -36
- package/src/panels/TranscriptionAdoption.tsx +40 -34
- package/src/panels/VoiceCloneDialog.tsx +2 -1
- package/src/panels/VoiceoverDialog.tsx +1 -1
- package/src/places.ts +1 -36
- package/src/preview-playback.ts +1 -1
- package/src/production-draft-actions.ts +37 -0
- package/src/production-messages.ts +6 -0
- package/src/production-playback.ts +1 -1
- package/src/production-voice-playback.ts +3 -2
- package/src/sha256.ts +9 -0
- package/src/styles.css +21 -43
- package/src/transcription-drafts.ts +124 -0
- package/src/use-recording-adoption.ts +2 -2
- package/src/voice-drafts.ts +32 -8
- package/src/voiceover-jobs.ts +1 -1
- package/src/workbench-state.ts +157 -0
- package/src/workbench.ts +258 -951
- package/src/workspace-client.ts +21 -11
- package/src/assistant-mascot.ts +0 -62
- package/src/mascot-preference.ts +0 -37
- package/src/panels/ChangeTrail.tsx +0 -79
|
@@ -5,11 +5,15 @@ import { components } from '@blocknote/mantine'
|
|
|
5
5
|
import { ComponentsContext, FloatingComposer, PositionPopover, useBlockNoteEditor, useComponentsContext, 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'
|
|
@@ -25,13 +29,18 @@ interface ComposerBinding {
|
|
|
25
29
|
input: number
|
|
26
30
|
composing: boolean
|
|
27
31
|
active: boolean
|
|
32
|
+
submitting: boolean
|
|
33
|
+
adopting?: boolean
|
|
34
|
+
previous?: ComposerBinding
|
|
35
|
+
adoption?: { guard(): void, finish(record?: CommentDraftRecord): void }
|
|
28
36
|
}
|
|
29
|
-
interface PreparedDraft { record: CommentDraftRecord, origin
|
|
37
|
+
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
38
|
interface NewDraftOwner {
|
|
31
39
|
editor: NativeDocumentEditor
|
|
32
40
|
latest: { current: ComposerBinding | undefined }
|
|
33
41
|
prepared: { current: PreparedDraft | undefined }
|
|
34
|
-
|
|
42
|
+
generation: number
|
|
43
|
+
restore(candidate: CommentDraftCandidate, current?: () => boolean, operation?: CommentDraftOperation): Promise<CommentDraftRecord | undefined>
|
|
35
44
|
failure?: boolean
|
|
36
45
|
}
|
|
37
46
|
const NEW_DRAFT_OWNER = createContext<NewDraftOwner | undefined>(undefined)
|
|
@@ -42,27 +51,33 @@ const emptyState = { candidates: [], pending: false, failed: false, reading: fal
|
|
|
42
51
|
export function NewCommentDraftProvider({ children }: { children?: ReactNode }) {
|
|
43
52
|
const context = useContext(COMMENT_EDITOR_CONTEXT), editor = useBlockNoteEditor() as NativeDocumentEditor, comments = useExtension(CommentsExtension)
|
|
44
53
|
const latest = useRef<ComposerBinding>(), prepared = useRef<PreparedDraft>(), active = useRef(true), operation = useRef(0)
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
|
|
54
|
+
const composerId = useRef(randomUUID()), handoff = useRef<() => void>()
|
|
55
|
+
const [failure, setFailure] = useState(false), [generation, setGeneration] = useState(0)
|
|
56
|
+
useEffect(() => { active.current = true; return () => { active.current = false; ++operation.current; handoff.current?.(); prepared.current = undefined; latest.current = undefined } }, [editor])
|
|
57
|
+
const restore = async (candidate: CommentDraftCandidate, current = () => true, action?: CommentDraftOperation): Promise<CommentDraftRecord | undefined> => {
|
|
48
58
|
const store = context?.store, drafts = store?.drafts, target = candidate.target
|
|
49
59
|
if (!store || !drafts || !isNewCommentDraft(target) || candidate.storage !== 'durable' || editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing) return
|
|
50
|
-
const binding = latest.current
|
|
60
|
+
const binding = latest.current?.active ? latest.current : undefined
|
|
51
61
|
if (binding?.record && !drafts.owns(binding.record)) binding.record = undefined
|
|
62
|
+
handoff.current?.()
|
|
52
63
|
const request = ++operation.current, input = binding?.input, record = binding?.record
|
|
53
64
|
try {
|
|
54
65
|
store.beforeAction?.()
|
|
55
66
|
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
|
|
67
|
+
const version = store.version, native = editor.prosemirrorState, extensionState = comments.store.state, position = context.getPositionToken?.(), form = binding?.editor.prosemirrorState
|
|
68
|
+
if (!version || binding?.composing || binding?.submitting || binding?.editor.prosemirrorView.composing) return
|
|
58
69
|
const owns = () => active.current && current() && request === operation.current && !editor.prosemirrorView.isDestroyed && !editor.prosemirrorView.composing && store.version === version
|
|
59
70
|
&& context.getPositionToken?.() === position
|
|
60
71
|
&& editor.prosemirrorState.doc === native.doc && editor.prosemirrorState.selection === native.selection && comments.store.state === extensionState
|
|
61
72
|
&& (!binding || latest.current === binding && binding.input === input && binding.record === record && !binding.composing)
|
|
62
|
-
|
|
63
|
-
|
|
73
|
+
const guard = () => { action?.signal?.throwIfAborted(); action?.guard?.(); if (!owns()) throw new Error('client-comment-composer-changed') }
|
|
74
|
+
guard()
|
|
75
|
+
if (record && !await waitForDraft(drafts.confirm(record), action?.signal)) return
|
|
76
|
+
guard()
|
|
77
|
+
const nextTarget = { ...target, intentId: randomUUID() }, next = await drafts.recover(candidate, nextTarget, version, { signal: action?.signal, guard })
|
|
64
78
|
store.beforeAction?.()
|
|
65
|
-
if (!next
|
|
79
|
+
if (!next) return
|
|
80
|
+
guard()
|
|
66
81
|
const positions = store.newDraftPositions(nextTarget, editor)
|
|
67
82
|
if (!positions) { setFailure(true); return }
|
|
68
83
|
comments.stopPendingComment()
|
|
@@ -70,14 +85,46 @@ export function NewCommentDraftProvider({ children }: { children?: ReactNode })
|
|
|
70
85
|
editor.focus()
|
|
71
86
|
editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, positions.from, positions.to)).scrollIntoView())
|
|
72
87
|
// The public controller creates the actual editor; this is only its strictly committed handoff.
|
|
73
|
-
|
|
88
|
+
let finish!: (record?: CommentDraftRecord) => void
|
|
89
|
+
const adopted = new Promise<CommentDraftRecord | undefined>(resolve => { finish = resolve })
|
|
90
|
+
const pending: PreparedDraft = { record: next, previous: binding, ...!action ? { origin: candidate } : {}, doc: editor.prosemirrorState.doc, selection: editor.prosemirrorState.selection, version,
|
|
91
|
+
canUse: actual => (!binding || binding.input === input && binding.record === record && !binding.composing && !binding.submitting)
|
|
92
|
+
&& (actual === binding?.editor ? !actual.prosemirrorView.isDestroyed && actual.prosemirrorState.doc === form?.doc && actual.prosemirrorState.selection === form?.selection : actual.isEmpty) }
|
|
93
|
+
if (action) {
|
|
94
|
+
let settled = false
|
|
95
|
+
const complete = (value?: CommentDraftRecord) => { if (settled) return; settled = true; if (handoff.current === cancel) handoff.current = undefined; finish(value) }
|
|
96
|
+
const cancel = () => complete()
|
|
97
|
+
handoff.current = cancel
|
|
98
|
+
pending.adoption = { finish: complete, guard: () => {
|
|
99
|
+
action.signal?.throwIfAborted(); store.beforeAction?.()
|
|
100
|
+
const actual = latest.current
|
|
101
|
+
if (!active.current || !current() || request !== operation.current || store.version !== version || editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing
|
|
102
|
+
|| editor.prosemirrorState.doc !== pending.doc || editor.prosemirrorState.selection !== pending.selection || !actual?.active || actual.record !== next || actual.input !== 0
|
|
103
|
+
|| actual.composing || actual.submitting || !store.newDraftPositions(nextTarget, editor)) throw new Error('client-comment-composer-changed')
|
|
104
|
+
} }
|
|
105
|
+
}
|
|
106
|
+
prepared.current = pending
|
|
74
107
|
comments.startPendingComment()
|
|
75
|
-
|
|
108
|
+
pending.selection = editor.prosemirrorState.selection
|
|
109
|
+
setGeneration(value => value + 1)
|
|
76
110
|
setFailure(false)
|
|
77
111
|
context.onDraftRestore?.()
|
|
78
|
-
|
|
112
|
+
if (action) return await waitForDraft(adopted, action.signal)
|
|
113
|
+
} catch (error) { if (active.current && request === operation.current) setFailure(true); if (action) throw error }
|
|
114
|
+
finally { if (request === operation.current) handoff.current?.() }
|
|
79
115
|
}
|
|
80
|
-
|
|
116
|
+
useLayoutEffect(() => {
|
|
117
|
+
const store = context?.store, drafts = store?.drafts
|
|
118
|
+
if (!store || !drafts) return
|
|
119
|
+
return drafts.registerComposer({ id: composerId.current, target: { kind: 'create', intentId: composerId.current, documentId: store.document.id },
|
|
120
|
+
accepts: target => isNewCommentDraft(target) && Boolean(store.newDraftPositions(target, editor)),
|
|
121
|
+
snapshot: () => { const binding = latest.current?.active ? latest.current : undefined; return { record: binding?.record,
|
|
122
|
+
composing: editor.prosemirrorView.composing || Boolean(binding?.composing || binding?.editor.prosemirrorView.composing),
|
|
123
|
+
available: active.current && !context.readOnly && !editor.prosemirrorView.isDestroyed && !binding?.submitting && store.auth.canCreateThread() } },
|
|
124
|
+
targetState: target => target && isNewCommentDraft(target) && store.newDraftPositions(target, editor) ? 'current' : 'unavailable',
|
|
125
|
+
restore: (candidate, action) => restore(candidate, () => active.current, action) })
|
|
126
|
+
}, [context?.store, context?.readOnly, editor])
|
|
127
|
+
return <NEW_DRAFT_OWNER.Provider value={{ editor, latest, prepared, generation, restore, failure }}>{children}</NEW_DRAFT_OWNER.Provider>
|
|
81
128
|
}
|
|
82
129
|
|
|
83
130
|
/**
|
|
@@ -106,7 +153,8 @@ export function DocumentNewCommentController() {
|
|
|
106
153
|
const position = useEditorState({ editor, selector: ({ editor }) => pendingComment ? { from: editor.prosemirrorState.selection.from, to: editor.prosemirrorState.selection.to } : undefined })
|
|
107
154
|
const floating = useMemo(() => commentFloating(), [])
|
|
108
155
|
return <PositionPopover position={position} focusManagerProps={{ disabled: true }} elementProps={{ style: { zIndex: COMPOSER_LAYER } }}
|
|
109
|
-
useFloatingOptions={{ placement: 'bottom', ...floating, open: pendingComment, onOpenChange(open) {
|
|
156
|
+
useFloatingOptions={{ placement: 'bottom', ...floating, open: pendingComment, onOpenChange(open, event?: Event) {
|
|
157
|
+
if (!open && isApprovalTarget(event?.target ?? document.activeElement)) return
|
|
110
158
|
if (open || !owner || owner.latest.current?.composing || owner.latest.current?.editor.prosemirrorView.composing) return
|
|
111
159
|
try { context?.store.beforeAction?.() } catch { return }
|
|
112
160
|
comments.stopPendingComment()
|
|
@@ -126,15 +174,20 @@ function DocumentNewCommentComposer({ newCommentEditor }: { newCommentEditor: Co
|
|
|
126
174
|
try {
|
|
127
175
|
context.store.beforeAction?.()
|
|
128
176
|
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
|
|
177
|
+
&& restored.doc === owner.editor.prosemirrorState.doc && restored.selection === owner.editor.prosemirrorState.selection && restored.canUse(newCommentEditor)
|
|
130
178
|
&& isNewCommentDraft(restored.record.target) && context.store.newDraftPositions(restored.record.target, owner.editor) ? restored : undefined
|
|
179
|
+
if (restored && !prepared && owner.latest.current?.editor === newCommentEditor) {
|
|
180
|
+
const retained = owner.latest.current
|
|
181
|
+
retained.active = true; owner.prepared.current = undefined; restored.adoption?.finish(); setBinding(retained)
|
|
182
|
+
return () => { retained.active = false }
|
|
183
|
+
}
|
|
131
184
|
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
|
|
185
|
+
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 }
|
|
186
|
+
if (restored) { if (!prepared) restored.adoption?.finish(); owner.prepared.current = undefined }
|
|
134
187
|
owner.latest.current = value; setBinding(value)
|
|
135
188
|
return () => { value.active = false }
|
|
136
189
|
} catch { /* The unchanged native form remains available when no authoritative target can be confirmed. */ }
|
|
137
|
-
}, [newCommentEditor, context?.store, owner?.editor])
|
|
190
|
+
}, [newCommentEditor, context?.store, owner?.editor, owner?.generation])
|
|
138
191
|
const value = useMemo(() => ({ ...nativeComponents, Comments: { ...nativeComponents.Comments, Editor: NewCommentEditor } }), [nativeComponents])
|
|
139
192
|
return <NEW_COMPOSER_BINDING.Provider value={{ binding, ready: () => render(value => value + 1) }}><ComponentsContext.Provider value={value}>
|
|
140
193
|
<FloatingComposer newCommentEditor={newCommentEditor} />
|
|
@@ -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
|
-
|
|
154
|
-
|
|
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(
|
|
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.
|
|
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
|
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
import { useContext, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
|
2
|
+
import type { ContextType } from 'react'
|
|
3
|
+
import type { BlockNoteEditor } from '@blocknote/core'
|
|
4
|
+
import { CommentEditorSubmitExtension } from '@blocknote/core/comments'
|
|
5
|
+
import { components } from '@blocknote/mantine'
|
|
6
|
+
import { useCreateBlockNote, useDictionary, useEditorState, useThreads } from '@blocknote/react'
|
|
7
|
+
import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
|
|
8
|
+
import { PmButton, PmIconButton, PmNotice, PmPopover, PmSelect } from '../components.tsx'
|
|
9
|
+
import { useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
10
|
+
import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
|
|
11
|
+
import { isNewCommentDraft, newCommentDraftSignature, sameCommentDraftTarget } from './comment-drafts.ts'
|
|
12
|
+
import type { CommentDraftCandidate, CommentDraftRecord, CommentDraftOperation, CommentDraftComposer, NewCommentDraftTarget } from './comment-drafts.ts'
|
|
13
|
+
import { discardNativeCommentDraft } from './comment-draft-actions.ts'
|
|
14
|
+
import { waitForDraft } from '../document-draft-store.ts'
|
|
15
|
+
import { isApprovalTarget } from '../approvals.tsx'
|
|
16
|
+
import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
|
|
17
|
+
import { commentEditorSchema } from './schema.tsx'
|
|
18
|
+
import type { DocumentEditorBlock } from './schema.tsx'
|
|
19
|
+
import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
|
|
20
|
+
|
|
21
|
+
const MantineCommentEditor = components.Comments.Editor
|
|
22
|
+
const emptyDrafts = { candidates: [], pending: false, failed: false, reading: false } as const
|
|
23
|
+
const subscribeEmpty = () => () => {}
|
|
24
|
+
type CommentContext = NonNullable<ContextType<typeof COMMENT_EDITOR_CONTEXT>>
|
|
25
|
+
|
|
26
|
+
/** The step's place anchor: the whole block when no step is chosen. */
|
|
27
|
+
function placeOf(blockId: string, stepId: string | undefined) {
|
|
28
|
+
return stepId === undefined ? { blockId } : { blockId, stepId }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* A block preview's own comment entry. The button belongs to the preview header; the composer reuses the canonical
|
|
33
|
+
* comment editor and draft bank instead of inventing a second comment flow.
|
|
34
|
+
*/
|
|
35
|
+
export function PlaceCommentButton(props: {
|
|
36
|
+
blockId: string, sectionId: string, stepId: string, stepIndex: number, onPause(): void,
|
|
37
|
+
}) {
|
|
38
|
+
const context = useContext(COMMENT_EDITOR_CONTEXT)
|
|
39
|
+
if (!context || context.readOnly || !context.store.auth.canCreateThread()) return null
|
|
40
|
+
return <PlaceCommentButtonContent {...props} context={context} />
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function PlaceCommentButtonContent({ blockId, sectionId, stepId, stepIndex, onPause, context }: {
|
|
44
|
+
blockId: string, sectionId: string, stepId: string, stepIndex: number, onPause(): void, context: CommentContext,
|
|
45
|
+
}) {
|
|
46
|
+
const threads = useThreads(), workbench = useWorkbench()
|
|
47
|
+
const t = DOCUMENT_EDITOR_MESSAGES[context.locale]
|
|
48
|
+
const [open, setOpen] = useState(false), [selected, setSelected] = useState<string | undefined>(stepId)
|
|
49
|
+
const drafts = context.store.drafts, native = useRef<CommentDraftComposer>(), composerId = useRef(randomUUID()), revision = useRef(0)
|
|
50
|
+
const draftState = useSyncExternalStore(drafts?.subscribe ?? subscribeEmpty, drafts?.snapshot ?? (() => emptyDrafts))
|
|
51
|
+
const needed = open || draftState.candidates.some(candidate => isNewCommentDraft(candidate.target) && candidate.target.anchor && isDocumentPlaceAnchor(candidate.target.anchor) && candidate.target.anchor.blockId === blockId)
|
|
52
|
+
const opening = useRef<{ previous?: CommentDraftRecord, ready?(owner?: CommentDraftComposer): void }>()
|
|
53
|
+
const alive = useRef(true)
|
|
54
|
+
const accept = (target: CommentDraftCandidate['target']) => isNewCommentDraft(target) && Boolean(target.anchor && isDocumentPlaceAnchor(target.anchor) && target.anchor.blockId === blockId
|
|
55
|
+
&& (target.anchor.stepId === undefined || context.store.document.sections[sectionId]?.stepOrder.includes(target.anchor.stepId)) && context.store.draftTargetState(target) === 'current')
|
|
56
|
+
const ready = useMemo(() => (owner: CommentDraftComposer | undefined) => { native.current = owner; if (owner) opening.current?.ready?.(owner) }, [])
|
|
57
|
+
useLayoutEffect(() => {
|
|
58
|
+
alive.current = true
|
|
59
|
+
if (!drafts || !needed) return
|
|
60
|
+
const restore = async (candidate: CommentDraftCandidate, action: CommentDraftOperation): Promise<CommentDraftRecord | undefined> => {
|
|
61
|
+
if (!accept(candidate.target) || !isNewCommentDraft(candidate.target) || !candidate.target.anchor || !isDocumentPlaceAnchor(candidate.target.anchor)) return
|
|
62
|
+
const before = native.current, previous = before?.snapshot().record, version = context.store.version, request = ++revision.current, targetStep = candidate.target.anchor.stepId
|
|
63
|
+
const guard = () => {
|
|
64
|
+
action.signal?.throwIfAborted(); action.guard?.(); context.store.beforeAction?.()
|
|
65
|
+
if (!alive.current || revision.current !== request || context.store.version !== version || !accept(candidate.target)) throw new Error('client-comment-composer-changed')
|
|
66
|
+
}
|
|
67
|
+
guard()
|
|
68
|
+
if (previous && !await waitForDraft(drafts.confirm(previous), action.signal)) return
|
|
69
|
+
guard()
|
|
70
|
+
let resolve!: (owner?: CommentDraftComposer) => void
|
|
71
|
+
const mounted = new Promise<CommentDraftComposer | undefined>(yes => { resolve = yes })
|
|
72
|
+
const transition = { previous, ready: resolve }; opening.current = transition
|
|
73
|
+
try {
|
|
74
|
+
onPause(); setSelected(targetStep); setOpen(true)
|
|
75
|
+
if (targetStep !== undefined) workbench.observeDocumentStep(sectionId, targetStep)
|
|
76
|
+
// A mounted matching form can be reused; otherwise the keyed native form supplies readiness.
|
|
77
|
+
const same = before && sameCommentDraftTarget(before.target, candidate.target)
|
|
78
|
+
const actual = same ? before : await waitForDraft(mounted, action.signal)
|
|
79
|
+
guard()
|
|
80
|
+
if (!actual?.restore || native.current !== actual || !actual.snapshot().available || actual.snapshot().composing || !same && actual.snapshot().record) return
|
|
81
|
+
const value = await actual.restore(candidate, { signal: action.signal, guard })
|
|
82
|
+
return value
|
|
83
|
+
} finally { if (opening.current === transition) opening.current = undefined }
|
|
84
|
+
}
|
|
85
|
+
const stop = drafts.registerComposer({ id: composerId.current, target: { kind: 'create', intentId: composerId.current, documentId: context.store.document.id }, accepts: accept,
|
|
86
|
+
snapshot: () => { const current = native.current?.snapshot(); return { record: opening.current ? opening.current.previous : current?.record,
|
|
87
|
+
composing: current?.composing ?? false, available: alive.current && !context.readOnly && context.store.auth.canCreateThread() && (current?.available ?? true) } },
|
|
88
|
+
targetState: target => target && accept(target) ? 'current' : 'unavailable', restore })
|
|
89
|
+
return () => { alive.current = false; revision.current++; opening.current?.ready?.(); opening.current = undefined; stop() }
|
|
90
|
+
}, [drafts, context.store, blockId, sectionId, needed])
|
|
91
|
+
const count = useMemo(() => [...threads.values()].filter(thread => {
|
|
92
|
+
if (thread.deletedAt || thread.resolved) return false
|
|
93
|
+
const anchor = context.store.placeAnchorOf(thread.id)
|
|
94
|
+
return anchor?.blockId === blockId && anchor.stepId === stepId
|
|
95
|
+
}).length, [threads, context, blockId, stepId])
|
|
96
|
+
const change = (next: boolean) => {
|
|
97
|
+
revision.current++; opening.current?.ready?.()
|
|
98
|
+
setOpen(next)
|
|
99
|
+
if (next) setSelected(stepId)
|
|
100
|
+
}
|
|
101
|
+
return <PmPopover open={open} label={t.stepComment(stepIndex)} name="pm-document-place-comment" placement="below-end" onOpenChange={change}
|
|
102
|
+
onInteractOutside={event => { if (isApprovalTarget(event.detail.originalEvent.target)) event.preventDefault() }}
|
|
103
|
+
trigger={<PmIconButton tooltip={false} small icon="comment-add" label={t.stepCommentHint(stepIndex, count)} onClick={onPause} />}>
|
|
104
|
+
{open && <PlaceCommentComposer key={selected ?? 'block'} context={context} blockId={blockId} sectionId={sectionId} stepId={selected}
|
|
105
|
+
onReady={ready} onSelect={next => { revision.current++; setSelected(next); if (next !== undefined) workbench.observeDocumentStep(sectionId, next) }} onClose={() => change(false)} />}
|
|
106
|
+
</PmPopover>
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, onClose, onReady }: {
|
|
110
|
+
context: CommentContext, blockId: string, sectionId: string, stepId: string | undefined, onSelect(stepId: string | undefined): void, onClose(): void, onReady(owner?: CommentDraftComposer): void,
|
|
111
|
+
}) {
|
|
112
|
+
const workbench = useWorkbench()
|
|
113
|
+
const fallback = context.store.document
|
|
114
|
+
const document = useWorkbenchState(state => state.authoring?.content) ?? fallback
|
|
115
|
+
const section = document?.sections[sectionId]
|
|
116
|
+
const t = DOCUMENT_EDITOR_MESSAGES[context.locale]
|
|
117
|
+
const store = context.store, drafts = store.drafts, dictionary = useDictionary()
|
|
118
|
+
const rich = useMemo(() => createRichProjection(), [])
|
|
119
|
+
const [target] = useState<NewCommentDraftTarget>(() => {
|
|
120
|
+
const anchor = placeOf(blockId, stepId)
|
|
121
|
+
return { kind: 'create', intentId: randomUUID(), documentId: document!.id, anchor, signature: newCommentDraftSignature(document!, anchor) }
|
|
122
|
+
})
|
|
123
|
+
const [busy, setBusy] = useState(false), [failure, setFailure] = useState(false)
|
|
124
|
+
const record = useRef<CommentDraftRecord>(), composing = useRef(false), submitting = useRef(false), composer = useRef(randomUUID())
|
|
125
|
+
const active = useRef(true), input = useRef(0), suppress = useRef(false)
|
|
126
|
+
const submitRef = useRef<() => Promise<void>>(() => Promise.resolve())
|
|
127
|
+
const editor: BlockNoteEditor<any, any, any> = useCreateBlockNote({
|
|
128
|
+
schema: commentEditorSchema, trailingBlock: false,
|
|
129
|
+
dictionary: { ...dictionary, placeholders: { ...dictionary.placeholders, emptyDocument: t.stepCommentPlaceholder } },
|
|
130
|
+
extensions: [CommentEditorSubmitExtension({ onSubmit: async () => submitRef.current() })],
|
|
131
|
+
}, [blockId, stepId])
|
|
132
|
+
const empty = useEditorState({ editor, selector: ({ editor }) => editor.isEmpty })
|
|
133
|
+
const write = (composingNow: boolean) => {
|
|
134
|
+
const version = store.version, current = record.current
|
|
135
|
+
if (!drafts || !version) return
|
|
136
|
+
if (editor.isEmpty) {
|
|
137
|
+
if (current) { record.current = undefined; void drafts.clearOwn(current) }
|
|
138
|
+
return
|
|
139
|
+
}
|
|
140
|
+
const next = drafts.write(current?.target ?? target, current?.version ?? version, nativeRichTextToProduct(editor.document as DocumentEditorBlock[], rich), composingNow, current)
|
|
141
|
+
if (next) record.current = next
|
|
142
|
+
}
|
|
143
|
+
useLayoutEffect(() => {
|
|
144
|
+
if (!drafts) return
|
|
145
|
+
active.current = true
|
|
146
|
+
const stop = editor.onChange(() => { if (!submitting.current && !suppress.current) { input.current++; write(composing.current) } })
|
|
147
|
+
return () => { active.current = false; input.current++; stop() }
|
|
148
|
+
}, [drafts, editor, target, rich])
|
|
149
|
+
useLayoutEffect(() => {
|
|
150
|
+
if (!drafts) return
|
|
151
|
+
const owner: CommentDraftComposer = { id: composer.current, target,
|
|
152
|
+
snapshot: () => ({ record: record.current, composing: composing.current || editor.prosemirrorView.composing, available: active.current && !submitting.current && !editor.prosemirrorView.isDestroyed }),
|
|
153
|
+
targetState: () => store.draftTargetState(target), restore: recover, discard: discardActive }
|
|
154
|
+
const stop = drafts.registerComposer(owner); onReady(owner)
|
|
155
|
+
return () => { onReady(); stop() }
|
|
156
|
+
}, [drafts, store, target, editor])
|
|
157
|
+
const composition = (value: boolean) => { composing.current = value; input.current++; write(value) }
|
|
158
|
+
const submit = async () => {
|
|
159
|
+
if (submitting.current || busy || editor.isEmpty || editor.prosemirrorView.composing) return
|
|
160
|
+
if (!store.auth.canCreateThread() || store.draftTargetState(target) !== 'current') { setFailure(true); return }
|
|
161
|
+
setBusy(true); setFailure(false); submitting.current = true
|
|
162
|
+
try {
|
|
163
|
+
store.beforeAction?.()
|
|
164
|
+
const thread = await store.createPlaceThread({ blockId, stepId, body: editor.document })
|
|
165
|
+
const actual = store.threadSnapshot(thread.id)
|
|
166
|
+
if (actual) { const current = record.current; if (current) { drafts?.submitted(current, actual.comments[0]!, actual); record.current = undefined } }
|
|
167
|
+
context?.openComments?.()
|
|
168
|
+
onClose()
|
|
169
|
+
} catch { setFailure(true) } finally { submitting.current = false; setBusy(false) }
|
|
170
|
+
}
|
|
171
|
+
submitRef.current = submit
|
|
172
|
+
const draftsState = useSyncExternalStore(drafts?.subscribe ?? subscribeEmpty, drafts?.snapshot ?? (() => emptyDrafts))
|
|
173
|
+
const candidates = draftsState.candidates.filter(candidate => isNewCommentDraft(candidate.target) && sameCommentDraftTarget(candidate.target, target))
|
|
174
|
+
const nativeGuard = () => {
|
|
175
|
+
const version = store.version, before = input.current, own = record.current, native = editor.prosemirrorState, position = context.getPositionToken?.()
|
|
176
|
+
return () => {
|
|
177
|
+
store.beforeAction?.()
|
|
178
|
+
if (!active.current || !version || store.version !== version || input.current !== before || record.current !== own || composing.current || submitting.current
|
|
179
|
+
|| editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing || editor.prosemirrorState.doc !== native.doc || editor.prosemirrorState.selection !== native.selection
|
|
180
|
+
|| context.getPositionToken?.() !== position || !store.auth.canCreateThread()) throw new Error('client-comment-composer-changed')
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const recover = async (candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<CommentDraftRecord | undefined> => {
|
|
184
|
+
const version = store.version
|
|
185
|
+
if (!drafts || !version) return
|
|
186
|
+
const current = nativeGuard(), guard = () => { operation?.signal?.throwIfAborted(); operation?.guard?.(); current(); if (store.draftTargetState(target) !== 'current') throw new Error('client-comment-target-changed') }
|
|
187
|
+
guard()
|
|
188
|
+
if (record.current && !await waitForDraft(drafts.confirm(record.current), operation?.signal)) return
|
|
189
|
+
guard()
|
|
190
|
+
const next = await drafts.recover(candidate, target, version, { signal: operation?.signal, guard })
|
|
191
|
+
if (!next) return
|
|
192
|
+
guard(); suppress.current = true
|
|
193
|
+
try {
|
|
194
|
+
editor.replaceBlocks(editor.document, productRichTextToNative(next.content, rich))
|
|
195
|
+
if (JSON.stringify(nativeRichTextToProduct(editor.document as DocumentEditorBlock[], rich)) !== JSON.stringify(next.content)) throw new Error('client-comment-native-unverified')
|
|
196
|
+
record.current = next; input.current++
|
|
197
|
+
} finally { suppress.current = false }
|
|
198
|
+
if (!operation) await drafts.discard(candidate)
|
|
199
|
+
return next
|
|
200
|
+
}
|
|
201
|
+
const discardActive = async (candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean> => {
|
|
202
|
+
if (!drafts) return false
|
|
203
|
+
const own = record.current
|
|
204
|
+
if (!own || own.id !== candidate.id || own.revision !== candidate.revision) return false
|
|
205
|
+
return discardNativeCommentDraft(drafts, candidate, operation, nativeGuard(), () => {
|
|
206
|
+
suppress.current = true
|
|
207
|
+
try { editor.replaceBlocks(editor.document, [{ type: 'paragraph', content: [] }]); record.current = undefined; input.current++ }
|
|
208
|
+
finally { suppress.current = false }
|
|
209
|
+
})
|
|
210
|
+
}
|
|
211
|
+
const discard = async (candidate: CommentDraftCandidate) => { await drafts?.discardProposal(candidate) }
|
|
212
|
+
return <div className="pm-document-place-comment__body pm-ui-block-editor">
|
|
213
|
+
<PmSelect label={t.stepCommentStep} value={stepId ?? ''} disabled={busy || !empty} onChange={event => onSelect(event.currentTarget.value || undefined)}>
|
|
214
|
+
<option value="">{t.stepCommentWhole}</option>
|
|
215
|
+
{section?.stepOrder.map((id, index) => <option key={id} value={id}>{t.stepCommentOption(index + 1, document?.steps[id]?.title ?? '')}</option>)}
|
|
216
|
+
</PmSelect>
|
|
217
|
+
<div className="pm-document-place-comment__editor" onCompositionStart={() => composition(true)} onCompositionEnd={() => composition(false)}>
|
|
218
|
+
<MantineCommentEditor editor={editor} editable autoFocus />
|
|
219
|
+
</div>
|
|
220
|
+
{failure && <PmNotice tone="warn">{t.stepCommentFailed}</PmNotice>}
|
|
221
|
+
{candidates.length > 0 && <DraftChoices candidates={candidates} preview disabled={busy} canRecover={() => store.draftTargetState(target) === 'current'}
|
|
222
|
+
unavailableMessage={t.commentTargetUnavailable} onRecover={async candidate => { await recover(candidate) }} onDiscard={discard} />}
|
|
223
|
+
<div className="pm-document-place-comment__actions">
|
|
224
|
+
<PmButton small disabled={busy} onClick={onClose}>{t.stepCommentCancel}</PmButton>
|
|
225
|
+
<PmButton small variant="primary" loading={busy} disabled={busy || empty} onClick={() => void submit()}>{t.stepCommentSave}</PmButton>
|
|
226
|
+
</div>
|
|
227
|
+
</div>
|
|
228
|
+
}
|
|
@@ -1,58 +1,78 @@
|
|
|
1
1
|
import type { AuthoringClientAction, AuthoringClientActionResult, ClientCommentDraftReference } from '@lincyaw/kernel'
|
|
2
2
|
import { draftContentHash } from '../authoring-draft-fragment.ts'
|
|
3
3
|
import { commentDraftReference } from './comment-draft-inspection.ts'
|
|
4
|
-
import {
|
|
5
|
-
|
|
4
|
+
import type { CommentDrafts, CommentDraftCandidate, CommentDraftOperation } from './comment-drafts.ts'
|
|
5
|
+
|
|
6
|
+
/** Native views call this same guarded retirement before clearing their visible form state. */
|
|
7
|
+
export async function discardNativeCommentDraft(drafts: CommentDrafts, candidate: CommentDraftCandidate, operation: CommentDraftOperation | undefined, guard: () => void, clear: () => void): Promise<boolean> {
|
|
8
|
+
const current = () => { operation?.signal?.throwIfAborted(); operation?.guard?.(); guard() }
|
|
9
|
+
current()
|
|
10
|
+
if (!await drafts.discard(candidate, { signal: operation?.signal, guard: current })) return false
|
|
11
|
+
current(); clear(); return true
|
|
12
|
+
}
|
|
6
13
|
|
|
7
14
|
const sameReference = (a: ClientCommentDraftReference | null, b: ClientCommentDraftReference | null): boolean => a === null || b === null ? a === b
|
|
8
15
|
: a.id === b.id && a.revision === b.revision && a.token === b.token
|
|
9
16
|
|
|
10
17
|
/** The native composer, rather than its backup, acknowledges actual editor adoption. */
|
|
11
18
|
export async function mutateCommentDrafts(drafts: CommentDrafts, action: Extract<AuthoringClientAction, { type: 'comment-drafts.restore' | 'comment-drafts.discard' }>, signal: AbortSignal, owned: () => void, fits: (result: AuthoringClientActionResult) => boolean): Promise<AuthoringClientActionResult> {
|
|
12
|
-
const
|
|
19
|
+
const input = drafts.inputGuard()
|
|
20
|
+
const readBeforeMutation = async (reference: ClientCommentDraftReference) => {
|
|
21
|
+
for (let attempt = 0; ; attempt++) {
|
|
22
|
+
signal.throwIfAborted(); owned(); input()
|
|
23
|
+
try { const value = await drafts.readForAgent(signal, reference); signal.throwIfAborted(); owned(); input(); return value }
|
|
24
|
+
catch (error) {
|
|
25
|
+
signal.throwIfAborted(); owned(); input()
|
|
26
|
+
if (attempt >= 3 || !(error instanceof Error) || error.message !== 'client-comment-drafts-changed') throw error
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const read = await readBeforeMutation(action.draft), candidate = read.candidates[0]!
|
|
13
31
|
owned()
|
|
14
32
|
if (action.type === 'comment-drafts.discard') {
|
|
15
|
-
const guard = () => { signal.throwIfAborted(); owned(); if (drafts.
|
|
33
|
+
const guard = () => { signal.throwIfAborted(); owned(); if (!drafts.canDiscard(candidate)) throw new Error('client-comment-draft-needs-human') }
|
|
16
34
|
const result: AuthoringClientActionResult = { type: action.type, family: 'comment', draft: action.draft, discarded: true }
|
|
17
35
|
guard()
|
|
18
36
|
if (!fits(result)) throw new Error('client-comment-result-too-large')
|
|
19
|
-
if (!await drafts.
|
|
20
|
-
|
|
37
|
+
if (!await drafts.discardProposal(candidate, { signal, guard })) throw new Error('client-comment-drafts-changed')
|
|
38
|
+
signal.throwIfAborted(); owned()
|
|
21
39
|
return result
|
|
22
40
|
}
|
|
23
|
-
if (
|
|
24
|
-
const
|
|
25
|
-
owned()
|
|
26
|
-
if (!
|
|
41
|
+
if (candidate.composing || candidate.pending || candidate.storage !== 'durable') throw new Error('client-comment-draft-needs-human')
|
|
42
|
+
const choice = await drafts.restoreChoice(candidate, signal)
|
|
43
|
+
owned(); input()
|
|
44
|
+
if (!choice || action.composerId !== undefined && (choice.composerId !== action.composerId || !sameReference(choice.expectedCurrent, action.expectedCurrent ?? null))) throw new Error('client-comment-composer-unavailable')
|
|
45
|
+
const { composerId, expectedCurrent } = choice, composer = drafts.composer(composerId)
|
|
46
|
+
if (!composer?.restore) throw new Error('client-comment-composer-unavailable')
|
|
27
47
|
const previous = composer.snapshot().record
|
|
28
48
|
if (previous) {
|
|
29
|
-
if (!
|
|
30
|
-
const current = await
|
|
49
|
+
if (!expectedCurrent) throw new Error('client-comment-drafts-changed')
|
|
50
|
+
const current = await readBeforeMutation(expectedCurrent)
|
|
31
51
|
owned()
|
|
32
52
|
if (current.candidates[0]?.storage !== 'durable') throw new Error('client-comment-draft-needs-human')
|
|
33
|
-
} else if (
|
|
53
|
+
} else if (expectedCurrent !== null) throw new Error('client-comment-drafts-changed')
|
|
34
54
|
const guard = () => {
|
|
35
55
|
signal.throwIfAborted(); owned()
|
|
36
56
|
const state = composer.snapshot()
|
|
37
|
-
if (!drafts.ownersKnown || drafts.composer(
|
|
57
|
+
if (!drafts.ownersKnown || drafts.composer(composerId) !== composer || state.record !== previous || !state.available || state.composing || composer.targetState(candidate.target) === 'unavailable') throw new Error('client-comment-composer-changed')
|
|
38
58
|
}
|
|
39
59
|
guard()
|
|
40
|
-
const targetState = composer.targetState()
|
|
60
|
+
const targetState = composer.targetState(candidate.target)
|
|
41
61
|
if (targetState === 'unavailable') throw new Error('client-comment-composer-unavailable')
|
|
42
|
-
if (!fits({ type: action.type, family: 'comment', draft: action.draft, composerId
|
|
43
|
-
restored: { id: '0'.repeat(36), revision: 1, token: '0'.repeat(64) }, preservedCurrent:
|
|
62
|
+
if (!fits({ type: action.type, family: 'comment', draft: action.draft, composerId,
|
|
63
|
+
restored: { id: '0'.repeat(36), revision: 1, token: '0'.repeat(64) }, preservedCurrent: expectedCurrent, targetState })) throw new Error('client-comment-result-too-large')
|
|
44
64
|
const record = await composer.restore(candidate, { signal, guard })
|
|
45
65
|
if (!record) throw new Error('client-comment-native-unverified')
|
|
46
66
|
const adopted = () => {
|
|
47
67
|
signal.throwIfAborted(); owned()
|
|
48
68
|
const state = composer.snapshot()
|
|
49
|
-
if (!drafts.ownersKnown || drafts.composer(
|
|
69
|
+
if (!drafts.ownersKnown || drafts.composer(composerId) !== composer || state.record !== record || !state.available || state.composing || !drafts.owns(record)) throw new Error('client-comment-composer-changed')
|
|
50
70
|
}
|
|
51
71
|
adopted()
|
|
52
72
|
const token = await draftContentHash(JSON.stringify(record))
|
|
53
73
|
adopted()
|
|
54
|
-
const result: AuthoringClientActionResult = { type: action.type, family: 'comment', draft: action.draft, composerId
|
|
55
|
-
restored: commentDraftReference({ ...record, token, storage: 'durable' }), preservedCurrent:
|
|
74
|
+
const result: AuthoringClientActionResult = { type: action.type, family: 'comment', draft: action.draft, composerId,
|
|
75
|
+
restored: commentDraftReference({ ...record, token, storage: 'durable' }), preservedCurrent: expectedCurrent, targetState }
|
|
56
76
|
if (!fits(result)) throw new Error('client-comment-result-too-large')
|
|
57
77
|
return result
|
|
58
78
|
}
|
|
@@ -9,7 +9,7 @@ export const commentDraftReference = (value: CommentDraftCandidate) => ({ id: va
|
|
|
9
9
|
export function commentDraftMetadata(value: CommentDraftCandidate, drafts: CommentDrafts): ClientCommentDraftMetadata {
|
|
10
10
|
const target = value.target
|
|
11
11
|
return { draft: commentDraftReference(value), kind: isNewCommentDraft(target) ? 'create' : target.commentId ? 'edit' : 'reply', storage: value.storage,
|
|
12
|
-
updatedAt: value.updatedAt, baseVersion: value.version, composing: value.composing, pendingSubmission: Boolean(value.pending), ownersKnown: drafts.ownersKnown, active: drafts.activeRecord(value), discardable:
|
|
12
|
+
updatedAt: value.updatedAt, baseVersion: value.version, composing: value.composing, pendingSubmission: Boolean(value.pending), ownersKnown: drafts.ownersKnown, active: drafts.activeRecord(value), discardable: drafts.canDiscard(value),
|
|
13
13
|
...isNewCommentDraft(target) ? {} : { threadId: target.threadId, ...target.commentId ? { commentId: target.commentId } : {} } }
|
|
14
14
|
}
|
|
15
15
|
|
|
@@ -17,7 +17,7 @@ export async function inspectCommentDrafts(drafts: CommentDrafts, action: Extrac
|
|
|
17
17
|
const read = await drafts.readForAgent(signal, action.type === 'comment-drafts.read' ? action.draft : undefined)
|
|
18
18
|
const current = () => { signal.throwIfAborted(); if (drafts.revision !== read.revision) throw new Error('client-comment-drafts-changed') }
|
|
19
19
|
if (action.type === 'comment-drafts.inspect') {
|
|
20
|
-
const values = await Promise.all(read.candidates.map(async value => { const restore = await drafts.restoreChoice(value, signal); return { ...commentDraftMetadata(value, drafts), ...restore ? { restore } : {} } })), token = await hash(JSON.stringify({ values, coverage: read.coverage, skippedInvalid: read.skippedInvalid }))
|
|
20
|
+
const values = await Promise.all(read.candidates.map(async value => { const restore = await drafts.restoreChoice(value, signal); return { ...commentDraftMetadata(value, drafts), ...restore ? { restorable: true as const, ...action.details ? { restore } : {} } : {} } })), token = await hash(JSON.stringify({ values, coverage: read.coverage, skippedInvalid: read.skippedInvalid }))
|
|
21
21
|
current()
|
|
22
22
|
if (action.cursor && action.cursor.token !== token) throw new Error('client-comment-drafts-changed')
|
|
23
23
|
const start = action.cursor ? values.findIndex(value => value.draft.id === action.cursor!.after) + 1 : 0
|