@lincyaw/workbench 0.2.0-rc.52 → 0.2.0-rc.54
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 +4 -4
- package/src/StepProductionEditor.tsx +13 -4
- package/src/approvals.tsx +6 -1
- package/src/caption-timing-drafts.ts +18 -1
- package/src/components.tsx +2 -2
- package/src/document-editor/DocumentComments.tsx +27 -5
- package/src/document-editor/DocumentStepNarration.tsx +3 -0
- package/src/document-editor/NewCommentDrafts.tsx +111 -29
- package/src/document-editor/PlaceComment.tsx +97 -19
- 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 +57 -11
- package/src/document-production.ts +109 -2
- package/src/document-timing-drafts.ts +22 -2
- package/src/panels/ProductionCaptionTiming.tsx +6 -3
- package/src/panels/ProductionRecordingRange.tsx +6 -4
- package/src/production-draft-actions.ts +37 -0
- package/src/workbench.ts +9 -3
|
@@ -4,12 +4,15 @@ import type { BlockNoteEditor } from '@blocknote/core'
|
|
|
4
4
|
import { CommentEditorSubmitExtension } from '@blocknote/core/comments'
|
|
5
5
|
import { components } from '@blocknote/mantine'
|
|
6
6
|
import { useCreateBlockNote, useDictionary, useEditorState, useThreads } from '@blocknote/react'
|
|
7
|
-
import { randomUUID } from '@lincyaw/kernel'
|
|
7
|
+
import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
|
|
8
8
|
import { PmButton, PmIconButton, PmNotice, PmPopover, PmSelect } from '../components.tsx'
|
|
9
9
|
import { useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
10
10
|
import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
|
|
11
11
|
import { isNewCommentDraft, newCommentDraftSignature, sameCommentDraftTarget } from './comment-drafts.ts'
|
|
12
|
-
import type { CommentDraftCandidate, CommentDraftRecord, NewCommentDraftTarget } 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'
|
|
13
16
|
import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
|
|
14
17
|
import { commentEditorSchema } from './schema.tsx'
|
|
15
18
|
import type { DocumentEditorBlock } from './schema.tsx'
|
|
@@ -43,24 +46,68 @@ function PlaceCommentButtonContent({ blockId, sectionId, stepId, stepIndex, onPa
|
|
|
43
46
|
const threads = useThreads(), workbench = useWorkbench()
|
|
44
47
|
const t = DOCUMENT_EDITOR_MESSAGES[context.locale]
|
|
45
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])
|
|
46
91
|
const count = useMemo(() => [...threads.values()].filter(thread => {
|
|
47
92
|
if (thread.deletedAt || thread.resolved) return false
|
|
48
93
|
const anchor = context.store.placeAnchorOf(thread.id)
|
|
49
94
|
return anchor?.blockId === blockId && anchor.stepId === stepId
|
|
50
95
|
}).length, [threads, context, blockId, stepId])
|
|
51
96
|
const change = (next: boolean) => {
|
|
97
|
+
revision.current++; opening.current?.ready?.()
|
|
52
98
|
setOpen(next)
|
|
53
99
|
if (next) setSelected(stepId)
|
|
54
100
|
}
|
|
55
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() }}
|
|
56
103
|
trigger={<PmIconButton tooltip={false} small icon="comment-add" label={t.stepCommentHint(stepIndex, count)} onClick={onPause} />}>
|
|
57
104
|
{open && <PlaceCommentComposer key={selected ?? 'block'} context={context} blockId={blockId} sectionId={sectionId} stepId={selected}
|
|
58
|
-
onSelect={next => { setSelected(next); if (next !== undefined) workbench.observeDocumentStep(sectionId, next) }} onClose={() =>
|
|
105
|
+
onReady={ready} onSelect={next => { revision.current++; setSelected(next); if (next !== undefined) workbench.observeDocumentStep(sectionId, next) }} onClose={() => change(false)} />}
|
|
59
106
|
</PmPopover>
|
|
60
107
|
}
|
|
61
108
|
|
|
62
|
-
function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, onClose }: {
|
|
63
|
-
context: CommentContext, blockId: string, sectionId: string, stepId: string | undefined, onSelect(stepId: string | undefined): void, onClose(): void,
|
|
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,
|
|
64
111
|
}) {
|
|
65
112
|
const workbench = useWorkbench()
|
|
66
113
|
const fallback = context.store.document
|
|
@@ -75,6 +122,7 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
|
|
|
75
122
|
})
|
|
76
123
|
const [busy, setBusy] = useState(false), [failure, setFailure] = useState(false)
|
|
77
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)
|
|
78
126
|
const submitRef = useRef<() => Promise<void>>(() => Promise.resolve())
|
|
79
127
|
const editor: BlockNoteEditor<any, any, any> = useCreateBlockNote({
|
|
80
128
|
schema: commentEditorSchema, trailingBlock: false,
|
|
@@ -94,16 +142,19 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
|
|
|
94
142
|
}
|
|
95
143
|
useLayoutEffect(() => {
|
|
96
144
|
if (!drafts) return
|
|
97
|
-
|
|
98
|
-
|
|
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() }
|
|
99
148
|
}, [drafts, editor, target, rich])
|
|
100
149
|
useLayoutEffect(() => {
|
|
101
150
|
if (!drafts) return
|
|
102
|
-
|
|
103
|
-
snapshot: () => ({ record: record.current, composing: composing.current || editor.prosemirrorView.composing, available: !editor.prosemirrorView.isDestroyed }),
|
|
104
|
-
targetState: () => store.draftTargetState(target) }
|
|
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() }
|
|
105
156
|
}, [drafts, store, target, editor])
|
|
106
|
-
const composition = (value: boolean) => { composing.current = value; write(value) }
|
|
157
|
+
const composition = (value: boolean) => { composing.current = value; input.current++; write(value) }
|
|
107
158
|
const submit = async () => {
|
|
108
159
|
if (submitting.current || busy || editor.isEmpty || editor.prosemirrorView.composing) return
|
|
109
160
|
if (!store.auth.canCreateThread() || store.draftTargetState(target) !== 'current') { setFailure(true); return }
|
|
@@ -120,17 +171,44 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
|
|
|
120
171
|
submitRef.current = submit
|
|
121
172
|
const draftsState = useSyncExternalStore(drafts?.subscribe ?? subscribeEmpty, drafts?.snapshot ?? (() => emptyDrafts))
|
|
122
173
|
const candidates = draftsState.candidates.filter(candidate => isNewCommentDraft(candidate.target) && sameCommentDraftTarget(candidate.target, target))
|
|
123
|
-
const
|
|
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> => {
|
|
124
184
|
const version = store.version
|
|
125
185
|
if (!drafts || !version) return
|
|
126
|
-
const
|
|
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 })
|
|
127
191
|
if (!next) return
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
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
|
+
})
|
|
132
210
|
}
|
|
133
|
-
const discard = async (candidate: CommentDraftCandidate) => { await drafts?.
|
|
211
|
+
const discard = async (candidate: CommentDraftCandidate) => { await drafts?.discardProposal(candidate) }
|
|
134
212
|
return <div className="pm-document-place-comment__body pm-ui-block-editor">
|
|
135
213
|
<PmSelect label={t.stepCommentStep} value={stepId ?? ''} disabled={busy || !empty} onChange={event => onSelect(event.currentTarget.value || undefined)}>
|
|
136
214
|
<option value="">{t.stepCommentWhole}</option>
|
|
@@ -141,7 +219,7 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
|
|
|
141
219
|
</div>
|
|
142
220
|
{failure && <PmNotice tone="warn">{t.stepCommentFailed}</PmNotice>}
|
|
143
221
|
{candidates.length > 0 && <DraftChoices candidates={candidates} preview disabled={busy} canRecover={() => store.draftTargetState(target) === 'current'}
|
|
144
|
-
unavailableMessage={t.commentTargetUnavailable} onRecover={recover} onDiscard={discard} />}
|
|
222
|
+
unavailableMessage={t.commentTargetUnavailable} onRecover={async candidate => { await recover(candidate) }} onDiscard={discard} />}
|
|
145
223
|
<div className="pm-document-place-comment__actions">
|
|
146
224
|
<PmButton small disabled={busy} onClick={onClose}>{t.stepCommentCancel}</PmButton>
|
|
147
225
|
<PmButton small variant="primary" loading={busy} disabled={busy || empty} onClick={() => void submit()}>{t.stepCommentSave}</PmButton>
|
|
@@ -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
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { documentAnchorKey, documentCommentTargets, isDocumentPlaceAnchor, isRecord, randomUUID, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
|
|
2
2
|
import type { DocumentComment, DocumentThread, DocumentThreadAnchor, RichTextNode, TeachingDocument } from '@lincyaw/kernel'
|
|
3
|
-
import { DocumentDraftStore } from '../document-draft-store.ts'
|
|
3
|
+
import { DocumentDraftStore, waitForDraft } from '../document-draft-store.ts'
|
|
4
4
|
import { sha256 as tokenOf } from '../sha256.ts'
|
|
5
5
|
import type { DraftStoreResult } from '../document-draft-store.ts'
|
|
6
6
|
|
|
@@ -39,8 +39,10 @@ export interface CommentDraftComposer {
|
|
|
39
39
|
id: string
|
|
40
40
|
target: CommentComposerTarget
|
|
41
41
|
snapshot(): { record?: CommentDraftRecord, composing: boolean, available: boolean }
|
|
42
|
-
targetState(): 'current' | 'changed' | 'unavailable'
|
|
42
|
+
targetState(target?: CommentComposerTarget): 'current' | 'changed' | 'unavailable'
|
|
43
|
+
accepts?(target: CommentComposerTarget): boolean
|
|
43
44
|
restore?(candidate: CommentDraftCandidate, operation: CommentDraftOperation): Promise<CommentDraftRecord | undefined>
|
|
45
|
+
discard?(candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean>
|
|
44
46
|
}
|
|
45
47
|
interface Writing { record: CommentDraftRecord, raw: string, store: DocumentDraftStore, generation: number, pending: boolean, failed: boolean, done: Promise<DraftStoreResult>, clearing?: boolean }
|
|
46
48
|
const PREFIX = 'presmium.comment-draft.v1:'
|
|
@@ -117,14 +119,56 @@ export class CommentDrafts {
|
|
|
117
119
|
targetActive(target: CommentComposerTarget): boolean { return !this.ownersKnown || [...this.#composers.values()].some(value => sameCommentDraftTarget(value.target, target) && value.snapshot().available) }
|
|
118
120
|
activeRecord(record: CommentDraftRecord): boolean { return [...this.#composers.values()].some(value => value.snapshot().record?.id === record.id && value.snapshot().record?.revision === record.revision && value.snapshot().available) }
|
|
119
121
|
owns(record: CommentDraftRecord): boolean { return !this.#closed && this.#writing.get(record.id)?.record === record }
|
|
122
|
+
/** Durability acknowledgements can settle without changing author input or native ownership. */
|
|
123
|
+
inputGuard(): () => void {
|
|
124
|
+
const records = new Map([...this.#writing].map(([id, value]) => [id, value.record])), unknown = this.#unregisteredComposers
|
|
125
|
+
const owners = [...this.#composers].map(([id, value]) => ({ id, value, ...value.snapshot() }))
|
|
126
|
+
return () => {
|
|
127
|
+
if (this.#closed || unknown !== this.#unregisteredComposers || records.size !== this.#writing.size || [...records].some(([id, record]) => this.#writing.get(id)?.record !== record)
|
|
128
|
+
|| owners.length !== this.#composers.size || owners.some(owner => {
|
|
129
|
+
const state = owner.value.snapshot()
|
|
130
|
+
return this.#composers.get(owner.id) !== owner.value || state.record !== owner.record || state.composing !== owner.composing || state.available !== owner.available
|
|
131
|
+
})) throw new Error('client-comment-drafts-changed')
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
#activeComposers(candidate: CommentDraftRecord): CommentDraftComposer[] {
|
|
135
|
+
return [...this.#composers.values()].filter(composer => {
|
|
136
|
+
if (composer.accepts) return false // A recovery controller is not a second owner of the visible editor.
|
|
137
|
+
const record = composer.snapshot().record
|
|
138
|
+
return record?.id === candidate.id && record.revision === candidate.revision
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
canDiscard(candidate: CommentDraftCandidate): boolean {
|
|
142
|
+
if (!this.ownersKnown || candidate.composing || candidate.pending) return false
|
|
143
|
+
const owners = this.#activeComposers(candidate)
|
|
144
|
+
return !owners.length || owners.length === 1 && Boolean(owners[0]!.discard && owners[0]!.snapshot().available && !owners[0]!.snapshot().composing)
|
|
145
|
+
}
|
|
146
|
+
/** Both the UI and MCP retire the exact branch before changing the actual mounted editor. */
|
|
147
|
+
async discardProposal(candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean> {
|
|
148
|
+
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
149
|
+
if (!this.canDiscard(candidate)) throw new Error('client-comment-draft-needs-human')
|
|
150
|
+
const owners = this.#activeComposers(candidate)
|
|
151
|
+
const guard = () => {
|
|
152
|
+
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
153
|
+
const current = this.#activeComposers(candidate)
|
|
154
|
+
if (!this.canDiscard(candidate) || current.length !== owners.length || current.some((owner, index) => owner !== owners[index])) throw new Error('client-comment-composer-changed')
|
|
155
|
+
}
|
|
156
|
+
guard()
|
|
157
|
+
return owners[0] ? owners[0].discard!(candidate, { signal: operation?.signal, guard }) : this.discard(candidate, { signal: operation?.signal, guard })
|
|
158
|
+
}
|
|
120
159
|
async restoreChoice(candidate: CommentDraftCandidate, signal: AbortSignal): Promise<{ composerId: string, expectedCurrent: CommentDraftReference | null } | undefined> {
|
|
121
|
-
if (!this.ownersKnown ||
|
|
122
|
-
const
|
|
160
|
+
if (!this.ownersKnown || candidate.storage !== 'durable' || candidate.composing || candidate.pending) return
|
|
161
|
+
const available = [...this.#composers.values()].filter(value => value.restore && value.snapshot().available && !value.snapshot().composing && value.targetState(candidate.target) !== 'unavailable')
|
|
162
|
+
const direct = available.filter(value => !value.accepts && sameCommentDraftTarget(value.target, candidate.target))
|
|
163
|
+
const matching = direct.length ? direct : available.filter(value => value.accepts?.(candidate.target))
|
|
123
164
|
if (matching.length !== 1) return
|
|
124
165
|
const composer = matching[0]!, current = composer.snapshot().record
|
|
125
166
|
if (!current) return { composerId: composer.id, expectedCurrent: null }
|
|
126
167
|
const writing = this.#writing.get(current.id)
|
|
127
|
-
if (current.id === candidate.id || current.composing || current.pending || !writing || writing.record !== current
|
|
168
|
+
if (current.id === candidate.id || current.composing || current.pending || !writing || writing.record !== current) return
|
|
169
|
+
if (writing.pending && await waitForDraft(writing.done, signal) !== 'committed') return
|
|
170
|
+
signal.throwIfAborted()
|
|
171
|
+
if (writing.failed || this.#writing.get(current.id) !== writing || !writing.store.owns(keyOf(this.#scope, current.id), writing.raw)) return
|
|
128
172
|
const token = await tokenOf(writing.raw); signal.throwIfAborted()
|
|
129
173
|
if (this.#composers.get(composer.id) !== composer || composer.snapshot().record !== current || !composer.snapshot().available || composer.snapshot().composing) throw new Error('client-comment-drafts-changed')
|
|
130
174
|
return { composerId: composer.id, expectedCurrent: { id: current.id, revision: current.revision, token } }
|
|
@@ -296,19 +340,21 @@ export class CommentDrafts {
|
|
|
296
340
|
this.#settling++; this.#touch()
|
|
297
341
|
try {
|
|
298
342
|
if (this.#closed || !this.#reader) return false
|
|
299
|
-
const values = await this.#reader.read([
|
|
343
|
+
const values = await this.#reader.read([keyOf(this.#scope, reference.id)], operation?.signal), writing = this.#writing.get(reference.id)
|
|
300
344
|
const raw = writing && writing.record.revision === reference.revision && await tokenOf(writing.raw) === reference.token ? writing.raw : values.get(keyOf(this.#scope, reference.id))
|
|
301
345
|
if (this.#closed || typeof raw !== 'string' || await tokenOf(raw) !== reference.token) return false
|
|
302
346
|
const value: unknown = JSON.parse(raw)
|
|
303
347
|
if (!valid(value, this.#scope) || value.revision !== reference.revision || this.#closed) return false
|
|
304
348
|
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
305
|
-
const committed = await this.#reader!.mark([[markerOf(this.#scope, reference), reference.token]])
|
|
349
|
+
const committed = await this.#reader!.mark([[markerOf(this.#scope, reference), reference.token]], operation)
|
|
350
|
+
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
351
|
+
const writtenToken = writing ? await tokenOf(writing.raw) : undefined
|
|
306
352
|
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
307
353
|
if (!this.#closed) {
|
|
308
354
|
if (committed) this.#touch()
|
|
309
|
-
if (committed && writing && this.#writing.get(reference.id) === writing && writing.record.revision === reference.revision &&
|
|
355
|
+
if (committed && writing && this.#writing.get(reference.id) === writing && writing.record.revision === reference.revision && writtenToken === reference.token) { this.#writing.delete(reference.id); writing.store.close() }
|
|
310
356
|
if (!committed) this.#admissionFailure = true
|
|
311
|
-
this.#pending();
|
|
357
|
+
this.#pending(); void this.refresh()
|
|
312
358
|
}
|
|
313
359
|
return committed
|
|
314
360
|
} catch (error) { if (operation) throw error; this.#readFailure = true; this.#pending(); return false }
|
|
@@ -319,7 +365,7 @@ export class CommentDrafts {
|
|
|
319
365
|
if (this.#closed || !this.#reader) return
|
|
320
366
|
this.#settling++; this.#touch()
|
|
321
367
|
try {
|
|
322
|
-
const values = await this.#reader.read([
|
|
368
|
+
const values = await this.#reader.read([keyOf(this.#scope, reference.id), markerOf(this.#scope, reference)], operation?.signal), writing = this.#writing.get(reference.id)
|
|
323
369
|
const raw = writing && writing.record.revision === reference.revision && await tokenOf(writing.raw) === reference.token ? writing.raw : values.get(keyOf(this.#scope, reference.id))
|
|
324
370
|
if (this.#closed || typeof raw !== 'string' || await tokenOf(raw) !== reference.token || values.get(markerOf(this.#scope, reference)) === reference.token) return
|
|
325
371
|
const value: unknown = JSON.parse(raw)
|
|
@@ -327,7 +373,7 @@ export class CommentDrafts {
|
|
|
327
373
|
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
328
374
|
const record: CommentDraftRecord = { ...value, target: isNewCommentDraft(target) ? structuredClone(target) : value.target, id: randomUUID(), owner: this.#owner, revision: 1, updatedAt: Date.now(), version, composing: false, pending: undefined }
|
|
329
375
|
const store = new DocumentDraftStore(this.#scope, undefined, { family: 'comment', owner: this.#owner }), next = JSON.stringify(record)
|
|
330
|
-
if (next.length > MAX_CHARS || !await store.create(keyOf(this.#scope, record.id), next) || this.#closed) { store.close(); if (!this.#closed) { this.#admissionFailure = true; this.#pending() }; return }
|
|
376
|
+
if (next.length > MAX_CHARS || !await store.create(keyOf(this.#scope, record.id), next, operation) || this.#closed) { store.close(); if (!this.#closed) { this.#admissionFailure = true; this.#pending() }; return }
|
|
331
377
|
try { operation?.signal?.throwIfAborted(); operation?.guard?.() } catch (error) { store.close(); throw error }
|
|
332
378
|
this.#writing.set(record.id, { record, raw: next, store, generation: 0, pending: false, failed: false, done: Promise.resolve('committed') })
|
|
333
379
|
this.#touch(); void this.refresh()
|
|
@@ -16,6 +16,7 @@ import type { StepDurationDraft, StepDurationKey, StepTimingPatch } from './step
|
|
|
16
16
|
import { DocumentTimingDrafts } from './document-timing-drafts.ts'
|
|
17
17
|
import { CaptionTimingDrafts } from './caption-timing-drafts.ts'
|
|
18
18
|
import type { CaptionTimingDraft } from './caption-timing-drafts.ts'
|
|
19
|
+
import type { ClientProductionDraftMetadata } from '@lincyaw/kernel'
|
|
19
20
|
|
|
20
21
|
interface ProductionOptions {
|
|
21
22
|
store: WorkbenchStore
|
|
@@ -30,6 +31,19 @@ interface ProductionOptions {
|
|
|
30
31
|
sourceCurrent(binding: ProductionBinding): boolean
|
|
31
32
|
}
|
|
32
33
|
export interface RecordingRangeDraft { version: string, voice: Extract<VoiceSource, { type: 'recording' }>, range?: TimeRange, startText?: string, endText?: string }
|
|
34
|
+
export interface ProductionDraftView {
|
|
35
|
+
identity: string
|
|
36
|
+
kind: ClientProductionDraftMetadata['kind']
|
|
37
|
+
has(key: string): boolean
|
|
38
|
+
blocked(): boolean
|
|
39
|
+
clear(key: string): void
|
|
40
|
+
}
|
|
41
|
+
export interface ProductionDraftSnapshot {
|
|
42
|
+
stamp: string
|
|
43
|
+
coverage: 'tab-state' | 'partial'
|
|
44
|
+
candidates: { key: string, metadata: Omit<ClientProductionDraftMetadata, 'draft'>, value: unknown, discard(): void }[]
|
|
45
|
+
guard(): void
|
|
46
|
+
}
|
|
33
47
|
|
|
34
48
|
/** Source-bound media transactions, timing drafts and narration edits share the document actor. */
|
|
35
49
|
export class DocumentProduction {
|
|
@@ -38,6 +52,11 @@ export class DocumentProduction {
|
|
|
38
52
|
readonly #documentTimingDrafts = new DocumentTimingDrafts()
|
|
39
53
|
readonly #captionTimingDrafts = new CaptionTimingDrafts()
|
|
40
54
|
readonly #recordingRangeDrafts = new Map<string, Map<string, RecordingRangeDraft>>()
|
|
55
|
+
readonly #draftViews = new Set<ProductionDraftView>()
|
|
56
|
+
readonly #draftSalt = randomUUID()
|
|
57
|
+
#draftRevision = 0
|
|
58
|
+
#unknownDraftViews = 0
|
|
59
|
+
#closed = false
|
|
41
60
|
readonly #removedCueTimings = new Map<string, { pauseMs: number }>()
|
|
42
61
|
readonly #removedNarrations = new Map<string, { narration: Narration, override?: { narrationStart: 'with-animation' | 'after-animation' } }>()
|
|
43
62
|
#cueTimingScope?: string
|
|
@@ -54,13 +73,92 @@ export class DocumentProduction {
|
|
|
54
73
|
}
|
|
55
74
|
}
|
|
56
75
|
reset(): void { this.#removedCueTimings.clear(); this.#removedNarrations.clear(); this.#cueTimingScope = undefined }
|
|
57
|
-
dispose(): void { this.reset(); this.#captionTimingDrafts.close(); this.#recordingRangeDrafts.clear() }
|
|
76
|
+
dispose(): void { this.#closed = true; this.reset(); this.#captionTimingDrafts.close(); this.#recordingRangeDrafts.clear(); this.#draftViews.clear() }
|
|
77
|
+
get draftRevision(): number { return this.#draftRevision }
|
|
78
|
+
get productionDraftsBlocked(): boolean {
|
|
79
|
+
const identity = this.#options.store.state.authoring?.identity
|
|
80
|
+
return this.#closed || Boolean(this.#unknownDraftViews) || this.#options.session.hasPendingAssetWrite()
|
|
81
|
+
|| [...this.#draftViews].some(view => view.identity === identity && view.blocked())
|
|
82
|
+
}
|
|
83
|
+
#draftChanged(): void {
|
|
84
|
+
if (this.#closed) return
|
|
85
|
+
this.#draftRevision++
|
|
86
|
+
const source = this.#options.store.state.authoring
|
|
87
|
+
if (source) this.#options.store.set({ authoring: { ...source }, ...this.draftState(source) })
|
|
88
|
+
}
|
|
89
|
+
registerDraftView(view: ProductionDraftView): () => void {
|
|
90
|
+
if (this.#closed) return () => {}
|
|
91
|
+
let closed = false
|
|
92
|
+
if (this.#draftViews.size >= 128) {
|
|
93
|
+
this.#unknownDraftViews++; this.#draftChanged()
|
|
94
|
+
return () => { if (closed) return; closed = true; this.#unknownDraftViews--; this.#draftChanged() }
|
|
95
|
+
}
|
|
96
|
+
this.#draftViews.add(view); this.#draftChanged()
|
|
97
|
+
return () => { if (closed) return; closed = true; this.#draftViews.delete(view); this.#draftChanged() }
|
|
98
|
+
}
|
|
58
99
|
/** Native pending range input survives mode and document changes within this workbench. */
|
|
59
|
-
recordingRangeDrafts(identity: string):
|
|
100
|
+
recordingRangeDrafts(identity: string): ReadonlyMap<string, RecordingRangeDraft> {
|
|
60
101
|
let values = this.#recordingRangeDrafts.get(identity)
|
|
61
102
|
if (!values) { values = new Map(); this.#recordingRangeDrafts.set(identity, values) }
|
|
62
103
|
return values
|
|
63
104
|
}
|
|
105
|
+
setRecordingRangeDraft(identity: string, key: string, value: RecordingRangeDraft | undefined): void {
|
|
106
|
+
this.recordingRangeDrafts(identity)
|
|
107
|
+
const values = this.#recordingRangeDrafts.get(identity)!
|
|
108
|
+
if (value) values.set(key, value); else values.delete(key)
|
|
109
|
+
this.#draftChanged()
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Native banks remain the sole content owners. A snapshot exposes metadata until an explicit read. */
|
|
113
|
+
productionDraftSnapshot(): ProductionDraftSnapshot {
|
|
114
|
+
const state = this.#options.store.state, source = state.authoring, identity = source?.identity, memberId = source?.member?.id, content = source?.content
|
|
115
|
+
if (this.#closed || !source || !identity || !memberId || !content || !source.version || !source.fingerprint || source.loading) throw new Error('client-production-drafts-unavailable')
|
|
116
|
+
const revision = this.#draftRevision, version = source.version, reset = source.reset
|
|
117
|
+
const views = [...this.#draftViews].filter(view => view.identity === identity)
|
|
118
|
+
const viewState = () => JSON.stringify(views.map(view => view.blocked()))
|
|
119
|
+
const blocked = viewState()
|
|
120
|
+
const clean = () => {
|
|
121
|
+
const value = this.#options.store.state, current = value.authoring
|
|
122
|
+
return Boolean(this.#options.client.capabilities?.readOnly !== true && current && !current.loading && !current.dirty && !current.saving && !current.composing && !current.restored && !current.recovering && !current.error
|
|
123
|
+
&& !isAgentChanging(value) && !value.isCreatingPage && !value.isEditingPage && !value.isHistoryBusy && !value.isHistoryPreparing && !this.productionDraftsBlocked)
|
|
124
|
+
}
|
|
125
|
+
const guard = () => {
|
|
126
|
+
const current = this.#options.store.state.authoring
|
|
127
|
+
if (!current || current.identity !== identity || current.member?.id !== memberId || current.content !== content || current.version !== version || current.reset !== reset
|
|
128
|
+
|| current.loading || revision !== this.#draftRevision || viewState() !== blocked) throw new Error('client-production-drafts-changed')
|
|
129
|
+
}
|
|
130
|
+
const candidates: ProductionDraftSnapshot['candidates'] = []
|
|
131
|
+
const add = (kind: ClientProductionDraftMetadata['kind'], key: string, stepId: string, value: unknown, requiresReview: boolean, storage: 'tab' | 'memory', remove: () => boolean, extra: { field?: StepDurationKey, assetId?: string } = {}, readable = true) => {
|
|
132
|
+
const matches = views.filter(view => view.kind === kind && view.has(key))
|
|
133
|
+
const discardable = readable && clean() && !this.#unknownDraftViews && !matches.some(view => view.blocked())
|
|
134
|
+
candidates.push({ key: JSON.stringify([kind, key]), metadata: { kind, stepId, ...extra, targetAvailable: Object.hasOwn(content.steps, stepId), requiresReview, storage, discardable }, value,
|
|
135
|
+
discard: () => {
|
|
136
|
+
guard()
|
|
137
|
+
const activeViews = views.filter(view => view.kind === kind && view.has(key))
|
|
138
|
+
if (!discardable || !clean() || activeViews.some(view => view.blocked())) throw new Error('client-production-draft-needs-human')
|
|
139
|
+
if (!remove()) { this.#draftChanged(); throw new Error('client-production-draft-storage-unavailable') }
|
|
140
|
+
for (const view of activeViews) view.clear(key)
|
|
141
|
+
this.#draftChanged()
|
|
142
|
+
} })
|
|
143
|
+
}
|
|
144
|
+
const timingPartial = this.#documentTimingDrafts.partial(identity), scope = { identity, memberId }
|
|
145
|
+
for (const [key, value] of this.#documentTimingDrafts.entries(identity)) {
|
|
146
|
+
const [stepId, field] = JSON.parse(key) as [string, StepDurationKey]
|
|
147
|
+
add('step-timing', key, stepId, value, !Object.hasOwn(content.steps, stepId) || (this.#documentTimingDrafts.get(identity, content, stepId, field)?.review ?? true), this.#documentTimingDrafts.failed || timingPartial ? 'memory' : 'tab', () => this.#documentTimingDrafts.discard(identity, key), { field }, !timingPartial)
|
|
148
|
+
}
|
|
149
|
+
const captionPartial = this.#captionTimingDrafts.partial(scope)
|
|
150
|
+
for (const [stepId, value] of this.#captionTimingDrafts.entries(scope)) {
|
|
151
|
+
const basis = state.productionPlan?.pages.flatMap(page => page.steps).find(step => step.stepId === stepId)?.captionTiming
|
|
152
|
+
add('caption-timing', stepId, stepId, value, value.version !== version || !basis || JSON.stringify(basis) !== JSON.stringify(value.basis), this.#captionTimingDrafts.failed(scope) || captionPartial ? 'memory' : 'tab', () => this.#captionTimingDrafts.discard(scope, stepId), {}, !captionPartial)
|
|
153
|
+
}
|
|
154
|
+
for (const [key, value] of this.#recordingRangeDrafts.get(identity) ?? []) {
|
|
155
|
+
const [stepId] = JSON.parse(key) as [string]
|
|
156
|
+
add('recording-range', key, stepId, value, value.version !== version, 'memory', () => this.#recordingRangeDrafts.get(identity)!.delete(key), { assetId: value.voice.assetId })
|
|
157
|
+
}
|
|
158
|
+
candidates.sort((a, b) => a.key.localeCompare(b.key))
|
|
159
|
+
guard()
|
|
160
|
+
return { stamp: JSON.stringify([this.#draftSalt, identity, memberId, version, reset, revision]), coverage: timingPartial || captionPartial ? 'partial' : 'tab-state', candidates, guard }
|
|
161
|
+
}
|
|
64
162
|
|
|
65
163
|
source(expected: { identity: string, version: string }): DocumentSessionState {
|
|
66
164
|
const source = this.#options.store.state.authoring
|
|
@@ -280,6 +378,7 @@ export class DocumentProduction {
|
|
|
280
378
|
const source = this.#options.store.state.authoring, document = this.#options.document(identity)
|
|
281
379
|
if (!document?.steps[stepId] || source?.reset !== reset || isAgentChanging(this.#options.store.state)) return
|
|
282
380
|
if (!this.#documentTimingDrafts.set(identity, document, stepId, key, draft)) return
|
|
381
|
+
this.#draftRevision++
|
|
283
382
|
this.#options.store.set({ authoring: { ...source }, hasDocumentTimingDrafts: this.#documentTimingDrafts.has(identity, document), documentTimingDraftStorageFailure: this.#documentTimingDrafts.failed })
|
|
284
383
|
}
|
|
285
384
|
captionTimingDraft(stepId: string, identity: string): CaptionTimingDraft | undefined {
|
|
@@ -291,8 +390,16 @@ export class DocumentProduction {
|
|
|
291
390
|
if (!document?.steps[stepId] || source?.identity !== identity || !source.member?.id) return
|
|
292
391
|
const scope = { identity, memberId: source.member.id }
|
|
293
392
|
this.#captionTimingDrafts.set(scope, stepId, draft)
|
|
393
|
+
this.#draftRevision++
|
|
294
394
|
this.#options.store.set({ captionTimingDraftSteps: this.#captionTimingDrafts.steps(scope, document), captionTimingDraftStorageFailure: this.#captionTimingDrafts.failed(scope) })
|
|
295
395
|
}
|
|
396
|
+
discardCaptionTimingDraft(stepId: string, identity: string): boolean {
|
|
397
|
+
const source = this.#options.store.state.authoring
|
|
398
|
+
if (source?.identity !== identity || !source.member?.id) return false
|
|
399
|
+
const discarded = this.#captionTimingDrafts.discard({ identity, memberId: source.member.id }, stepId)
|
|
400
|
+
this.#draftChanged()
|
|
401
|
+
return discarded
|
|
402
|
+
}
|
|
296
403
|
copyNarrationCueTiming(from: string, to: string, identity: string): void {
|
|
297
404
|
const document = this.#options.document(identity)
|
|
298
405
|
if (!document || isAgentChanging(this.#options.store.state)) return
|