@lincyaw/workbench 0.2.0-rc.12 → 0.2.0-rc.121
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/README.md +1 -1
- package/package.json +5 -4
- package/src/AgentActivityBar.tsx +25 -0
- package/src/MediaClipEditor.tsx +7 -6
- package/src/StepProductionEditor.tsx +16 -7
- package/src/agent-activity-messages.ts +14 -0
- package/src/agent-activity.ts +38 -0
- package/src/approvals.tsx +6 -1
- package/src/audio-recording-messages.ts +5 -5
- package/src/audio-recording.ts +27 -5
- package/src/authoring-client.ts +10 -10
- package/src/authoring-draft-fragment.ts +3 -1
- package/src/authoring-window.ts +100 -0
- package/src/base-controls.tsx +28 -7
- package/src/body-draft-actions.ts +60 -0
- package/src/caption-timing-drafts.ts +20 -3
- package/src/caption-timing-messages.ts +2 -2
- package/src/caption-timing.ts +2 -2
- package/src/component-draft-actions.ts +1 -1
- package/src/component-properties.ts +3 -3
- package/src/component-property-drafts.ts +6 -6
- package/src/components.tsx +43 -38
- package/src/container-layout.ts +21 -0
- package/src/context.tsx +5 -3
- package/src/diagnostics.ts +1 -1
- package/src/document-draft-store.ts +45 -18
- package/src/document-drafts.ts +30 -21
- package/src/document-editing.ts +485 -0
- package/src/document-editor/BlockNoteSurface.tsx +40 -14
- package/src/document-editor/CommentComposer.tsx +24 -0
- package/src/document-editor/ComponentMaterials.tsx +4 -10
- package/src/document-editor/ComponentPropertiesDialog.tsx +12 -12
- package/src/document-editor/DocumentBlockFallback.tsx +4 -3
- package/src/document-editor/DocumentBlockPreview.tsx +11 -4
- package/src/document-editor/DocumentComments.tsx +87 -17
- package/src/document-editor/DocumentEditor.tsx +66 -14
- package/src/document-editor/DocumentStepNarration.tsx +39 -27
- package/src/document-editor/NarrationEditor.tsx +55 -21
- package/src/document-editor/NewCommentDrafts.tsx +120 -37
- package/src/document-editor/PlaceComment.tsx +252 -0
- package/src/document-editor/agent-targets.ts +34 -0
- package/src/document-editor/blocknote-messages.ts +2 -0
- package/src/document-editor/comment-draft-actions.ts +40 -20
- package/src/document-editor/comment-draft-inspection.ts +2 -2
- package/src/document-editor/comment-drafts.ts +75 -27
- package/src/document-editor/comments.ts +34 -14
- package/src/document-editor/component-label.ts +11 -0
- package/src/document-editor/file-input.ts +2 -2
- package/src/document-editor/focus.ts +0 -2
- package/src/document-editor/inline.ts +1 -0
- package/src/document-editor/insertion-place.ts +60 -0
- package/src/document-editor/messages.ts +3 -3
- package/src/document-editor/narration-schema.tsx +12 -6
- package/src/document-editor/narration.ts +19 -3
- package/src/document-editor/page-body.ts +60 -0
- package/src/document-editor/popover.tsx +4 -2
- package/src/document-editor/projection.ts +21 -19
- package/src/document-editor/rich-text.ts +3 -2
- package/src/document-editor/selection.ts +13 -0
- package/src/document-editor/style.css +8 -3
- package/src/document-editor/table-identities.ts +2 -1
- package/src/document-preview.ts +3 -2
- package/src/document-production.ts +492 -0
- package/src/document-return-point.ts +2 -2
- package/src/document-session.ts +216 -67
- package/src/document-timing-drafts.ts +26 -6
- package/src/effective-settings.ts +12 -0
- package/src/history.ts +5 -5
- package/src/import-messages.ts +40 -0
- package/src/index.ts +11 -5
- package/src/jobs.ts +1 -1
- package/src/mcp-settings-messages.ts +39 -0
- package/src/media-drafts.ts +43 -1
- package/src/messages.ts +39 -18
- package/src/outline.ts +5 -5
- package/src/panels/DocumentImportDialog.tsx +59 -0
- package/src/panels/DocumentNarrationPanel.tsx +2 -2
- package/src/panels/DocumentView.tsx +106 -77
- package/src/panels/DocumentVoiceDialog.tsx +29 -12
- package/src/panels/DocumentVoiceField.tsx +3 -2
- package/src/panels/ExportPanel.tsx +2 -10
- package/src/panels/HistoryPanel.tsx +36 -10
- package/src/panels/HomePanel.tsx +12 -1
- package/src/panels/McpSettingsPanel.tsx +86 -0
- package/src/panels/PageDeleteDialog.tsx +4 -4
- package/src/panels/PageRenameDialog.tsx +1 -1
- package/src/panels/PreviewPanel.tsx +4 -7
- package/src/panels/ProductionCaptionSize.tsx +20 -0
- package/src/panels/ProductionCaptionTiming.tsx +12 -9
- package/src/panels/ProductionMediaClips.tsx +25 -9
- package/src/panels/ProductionPanel.tsx +21 -17
- package/src/panels/ProductionRecording.tsx +86 -9
- package/src/panels/ProductionRecordingRange.tsx +26 -23
- package/src/panels/ProductionTimeline.tsx +6 -1
- package/src/panels/ProductionTranscription.tsx +8 -6
- package/src/panels/SourceDocumentPanel.tsx +24 -40
- package/src/panels/SpeechSettingsPanel.tsx +2 -2
- package/src/panels/TranscriptionAdoption.tsx +42 -36
- package/src/panels/VoiceCloneDialog.tsx +2 -1
- package/src/panels/VoicePreviewDialog.tsx +1 -1
- package/src/panels/VoiceScopeField.tsx +2 -2
- package/src/panels/VoiceoverDialog.tsx +11 -10
- package/src/places.ts +1 -36
- package/src/preview-playback.ts +1 -1
- package/src/production-draft-actions.ts +37 -0
- package/src/production-messages.ts +6 -0
- package/src/production-playback.ts +1 -1
- package/src/production-voice-playback.ts +3 -2
- package/src/recording-adoption.ts +4 -4
- package/src/sha256.ts +9 -0
- package/src/speech-settings-messages.ts +6 -6
- package/src/step-production.ts +4 -4
- package/src/styles.css +43 -92
- package/src/transcription-drafts.ts +124 -0
- package/src/use-recording-adoption.ts +5 -4
- package/src/voice-drafts.ts +32 -8
- package/src/voice-messages.ts +9 -9
- package/src/voiceover-jobs.ts +1 -1
- package/src/workbench-state.ts +159 -0
- package/src/workbench.ts +323 -956
- package/src/workspace-client.ts +41 -12
- package/src/assistant-mascot.ts +0 -62
- package/src/mascot-preference.ts +0 -37
- package/src/panels/ChangeTrail.tsx +0 -79
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { createContext, useContext, useMemo } from 'react'
|
|
2
|
+
import type { ComponentType, ReactNode } from 'react'
|
|
3
|
+
import { components } from '@blocknote/mantine'
|
|
4
|
+
import { ComponentsContext, FloatingComposer, useComponentsContext } from '@blocknote/react'
|
|
5
|
+
import type { ComponentProps } from '@blocknote/react'
|
|
6
|
+
import type { BlockNoteEditor } from '@blocknote/core'
|
|
7
|
+
|
|
8
|
+
const COMPOSER_CARD = createContext<{ Card: ComponentType<ComponentProps['Comments']['Card']>, header?: ReactNode } | undefined>(undefined)
|
|
9
|
+
|
|
10
|
+
function ComposerCard(props: ComponentProps['Comments']['Card']) {
|
|
11
|
+
const { Card, header } = useContext(COMPOSER_CARD)!
|
|
12
|
+
return <Card {...props}>{header && <div className="pm-ui-comment-target">{header}</div>}{props.children}</Card>
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Text selections and block/step anchors share the native card, editor and Post action. */
|
|
16
|
+
export function CommentComposer({ editor, editorComponent = components.Comments.Editor, children }: {
|
|
17
|
+
editor: BlockNoteEditor<any, any, any>, editorComponent?: ComponentType<ComponentProps['Comments']['Editor']>, children?: ReactNode,
|
|
18
|
+
}) {
|
|
19
|
+
const native = useComponentsContext()!
|
|
20
|
+
const value = useMemo(() => ({ ...native, Comments: { ...native.Comments, Card: ComposerCard, Editor: editorComponent } }), [native, editorComponent])
|
|
21
|
+
return <COMPOSER_CARD.Provider value={{ Card: native.Comments.Card, header: children }}><ComponentsContext.Provider value={value}>
|
|
22
|
+
<FloatingComposer newCommentEditor={editor} />
|
|
23
|
+
</ComponentsContext.Provider></COMPOSER_CARD.Provider>
|
|
24
|
+
}
|
|
@@ -1,21 +1,15 @@
|
|
|
1
1
|
import { useMemo } from 'react'
|
|
2
2
|
import { applyDocumentComponentAction } from '@lincyaw/kernel'
|
|
3
|
-
import type {
|
|
3
|
+
import type { PresmiumDocument } from '@lincyaw/kernel'
|
|
4
4
|
import { PmButton, PmMenu, PmSearchList } from '../components.tsx'
|
|
5
5
|
import type { ComponentPropertyMessages } from '../component-property-messages.ts'
|
|
6
|
+
import { componentDefinitionLabel } from './component-label.ts'
|
|
6
7
|
|
|
7
|
-
export
|
|
8
|
-
const title = typeof definition.parameterSchema === 'object' && typeof definition.parameterSchema.title === 'string' ? definition.parameterSchema.title.trim() : ''
|
|
9
|
-
if (title) return Array.from(title).slice(0, 80).join('')
|
|
10
|
-
const implementation = definition.implementation
|
|
11
|
-
const name = implementation.type === 'file' ? implementation.path.split('/').at(-1)?.replace(/\.(tsx?|jsx?|mjs|cjs)$/, '')
|
|
12
|
-
: implementation.type === 'plugin' ? implementation.name : implementation.specifier.split('/').at(-1)
|
|
13
|
-
return Array.from(name || definition.kind).slice(0, 80).join('')
|
|
14
|
-
}
|
|
8
|
+
export { componentDefinitionLabel } from './component-label.ts'
|
|
15
9
|
|
|
16
10
|
/** Selection is a proposal; only the caller's source-bound Apply changes a binding. */
|
|
17
11
|
export function ComponentMaterials({ document, blockId, selected, onSelect, onLocate, disabled, messages: t }: {
|
|
18
|
-
document:
|
|
12
|
+
document: PresmiumDocument, blockId: string, selected: string, onSelect(id: string): void,
|
|
19
13
|
onLocate(blockId: string): void, disabled: boolean, messages: ComponentPropertyMessages,
|
|
20
14
|
}) {
|
|
21
15
|
const current = document.blocks[blockId]
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
|
2
|
-
import { applyDocumentComponentAction, effectiveComponentParameters, isRecord, validateDocumentParameters } from '@lincyaw/kernel'
|
|
3
|
-
import type { CanonicalSource, DocumentComponentAction, DocumentParameterValidation, JsonObject,
|
|
2
|
+
import { applyDocumentComponentAction, effectiveComponentParameters, isRecord, randomUUID, validateDocumentParameters } from '@lincyaw/kernel'
|
|
3
|
+
import type { CanonicalSource, DocumentComponentAction, DocumentParameterValidation, JsonObject, PresmiumDocument } from '@lincyaw/kernel'
|
|
4
4
|
import { PmButton, PmDialog, PmNotice, PmSelect } from '../components.tsx'
|
|
5
5
|
import { useWorkbench, useWorkbenchState } from '../context.tsx'
|
|
6
|
-
import { isAgentChanging } from '../workbench.ts'
|
|
6
|
+
import { isAgentChanging } from '../workbench-state.ts'
|
|
7
7
|
import { COMPONENT_PROPERTY_MESSAGES } from '../component-property-messages.ts'
|
|
8
8
|
import type { ComponentPropertyMessages } from '../component-property-messages.ts'
|
|
9
9
|
import { componentPropertyAction, componentSource, rebaseComponentPropertyDraft, sameComponentSource } from '../component-properties.ts'
|
|
@@ -13,11 +13,11 @@ import { ComponentMaterials, componentDefinitionLabel } from './ComponentMateria
|
|
|
13
13
|
|
|
14
14
|
const subscribeEmpty = () => () => {}, snapshotEmpty = () => 0
|
|
15
15
|
const targetKey = (target: ComponentPropertyTarget) => JSON.stringify([target.identity, target.memberId, target.blockId, target.stepId ?? null])
|
|
16
|
-
function fresh(document:
|
|
16
|
+
function fresh(document: PresmiumDocument, source: CanonicalSource, target: ComponentPropertyTarget): ComponentPropertyDraft {
|
|
17
17
|
const block = document.blocks[target.blockId]
|
|
18
18
|
if (block?.type !== 'component') throw new Error('component-block-missing')
|
|
19
19
|
const value = effectiveComponentParameters(document, block.id, target.stepId).parameters
|
|
20
|
-
return { format: 1, id:
|
|
20
|
+
return { format: 1, id: randomUUID(), revision: 0, target, source, definitionId: block.definitionId, baseline: value, value,
|
|
21
21
|
composing: false, reset: false, updatedAt: new Date().toISOString() }
|
|
22
22
|
}
|
|
23
23
|
function message(error: unknown, t: ComponentPropertyMessages): string {
|
|
@@ -164,7 +164,7 @@ export function ComponentPropertiesDialog({ identity, blockId, stepId, onClose }
|
|
|
164
164
|
const submit = async (action: DocumentComponentAction, submitted?: ComponentPropertyDraft) => {
|
|
165
165
|
if (!canonical || !source?.version || !clean || current.current.busy) return
|
|
166
166
|
const expected = { identity, version: source.version, fingerprint: source.fingerprint! }, signature = JSON.stringify([canonical, action])
|
|
167
|
-
if (!intent.current || intent.current.signature !== signature || intent.current.draft !== submitted) intent.current = { signature, draft: submitted, id:
|
|
167
|
+
if (!intent.current || intent.current.signature !== signature || intent.current.draft !== submitted) intent.current = { signature, draft: submitted, id: randomUUID() }
|
|
168
168
|
const captured = intent.current, controller = new AbortController(), submittedKey = key
|
|
169
169
|
flight.current = controller; current.current.busy = true; setBusy(true); setError(undefined)
|
|
170
170
|
try {
|
|
@@ -229,10 +229,10 @@ export function ComponentPropertiesDialog({ identity, blockId, stepId, onClose }
|
|
|
229
229
|
{error && !((stale || materialStale || source?.error) && error === t.changed) && <PmNotice tone="danger">{error}</PmNotice>}
|
|
230
230
|
{!ready && error && <PmButton disabled={busy || !source} onClick={() => void retrySource()}>{t.retry}</PmButton>}
|
|
231
231
|
{!ready && !error && <PmNotice>{t.loading}</PmNotice>}
|
|
232
|
-
{ready && source?.error && <PmNotice tone="warn"
|
|
232
|
+
{ready && source?.error && <PmNotice tone="warn" action={<PmButton small disabled={busy} onClick={() => void retrySource()}>{t.retry}</PmButton>}>{t.changed}</PmNotice>}
|
|
233
233
|
{ready && (!document || block?.type !== 'component' || !definition) && <PmNotice tone="warn">{t.missing}</PmNotice>}
|
|
234
234
|
{ready && document && definition && block?.type === 'component' && page === 'materials' && <>
|
|
235
|
-
{materialStale && <PmNotice tone="warn"
|
|
235
|
+
{materialStale && <PmNotice tone="warn" action={<PmButton small disabled={!clean || busy} onClick={() => { if (canonical) { setMaterial(value => value && { ...value, source: canonical }); setError(undefined) } }}>{t.recheck}</PmButton>}>{t.changed}</PmNotice>}
|
|
236
236
|
<ComponentMaterials document={document} blockId={blockId} selected={material?.definitionId ?? block.definitionId} disabled={busy}
|
|
237
237
|
messages={t} onSelect={definitionId => setMaterial(value => ({ definitionId, source: value?.source ?? canonical! }))}
|
|
238
238
|
onLocate={id => { locateOnClose.current = true; close(); workbench.revealDocumentComponent(id, identity) }} />
|
|
@@ -241,8 +241,8 @@ export function ComponentPropertiesDialog({ identity, blockId, stepId, onClose }
|
|
|
241
241
|
<PmSelect label={t.scope} value={scope} onChange={event => { setScope(event.currentTarget.value as 'base' | 'step'); setError(undefined); setValidation(undefined) }}>
|
|
242
242
|
<option value="base">{t.base}</option><option value="step" disabled={!stepId}>{t.step}</option>
|
|
243
243
|
</PmSelect>
|
|
244
|
-
{stale && <PmNotice tone="warn"
|
|
245
|
-
{stored && (stale || error) && <PmButton small variant="
|
|
244
|
+
{stale && <PmNotice tone="warn" action={<PmButton small disabled={!clean || busy} onClick={recheck}>{t.recheck}</PmButton>}>{t.changed}</PmNotice>}
|
|
245
|
+
{stored && (stale || error) && <PmButton small variant="text" disabled={busy} onClick={() => void discardLocal()}>{t.discardChanges}</PmButton>}
|
|
246
246
|
{preview.effect && <span>{t.impact(preview.effect.affected.steps.length)}{scope === 'base' ? ` · ${t.preserved}` : ''}</span>}
|
|
247
247
|
{preview.error && <PmNotice tone="danger">{preview.error}</PmNotice>}
|
|
248
248
|
{bank?.status(target) === 'session-only' && <PmNotice tone="warn">{t.storage}</PmNotice>}
|
|
@@ -265,9 +265,9 @@ export function ComponentPropertiesDialog({ identity, blockId, stepId, onClose }
|
|
|
265
265
|
else { const reset = applyDocumentComponentAction(document, { type: 'component.step-parameters.reset', blockId, stepId: target.stepId! }).content; keep(effectiveComponentParameters(reset, blockId, target.stepId).parameters, false, true) }
|
|
266
266
|
} catch (error) { setError(message(error, t)) }
|
|
267
267
|
}}>{draft.reset ? t.edit : t.reset}</PmButton>}
|
|
268
|
-
<PmButton variant="
|
|
268
|
+
<PmButton variant="text" onClick={enterMaterials}>{t.materials}</PmButton>
|
|
269
269
|
</div>
|
|
270
|
-
{backupError && <PmNotice tone="warn"
|
|
270
|
+
{backupError && <PmNotice tone="warn" action={<PmButton small onClick={() => setBackupRead(value => value + 1)}>{t.retry}</PmButton>}>{t.storageRead}</PmNotice>}
|
|
271
271
|
{Boolean(backups?.unreadable) && <PmNotice tone="warn">{t.unreadable}</PmNotice>}
|
|
272
272
|
{Boolean(backups?.candidates.length) && <div className="component-properties__backups">
|
|
273
273
|
<PmSelect label={t.backup} value={backupIndex} disabled={backupBusy} onChange={event => setBackupIndex(Number(event.currentTarget.value))}>
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DocumentBlock,
|
|
1
|
+
import type { DocumentBlock, PresmiumDocument } from '@lincyaw/kernel'
|
|
2
2
|
import type { Locale } from '../messages.ts'
|
|
3
3
|
import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
|
|
4
4
|
import { BLOCK_PREVIEW_MESSAGES } from './block-preview-messages.ts'
|
|
@@ -14,9 +14,10 @@ const authorText = (value: unknown) => typeof value === 'string' && value.trim()
|
|
|
14
14
|
* A readable source fallback while the independent component snapshot is unavailable. It names the content only by what
|
|
15
15
|
* the author wrote (a title) or by its kind, never by its code (the component, file or definition names).
|
|
16
16
|
*/
|
|
17
|
-
export function DocumentBlockFallback({ block, document, locale }: { block: DocumentBlock, document:
|
|
17
|
+
export function DocumentBlockFallback({ block, document, locale }: { block: DocumentBlock, document: PresmiumDocument, locale: Locale }) {
|
|
18
18
|
const t = DOCUMENT_EDITOR_MESSAGES[locale], p = BLOCK_PREVIEW_MESSAGES[locale]
|
|
19
|
-
if (isDiagram(block, document)) return <PmNotice>{t.diagram(block.type === 'code' && block.title || '')}</PmNotice>
|
|
19
|
+
if (isDiagram(block, document.metadata.plugins)) return <PmNotice>{t.diagram(block.type === 'code' && block.title || '')}</PmNotice>
|
|
20
|
+
if (block.type === 'embed') return <PmNotice>{t.syncedBlock(block.source.document)}</PmNotice>
|
|
20
21
|
if (block.type === 'code') return <PmNotice>{t.codeReference(block.title ?? block.origin?.anchor ?? block.language)}</PmNotice>
|
|
21
22
|
if (block.type !== 'component') return null
|
|
22
23
|
const definition = document.definitions[block.definitionId]
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useCallback, useEffect, useId, useRef, useState } from 'react'
|
|
1
|
+
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
|
|
2
2
|
import type { CSSProperties, ReactNode } from 'react'
|
|
3
3
|
import type { BlockPreviewCommand } from '@lincyaw/kernel'
|
|
4
4
|
import { toBlockPreviewPlaybackCancelled, toBlockPreviewPlaybackRequest, toBlockPreviewPosition } from '@lincyaw/kernel'
|
|
@@ -10,6 +10,7 @@ import { BLOCK_PREVIEW_MESSAGES } from './block-preview-messages.ts'
|
|
|
10
10
|
import { documentBlockSection, DocumentStepNarration } from './DocumentStepNarration.tsx'
|
|
11
11
|
import { DocumentBlockPlayback } from './block-playback.ts'
|
|
12
12
|
import { ComponentPropertiesDialog } from './ComponentPropertiesDialog.tsx'
|
|
13
|
+
import { PlaceCommentButton } from './PlaceComment.tsx'
|
|
13
14
|
import { COMPONENT_PROPERTY_MESSAGES } from '../component-property-messages.ts'
|
|
14
15
|
|
|
15
16
|
interface Snapshot { address: string, revision: string }
|
|
@@ -26,11 +27,13 @@ export function DocumentBlockPreview({ blockId, fallback }: { blockId: string, f
|
|
|
26
27
|
const position = useWorkbenchState(state => state.position)
|
|
27
28
|
const navigation = useWorkbenchState(state => state.documentPositionToken)
|
|
28
29
|
const navigationIntent = useWorkbenchState(state => state.documentPositionIntent)
|
|
30
|
+
const block = source?.content?.blocks[blockId]
|
|
31
|
+
const definition = block?.type === 'component' ? source?.content?.definitions[block.definitionId] : undefined
|
|
29
32
|
const sectionId = source?.content && documentBlockSection(source.content, blockId)
|
|
30
33
|
const section = sectionId ? source?.content?.sections[sectionId] : undefined
|
|
31
34
|
const stepId = section?.stepOrder[position && position.section === sectionId ? position.step : 0] ?? section?.stepOrder[0]
|
|
32
|
-
const [narrationOpen, setNarrationOpen] = useState(() => Boolean(workbench.
|
|
33
|
-
|| source?.identity && stepId && (workbench.
|
|
35
|
+
const [narrationOpen, setNarrationOpen] = useState(() => Boolean(workbench.editing.pendingField(blockId, source?.identity)
|
|
36
|
+
|| source?.identity && stepId && (workbench.production.timingDraft(stepId, 'minimumHoldMs', source.identity, source.reset) || workbench.production.timingDraft(stepId, 'trailingPauseMs', source.identity, source.reset)))), narrationPanel = useId()
|
|
34
37
|
const root = useRef<HTMLElement>(null), viewport = useRef<HTMLDivElement>(null), frame = useRef<HTMLIFrameElement | null>(null)
|
|
35
38
|
const mountFrame = useCallback((element: HTMLIFrameElement | null) => {
|
|
36
39
|
frame.current = element
|
|
@@ -106,6 +109,9 @@ export function DocumentBlockPreview({ blockId, fallback }: { blockId: string, f
|
|
|
106
109
|
// A saved version changes only the runtime frame; it never resets the native editor.
|
|
107
110
|
address?.searchParams.set('presmium-block-version', loadedVersion ?? '')
|
|
108
111
|
address?.searchParams.set('presmium-block-refresh', `${loadedProject}:${loadedAttempt}`)
|
|
112
|
+
// Pin the first cursor to this frame's lifetime; playback and step selection keep the same URL.
|
|
113
|
+
const initialStep = useMemo(() => stepId, [address?.href, enabled])
|
|
114
|
+
if (initialStep) address?.searchParams.set('presmium-block-step', initialStep)
|
|
109
115
|
const src = address?.href, origin = address?.origin
|
|
110
116
|
const command = useCallback((action: 'seek' | 'pause', at?: 'start' | 'end', token = navigation) => {
|
|
111
117
|
if (!origin || !state.snapshot || !sectionId || !stepId) return
|
|
@@ -216,7 +222,8 @@ export function DocumentBlockPreview({ blockId, fallback }: { blockId: string, f
|
|
|
216
222
|
return <section ref={root} className="pm-ui-block-preview" data-block-preview={blockId} data-status={state.status} contentEditable={false}>
|
|
217
223
|
<header className="pm-ui-block-preview__header"><span className="pm-ui-block-preview__label" role={state.status === 'failed' ? 'status' : undefined}><PmIcon name="slides" />{state.status === 'failed' ? t.previewFailure : old && state.snapshot ? t.previewPrevious : state.status === 'preparing' ? p.preparing : state.status === 'loading' ? t.previewLoading : t.previewSnapshot}</span>
|
|
218
224
|
<span className="pm-ui-block-preview__actions">
|
|
219
|
-
{
|
|
225
|
+
{sectionId && stepId && <PlaceCommentButton blockId={blockId} sectionId={sectionId} stepId={stepId} stepIndex={section ? section.stepOrder.indexOf(stepId) + 1 : 1} onPause={pause} />}
|
|
226
|
+
{source && block?.type === 'component' && definition?.kind !== 'scene' && <PmIconButton small icon="sliders" label={COMPONENT_PROPERTY_MESSAGES[locale].properties}
|
|
220
227
|
data-component-properties={blockId} disabled={!source.identity || workbench.client.capabilities?.readOnly} onClick={() => { if (source.identity && !workbench.client.capabilities?.readOnly) setProperties({ identity: source.identity, stepId }) }} />}
|
|
221
228
|
{workbench.client.capabilities?.narration !== false && <PmIconButton small icon="captions" label={t.stepCaptions} aria-expanded={narrationOpen} aria-controls={narrationOpen ? narrationPanel : undefined} aria-pressed={narrationOpen} disabled={!stepId} onClick={() => {
|
|
222
229
|
pause()
|
|
@@ -1,22 +1,29 @@
|
|
|
1
1
|
import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
|
|
2
2
|
import type { FocusEvent, ReactNode } from 'react'
|
|
3
|
+
import { documentAnchorOrder, isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
|
|
4
|
+
import type { DocumentPlaceAnchor, PresmiumDocument } from '@lincyaw/kernel'
|
|
3
5
|
import { CommentEditorSubmitExtension, CommentsExtension } from '@blocknote/core/comments'
|
|
4
6
|
import { components } from '@blocknote/mantine'
|
|
5
7
|
import { FloatingThreadController, getReferenceText, Thread, useBlockNoteEditor, useCreateBlockNote, useEditorState, useExtension, useExtensionState, useThreads } from '@blocknote/react'
|
|
6
8
|
import type { ComponentProps, ThreadProps } from '@blocknote/react'
|
|
7
9
|
import type { Locale } from '../messages.ts'
|
|
8
10
|
import { PmButton, PmEmpty, PmNotice, PmSelect } from '../components.tsx'
|
|
11
|
+
import { isApprovalTarget } from '../approvals.tsx'
|
|
12
|
+
import { useWorkbenchState } from '../context.tsx'
|
|
9
13
|
import { enterSubmits } from './comments.ts'
|
|
10
14
|
import type { DocumentCommentEditorHandle, DocumentThreadStore } from './comments.ts'
|
|
11
15
|
import type { CommentDrafts, CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, CommentDraftOperation } from './comment-drafts.ts'
|
|
12
|
-
import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
|
|
13
|
-
import {
|
|
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'
|
|
19
|
+
import { createRichProjection, fallbackText, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
|
|
14
20
|
import { commentEditorSchema } from './schema.tsx'
|
|
15
21
|
import type { DocumentEditorBlock } from './schema.tsx'
|
|
16
22
|
import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
|
|
23
|
+
import { componentDefinitionLabel } from './component-label.ts'
|
|
17
24
|
import { commentFloating } from './popover.tsx'
|
|
18
25
|
|
|
19
|
-
export const COMMENT_EDITOR_CONTEXT = createContext<{ store: DocumentThreadStore, locale: Locale, sidebar: boolean, getPositionToken?(): string | undefined, onDraftRestore?(): void } | undefined>(undefined)
|
|
26
|
+
export const COMMENT_EDITOR_CONTEXT = createContext<{ store: DocumentThreadStore, locale: Locale, sidebar: boolean, readOnly?: boolean, getPositionToken?(): string | undefined, onDraftRestore?(): void, openComments?(): void } | undefined>(undefined)
|
|
20
27
|
const THREAD_CONTEXT = createContext<string | undefined>(undefined)
|
|
21
28
|
const emptySubscribe = () => () => {}
|
|
22
29
|
const emptyState = { candidates: [], pending: false, failed: false, reading: false } as const
|
|
@@ -32,12 +39,14 @@ export function DocumentCommentThread(props: ThreadProps) {
|
|
|
32
39
|
|
|
33
40
|
/** Keep the native controller and reply editor while body selection owns the pointer. */
|
|
34
41
|
export function DocumentFloatingThreadController() {
|
|
35
|
-
const editor = useBlockNoteEditor(), { selectedThreadId } = useExtensionState(CommentsExtension)
|
|
42
|
+
const editor = useBlockNoteEditor(), { selectedThreadId, threadPositions } = useExtensionState(CommentsExtension)
|
|
36
43
|
const empty = useEditorState({ editor, on: 'selection', selector: ({ editor }) => editor.prosemirrorState.selection.empty })
|
|
37
44
|
const [selecting, setSelecting] = useState(false)
|
|
38
45
|
const blocked = selecting || !empty
|
|
46
|
+
// A place thread has no text mark; it belongs to the sidebar only and must not open a floating card.
|
|
47
|
+
const positioned = Boolean(selectedThreadId && threadPositions.has(selectedThreadId))
|
|
39
48
|
const shown = useRef(false), thread = useRef(selectedThreadId)
|
|
40
|
-
shown.current =
|
|
49
|
+
shown.current = positioned && !blocked
|
|
41
50
|
thread.current = selectedThreadId
|
|
42
51
|
// The pointer that last pressed commented text, and the line of the thread chosen from it (the first line without one).
|
|
43
52
|
const point = useRef<{ x: number, y: number }>(), line = useRef<{ thread: string, index: number }>()
|
|
@@ -101,26 +110,69 @@ export function DocumentFloatingThreadController() {
|
|
|
101
110
|
return rects[Math.min(line.current.index, rects.length - 1)]
|
|
102
111
|
}), [editor])
|
|
103
112
|
return <FloatingThreadController floatingThread={DocumentCommentThread} floatingUIOptions={{
|
|
104
|
-
useFloatingOptions: { ...floating, open:
|
|
113
|
+
useFloatingOptions: { ...floating, open: positioned && !blocked },
|
|
105
114
|
elementProps: { className: blocked ? 'pm-ui-comment-hidden' : undefined },
|
|
106
115
|
}} />
|
|
107
116
|
}
|
|
108
117
|
|
|
118
|
+
export function placeReference(document: PresmiumDocument | undefined, anchor: DocumentPlaceAnchor, t: typeof DOCUMENT_EDITOR_MESSAGES['zh-CN']): string {
|
|
119
|
+
if (!document) return ''
|
|
120
|
+
const block = document.blocks[anchor.blockId]
|
|
121
|
+
let label: string
|
|
122
|
+
if (block?.type === 'component') {
|
|
123
|
+
const definition = document.definitions[block.definitionId]
|
|
124
|
+
const author = typeof block.parameters.title === 'string' ? block.parameters.title.trim() : ''
|
|
125
|
+
const data = definition?.data && typeof definition.data.title === 'string' ? definition.data.title.trim() : ''
|
|
126
|
+
const schema = definition && typeof definition.parameterSchema === 'object' && typeof definition.parameterSchema.title === 'string' ? definition.parameterSchema.title.trim() : ''
|
|
127
|
+
const name = author || data || schema || (definition ? componentDefinitionLabel(definition) : block.definitionId)
|
|
128
|
+
label = definition?.kind === 'scene' ? t.animation(name) : t.component(name)
|
|
129
|
+
} else if (block?.type === 'code') label = t.codeReference(block.title ?? block.origin?.anchor ?? block.language)
|
|
130
|
+
else if (block?.type === 'image') label = block.alt || t.block
|
|
131
|
+
else if (block?.type === 'text') label = (block.content[0] ? Array.from(fallbackText(block.content[0]).replace(/\s+/g, ' ').trim()).slice(0, 40).join('') : '') || t.block
|
|
132
|
+
else if (block?.type === 'container') label = block.properties.title || t.block
|
|
133
|
+
else label = t.block
|
|
134
|
+
if (anchor.stepId === undefined) return t.placeCommentReference(label)
|
|
135
|
+
const step = document.steps[anchor.stepId], section = step ? document.sections[step.sectionId] : undefined
|
|
136
|
+
return t.placeCommentReference(label, step && section ? section.stepOrder.indexOf(step.id) + 1 : 0)
|
|
137
|
+
}
|
|
138
|
+
|
|
109
139
|
/** Native Thread composition, with the same public focus/blur and position ordering as the sidebar. */
|
|
110
140
|
export function DocumentThreadsSidebar({ children }: { children?: ReactNode }) {
|
|
111
141
|
const editor = useBlockNoteEditor(), comments = useExtension(CommentsExtension), threads = useThreads()
|
|
112
142
|
const { selectedThreadId, threadPositions } = useExtensionState(CommentsExtension)
|
|
113
|
-
const
|
|
143
|
+
const context = useContext(COMMENT_EDITOR_CONTEXT), t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
|
|
144
|
+
const document = useWorkbenchState(state => state.authoring?.content) ?? context?.store.document
|
|
145
|
+
const places = useMemo(() => document ? documentAnchorOrder(document) : new Map<string, number>(), [document])
|
|
146
|
+
const place = (threadId: string): number => {
|
|
147
|
+
const anchor = context?.store.anchorOf(threadId)
|
|
148
|
+
if (!anchor) return Number.MAX_VALUE
|
|
149
|
+
if (isDocumentPlaceAnchor(anchor)) {
|
|
150
|
+
const order = places.get(anchor.blockId)
|
|
151
|
+
const step = anchor.stepId === undefined ? undefined : document?.steps[anchor.stepId]
|
|
152
|
+
const section = step && document ? document.sections[step.sectionId] : undefined
|
|
153
|
+
return order === undefined ? Number.MAX_VALUE : order * 1_000_000 + (step && section ? section.stepOrder.indexOf(step.id) : 0)
|
|
154
|
+
}
|
|
155
|
+
const order = places.get(anchor.from.blockId)
|
|
156
|
+
return order === undefined ? Number.MAX_VALUE : order * 1_000_000 + Math.min(999_999, anchor.from.offset)
|
|
157
|
+
}
|
|
158
|
+
const reference = (threadId: string): string | undefined => {
|
|
159
|
+
const anchor = context?.store.anchorOf(threadId)
|
|
160
|
+
return anchor && isDocumentPlaceAnchor(anchor) ? placeReference(document, anchor, t) : getReferenceText(editor, threadPositions.get(threadId))
|
|
161
|
+
}
|
|
162
|
+
const orphaned = (threadId: string): boolean => {
|
|
163
|
+
const anchor = context?.store.anchorOf(threadId)
|
|
164
|
+
return !(anchor && isDocumentPlaceAnchor(anchor)) && !threadPositions.has(threadId)
|
|
165
|
+
}
|
|
166
|
+
const ordered = [...threads.values()].sort((a, b) => place(a.id) - place(b.id) || a.createdAt.getTime() - b.createdAt.getTime())
|
|
114
167
|
const focus = (id: string, event: FocusEvent) => { if (!(event.target as HTMLElement).closest('.bn-action-toolbar')) comments.selectThread(id) }
|
|
115
168
|
const blur = (event: FocusEvent) => {
|
|
116
169
|
const next = event.relatedTarget
|
|
117
|
-
if (!next || next.closest('.bn-action-toolbar')) return
|
|
170
|
+
if (!next || isApprovalTarget(next) || next.closest('.bn-action-toolbar')) return
|
|
118
171
|
const parent = next.closest('.bn-thread')
|
|
119
172
|
if (!parent || !(event.target instanceof Node) || !parent.contains(event.target)) comments.selectThread(undefined)
|
|
120
173
|
}
|
|
121
|
-
const context = useContext(COMMENT_EDITOR_CONTEXT), t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
|
|
122
174
|
return <div className="bn-threads-sidebar">{children}<CommentDraftRetrieval />{!ordered.length && <PmEmpty icon="comment">{t.commentsEmpty}</PmEmpty>}{ordered.map(thread => <DocumentCommentThread key={thread.id} thread={thread}
|
|
123
|
-
selected={selectedThreadId === thread.id} orphaned={
|
|
175
|
+
selected={selectedThreadId === thread.id} orphaned={orphaned(thread.id)} referenceText={reference(thread.id)}
|
|
124
176
|
onFocus={event => focus(thread.id, event)} onBlur={blur} tabIndex={0} />)}</div>
|
|
125
177
|
}
|
|
126
178
|
|
|
@@ -143,12 +195,11 @@ export function DraftChoices({ candidates, disabled, onRecover, onDiscard, previ
|
|
|
143
195
|
try { await action(candidate) } finally { setBusy(false) }
|
|
144
196
|
}
|
|
145
197
|
if (!candidates.length) return null
|
|
146
|
-
return <PmNotice tone="accent"
|
|
198
|
+
return <PmNotice tone="accent" action={<>{onRecover && <PmButton small variant="primary" disabled={!candidate || disabled || busy || candidate.storage === 'session' || canRecover && !canRecover(candidate)} loading={busy} onClick={() => void act(onRecover)}>{t.commentRecover}</PmButton>}
|
|
199
|
+
<PmButton small disabled={!candidate || disabled || busy} onClick={() => void act(onDiscard)}>{t.commentDiscard}</PmButton></>}><PmSelect label={t.commentDrafts} value={candidate ? selected : ''} disabled={disabled || busy} onChange={event => setSelected(event.target.value)}>
|
|
147
200
|
<option value="">{t.commentChooseDraft}</option>{candidates.map(value => <option key={referenceKey(value)} value={referenceKey(value)}>{new Date(value.updatedAt).toLocaleString(context?.locale)} · {isNewCommentDraft(value.target) ? t.commentNewDraft : value.target.commentId ? t.commentEditDraft : t.commentReplyDraft}{value.storage === 'session' ? ` · ${t.commentSessionOnly}` : ''}</option>)}
|
|
148
201
|
</PmSelect>{candidate && preview && <DraftPreview candidate={candidate} />}
|
|
149
202
|
{candidate && unavailableMessage && canRecover && !canRecover(candidate) && <PmNotice tone="warn">{unavailableMessage}</PmNotice>}
|
|
150
|
-
<span className="pmw-notice__actions">{onRecover && <PmButton small variant="primary" disabled={!candidate || disabled || busy || candidate.storage === 'session' || canRecover && !canRecover(candidate)} loading={busy} onClick={() => void act(onRecover)}>{t.commentRecover}</PmButton>}
|
|
151
|
-
<PmButton small disabled={!candidate || disabled || busy} onClick={() => void act(onDiscard)}>{t.commentDiscard}</PmButton></span>
|
|
152
203
|
</PmNotice>
|
|
153
204
|
}
|
|
154
205
|
|
|
@@ -174,7 +225,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
|
|
|
174
225
|
return value
|
|
175
226
|
}, [props.editor, drafts])
|
|
176
227
|
const rich = useMemo(() => ({ current: record.rich }), [record])
|
|
177
|
-
const composerId = useRef(
|
|
228
|
+
const composerId = useRef(randomUUID())
|
|
178
229
|
const state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState))
|
|
179
230
|
useLayoutEffect(() => {
|
|
180
231
|
if (!context || !threadId) return
|
|
@@ -242,7 +293,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
|
|
|
242
293
|
|| props.editor.prosemirrorState.selection !== native.selection || context.getPositionToken?.() !== position || record.current !== own
|
|
243
294
|
|| context.store.draftTargetState(target) === 'unavailable') throw new Error('client-comment-composer-changed')
|
|
244
295
|
}
|
|
245
|
-
if (own && !await drafts.confirm(own)) return
|
|
296
|
+
if (own && !await waitForDraft(drafts.confirm(own), operation?.signal)) return
|
|
246
297
|
owns()
|
|
247
298
|
const value = await drafts.recover(candidate, target, version, { signal: operation?.signal, guard: owns })
|
|
248
299
|
if (!value) return
|
|
@@ -258,11 +309,30 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
|
|
|
258
309
|
if (!operation) await drafts.discard(candidate)
|
|
259
310
|
return value
|
|
260
311
|
}
|
|
312
|
+
const discardActive = async (candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean> => {
|
|
313
|
+
const own = record.current, version = context?.store.version, before = input.current, native = props.editor.prosemirrorState, position = context?.getPositionToken?.()
|
|
314
|
+
if (!drafts || !context || !target || !version || !own || own.id !== candidate.id || own.revision !== candidate.revision) return false
|
|
315
|
+
const guard = () => {
|
|
316
|
+
context.store.beforeAction?.()
|
|
317
|
+
if (!active.current || !current.current.editable || context.store.version !== version || composing.current || submitting.current || input.current !== before || record.current !== own
|
|
318
|
+
|| props.editor.prosemirrorView.isDestroyed || props.editor.prosemirrorView.composing || props.editor.prosemirrorState.doc !== native.doc
|
|
319
|
+
|| props.editor.prosemirrorState.selection !== native.selection || context.getPositionToken?.() !== position) throw new Error('client-comment-composer-changed')
|
|
320
|
+
}
|
|
321
|
+
const saved = target.commentId ? context.store.threadSnapshot(target.threadId)?.comments.find(value => value.id === target.commentId && !value.deletedAt) : undefined
|
|
322
|
+
if (target.commentId && !saved?.content) return false
|
|
323
|
+
return discardNativeCommentDraft(drafts, candidate, operation, guard, () => {
|
|
324
|
+
suppress.current = true
|
|
325
|
+
try {
|
|
326
|
+
props.editor.replaceBlocks(props.editor.document, saved?.content ? productRichTextToNative(saved.content, rich.current) : [{ type: 'paragraph', content: [] }])
|
|
327
|
+
record.current = undefined; input.current++; handle?.restoreBaseline(saved ? commentDraftBaseline(saved) : undefined); setRevision(value => value + 1)
|
|
328
|
+
} finally { suppress.current = false }
|
|
329
|
+
})
|
|
330
|
+
}
|
|
261
331
|
useLayoutEffect(() => {
|
|
262
332
|
if (!drafts || !target || !props.editable) return
|
|
263
333
|
return drafts.registerComposer({ id: composerId.current, target,
|
|
264
334
|
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 } },
|
|
265
|
-
targetState: () => context?.store.draftTargetState(target) ?? 'unavailable', restore: recover })
|
|
335
|
+
targetState: () => context?.store.draftTargetState(target) ?? 'unavailable', restore: recover, discard: discardActive })
|
|
266
336
|
}, [drafts, handle, props.editor, props.editable])
|
|
267
337
|
const composition = (value: boolean) => {
|
|
268
338
|
composing.current = value
|
|
@@ -276,7 +346,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
|
|
|
276
346
|
<MantineCommentEditor {...props} />
|
|
277
347
|
{recoveryFailure && <PmNotice tone="warn">{t.commentRecoveryChanged}</PmNotice>}
|
|
278
348
|
{failure && <PmNotice tone="danger">{failure === 'changed' ? t.commentChanged : t.commentUnavailable}</PmNotice>}
|
|
279
|
-
{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.
|
|
349
|
+
{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) }} />}
|
|
280
350
|
{drafts && props.editable && state.failed && !context?.sidebar && <PmNotice tone="warn">{t.commentBackupFailed}</PmNotice>}
|
|
281
351
|
</div>
|
|
282
352
|
}
|
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { useEffect, useMemo, useRef } from 'react'
|
|
2
|
+
import { markAgentTargets } from './agent-targets.ts'
|
|
2
3
|
import type { Transaction } from '@tiptap/pm/state'
|
|
4
|
+
import { TextSelection } from '@tiptap/pm/state'
|
|
3
5
|
import { closeHistory } from '@tiptap/pm/history'
|
|
4
|
-
import { allocateDocumentPage } from '@lincyaw/kernel'
|
|
5
|
-
import type { Member,
|
|
6
|
+
import { allocateDocumentPage, randomUUID } from '@lincyaw/kernel'
|
|
7
|
+
import type { Member, PresmiumDocument } from '@lincyaw/kernel'
|
|
6
8
|
import type { Locale } from '../messages.ts'
|
|
7
9
|
import { BlockNoteSurface } from './BlockNoteSurface.tsx'
|
|
8
10
|
import type { CommentDrafts } from './comment-drafts.ts'
|
|
@@ -12,22 +14,34 @@ import type { NativePageCreation } from './projection.ts'
|
|
|
12
14
|
import { captureRichBaseline } from './rich-text.ts'
|
|
13
15
|
import { captureTableIdentities, seedTableIdentities } from './table-identities.ts'
|
|
14
16
|
import type { DocumentNodeViews, NativeDocumentEditor } from './schema.tsx'
|
|
15
|
-
import { nativeEditingCursor } from './selection.ts'
|
|
16
|
-
import type { NativeDocumentSelection } from './selection.ts'
|
|
17
|
+
import { nativeEditingCursor, nativeTextPoint, nativeTextPosition } from './selection.ts'
|
|
18
|
+
import type { NativeDocumentSelection, NativeTextPoint } from './selection.ts'
|
|
19
|
+
import { documentInsertionPlace } from './insertion-place.ts'
|
|
20
|
+
import type { DocumentInsertionPlace } from './insertion-place.ts'
|
|
21
|
+
import { effectiveOf } from '../effective-settings.ts'
|
|
17
22
|
|
|
18
23
|
export interface DocumentEditingPosition {
|
|
19
24
|
nativeBlockId: string
|
|
20
25
|
sectionId: string
|
|
21
26
|
position: number
|
|
22
27
|
}
|
|
28
|
+
/** Who takes the slash menu's request for an animation where it was opened; while none is available the menu has no such item. */
|
|
29
|
+
export interface DocumentAnimationRequests {
|
|
30
|
+
available(): boolean
|
|
31
|
+
request(place: DocumentInsertionPlace): void
|
|
32
|
+
}
|
|
23
33
|
export interface DocumentEditorCommands {
|
|
24
34
|
insertPage(after: string | undefined, title: string): NativePageCreation
|
|
25
|
-
rememberComponentConfiguration(document:
|
|
35
|
+
rememberComponentConfiguration(document: PresmiumDocument): void
|
|
36
|
+
handleAnimationRequests(requests: DocumentAnimationRequests | undefined): void
|
|
26
37
|
}
|
|
27
38
|
|
|
28
39
|
export interface DocumentEditorProps {
|
|
40
|
+
agentActivities?: import('@lincyaw/kernel').AgentActivity[]
|
|
29
41
|
identity: string
|
|
30
|
-
document:
|
|
42
|
+
document: PresmiumDocument
|
|
43
|
+
/** What the document inherits from its ancestors: its content language and plugins when it sets none. */
|
|
44
|
+
inherited?: import('@lincyaw/kernel').DocumentDefaults
|
|
31
45
|
version?: string
|
|
32
46
|
member?: Member
|
|
33
47
|
commentDrafts?: CommentDrafts
|
|
@@ -37,7 +51,7 @@ export interface DocumentEditorProps {
|
|
|
37
51
|
acknowledged?: boolean
|
|
38
52
|
getDocumentAcknowledged?(): boolean
|
|
39
53
|
/** Read sibling field edits before their React render has committed. */
|
|
40
|
-
getDocument?():
|
|
54
|
+
getDocument?(): PresmiumDocument | undefined
|
|
41
55
|
/** Ownership of a deferred native focus notification. */
|
|
42
56
|
getPositionToken?(): string
|
|
43
57
|
/** Display-only URL resolution; native block URLs keep their canonical source locations. */
|
|
@@ -47,7 +61,7 @@ export interface DocumentEditorProps {
|
|
|
47
61
|
locale: Locale
|
|
48
62
|
readOnly?: boolean
|
|
49
63
|
nodeViews?: DocumentNodeViews
|
|
50
|
-
onChange(document:
|
|
64
|
+
onChange(document: PresmiumDocument): void
|
|
51
65
|
onSelection?(selection: NativeDocumentSelection | undefined): void
|
|
52
66
|
onEditingPosition?(position: DocumentEditingPosition, editor: NativeDocumentEditor): void
|
|
53
67
|
onReady?(editor: NativeDocumentEditor | undefined, commands?: DocumentEditorCommands): void
|
|
@@ -56,11 +70,12 @@ export interface DocumentEditorProps {
|
|
|
56
70
|
onError?(error: Error): void
|
|
57
71
|
commentsPortal?: HTMLElement | null
|
|
58
72
|
onCommentDraftRestore?(): void
|
|
73
|
+
onOpenComments?(): void
|
|
59
74
|
}
|
|
60
75
|
|
|
61
76
|
/** A source version reset replaces the editor; its own save receipts never replace it. */
|
|
62
77
|
export function DocumentEditor(props: DocumentEditorProps) {
|
|
63
|
-
const projection = useMemo(() => createDocumentProjection(props.document), [props.identity, props.reset])
|
|
78
|
+
const projection = useMemo(() => createDocumentProjection(props.document, effectiveOf(props.document, props.inherited).metadata.plugins), [props.identity, props.reset])
|
|
64
79
|
useEffect(() => rememberComponentConfiguration(projection, props.document), [projection, props.version])
|
|
65
80
|
const comments = useMemo(() => new DocumentThreadStore(props.document, props.member, props.version, props.identity, props.commentDrafts), [props.identity, props.reset])
|
|
66
81
|
useEffect(() => {
|
|
@@ -73,13 +88,31 @@ export function DocumentEditor(props: DocumentEditorProps) {
|
|
|
73
88
|
return () => comments.close()
|
|
74
89
|
}, [comments])
|
|
75
90
|
const current = useRef(props), editor = useRef<NativeDocumentEditor>(), unsubscribe = useRef<() => void>()
|
|
91
|
+
const animationRequests = useRef<DocumentAnimationRequests>()
|
|
76
92
|
const projectedDocument = useRef<NativeDocumentEditor['prosemirrorState']['doc']>()
|
|
77
93
|
const pendingTransaction = useRef<Transaction>()
|
|
78
94
|
const focusFrame = useRef<number>()
|
|
79
95
|
const binding = useRef(projection)
|
|
80
96
|
const active = useRef(projection)
|
|
97
|
+
const editorIdentity = useRef(props.identity)
|
|
98
|
+
const retainedSelection = useRef<{ from: NativeTextPoint, to: NativeTextPoint }>()
|
|
99
|
+
const previous = editor.current
|
|
100
|
+
if (binding.current !== projection && editorIdentity.current === props.identity && previous?.isFocused() && !previous.prosemirrorView.composing) {
|
|
101
|
+
const from = nativeTextPoint(previous, previous.prosemirrorState.selection.anchor), to = nativeTextPoint(previous, previous.prosemirrorState.selection.head)
|
|
102
|
+
if (from && to) retainedSelection.current = { from, to }
|
|
103
|
+
}
|
|
81
104
|
active.current = projection
|
|
82
105
|
current.current = props
|
|
106
|
+
useEffect(() => {
|
|
107
|
+
const root = editor.current?.prosemirrorView.dom
|
|
108
|
+
if (!root || !props.agentActivities?.length) return
|
|
109
|
+
let unmark = () => {}
|
|
110
|
+
const paint = () => { unmark(); unmark = markAgentTargets(root, active.current, current.current.document, current.current.agentActivities ?? []) }
|
|
111
|
+
paint()
|
|
112
|
+
const observer = new MutationObserver(paint)
|
|
113
|
+
observer.observe(root, { childList: true, subtree: true })
|
|
114
|
+
return () => { observer.disconnect(); unmark() }
|
|
115
|
+
}, [props.agentActivities, projection, props.version])
|
|
83
116
|
const cancelFocus = () => { if (focusFrame.current !== undefined) cancelAnimationFrame(focusFrame.current); focusFrame.current = undefined }
|
|
84
117
|
const reportPosition = () => {
|
|
85
118
|
const value = editor.current
|
|
@@ -113,7 +146,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
|
|
|
113
146
|
if (!latest || current.current.getDocumentVersion && current.current.getDocumentVersion() === undefined) return
|
|
114
147
|
syncComments()
|
|
115
148
|
const document = nativeDocumentToProduct(editor.current.document, projection, latest)
|
|
116
|
-
const threads = comments.snapshot(editor.current)
|
|
149
|
+
const threads = comments.snapshot(editor.current, document)
|
|
117
150
|
if (Object.keys(threads).length) document.comments = threads
|
|
118
151
|
else delete document.comments
|
|
119
152
|
current.current.onChange(document)
|
|
@@ -123,9 +156,18 @@ export function DocumentEditor(props: DocumentEditorProps) {
|
|
|
123
156
|
reportPosition()
|
|
124
157
|
} catch (error) { current.current.onError?.(error instanceof Error ? error : new Error(String(error))) }
|
|
125
158
|
}
|
|
126
|
-
return <BlockNoteSurface identity={props.identity} reset={props.reset} initialContent={projection.content} locale={props.locale} contentLang={props.document.metadata.lang
|
|
159
|
+
return <BlockNoteSurface identity={props.identity} reset={props.reset} initialContent={projection.content} locale={props.locale} contentLang={effectiveOf(props.document, props.inherited).metadata.lang} readOnly={props.readOnly}
|
|
127
160
|
resolveAssetURL={props.resolveAssetURL} uploadImage={props.uploadImage}
|
|
128
|
-
comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection}
|
|
161
|
+
comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} onOpenComments={() => current.current.onOpenComments?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection}
|
|
162
|
+
animationRequest={{
|
|
163
|
+
available: () => !current.current.readOnly && binding.current === projection && active.current === projection && Boolean(animationRequests.current?.available()),
|
|
164
|
+
request: value => {
|
|
165
|
+
if (value !== editor.current || binding.current !== projection || active.current !== projection) return
|
|
166
|
+
const place = documentInsertionPlace(value, projection)
|
|
167
|
+
if (place) animationRequests.current?.request(place)
|
|
168
|
+
},
|
|
169
|
+
}}
|
|
170
|
+
onSectionLink={sectionId => {
|
|
129
171
|
if (!current.current.onSectionLink?.(sectionId)) return false
|
|
130
172
|
// The click placed the caret in the link; it follows the reader to the page they asked for.
|
|
131
173
|
const value = editor.current
|
|
@@ -147,7 +189,17 @@ export function DocumentEditor(props: DocumentEditorProps) {
|
|
|
147
189
|
comments.restoreAnchors(value)
|
|
148
190
|
binding.current = projection
|
|
149
191
|
editor.current = value
|
|
192
|
+
editorIdentity.current = props.identity
|
|
150
193
|
projectedDocument.current = value.prosemirrorState.doc
|
|
194
|
+
const selection = retainedSelection.current
|
|
195
|
+
retainedSelection.current = undefined
|
|
196
|
+
if (selection) {
|
|
197
|
+
const from = nativeTextPosition(value, selection.from), to = nativeTextPosition(value, selection.to)
|
|
198
|
+
if (from !== undefined && to !== undefined) {
|
|
199
|
+
value.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, from, to)).setMeta('addToHistory', false))
|
|
200
|
+
value.focus()
|
|
201
|
+
}
|
|
202
|
+
}
|
|
151
203
|
const stopBefore = value.onBeforeChange(({ tr }) => { if (!comments.synchronizing && tr.docChanged) pendingTransaction.current = tr })
|
|
152
204
|
const stopComments = comments.subscribe(emit)
|
|
153
205
|
const stopSelection = value.onSelectionChange(() => { cancelFocus(); reportPosition() })
|
|
@@ -162,7 +214,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
|
|
|
162
214
|
})
|
|
163
215
|
unsubscribe.current = () => { stopBefore(); stopComments(); stopSelection(); stopFocus(); cancelFocus() }
|
|
164
216
|
}
|
|
165
|
-
const commands: DocumentEditorCommands | undefined = value ? { rememberComponentConfiguration: document => {
|
|
217
|
+
const commands: DocumentEditorCommands | undefined = value ? { handleAnimationRequests: requests => { animationRequests.current = requests }, rememberComponentConfiguration: document => {
|
|
166
218
|
if (editor.current === value && active.current === projection && binding.current === projection && !value.prosemirrorView.isDestroyed) rememberComponentConfiguration(projection, document)
|
|
167
219
|
}, insertPage: (after, title) => {
|
|
168
220
|
if (current.current.readOnly || editor.current !== value || active.current !== projection || binding.current !== projection || value.prosemirrorView.isDestroyed) throw new Error('page-context-changed')
|
|
@@ -171,7 +223,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
|
|
|
171
223
|
const next = after ? blocks.slice(index + 1).find(block => block.type === 'presmiumPage') : undefined
|
|
172
224
|
const latest = current.current.getDocument ? current.current.getDocument() : current.current.document
|
|
173
225
|
if (!latest) throw new Error('page-context-changed')
|
|
174
|
-
const creation = allocateDocumentPage(latest, () =>
|
|
226
|
+
const creation = allocateDocumentPage(latest, () => randomUUID())
|
|
175
227
|
projection.createdPages.set(creation.sectionId, creation)
|
|
176
228
|
try {
|
|
177
229
|
value.transact(transaction => {
|