@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
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.55",
|
|
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/design": "1.0.0-rc.
|
|
59
|
-
"@lincyaw/kernel": "1.0.0-rc.
|
|
58
|
+
"@lincyaw/design": "1.0.0-rc.55",
|
|
59
|
+
"@lincyaw/kernel": "1.0.0-rc.55"
|
|
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.55"
|
|
71
71
|
}
|
|
72
72
|
}
|
package/src/MediaClipEditor.tsx
CHANGED
|
@@ -45,6 +45,7 @@ export interface MediaClipEditorProps {
|
|
|
45
45
|
onReview(): void
|
|
46
46
|
onApply(clip: MediaClip): void
|
|
47
47
|
onRemove(): void
|
|
48
|
+
onInteraction?(busy: boolean): void
|
|
48
49
|
onEditStart(): void
|
|
49
50
|
}
|
|
50
51
|
|
|
@@ -72,7 +73,7 @@ export function MediaClipEditor(props: MediaClipEditorProps) {
|
|
|
72
73
|
props.onApply({ ...clip, sourceRange: { startMs: startMs!, endMs: endMs! }, attachment: { ...clip.attachment, offsetMs: offsetMs! } })
|
|
73
74
|
}
|
|
74
75
|
const change = (patch: Partial<MediaClipDraft>) => props.onChange({ ...draft, ...patch })
|
|
75
|
-
const composition = (field: string) => ({ onCompositionStart: () => composing.current.add(field), onCompositionEnd: () => { composing.current.delete(field) } })
|
|
76
|
+
const composition = (field: string) => ({ onCompositionStart: () => { composing.current.add(field); props.onInteraction?.(true) }, onCompositionEnd: () => { composing.current.delete(field); props.onInteraction?.(composing.current.size > 0 || volumePreview !== undefined) } })
|
|
76
77
|
return <section className="pm-ui-media-clip-editor" aria-label={t.title} data-density={density} onFocusCapture={props.onEditStart} onPointerDownCapture={props.onEditStart}
|
|
77
78
|
onKeyDown={event => {
|
|
78
79
|
event.stopPropagation()
|
|
@@ -102,7 +103,7 @@ export function MediaClipEditor(props: MediaClipEditorProps) {
|
|
|
102
103
|
<PmInput label={t.offset} density={density} width="number" inputMode="decimal" maxLength={32} value={draft.offsetText ?? (clip.attachment.offsetMs / 1000).toFixed(3)}
|
|
103
104
|
readOnly={disabled || !inspected} error={offsetMs === undefined ? t.invalidOffset : undefined} onChange={event => change({ offsetText: event.target.value })} {...composition('offset')} />
|
|
104
105
|
<PmField label={t.volume} density={density} group><div className="pm-ui-range-row">
|
|
105
|
-
<PmRange label={t.volume} density={density} value={clip.volume * 100} max={100} disabled={disabled || !inspected} valueText={value => `${Math.round(value)}%`} onPreviewChange={setVolumePreview}
|
|
106
|
+
<PmRange label={t.volume} density={density} value={clip.volume * 100} max={100} disabled={disabled || !inspected} valueText={value => `${Math.round(value)}%`} onPreviewChange={value => { setVolumePreview(value); props.onInteraction?.(value !== undefined || composing.current.size > 0) }}
|
|
106
107
|
onValueCommit={value => change({ clip: { ...clip, volume: value / 100 } })} />
|
|
107
108
|
<output>{Math.round(volumePreview ?? clip.volume * 100)}%</output><PmButton density={density} aria-pressed={Boolean(clip.muted)} disabled={disabled || !inspected} onClick={() => change({ clip: { ...clip, muted: !clip.muted } })}>{clip.muted ? t.unmute : t.mute}</PmButton>
|
|
108
109
|
</div></PmField>
|
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">
|
package/src/components.tsx
CHANGED
|
@@ -5,7 +5,7 @@ import * as Popover from '@radix-ui/react-popover'
|
|
|
5
5
|
import * as Tabs from '@radix-ui/react-tabs'
|
|
6
6
|
import * as Toolbar from '@radix-ui/react-toolbar'
|
|
7
7
|
import * as RadioGroup from '@radix-ui/react-radio-group'
|
|
8
|
-
import { forwardRef, useEffect, useId, useMemo, useRef, useState } from 'react'
|
|
8
|
+
import { createContext, forwardRef, useContext, useEffect, useId, useMemo, useRef, useState } from 'react'
|
|
9
9
|
import type { ComponentProps, CSSProperties, InputHTMLAttributes, ReactNode, Ref, SelectHTMLAttributes, TextareaHTMLAttributes } from 'react'
|
|
10
10
|
import { Group as ResizableGroup, Panel as ResizablePanel, Separator as ResizableSeparator } from 'react-resizable-panels'
|
|
11
11
|
import { PmButton, PmIcon, PmIconButton, PmTooltip } from './base-controls.tsx'
|
|
@@ -286,8 +286,13 @@ export function PmWorkspaceSwitcher({ label, value, items, onValueChange, placeh
|
|
|
286
286
|
export type PopoverPlacement = 'below-end' | 'below-start' | 'above-end' | 'above-start'
|
|
287
287
|
const placementOf = (placement: PopoverPlacement) => ({ side: placement.startsWith('above') ? 'top' as const : 'bottom' as const, align: placement.endsWith('start') ? 'start' as const : 'end' as const })
|
|
288
288
|
|
|
289
|
+
/** Host controls remain reachable inside the active modal without weakening its focus boundary. */
|
|
290
|
+
export const PmDialogActionsContext = createContext<ReactNode>(undefined)
|
|
291
|
+
const PmDialogLayerContext = createContext(false)
|
|
292
|
+
|
|
289
293
|
export function PmDialog({ open, label, closeLabel, name, actions, description, footer, busy, onClose, onOpenAutoFocus, onCloseAutoFocus, children }: { open: boolean, label: string, closeLabel: string, name?: string, actions?: ReactNode, description?: string, footer?: ReactNode, busy?: boolean, onClose(): void, onOpenAutoFocus?(event: Event): void, onCloseAutoFocus?(event: Event): void, children?: ReactNode }) {
|
|
290
294
|
const id = useId()
|
|
295
|
+
const hostActions = useContext(PmDialogActionsContext)
|
|
291
296
|
// A descendant's React autoFocus runs before Radix's open-focus event.
|
|
292
297
|
const trigger = useRef<HTMLElement | null>(typeof document === 'undefined' ? null : document.activeElement as HTMLElement)
|
|
293
298
|
useEffect(() => {
|
|
@@ -318,14 +323,17 @@ export function PmDialog({ open, label, closeLabel, name, actions, description,
|
|
|
318
323
|
const target = available(trigger.current) ? trigger.current : [...document.querySelectorAll<HTMLElement>('[role="toolbar"] button, main button')].find(available)
|
|
319
324
|
target?.focus()
|
|
320
325
|
}}>
|
|
326
|
+
<PmDialogLayerContext.Provider value>
|
|
321
327
|
<div className="pm-ui-dialog__header">
|
|
322
328
|
<Dialog.Title className="pm-ui-dialog__title">{label}</Dialog.Title>
|
|
323
329
|
{actions}
|
|
330
|
+
{hostActions}
|
|
324
331
|
<Dialog.Close asChild><PmIconButton icon="close" label={closeLabel} small disabled={busy} /></Dialog.Close>
|
|
325
332
|
</div>
|
|
326
333
|
{description && <Dialog.Description className="pm-ui-dialog__description">{description}</Dialog.Description>}
|
|
327
334
|
<div className="pm-ui-dialog__body">{children}</div>
|
|
328
335
|
{footer && <div className="pm-ui-dialog__footer">{footer}</div>}
|
|
336
|
+
</PmDialogLayerContext.Provider>
|
|
329
337
|
</Dialog.Content>
|
|
330
338
|
</Dialog.Portal>
|
|
331
339
|
</Dialog.Root>
|
|
@@ -333,12 +341,13 @@ export function PmDialog({ open, label, closeLabel, name, actions, description,
|
|
|
333
341
|
}
|
|
334
342
|
|
|
335
343
|
/** 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 }) {
|
|
344
|
+
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 }) {
|
|
345
|
+
const inDialog = useContext(PmDialogLayerContext)
|
|
337
346
|
return (
|
|
338
347
|
<Popover.Root open={open} onOpenChange={onOpenChange}>
|
|
339
348
|
<Popover.Trigger asChild>{trigger}</Popover.Trigger>
|
|
340
349
|
<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()}>
|
|
350
|
+
<Popover.Content className={cls('pm-ui-popover', 'pm-ui-floating', 'pm-ui', name)} data-layer={inDialog ? 'dialog' : undefined} aria-label={label} {...placementOf(placement)} sideOffset={6} collisionPadding={16} onInteractOutside={onInteractOutside} onEscapeKeyDown={event => event.stopPropagation()}>
|
|
342
351
|
{children}
|
|
343
352
|
</Popover.Content>
|
|
344
353
|
</Popover.Portal>
|
package/src/context.tsx
CHANGED
|
@@ -4,12 +4,13 @@ import { MESSAGES } from './messages.ts'
|
|
|
4
4
|
import type { WorkbenchMessages } from './messages.ts'
|
|
5
5
|
import type { Workbench } from './workbench.ts'
|
|
6
6
|
import type { WorkbenchState } from './workbench-state.ts'
|
|
7
|
+
import { PmDialogActionsContext } from './components.tsx'
|
|
7
8
|
|
|
8
9
|
const WORKBENCH = createContext<Workbench | undefined>(undefined)
|
|
9
10
|
|
|
10
11
|
/** Gives the panels drawn in it one workbench. */
|
|
11
|
-
export function WorkbenchProvider({ workbench, children }: { workbench: Workbench, children?: ReactNode }) {
|
|
12
|
-
return <WORKBENCH.Provider value={workbench}>{children}</WORKBENCH.Provider>
|
|
12
|
+
export function WorkbenchProvider({ workbench, children, dialogActions }: { workbench: Workbench, children?: ReactNode, dialogActions?: ReactNode }) {
|
|
13
|
+
return <WORKBENCH.Provider value={workbench}>{dialogActions === undefined ? children : <PmDialogActionsContext.Provider value={dialogActions}>{children}</PmDialogActionsContext.Provider>}</WORKBENCH.Provider>
|
|
13
14
|
}
|
|
14
15
|
|
|
15
16
|
export function useWorkbench(): Workbench {
|
|
@@ -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
|
}
|
|
@@ -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
|
}
|