@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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lincyaw/workbench",
|
|
3
|
-
"version": "0.2.0-rc.
|
|
3
|
+
"version": "0.2.0-rc.54",
|
|
4
4
|
"description": "Presmium's workbench panels in React (the documents, a document edited on its rendered page with comments and version history) with the workspace service's client and the preview protocol's workbench side; @lincyaw/dsh places them in presmium studio (experimental)",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -55,8 +55,8 @@
|
|
|
55
55
|
"@tiptap/pm": "3.32.0",
|
|
56
56
|
"katex": "0.18.10",
|
|
57
57
|
"react-resizable-panels": "4.14.5",
|
|
58
|
-
"@lincyaw/
|
|
59
|
-
"@lincyaw/
|
|
58
|
+
"@lincyaw/design": "1.0.0-rc.54",
|
|
59
|
+
"@lincyaw/kernel": "1.0.0-rc.54"
|
|
60
60
|
},
|
|
61
61
|
"peerDependencies": {
|
|
62
62
|
"react": "^18.3.1",
|
|
@@ -67,6 +67,6 @@
|
|
|
67
67
|
"@types/react-dom": "18.3.7",
|
|
68
68
|
"react": "^18.3.1",
|
|
69
69
|
"react-dom": "^18.3.1",
|
|
70
|
-
"@lincyaw/compiler": "1.0.0-rc.
|
|
70
|
+
"@lincyaw/compiler": "1.0.0-rc.54"
|
|
71
71
|
}
|
|
72
72
|
}
|
|
@@ -40,16 +40,21 @@ interface DurationFieldProps {
|
|
|
40
40
|
onDraft?(draft: StepDurationDraft | undefined): void
|
|
41
41
|
onChange(value: number | null): void
|
|
42
42
|
onComposition?(composing: boolean): void
|
|
43
|
+
controlKey?: string
|
|
44
|
+
registerControl?(control: StepDraftControl): () => void
|
|
43
45
|
}
|
|
46
|
+
export interface StepDraftControl { composing(): boolean, clear(): void }
|
|
44
47
|
|
|
45
48
|
/** Short author intent, never an estimated timestamp or a second playback clock. */
|
|
46
|
-
function DurationField({ label, value, source, locale, readOnly, draft, onDraft, onChange, onComposition }: DurationFieldProps) {
|
|
47
|
-
const t = MESSAGES[locale], current = useRef({ onComposition, onChange, onDraft, value })
|
|
48
|
-
current.current = { onComposition, onChange, onDraft, value }
|
|
49
|
+
function DurationField({ label, value, source, locale, readOnly, draft, onDraft, onChange, onComposition, controlKey, registerControl }: DurationFieldProps) {
|
|
50
|
+
const t = MESSAGES[locale], current = useRef({ onComposition, onChange, onDraft, value, registerControl })
|
|
51
|
+
current.current = { onComposition, onChange, onDraft, value, registerControl }
|
|
49
52
|
const [text, setText] = useState(draft?.text ?? (value === undefined ? '' : String(value))), [error, setError] = useState(draft?.error ?? false)
|
|
50
53
|
const focused = useRef(false), composing = useRef(false)
|
|
51
54
|
useEffect(() => { if (!focused.current) { setText(draft?.text ?? (value === undefined ? '' : String(value))); setError(draft?.error ?? false) } }, [value, source, draft?.text, draft?.error, draft?.review])
|
|
52
55
|
useEffect(() => () => { if (composing.current) current.current.onComposition?.(false) }, [])
|
|
56
|
+
useEffect(() => current.current.registerControl?.({ composing: () => composing.current,
|
|
57
|
+
clear: () => { setText(current.current.value === undefined ? '' : String(current.current.value)); setError(false) } }), [controlKey])
|
|
53
58
|
const commit = (input: string): boolean => {
|
|
54
59
|
const normalized = input.normalize('NFKC').trim()
|
|
55
60
|
if (!normalized) { setError(false); current.current.onDraft?.(undefined); current.current.onChange(null); return true }
|
|
@@ -92,10 +97,12 @@ export interface StepProductionEditorProps {
|
|
|
92
97
|
draftStorageFailure?: boolean
|
|
93
98
|
onDraft?(key: StepDurationKey, draft: StepDurationDraft | undefined): void
|
|
94
99
|
onComposition?(key: StepDurationKey, composing: boolean): void
|
|
100
|
+
draftControlKey?: string
|
|
101
|
+
registerDraftControl?(key: StepDurationKey, control: StepDraftControl): () => void
|
|
95
102
|
}
|
|
96
103
|
|
|
97
104
|
/** A reusable view of the canonical step production, including inherited and migrated settings. */
|
|
98
|
-
export function StepProductionEditor({ document, stepId, locale, readOnly, advanced = true, onPause, onInteraction, onChange, drafts, onDraft, draftStorageFailure, onComposition }: StepProductionEditorProps) {
|
|
105
|
+
export function StepProductionEditor({ document, stepId, locale, readOnly, advanced = true, onPause, onInteraction, onChange, drafts, onDraft, draftStorageFailure, onComposition, draftControlKey, registerDraftControl }: StepProductionEditorProps) {
|
|
99
106
|
const t = MESSAGES[locale], [unifying, setUnifying] = useState(false)
|
|
100
107
|
const start = stepTimingValue(document, stepId, 'narrationStart'), minimum = stepTimingValue(document, stepId, 'minimumHoldMs'), trailing = stepTimingValue(document, stepId, 'trailingPauseMs')
|
|
101
108
|
const narrations = stepNarrationStarts(document, stepId), hasOverrides = narrations.some(value => value.overridden)
|
|
@@ -120,8 +127,10 @@ export function StepProductionEditor({ document, stepId, locale, readOnly, advan
|
|
|
120
127
|
</PmField>
|
|
121
128
|
<div className="pm-ui-step-production__durations">
|
|
122
129
|
<DurationField label={t.minimum} value={minimum.value} source={minimum.source} locale={locale} readOnly={readOnly} draft={drafts?.minimumHoldMs} onDraft={draft => onDraft?.('minimumHoldMs', draft)}
|
|
130
|
+
controlKey={draftControlKey} registerControl={registerDraftControl && (control => registerDraftControl('minimumHoldMs', control))}
|
|
123
131
|
onChange={value => apply({ minimumHoldMs: value })} onComposition={composing => onComposition?.('minimumHoldMs', composing)} />
|
|
124
132
|
<DurationField label={t.trailing} value={trailing.value} source={trailing.source} locale={locale} readOnly={readOnly} draft={drafts?.trailingPauseMs} onDraft={draft => onDraft?.('trailingPauseMs', draft)}
|
|
133
|
+
controlKey={draftControlKey} registerControl={registerDraftControl && (control => registerDraftControl('trailingPauseMs', control))}
|
|
125
134
|
onChange={value => apply({ trailingPauseMs: value })} onComposition={composing => onComposition?.('trailingPauseMs', composing)} />
|
|
126
135
|
</div></>}
|
|
127
136
|
{!advanced && (drafts?.minimumHoldMs || drafts?.trailingPauseMs || draftStorageFailure) ? <span className="pm-ui-field__error" role="alert">{t.advancedDraft}</span>
|
package/src/approvals.tsx
CHANGED
|
@@ -6,6 +6,11 @@ import { WorkspaceServerError } from './workspace-client.ts'
|
|
|
6
6
|
|
|
7
7
|
interface Pending { id: string, request: ApprovalRequest }
|
|
8
8
|
|
|
9
|
+
/** Approval controls belong to the operation's editing context, including their portaled panel. */
|
|
10
|
+
export function isApprovalTarget(target: EventTarget | null | undefined): boolean {
|
|
11
|
+
return target instanceof Element && Boolean(target.closest('[data-approval-trigger], .pmw-approvals'))
|
|
12
|
+
}
|
|
13
|
+
|
|
9
14
|
/**
|
|
10
15
|
* The host's operations waiting for the author, such as an external MCP client's import: shown only while one is
|
|
11
16
|
* pending, answered here as in the viewer's "Approvals". The host times them out; a late answer is reported, not retried.
|
|
@@ -38,7 +43,7 @@ export function WorkbenchApprovals({ density = 'compact' }: { density?: 'compact
|
|
|
38
43
|
}
|
|
39
44
|
return (
|
|
40
45
|
<PmPopover open={open} onOpenChange={setOpen} label={t.approvalsTitle} name="pmw-approvals" trigger={
|
|
41
|
-
<PmButton variant="accent" density={density}>{t.approvals(pending.length)}</PmButton>
|
|
46
|
+
<PmButton data-approval-trigger="" variant="accent" density={density}>{t.approvals(pending.length)}</PmButton>
|
|
42
47
|
}>
|
|
43
48
|
<h2 className="pmw-approvals__heading">{t.approvalsTitle}</h2>
|
|
44
49
|
<ul className="pmw-approvals__list">
|
|
@@ -3,7 +3,7 @@ import type { CaptionTimingSource, TeachingDocument } from '@lincyaw/kernel'
|
|
|
3
3
|
export interface CaptionTimingRow { id: string, from: number, to: number, start: string, end: string }
|
|
4
4
|
export interface CaptionTimingDraft { version: string, text: string, basis: CaptionTimingSource, rows: CaptionTimingRow[] }
|
|
5
5
|
type Scope = { identity: string, memberId: string }
|
|
6
|
-
interface Entry { values: Map<string, CaptionTimingDraft>, failed: boolean, unreadable: boolean }
|
|
6
|
+
interface Entry { raw?: string | null, values: Map<string, CaptionTimingDraft>, failed: boolean, unreadable: boolean }
|
|
7
7
|
const MAX_CHARS = 1 << 20
|
|
8
8
|
const MAX_TARGETS = 512
|
|
9
9
|
const valid = (value: unknown): value is CaptionTimingDraft => {
|
|
@@ -32,6 +32,7 @@ export class CaptionTimingDrafts {
|
|
|
32
32
|
const result: Entry = { values: new Map(), failed: false, unreadable: false }; this.#entries.set(key, result)
|
|
33
33
|
try {
|
|
34
34
|
const raw = sessionStorage.getItem(key)
|
|
35
|
+
result.raw = raw
|
|
35
36
|
if (raw === null) return result
|
|
36
37
|
if (raw.length > MAX_CHARS) throw new Error('caption-draft-limit')
|
|
37
38
|
const data: unknown = JSON.parse(raw)
|
|
@@ -44,6 +45,21 @@ export class CaptionTimingDrafts {
|
|
|
44
45
|
return result
|
|
45
46
|
}
|
|
46
47
|
get(scope: Scope, stepId: string): CaptionTimingDraft | undefined { return this.#entry(scope).values.get(stepId) }
|
|
48
|
+
entries(scope: Scope): readonly (readonly [string, CaptionTimingDraft])[] { return [...this.#entry(scope).values] }
|
|
49
|
+
partial(scope: Scope): boolean { const entry = this.#entry(scope); try { return entry.unreadable || sessionStorage.getItem(this.#key(scope)) !== entry.raw } catch { return true } }
|
|
50
|
+
discard(scope: Scope, stepId: string): boolean {
|
|
51
|
+
const entry = this.#entry(scope)
|
|
52
|
+
if (entry.unreadable || !entry.values.has(stepId)) return false
|
|
53
|
+
try {
|
|
54
|
+
const next = [...entry.values].filter(([target]) => target !== stepId), key = this.#key(scope)
|
|
55
|
+
if (sessionStorage.getItem(key) !== entry.raw) { entry.failed = true; return false }
|
|
56
|
+
if (next.length) sessionStorage.setItem(key, JSON.stringify(next))
|
|
57
|
+
else sessionStorage.removeItem(key)
|
|
58
|
+
entry.raw = next.length ? JSON.stringify(next) : null
|
|
59
|
+
entry.values.delete(stepId); entry.failed = false
|
|
60
|
+
return true
|
|
61
|
+
} catch { entry.failed = true; return false }
|
|
62
|
+
}
|
|
47
63
|
steps(scope: Scope, document: TeachingDocument): string[] { return [...this.#entry(scope).values.keys()].filter(id => Object.hasOwn(document.steps, id)) }
|
|
48
64
|
failed(scope: Scope): boolean { return this.#entry(scope).failed }
|
|
49
65
|
set(scope: Scope, stepId: string, value: CaptionTimingDraft | undefined): void {
|
|
@@ -54,6 +70,7 @@ export class CaptionTimingDrafts {
|
|
|
54
70
|
const key = this.#key(scope), raw = JSON.stringify([...entry.values])
|
|
55
71
|
if (raw.length > MAX_CHARS || entry.values.size > MAX_TARGETS || [...entry.values.values()].some(draft => !valid(draft))) throw new Error('caption-draft-limit')
|
|
56
72
|
if (entry.values.size) sessionStorage.setItem(key, raw); else sessionStorage.removeItem(key)
|
|
73
|
+
entry.raw = entry.values.size ? raw : null
|
|
57
74
|
entry.failed = false
|
|
58
75
|
} catch { entry.failed = true }
|
|
59
76
|
}
|
package/src/components.tsx
CHANGED
|
@@ -333,12 +333,12 @@ export function PmDialog({ open, label, closeLabel, name, actions, description,
|
|
|
333
333
|
}
|
|
334
334
|
|
|
335
335
|
/** A non-modal floating panel on its trigger, with the shared `pm-ui-popover` surface (host's PmPopover for React pages). */
|
|
336
|
-
export function PmPopover({ open, label, name, placement = 'below-end', trigger, onOpenChange, children }: { open: boolean, label: string, name?: string, placement?: PopoverPlacement, trigger: ReactNode, onOpenChange(open: boolean): void, children?: ReactNode }) {
|
|
336
|
+
export function PmPopover({ open, label, name, placement = 'below-end', trigger, onOpenChange, onInteractOutside, children }: { open: boolean, label: string, name?: string, placement?: PopoverPlacement, trigger: ReactNode, onOpenChange(open: boolean): void, onInteractOutside?: ComponentProps<typeof Popover.Content>['onInteractOutside'], children?: ReactNode }) {
|
|
337
337
|
return (
|
|
338
338
|
<Popover.Root open={open} onOpenChange={onOpenChange}>
|
|
339
339
|
<Popover.Trigger asChild>{trigger}</Popover.Trigger>
|
|
340
340
|
<Popover.Portal>
|
|
341
|
-
<Popover.Content className={cls('pm-ui-popover', 'pm-ui-floating', 'pm-ui', name)} aria-label={label} {...placementOf(placement)} sideOffset={6} collisionPadding={16} onEscapeKeyDown={event => event.stopPropagation()}>
|
|
341
|
+
<Popover.Content className={cls('pm-ui-popover', 'pm-ui-floating', 'pm-ui', name)} aria-label={label} {...placementOf(placement)} sideOffset={6} collisionPadding={16} onInteractOutside={onInteractOutside} onEscapeKeyDown={event => event.stopPropagation()}>
|
|
342
342
|
{children}
|
|
343
343
|
</Popover.Content>
|
|
344
344
|
</Popover.Portal>
|
|
@@ -8,11 +8,14 @@ import { FloatingThreadController, getReferenceText, Thread, useBlockNoteEditor,
|
|
|
8
8
|
import type { ComponentProps, ThreadProps } from '@blocknote/react'
|
|
9
9
|
import type { Locale } from '../messages.ts'
|
|
10
10
|
import { PmButton, PmEmpty, PmNotice, PmSelect } from '../components.tsx'
|
|
11
|
+
import { isApprovalTarget } from '../approvals.tsx'
|
|
11
12
|
import { useWorkbenchState } from '../context.tsx'
|
|
12
13
|
import { enterSubmits } from './comments.ts'
|
|
13
14
|
import type { DocumentCommentEditorHandle, DocumentThreadStore } from './comments.ts'
|
|
14
15
|
import type { CommentDrafts, CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, CommentDraftOperation } from './comment-drafts.ts'
|
|
15
|
-
import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
|
|
16
|
+
import { commentDraftBaseline, isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
|
|
17
|
+
import { discardNativeCommentDraft } from './comment-draft-actions.ts'
|
|
18
|
+
import { waitForDraft } from '../document-draft-store.ts'
|
|
16
19
|
import { createRichProjection, fallbackText, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
|
|
17
20
|
import { commentEditorSchema } from './schema.tsx'
|
|
18
21
|
import type { DocumentEditorBlock } from './schema.tsx'
|
|
@@ -164,7 +167,7 @@ export function DocumentThreadsSidebar({ children }: { children?: ReactNode }) {
|
|
|
164
167
|
const focus = (id: string, event: FocusEvent) => { if (!(event.target as HTMLElement).closest('.bn-action-toolbar')) comments.selectThread(id) }
|
|
165
168
|
const blur = (event: FocusEvent) => {
|
|
166
169
|
const next = event.relatedTarget
|
|
167
|
-
if (!next || next.closest('.bn-action-toolbar')) return
|
|
170
|
+
if (!next || isApprovalTarget(next) || next.closest('.bn-action-toolbar')) return
|
|
168
171
|
const parent = next.closest('.bn-thread')
|
|
169
172
|
if (!parent || !(event.target instanceof Node) || !parent.contains(event.target)) comments.selectThread(undefined)
|
|
170
173
|
}
|
|
@@ -291,7 +294,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
|
|
|
291
294
|
|| props.editor.prosemirrorState.selection !== native.selection || context.getPositionToken?.() !== position || record.current !== own
|
|
292
295
|
|| context.store.draftTargetState(target) === 'unavailable') throw new Error('client-comment-composer-changed')
|
|
293
296
|
}
|
|
294
|
-
if (own && !await drafts.confirm(own)) return
|
|
297
|
+
if (own && !await waitForDraft(drafts.confirm(own), operation?.signal)) return
|
|
295
298
|
owns()
|
|
296
299
|
const value = await drafts.recover(candidate, target, version, { signal: operation?.signal, guard: owns })
|
|
297
300
|
if (!value) return
|
|
@@ -307,11 +310,30 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
|
|
|
307
310
|
if (!operation) await drafts.discard(candidate)
|
|
308
311
|
return value
|
|
309
312
|
}
|
|
313
|
+
const discardActive = async (candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean> => {
|
|
314
|
+
const own = record.current, version = context?.store.version, before = input.current, native = props.editor.prosemirrorState, position = context?.getPositionToken?.()
|
|
315
|
+
if (!drafts || !context || !target || !version || !own || own.id !== candidate.id || own.revision !== candidate.revision) return false
|
|
316
|
+
const guard = () => {
|
|
317
|
+
context.store.beforeAction?.()
|
|
318
|
+
if (!active.current || !current.current.editable || context.store.version !== version || composing.current || submitting.current || input.current !== before || record.current !== own
|
|
319
|
+
|| props.editor.prosemirrorView.isDestroyed || props.editor.prosemirrorView.composing || props.editor.prosemirrorState.doc !== native.doc
|
|
320
|
+
|| props.editor.prosemirrorState.selection !== native.selection || context.getPositionToken?.() !== position) throw new Error('client-comment-composer-changed')
|
|
321
|
+
}
|
|
322
|
+
const saved = target.commentId ? context.store.threadSnapshot(target.threadId)?.comments.find(value => value.id === target.commentId && !value.deletedAt) : undefined
|
|
323
|
+
if (target.commentId && !saved?.content) return false
|
|
324
|
+
return discardNativeCommentDraft(drafts, candidate, operation, guard, () => {
|
|
325
|
+
suppress.current = true
|
|
326
|
+
try {
|
|
327
|
+
props.editor.replaceBlocks(props.editor.document, saved?.content ? productRichTextToNative(saved.content, rich.current) : [{ type: 'paragraph', content: [] }])
|
|
328
|
+
record.current = undefined; input.current++; handle?.restoreBaseline(saved ? commentDraftBaseline(saved) : undefined); setRevision(value => value + 1)
|
|
329
|
+
} finally { suppress.current = false }
|
|
330
|
+
})
|
|
331
|
+
}
|
|
310
332
|
useLayoutEffect(() => {
|
|
311
333
|
if (!drafts || !target || !props.editable) return
|
|
312
334
|
return drafts.registerComposer({ id: composerId.current, target,
|
|
313
335
|
snapshot: () => { const available = active.current && current.current.editable && !submitting.current && !props.editor.prosemirrorView.isDestroyed; return { record: record.current, composing: composing.current || available && props.editor.prosemirrorView.composing, available } },
|
|
314
|
-
targetState: () => context?.store.draftTargetState(target) ?? 'unavailable', restore: recover })
|
|
336
|
+
targetState: () => context?.store.draftTargetState(target) ?? 'unavailable', restore: recover, discard: discardActive })
|
|
315
337
|
}, [drafts, handle, props.editor, props.editable])
|
|
316
338
|
const composition = (value: boolean) => {
|
|
317
339
|
composing.current = value
|
|
@@ -325,7 +347,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
|
|
|
325
347
|
<MantineCommentEditor {...props} />
|
|
326
348
|
{recoveryFailure && <PmNotice tone="warn">{t.commentRecoveryChanged}</PmNotice>}
|
|
327
349
|
{failure && <PmNotice tone="danger">{failure === 'changed' ? t.commentChanged : t.commentUnavailable}</PmNotice>}
|
|
328
|
-
{drafts && props.editable && <DraftChoices candidates={candidates} disabled={composing.current || submitting.current} onRecover={async candidate => { const captured = handle, owner = recoveryOwner.current; setRecoveryFailure(false); try { await recover(candidate) } catch { if (active.current && current.current.editable && currentHandle.current === captured && recoveryOwner.current === owner) setRecoveryFailure(true) } }} onDiscard={async candidate => { await drafts.
|
|
350
|
+
{drafts && props.editable && <DraftChoices candidates={candidates} disabled={composing.current || submitting.current} onRecover={async candidate => { const captured = handle, owner = recoveryOwner.current; setRecoveryFailure(false); try { await recover(candidate) } catch { if (active.current && current.current.editable && currentHandle.current === captured && recoveryOwner.current === owner) setRecoveryFailure(true) } }} onDiscard={async candidate => { await drafts.discardProposal(candidate) }} />}
|
|
329
351
|
{drafts && props.editable && state.failed && !context?.sidebar && <PmNotice tone="warn">{t.commentBackupFailed}</PmNotice>}
|
|
330
352
|
</div>
|
|
331
353
|
}
|
|
@@ -92,6 +92,9 @@ export function DocumentStepNarration({ blockId, sectionId, stepId, expanded, ad
|
|
|
92
92
|
drafts={{ minimumHoldMs: workbench.production.timingDraft(stepId, 'minimumHoldMs', source.identity, source.reset), trailingPauseMs: workbench.production.timingDraft(stepId, 'trailingPauseMs', source.identity, source.reset) }}
|
|
93
93
|
draftStorageFailure={timingStorageFailure}
|
|
94
94
|
onDraft={(key, draft) => workbench.production.setTimingDraft(stepId, key, draft, source.identity!, source.reset)}
|
|
95
|
+
draftControlKey={JSON.stringify([source.identity, source.reset, stepId])}
|
|
96
|
+
registerDraftControl={(key, control) => workbench.production.registerDraftView({ identity: source.identity!, kind: 'step-timing',
|
|
97
|
+
has: target => target === JSON.stringify([stepId, key]), blocked: () => control.composing(), clear: () => control.clear() })}
|
|
95
98
|
onComposition={(key, composing) => workbench.documentComposition(composing, `production:${source.identity}:${source.reset}:${blockId}:${stepId}:${key}`, source.identity)} />
|
|
96
99
|
</div>}
|
|
97
100
|
</section>
|
|
@@ -9,8 +9,11 @@ import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
|
|
|
9
9
|
import { TextSelection } from '@tiptap/pm/state'
|
|
10
10
|
import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
|
|
11
11
|
import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
|
|
12
|
+
import { discardNativeCommentDraft } from './comment-draft-actions.ts'
|
|
13
|
+
import { waitForDraft } from '../document-draft-store.ts'
|
|
14
|
+
import { isApprovalTarget } from '../approvals.tsx'
|
|
12
15
|
import { enterSubmits } from './comments.ts'
|
|
13
|
-
import type { CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, NewCommentDraftTarget } from './comment-drafts.ts'
|
|
16
|
+
import type { CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, CommentDraftOperation, NewCommentDraftTarget } from './comment-drafts.ts'
|
|
14
17
|
import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
|
|
15
18
|
import type { DocumentEditorBlock, NativeDocumentEditor } from './schema.tsx'
|
|
16
19
|
import { PmNotice } from '../components.tsx'
|
|
@@ -26,13 +29,18 @@ interface ComposerBinding {
|
|
|
26
29
|
input: number
|
|
27
30
|
composing: boolean
|
|
28
31
|
active: boolean
|
|
32
|
+
submitting: boolean
|
|
33
|
+
adopting?: boolean
|
|
34
|
+
previous?: ComposerBinding
|
|
35
|
+
adoption?: { guard(): void, finish(record?: CommentDraftRecord): void }
|
|
29
36
|
}
|
|
30
|
-
interface PreparedDraft { record: CommentDraftRecord, origin
|
|
37
|
+
interface PreparedDraft { record: CommentDraftRecord, origin?: CommentDraftReference, previous?: ComposerBinding, doc: NativeDocumentEditor['prosemirrorState']['doc'], selection: NativeDocumentEditor['prosemirrorState']['selection'], version: string, adoption?: ComposerBinding['adoption'], canUse(editor: CommentEditor): boolean }
|
|
31
38
|
interface NewDraftOwner {
|
|
32
39
|
editor: NativeDocumentEditor
|
|
33
40
|
latest: { current: ComposerBinding | undefined }
|
|
34
41
|
prepared: { current: PreparedDraft | undefined }
|
|
35
|
-
|
|
42
|
+
generation: number
|
|
43
|
+
restore(candidate: CommentDraftCandidate, current?: () => boolean, operation?: CommentDraftOperation): Promise<CommentDraftRecord | undefined>
|
|
36
44
|
failure?: boolean
|
|
37
45
|
}
|
|
38
46
|
const NEW_DRAFT_OWNER = createContext<NewDraftOwner | undefined>(undefined)
|
|
@@ -43,27 +51,33 @@ const emptyState = { candidates: [], pending: false, failed: false, reading: fal
|
|
|
43
51
|
export function NewCommentDraftProvider({ children }: { children?: ReactNode }) {
|
|
44
52
|
const context = useContext(COMMENT_EDITOR_CONTEXT), editor = useBlockNoteEditor() as NativeDocumentEditor, comments = useExtension(CommentsExtension)
|
|
45
53
|
const latest = useRef<ComposerBinding>(), prepared = useRef<PreparedDraft>(), active = useRef(true), operation = useRef(0)
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
54
|
+
const composerId = useRef(randomUUID()), handoff = useRef<() => void>()
|
|
55
|
+
const [failure, setFailure] = useState(false), [generation, setGeneration] = useState(0)
|
|
56
|
+
useEffect(() => { active.current = true; return () => { active.current = false; ++operation.current; handoff.current?.(); prepared.current = undefined; latest.current = undefined } }, [editor])
|
|
57
|
+
const restore = async (candidate: CommentDraftCandidate, current = () => true, action?: CommentDraftOperation): Promise<CommentDraftRecord | undefined> => {
|
|
49
58
|
const store = context?.store, drafts = store?.drafts, target = candidate.target
|
|
50
59
|
if (!store || !drafts || !isNewCommentDraft(target) || candidate.storage !== 'durable' || editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing) return
|
|
51
|
-
const binding = latest.current
|
|
60
|
+
const binding = latest.current?.active ? latest.current : undefined
|
|
52
61
|
if (binding?.record && !drafts.owns(binding.record)) binding.record = undefined
|
|
62
|
+
handoff.current?.()
|
|
53
63
|
const request = ++operation.current, input = binding?.input, record = binding?.record
|
|
54
64
|
try {
|
|
55
65
|
store.beforeAction?.()
|
|
56
66
|
if (!store.auth.canCreateThread() || store.draftTargetState(target) !== 'current' || !store.newDraftPositions(target, editor)) { setFailure(true); return }
|
|
57
|
-
const version = store.version, native = editor.prosemirrorState, extensionState = comments.store.state, position = context.getPositionToken?.()
|
|
58
|
-
if (!version || binding?.composing || binding?.editor.prosemirrorView.composing) return
|
|
67
|
+
const version = store.version, native = editor.prosemirrorState, extensionState = comments.store.state, position = context.getPositionToken?.(), form = binding?.editor.prosemirrorState
|
|
68
|
+
if (!version || binding?.composing || binding?.submitting || binding?.editor.prosemirrorView.composing) return
|
|
59
69
|
const owns = () => active.current && current() && request === operation.current && !editor.prosemirrorView.isDestroyed && !editor.prosemirrorView.composing && store.version === version
|
|
60
70
|
&& context.getPositionToken?.() === position
|
|
61
71
|
&& editor.prosemirrorState.doc === native.doc && editor.prosemirrorState.selection === native.selection && comments.store.state === extensionState
|
|
62
72
|
&& (!binding || latest.current === binding && binding.input === input && binding.record === record && !binding.composing)
|
|
63
|
-
|
|
64
|
-
|
|
73
|
+
const guard = () => { action?.signal?.throwIfAborted(); action?.guard?.(); if (!owns()) throw new Error('client-comment-composer-changed') }
|
|
74
|
+
guard()
|
|
75
|
+
if (record && !await waitForDraft(drafts.confirm(record), action?.signal)) return
|
|
76
|
+
guard()
|
|
77
|
+
const nextTarget = { ...target, intentId: randomUUID() }, next = await drafts.recover(candidate, nextTarget, version, { signal: action?.signal, guard })
|
|
65
78
|
store.beforeAction?.()
|
|
66
|
-
if (!next
|
|
79
|
+
if (!next) return
|
|
80
|
+
guard()
|
|
67
81
|
const positions = store.newDraftPositions(nextTarget, editor)
|
|
68
82
|
if (!positions) { setFailure(true); return }
|
|
69
83
|
comments.stopPendingComment()
|
|
@@ -71,14 +85,46 @@ export function NewCommentDraftProvider({ children }: { children?: ReactNode })
|
|
|
71
85
|
editor.focus()
|
|
72
86
|
editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, positions.from, positions.to)).scrollIntoView())
|
|
73
87
|
// The public controller creates the actual editor; this is only its strictly committed handoff.
|
|
74
|
-
|
|
88
|
+
let finish!: (record?: CommentDraftRecord) => void
|
|
89
|
+
const adopted = new Promise<CommentDraftRecord | undefined>(resolve => { finish = resolve })
|
|
90
|
+
const pending: PreparedDraft = { record: next, previous: binding, ...!action ? { origin: candidate } : {}, doc: editor.prosemirrorState.doc, selection: editor.prosemirrorState.selection, version,
|
|
91
|
+
canUse: actual => (!binding || binding.input === input && binding.record === record && !binding.composing && !binding.submitting)
|
|
92
|
+
&& (actual === binding?.editor ? !actual.prosemirrorView.isDestroyed && actual.prosemirrorState.doc === form?.doc && actual.prosemirrorState.selection === form?.selection : actual.isEmpty) }
|
|
93
|
+
if (action) {
|
|
94
|
+
let settled = false
|
|
95
|
+
const complete = (value?: CommentDraftRecord) => { if (settled) return; settled = true; if (handoff.current === cancel) handoff.current = undefined; finish(value) }
|
|
96
|
+
const cancel = () => complete()
|
|
97
|
+
handoff.current = cancel
|
|
98
|
+
pending.adoption = { finish: complete, guard: () => {
|
|
99
|
+
action.signal?.throwIfAborted(); store.beforeAction?.()
|
|
100
|
+
const actual = latest.current
|
|
101
|
+
if (!active.current || !current() || request !== operation.current || store.version !== version || editor.prosemirrorView.isDestroyed || editor.prosemirrorView.composing
|
|
102
|
+
|| editor.prosemirrorState.doc !== pending.doc || editor.prosemirrorState.selection !== pending.selection || !actual?.active || actual.record !== next || actual.input !== 0
|
|
103
|
+
|| actual.composing || actual.submitting || !store.newDraftPositions(nextTarget, editor)) throw new Error('client-comment-composer-changed')
|
|
104
|
+
} }
|
|
105
|
+
}
|
|
106
|
+
prepared.current = pending
|
|
75
107
|
comments.startPendingComment()
|
|
76
|
-
|
|
108
|
+
pending.selection = editor.prosemirrorState.selection
|
|
109
|
+
setGeneration(value => value + 1)
|
|
77
110
|
setFailure(false)
|
|
78
111
|
context.onDraftRestore?.()
|
|
79
|
-
|
|
112
|
+
if (action) return await waitForDraft(adopted, action.signal)
|
|
113
|
+
} catch (error) { if (active.current && request === operation.current) setFailure(true); if (action) throw error }
|
|
114
|
+
finally { if (request === operation.current) handoff.current?.() }
|
|
80
115
|
}
|
|
81
|
-
|
|
116
|
+
useLayoutEffect(() => {
|
|
117
|
+
const store = context?.store, drafts = store?.drafts
|
|
118
|
+
if (!store || !drafts) return
|
|
119
|
+
return drafts.registerComposer({ id: composerId.current, target: { kind: 'create', intentId: composerId.current, documentId: store.document.id },
|
|
120
|
+
accepts: target => isNewCommentDraft(target) && Boolean(store.newDraftPositions(target, editor)),
|
|
121
|
+
snapshot: () => { const binding = latest.current?.active ? latest.current : undefined; return { record: binding?.record,
|
|
122
|
+
composing: editor.prosemirrorView.composing || Boolean(binding?.composing || binding?.editor.prosemirrorView.composing),
|
|
123
|
+
available: active.current && !context.readOnly && !editor.prosemirrorView.isDestroyed && !binding?.submitting && store.auth.canCreateThread() } },
|
|
124
|
+
targetState: target => target && isNewCommentDraft(target) && store.newDraftPositions(target, editor) ? 'current' : 'unavailable',
|
|
125
|
+
restore: (candidate, action) => restore(candidate, () => active.current, action) })
|
|
126
|
+
}, [context?.store, context?.readOnly, editor])
|
|
127
|
+
return <NEW_DRAFT_OWNER.Provider value={{ editor, latest, prepared, generation, restore, failure }}>{children}</NEW_DRAFT_OWNER.Provider>
|
|
82
128
|
}
|
|
83
129
|
|
|
84
130
|
/**
|
|
@@ -107,7 +153,8 @@ export function DocumentNewCommentController() {
|
|
|
107
153
|
const position = useEditorState({ editor, selector: ({ editor }) => pendingComment ? { from: editor.prosemirrorState.selection.from, to: editor.prosemirrorState.selection.to } : undefined })
|
|
108
154
|
const floating = useMemo(() => commentFloating(), [])
|
|
109
155
|
return <PositionPopover position={position} focusManagerProps={{ disabled: true }} elementProps={{ style: { zIndex: COMPOSER_LAYER } }}
|
|
110
|
-
useFloatingOptions={{ placement: 'bottom', ...floating, open: pendingComment, onOpenChange(open) {
|
|
156
|
+
useFloatingOptions={{ placement: 'bottom', ...floating, open: pendingComment, onOpenChange(open, event?: Event) {
|
|
157
|
+
if (!open && isApprovalTarget(event?.target ?? document.activeElement)) return
|
|
111
158
|
if (open || !owner || owner.latest.current?.composing || owner.latest.current?.editor.prosemirrorView.composing) return
|
|
112
159
|
try { context?.store.beforeAction?.() } catch { return }
|
|
113
160
|
comments.stopPendingComment()
|
|
@@ -127,15 +174,20 @@ function DocumentNewCommentComposer({ newCommentEditor }: { newCommentEditor: Co
|
|
|
127
174
|
try {
|
|
128
175
|
context.store.beforeAction?.()
|
|
129
176
|
const restored = owner.prepared.current, prepared = restored && restored.version === context.store.version
|
|
130
|
-
&& restored.doc === owner.editor.prosemirrorState.doc && restored.selection === owner.editor.prosemirrorState.selection && newCommentEditor
|
|
177
|
+
&& restored.doc === owner.editor.prosemirrorState.doc && restored.selection === owner.editor.prosemirrorState.selection && restored.canUse(newCommentEditor)
|
|
131
178
|
&& isNewCommentDraft(restored.record.target) && context.store.newDraftPositions(restored.record.target, owner.editor) ? restored : undefined
|
|
179
|
+
if (restored && !prepared && owner.latest.current?.editor === newCommentEditor) {
|
|
180
|
+
const retained = owner.latest.current
|
|
181
|
+
retained.active = true; owner.prepared.current = undefined; restored.adoption?.finish(); setBinding(retained)
|
|
182
|
+
return () => { retained.active = false }
|
|
183
|
+
}
|
|
132
184
|
const target = prepared && isNewCommentDraft(prepared.record.target) ? prepared.record.target : context.store.newDraftTarget(owner.editor)
|
|
133
|
-
const value: ComposerBinding = { target, editor: newCommentEditor, record: prepared?.record, origin: prepared?.origin, input: 0, composing: false, active: true }
|
|
134
|
-
if (prepared) owner.prepared.current = undefined
|
|
185
|
+
const value: ComposerBinding = { target, editor: newCommentEditor, record: prepared?.record, origin: prepared?.origin, adoption: prepared?.adoption, previous: prepared?.previous, adopting: Boolean(prepared), input: 0, composing: false, active: true, submitting: false }
|
|
186
|
+
if (restored) { if (!prepared) restored.adoption?.finish(); owner.prepared.current = undefined }
|
|
135
187
|
owner.latest.current = value; setBinding(value)
|
|
136
188
|
return () => { value.active = false }
|
|
137
189
|
} catch { /* The unchanged native form remains available when no authoritative target can be confirmed. */ }
|
|
138
|
-
}, [newCommentEditor, context?.store, owner?.editor])
|
|
190
|
+
}, [newCommentEditor, context?.store, owner?.editor, owner?.generation])
|
|
139
191
|
const value = useMemo(() => ({ ...nativeComponents, Comments: { ...nativeComponents.Comments, Editor: NewCommentEditor } }), [nativeComponents])
|
|
140
192
|
return <NEW_COMPOSER_BINDING.Provider value={{ binding, ready: () => render(value => value + 1) }}><ComponentsContext.Provider value={value}>
|
|
141
193
|
<FloatingComposer newCommentEditor={newCommentEditor} />
|
|
@@ -150,9 +202,24 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
|
|
|
150
202
|
const drafts = context?.store.drafts, state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState))
|
|
151
203
|
useLayoutEffect(() => {
|
|
152
204
|
if (!binding || !drafts || !context || !owner) return
|
|
153
|
-
if (binding.record && props.editor.isEmpty) {
|
|
154
|
-
|
|
155
|
-
|
|
205
|
+
if (binding.record && (props.editor.isEmpty || binding.adopting)) {
|
|
206
|
+
let replaced = false
|
|
207
|
+
try {
|
|
208
|
+
binding.adoption?.guard()
|
|
209
|
+
props.editor.replaceBlocks(props.editor.document, productRichTextToNative(binding.record.content, rich))
|
|
210
|
+
replaced = true
|
|
211
|
+
if (JSON.stringify(nativeRichTextToProduct(props.editor.document as DocumentEditorBlock[], rich)) !== JSON.stringify(binding.record.content)) throw new Error('client-comment-native-unverified')
|
|
212
|
+
binding.adoption?.finish(binding.record); binding.adoption = undefined; binding.adopting = false
|
|
213
|
+
if (binding.origin) { void drafts.discard(binding.origin); binding.origin = undefined }
|
|
214
|
+
} catch {
|
|
215
|
+
binding.adoption?.finish(); binding.adoption = undefined; binding.adopting = false
|
|
216
|
+
const previous = binding.previous
|
|
217
|
+
if (!replaced && previous?.editor === props.editor) {
|
|
218
|
+
binding.target = previous.target; binding.record = previous.record; binding.origin = previous.origin; binding.input = previous.input
|
|
219
|
+
} else binding.record = undefined
|
|
220
|
+
setFailure(true)
|
|
221
|
+
}
|
|
222
|
+
binding.previous = undefined
|
|
156
223
|
}
|
|
157
224
|
const original = props.editor.getExtension(CommentEditorSubmitExtension)
|
|
158
225
|
let guarded: typeof original, stopEnter = () => {}
|
|
@@ -164,13 +231,13 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
|
|
|
164
231
|
const positions = context.store.newDraftPositions(binding.target, owner.editor), selection = owner.editor.prosemirrorState.selection
|
|
165
232
|
if (!context.store.auth.canCreateThread() || !positions || selection.from !== positions.from || selection.to !== positions.to) { setFailure(true); return }
|
|
166
233
|
const before = new Set(context.store.getThreads().keys()), record = binding.record
|
|
167
|
-
submitting.current = true
|
|
234
|
+
submitting.current = true; binding.submitting = true
|
|
168
235
|
try {
|
|
169
236
|
const result = original.submit(), thread = [...context.store.getThreads().values()].find(thread => !before.has(thread.id))
|
|
170
237
|
const actual = thread && context.store.threadSnapshot(thread.id)
|
|
171
238
|
if (actual) { drafts.submitted(record, actual.comments[0], actual); binding.record = undefined }
|
|
172
239
|
await result
|
|
173
|
-
} finally { submitting.current = false }
|
|
240
|
+
} finally { submitting.current = false; binding.submitting = false }
|
|
174
241
|
} catch { setFailure(true) }
|
|
175
242
|
} }))
|
|
176
243
|
guarded = props.editor.getExtension(CommentEditorSubmitExtension); composer.ready()
|
|
@@ -187,11 +254,26 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
|
|
|
187
254
|
return () => { stop(); stopEnter(); if (original && guarded && !props.editor.prosemirrorView.isDestroyed && props.editor.getExtension(CommentEditorSubmitExtension) === guarded) props.editor.replaceExtension(guarded, original) }
|
|
188
255
|
}, [binding, drafts, props.editor])
|
|
189
256
|
const composerId = useRef(randomUUID())
|
|
257
|
+
const discardActive = async (candidate: CommentDraftCandidate, action?: CommentDraftOperation): Promise<boolean> => {
|
|
258
|
+
if (!binding || !drafts || !context || !owner || !binding.record || binding.record.id !== candidate.id || binding.record.revision !== candidate.revision) return false
|
|
259
|
+
const record = binding.record, input = binding.input, native = props.editor.prosemirrorState, version = context.store.version, position = context.getPositionToken?.()
|
|
260
|
+
const guard = () => {
|
|
261
|
+
context.store.beforeAction?.()
|
|
262
|
+
if (!binding.active || owner.latest.current !== binding || binding.record !== record || binding.input !== input || context.store.version !== version
|
|
263
|
+
|| context.getPositionToken?.() !== position || binding.composing || submitting.current || props.editor.prosemirrorView.isDestroyed
|
|
264
|
+
|| props.editor.prosemirrorView.composing || props.editor.prosemirrorState.doc !== native.doc || props.editor.prosemirrorState.selection !== native.selection) throw new Error('client-comment-composer-changed')
|
|
265
|
+
}
|
|
266
|
+
return discardNativeCommentDraft(drafts, candidate, action, guard, () => {
|
|
267
|
+
suppress.current = true
|
|
268
|
+
try { props.editor.replaceBlocks(props.editor.document, [{ type: 'paragraph', content: [] }]); binding.record = undefined; binding.origin = undefined; binding.input++ }
|
|
269
|
+
finally { suppress.current = false }
|
|
270
|
+
})
|
|
271
|
+
}
|
|
190
272
|
useLayoutEffect(() => {
|
|
191
273
|
if (!binding || !drafts || !context) return
|
|
192
274
|
return drafts.registerComposer({ id: composerId.current, target: binding.target,
|
|
193
275
|
snapshot: () => { const available = binding.active && !submitting.current && !props.editor.prosemirrorView.isDestroyed; return { record: binding.record, composing: binding.composing || available && props.editor.prosemirrorView.composing, available } },
|
|
194
|
-
targetState: () => context.store.draftTargetState(binding.target) })
|
|
276
|
+
targetState: () => context.store.draftTargetState(binding.target), discard: discardActive })
|
|
195
277
|
}, [binding, drafts, props.editor])
|
|
196
278
|
const t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
|
|
197
279
|
const composition = (value: boolean) => {
|
|
@@ -216,10 +298,10 @@ export function DocumentNewCommentRecovery() {
|
|
|
216
298
|
if (!drafts || !owner) return null
|
|
217
299
|
return <>{owner.failure && <PmNotice tone="warn">{t.commentTargetUnavailable}</PmNotice>}<DraftChoices candidates={candidates} preview
|
|
218
300
|
canRecover={candidate => isNewCommentDraft(candidate.target) && Boolean(context?.store.newDraftPositions(candidate.target, owner.editor))}
|
|
219
|
-
unavailableMessage={t.commentTargetUnavailable} onRecover={candidate => owner.restore(candidate, () => active.current)} onDiscard={async candidate => {
|
|
301
|
+
unavailableMessage={t.commentTargetUnavailable} onRecover={async candidate => { await owner.restore(candidate, () => active.current) }} onDiscard={async candidate => {
|
|
220
302
|
const binding = owner.latest.current, record = binding?.record, input = binding?.input
|
|
221
303
|
const { token, storage, ...value } = candidate
|
|
222
|
-
if (await drafts.
|
|
304
|
+
if (await drafts.discardProposal(candidate) && binding && owner.latest.current === binding && binding.input === input && binding.record === record
|
|
223
305
|
&& record && JSON.stringify(record) === JSON.stringify(value)) binding.record = undefined
|
|
224
306
|
}} /></>
|
|
225
307
|
}
|