@lincyaw/workbench 0.2.0-rc.53 → 0.2.0-rc.55
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/MediaClipEditor.tsx +3 -2
- package/src/approvals.tsx +6 -1
- package/src/components.tsx +12 -3
- package/src/context.tsx +3 -2
- package/src/document-editor/DocumentComments.tsx +27 -5
- 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 +28 -2
- package/src/media-drafts.ts +43 -1
- package/src/panels/DocumentVoiceDialog.tsx +23 -7
- package/src/panels/ProductionMediaClips.tsx +17 -2
- package/src/voice-drafts.ts +32 -8
- package/src/workbench.ts +2 -2
|
@@ -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()
|
|
@@ -17,6 +17,10 @@ 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
19
|
import type { ClientProductionDraftMetadata } from '@lincyaw/kernel'
|
|
20
|
+
import { clearVoiceDraft, keepVoiceDraft, voiceDraftSnapshot } from './voice-drafts.ts'
|
|
21
|
+
import type { VoiceDraft } from './voice-drafts.ts'
|
|
22
|
+
import { discardMediaDraft, keepMediaDrafts, mediaDraftSnapshot } from './media-drafts.ts'
|
|
23
|
+
import type { MediaDrafts } from './media-drafts.ts'
|
|
20
24
|
|
|
21
25
|
interface ProductionOptions {
|
|
22
26
|
store: WorkbenchStore
|
|
@@ -96,6 +100,18 @@ export class DocumentProduction {
|
|
|
96
100
|
this.#draftViews.add(view); this.#draftChanged()
|
|
97
101
|
return () => { if (closed) return; closed = true; this.#draftViews.delete(view); this.#draftChanged() }
|
|
98
102
|
}
|
|
103
|
+
keepVoiceDraft(identity: string, stepId: string, value: VoiceDraft): boolean {
|
|
104
|
+
const kept = keepVoiceDraft(this.#options.client, identity, stepId, value)
|
|
105
|
+
this.#draftChanged(); return kept
|
|
106
|
+
}
|
|
107
|
+
clearVoiceDraft(identity: string, stepId: string, expected: VoiceDraft): boolean {
|
|
108
|
+
const cleared = clearVoiceDraft(this.#options.client, identity, stepId, expected)
|
|
109
|
+
this.#draftChanged(); return cleared
|
|
110
|
+
}
|
|
111
|
+
keepMediaDrafts(identity: string, stepId: string, value: MediaDrafts): boolean {
|
|
112
|
+
const kept = keepMediaDrafts(this.#options.client, identity, stepId, value)
|
|
113
|
+
this.#draftChanged(); return kept
|
|
114
|
+
}
|
|
99
115
|
/** Native pending range input survives mode and document changes within this workbench. */
|
|
100
116
|
recordingRangeDrafts(identity: string): ReadonlyMap<string, RecordingRangeDraft> {
|
|
101
117
|
let values = this.#recordingRangeDrafts.get(identity)
|
|
@@ -128,7 +144,7 @@ export class DocumentProduction {
|
|
|
128
144
|
|| current.loading || revision !== this.#draftRevision || viewState() !== blocked) throw new Error('client-production-drafts-changed')
|
|
129
145
|
}
|
|
130
146
|
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) => {
|
|
147
|
+
const add = (kind: ClientProductionDraftMetadata['kind'], key: string, stepId: string, value: unknown, requiresReview: boolean, storage: 'tab' | 'memory', remove: () => boolean, extra: { field?: StepDurationKey, assetId?: string, clipId?: string } = {}, readable = true) => {
|
|
132
148
|
const matches = views.filter(view => view.kind === kind && view.has(key))
|
|
133
149
|
const discardable = readable && clean() && !this.#unknownDraftViews && !matches.some(view => view.blocked())
|
|
134
150
|
candidates.push({ key: JSON.stringify([kind, key]), metadata: { kind, stepId, ...extra, targetAvailable: Object.hasOwn(content.steps, stepId), requiresReview, storage, discardable }, value,
|
|
@@ -155,9 +171,19 @@ export class DocumentProduction {
|
|
|
155
171
|
const [stepId] = JSON.parse(key) as [string]
|
|
156
172
|
add('recording-range', key, stepId, value, value.version !== version, 'memory', () => this.#recordingRangeDrafts.get(identity)!.delete(key), { assetId: value.voice.assetId })
|
|
157
173
|
}
|
|
174
|
+
const voices = voiceDraftSnapshot(this.#options.client, identity)
|
|
175
|
+
for (const { stepId, value, persisted } of voices.entries) {
|
|
176
|
+
add('voice', stepId, stepId, value, value.version !== version, persisted ? 'tab' : 'memory', () => clearVoiceDraft(this.#options.client, identity, stepId, value), {}, !voices.partial)
|
|
177
|
+
}
|
|
178
|
+
const media = mediaDraftSnapshot(this.#options.client, identity)
|
|
179
|
+
for (const { stepId, value, persisted } of media.entries) for (const [name, draft] of Object.entries(value.entries)) {
|
|
180
|
+
const original = content.production.mediaClips.find(clip => clip.id === draft.clip.id)
|
|
181
|
+
add('media-clip', JSON.stringify([stepId, name]), stepId, draft, draft.version !== version || Boolean(draft.baseClip && JSON.stringify(draft.baseClip) !== JSON.stringify(original)), persisted ? 'tab' : 'memory',
|
|
182
|
+
() => discardMediaDraft(this.#options.client, identity, stepId, name, value), { clipId: draft.clip.id, ...draft.clip.assetId ? { assetId: draft.clip.assetId } : {} }, !media.partial)
|
|
183
|
+
}
|
|
158
184
|
candidates.sort((a, b) => a.key.localeCompare(b.key))
|
|
159
185
|
guard()
|
|
160
|
-
return { stamp: JSON.stringify([this.#draftSalt, identity, memberId, version, reset, revision]), coverage: timingPartial || captionPartial ? 'partial' : 'tab-state', candidates, guard }
|
|
186
|
+
return { stamp: JSON.stringify([this.#draftSalt, identity, memberId, version, reset, revision]), coverage: timingPartial || captionPartial || voices.partial || media.partial ? 'partial' : 'tab-state', candidates, guard }
|
|
161
187
|
}
|
|
162
188
|
|
|
163
189
|
source(expected: { identity: string, version: string }): DocumentSessionState {
|
package/src/media-drafts.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { MediaClipDraft } from './MediaClipEditor.tsx'
|
|
|
4
4
|
import type { WorkspaceClient } from './workspace-client.ts'
|
|
5
5
|
|
|
6
6
|
export interface MediaDrafts { selectedClipId?: string, entries: Record<string, MediaClipDraft> }
|
|
7
|
-
interface Entry { value: MediaDrafts, failed: boolean, volatile: boolean, unreadable?: string }
|
|
7
|
+
interface Entry { value: MediaDrafts, failed: boolean, volatile: boolean, unreadable?: string, raw?: string | null }
|
|
8
8
|
const memory = new WeakMap<WorkspaceClient, Map<string, Entry>>()
|
|
9
9
|
const prefix = 'presmium.media-drafts.v1:', limit = 64
|
|
10
10
|
const keyOf = (identity: string, stepId: string) => prefix + JSON.stringify([identity, stepId])
|
|
@@ -38,6 +38,7 @@ function load(client: WorkspaceClient, key: string): Entry {
|
|
|
38
38
|
const entry: Entry = { value: { entries: {} }, failed: false, volatile: false }
|
|
39
39
|
try {
|
|
40
40
|
const raw = sessionStorage.getItem(key)
|
|
41
|
+
entry.raw = raw
|
|
41
42
|
if (raw !== null) {
|
|
42
43
|
entry.unreadable = raw
|
|
43
44
|
if (raw.length > 131072) throw new Error('media-drafts-size')
|
|
@@ -68,6 +69,7 @@ export function keepMediaDrafts(client: WorkspaceClient, identity: string, stepI
|
|
|
68
69
|
if (raw.length > 131072) throw new Error('media-drafts-size')
|
|
69
70
|
if (entry.unreadable !== undefined) sessionStorage.setItem(`${key}:unreadable`, entry.unreadable)
|
|
70
71
|
sessionStorage.setItem(key, raw)
|
|
72
|
+
entry.raw = raw
|
|
71
73
|
const keys = Array.from({ length: sessionStorage.length }, (_, index) => sessionStorage.key(index)!).filter(name => name.startsWith(prefix) && !name.endsWith(':unreadable') && name !== key)
|
|
72
74
|
let excess = keys.length - limit + 1
|
|
73
75
|
for (const old of keys) {
|
|
@@ -81,3 +83,43 @@ export function keepMediaDrafts(client: WorkspaceClient, identity: string, stepI
|
|
|
81
83
|
return true
|
|
82
84
|
} catch { entry.failed = true; trim(known); return false }
|
|
83
85
|
}
|
|
86
|
+
|
|
87
|
+
/** This is the same step/form bank used when the author reopens Media, including session-only input. */
|
|
88
|
+
export function mediaDraftSnapshot(client: WorkspaceClient, identity: string): { entries: { stepId: string, value: MediaDrafts, persisted: boolean }[], partial: boolean } {
|
|
89
|
+
const scoped = `${prefix}${JSON.stringify([identity]).slice(0, -1)},`
|
|
90
|
+
const keys = new Set([...store(client).keys()].filter(key => key.startsWith(scoped)))
|
|
91
|
+
let partial = false
|
|
92
|
+
try {
|
|
93
|
+
for (let index = 0; index < sessionStorage.length; index++) {
|
|
94
|
+
const key = sessionStorage.key(index)
|
|
95
|
+
if (key?.startsWith(scoped) && !key.endsWith(':unreadable')) keys.add(key)
|
|
96
|
+
}
|
|
97
|
+
} catch { partial = true }
|
|
98
|
+
const entries: { stepId: string, value: MediaDrafts, persisted: boolean }[] = []
|
|
99
|
+
for (const key of keys) {
|
|
100
|
+
let target: unknown
|
|
101
|
+
try { target = JSON.parse(key.slice(prefix.length)) } catch { partial = true; continue }
|
|
102
|
+
if (!Array.isArray(target) || target.length !== 2 || target[0] !== identity || typeof target[1] !== 'string') { partial = true; continue }
|
|
103
|
+
const entry = load(client, key)
|
|
104
|
+
let persisted = false
|
|
105
|
+
try { const raw = sessionStorage.getItem(key); persisted = !entry.failed && raw === entry.raw; if (raw !== entry.raw) partial = true } catch { partial = true }
|
|
106
|
+
if (entry.unreadable !== undefined || entry.raw === undefined) partial = true
|
|
107
|
+
if (Object.keys(entry.value.entries).length) entries.push({ stepId: target[1], value: structuredClone(entry.value), persisted })
|
|
108
|
+
}
|
|
109
|
+
return { entries, partial }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Retire one exact clip proposal, preserving sibling forms and any independently changed storage. */
|
|
113
|
+
export function discardMediaDraft(client: WorkspaceClient, identity: string, stepId: string, name: string, expected: MediaDrafts): boolean {
|
|
114
|
+
const key = keyOf(identity, stepId), entry = load(client, key)
|
|
115
|
+
if (!Object.hasOwn(expected.entries, name) || JSON.stringify(entry.value) !== JSON.stringify(expected)) return false
|
|
116
|
+
try {
|
|
117
|
+
if (entry.raw === undefined || entry.unreadable !== undefined || sessionStorage.getItem(key) !== entry.raw) return false
|
|
118
|
+
const next = structuredClone(entry.value)
|
|
119
|
+
delete next.entries[name]
|
|
120
|
+
const raw = JSON.stringify(next)
|
|
121
|
+
sessionStorage.setItem(key, raw)
|
|
122
|
+
entry.value = next; entry.raw = raw; entry.failed = false; entry.volatile = false
|
|
123
|
+
return true
|
|
124
|
+
} catch { entry.failed = true; return false }
|
|
125
|
+
}
|