@lincyaw/workbench 0.2.0-rc.12 → 0.2.0-rc.120
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
|
@@ -1,16 +1,19 @@
|
|
|
1
|
-
import { documentCommentTargets, isRecord, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
|
|
2
|
-
import type { DocumentComment, DocumentThread, RichTextNode,
|
|
3
|
-
import { DocumentDraftStore } from '../document-draft-store.ts'
|
|
1
|
+
import { documentAnchorKey, documentCommentTargets, isDocumentPlaceAnchor, isRecord, randomUUID, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
|
|
2
|
+
import type { DocumentComment, DocumentThread, DocumentThreadAnchor, RichTextNode, PresmiumDocument } from '@lincyaw/kernel'
|
|
3
|
+
import { DocumentDraftStore, waitForDraft } from '../document-draft-store.ts'
|
|
4
|
+
import { sha256 as tokenOf } from '../sha256.ts'
|
|
4
5
|
import type { DraftStoreResult } from '../document-draft-store.ts'
|
|
5
6
|
|
|
6
7
|
export interface CommentDraftTarget { threadId: string, commentId?: string, threadCreatedAt: string, commentCreatedAt?: string, baseline?: string }
|
|
7
|
-
export interface NewCommentDraftTarget { kind: 'create', intentId: string, documentId: string, anchor?:
|
|
8
|
+
export interface NewCommentDraftTarget { kind: 'create', intentId: string, documentId: string, anchor?: DocumentThreadAnchor, signature?: string }
|
|
8
9
|
export type CommentComposerTarget = CommentDraftTarget | NewCommentDraftTarget
|
|
9
10
|
export const isNewCommentDraft = (target: CommentComposerTarget): target is NewCommentDraftTarget => 'kind' in target && target.kind === 'create'
|
|
10
|
-
export function newCommentDraftSignature(document:
|
|
11
|
+
export function newCommentDraftSignature(document: PresmiumDocument, anchor: DocumentThreadAnchor | undefined): string | undefined {
|
|
11
12
|
if (!anchor) return
|
|
12
13
|
try {
|
|
13
14
|
validateDocumentCommentAnchor(document, anchor)
|
|
15
|
+
// A place identity cannot drift like a text offset; its presence is the whole signature.
|
|
16
|
+
if (isDocumentPlaceAnchor(anchor)) return documentAnchorKey(anchor)
|
|
14
17
|
const targets = documentCommentTargets(document), from = targets.get(anchor.from.blockId)!, to = targets.get(anchor.to.blockId)!
|
|
15
18
|
return JSON.stringify([...targets].filter(([, value]) => value.order >= from.order && value.order <= to.order).map(([id, value]) => ({ id, text: value.text })))
|
|
16
19
|
} catch { return }
|
|
@@ -36,8 +39,10 @@ export interface CommentDraftComposer {
|
|
|
36
39
|
id: string
|
|
37
40
|
target: CommentComposerTarget
|
|
38
41
|
snapshot(): { record?: CommentDraftRecord, composing: boolean, available: boolean }
|
|
39
|
-
targetState(): 'current' | 'changed' | 'unavailable'
|
|
42
|
+
targetState(target?: CommentComposerTarget): 'current' | 'changed' | 'unavailable'
|
|
43
|
+
accepts?(target: CommentComposerTarget): boolean
|
|
40
44
|
restore?(candidate: CommentDraftCandidate, operation: CommentDraftOperation): Promise<CommentDraftRecord | undefined>
|
|
45
|
+
discard?(candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean>
|
|
41
46
|
}
|
|
42
47
|
interface Writing { record: CommentDraftRecord, raw: string, store: DocumentDraftStore, generation: number, pending: boolean, failed: boolean, done: Promise<DraftStoreResult>, clearing?: boolean }
|
|
43
48
|
const PREFIX = 'presmium.comment-draft.v1:'
|
|
@@ -50,18 +55,17 @@ const markerOf = (scope: string, value: CommentDraftReference) => `${SETTLED}${J
|
|
|
50
55
|
export const commentDraftBaseline = (comment: DocumentComment) => JSON.stringify({ userId: comment.userId, content: comment.content })
|
|
51
56
|
const committedValue = (comment: DocumentComment) => JSON.stringify({ id: comment.id, userId: comment.userId, createdAt: comment.createdAt, updatedAt: comment.updatedAt, content: comment.content })
|
|
52
57
|
export const sameCommentDraftTarget = (a: CommentComposerTarget, b: CommentComposerTarget) => isNewCommentDraft(a) || isNewCommentDraft(b)
|
|
53
|
-
? isNewCommentDraft(a) && isNewCommentDraft(b) && a.documentId === b.documentId && a.signature === b.signature &&
|
|
58
|
+
? isNewCommentDraft(a) && isNewCommentDraft(b) && a.documentId === b.documentId && a.signature === b.signature && documentAnchorKey(a.anchor) === documentAnchorKey(b.anchor)
|
|
54
59
|
: a.threadId === b.threadId && a.commentId === b.commentId && a.threadCreatedAt === b.threadCreatedAt && a.commentCreatedAt === b.commentCreatedAt
|
|
55
|
-
async function tokenOf(raw: string): Promise<string> {
|
|
56
|
-
const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw))
|
|
57
|
-
return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
|
|
58
|
-
}
|
|
59
60
|
const point = (value: unknown): boolean => isRecord(value) && typeof value.blockId === 'string' && value.blockId.length > 0 && value.blockId.length <= 205 && Number.isSafeInteger(value.offset) && Number(value.offset) >= 0
|
|
61
|
+
const place = (value: unknown): boolean => isRecord(value) && typeof value.blockId === 'string' && value.blockId.length > 0 && value.blockId.length <= 205
|
|
62
|
+
&& (value.stepId === undefined || typeof value.stepId === 'string' && value.stepId.length > 0 && value.stepId.length <= 205)
|
|
60
63
|
function targetShape(value: unknown): boolean {
|
|
61
64
|
if (!isRecord(value)) return false
|
|
62
65
|
if (value.kind === 'create') return typeof value.intentId === 'string' && value.intentId.length > 0 && value.intentId.length <= 200
|
|
63
66
|
&& typeof value.documentId === 'string' && value.documentId.length > 0 && value.documentId.length <= 200
|
|
64
|
-
&& (value.anchor === undefined && value.signature === undefined || isRecord(value.anchor) &&
|
|
67
|
+
&& (value.anchor === undefined && value.signature === undefined || isRecord(value.anchor) && typeof value.signature === 'string'
|
|
68
|
+
&& (point(value.anchor.from) && point(value.anchor.to) || place(value.anchor)))
|
|
65
69
|
return typeof value.threadId === 'string' && typeof value.threadCreatedAt === 'string'
|
|
66
70
|
&& (value.commentId === undefined || typeof value.commentId === 'string' && typeof value.commentCreatedAt === 'string' && typeof value.baseline === 'string')
|
|
67
71
|
}
|
|
@@ -77,7 +81,7 @@ function valid(value: unknown, scope: string): value is CommentDraftRecord {
|
|
|
77
81
|
/** Native composer backups use the document backup owner's strict transactions, never the source writer. */
|
|
78
82
|
export class CommentDrafts {
|
|
79
83
|
readonly #scope: string
|
|
80
|
-
readonly #owner =
|
|
84
|
+
readonly #owner = randomUUID()
|
|
81
85
|
#reader?: DocumentDraftStore
|
|
82
86
|
readonly #listeners = new Set<() => void>()
|
|
83
87
|
readonly #writing = new Map<string, Writing>()
|
|
@@ -86,7 +90,7 @@ export class CommentDrafts {
|
|
|
86
90
|
#closed = false
|
|
87
91
|
#started = false
|
|
88
92
|
#read = 0
|
|
89
|
-
#document?:
|
|
93
|
+
#document?: PresmiumDocument
|
|
90
94
|
#version?: string
|
|
91
95
|
#acknowledged = false
|
|
92
96
|
#revision = 0
|
|
@@ -115,14 +119,56 @@ export class CommentDrafts {
|
|
|
115
119
|
targetActive(target: CommentComposerTarget): boolean { return !this.ownersKnown || [...this.#composers.values()].some(value => sameCommentDraftTarget(value.target, target) && value.snapshot().available) }
|
|
116
120
|
activeRecord(record: CommentDraftRecord): boolean { return [...this.#composers.values()].some(value => value.snapshot().record?.id === record.id && value.snapshot().record?.revision === record.revision && value.snapshot().available) }
|
|
117
121
|
owns(record: CommentDraftRecord): boolean { return !this.#closed && this.#writing.get(record.id)?.record === record }
|
|
122
|
+
/** Durability acknowledgements can settle without changing author input or native ownership. */
|
|
123
|
+
inputGuard(): () => void {
|
|
124
|
+
const records = new Map([...this.#writing].map(([id, value]) => [id, value.record])), unknown = this.#unregisteredComposers
|
|
125
|
+
const owners = [...this.#composers].map(([id, value]) => ({ id, value, ...value.snapshot() }))
|
|
126
|
+
return () => {
|
|
127
|
+
if (this.#closed || unknown !== this.#unregisteredComposers || records.size !== this.#writing.size || [...records].some(([id, record]) => this.#writing.get(id)?.record !== record)
|
|
128
|
+
|| owners.length !== this.#composers.size || owners.some(owner => {
|
|
129
|
+
const state = owner.value.snapshot()
|
|
130
|
+
return this.#composers.get(owner.id) !== owner.value || state.record !== owner.record || state.composing !== owner.composing || state.available !== owner.available
|
|
131
|
+
})) throw new Error('client-comment-drafts-changed')
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
#activeComposers(candidate: CommentDraftRecord): CommentDraftComposer[] {
|
|
135
|
+
return [...this.#composers.values()].filter(composer => {
|
|
136
|
+
if (composer.accepts) return false // A recovery controller is not a second owner of the visible editor.
|
|
137
|
+
const record = composer.snapshot().record
|
|
138
|
+
return record?.id === candidate.id && record.revision === candidate.revision
|
|
139
|
+
})
|
|
140
|
+
}
|
|
141
|
+
canDiscard(candidate: CommentDraftCandidate): boolean {
|
|
142
|
+
if (!this.ownersKnown || candidate.composing || candidate.pending) return false
|
|
143
|
+
const owners = this.#activeComposers(candidate)
|
|
144
|
+
return !owners.length || owners.length === 1 && Boolean(owners[0]!.discard && owners[0]!.snapshot().available && !owners[0]!.snapshot().composing)
|
|
145
|
+
}
|
|
146
|
+
/** Both the UI and MCP retire the exact branch before changing the actual mounted editor. */
|
|
147
|
+
async discardProposal(candidate: CommentDraftCandidate, operation?: CommentDraftOperation): Promise<boolean> {
|
|
148
|
+
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
149
|
+
if (!this.canDiscard(candidate)) throw new Error('client-comment-draft-needs-human')
|
|
150
|
+
const owners = this.#activeComposers(candidate)
|
|
151
|
+
const guard = () => {
|
|
152
|
+
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
153
|
+
const current = this.#activeComposers(candidate)
|
|
154
|
+
if (!this.canDiscard(candidate) || current.length !== owners.length || current.some((owner, index) => owner !== owners[index])) throw new Error('client-comment-composer-changed')
|
|
155
|
+
}
|
|
156
|
+
guard()
|
|
157
|
+
return owners[0] ? owners[0].discard!(candidate, { signal: operation?.signal, guard }) : this.discard(candidate, { signal: operation?.signal, guard })
|
|
158
|
+
}
|
|
118
159
|
async restoreChoice(candidate: CommentDraftCandidate, signal: AbortSignal): Promise<{ composerId: string, expectedCurrent: CommentDraftReference | null } | undefined> {
|
|
119
|
-
if (!this.ownersKnown ||
|
|
120
|
-
const
|
|
160
|
+
if (!this.ownersKnown || candidate.storage !== 'durable' || candidate.composing || candidate.pending) return
|
|
161
|
+
const available = [...this.#composers.values()].filter(value => value.restore && value.snapshot().available && !value.snapshot().composing && value.targetState(candidate.target) !== 'unavailable')
|
|
162
|
+
const direct = available.filter(value => !value.accepts && sameCommentDraftTarget(value.target, candidate.target))
|
|
163
|
+
const matching = direct.length ? direct : available.filter(value => value.accepts?.(candidate.target))
|
|
121
164
|
if (matching.length !== 1) return
|
|
122
165
|
const composer = matching[0]!, current = composer.snapshot().record
|
|
123
166
|
if (!current) return { composerId: composer.id, expectedCurrent: null }
|
|
124
167
|
const writing = this.#writing.get(current.id)
|
|
125
|
-
if (current.id === candidate.id || current.composing || current.pending || !writing || writing.record !== current
|
|
168
|
+
if (current.id === candidate.id || current.composing || current.pending || !writing || writing.record !== current) return
|
|
169
|
+
if (writing.pending && await waitForDraft(writing.done, signal) !== 'committed') return
|
|
170
|
+
signal.throwIfAborted()
|
|
171
|
+
if (writing.failed || this.#writing.get(current.id) !== writing || !writing.store.owns(keyOf(this.#scope, current.id), writing.raw)) return
|
|
126
172
|
const token = await tokenOf(writing.raw); signal.throwIfAborted()
|
|
127
173
|
if (this.#composers.get(composer.id) !== composer || composer.snapshot().record !== current || !composer.snapshot().available || composer.snapshot().composing) throw new Error('client-comment-drafts-changed')
|
|
128
174
|
return { composerId: composer.id, expectedCurrent: { id: current.id, revision: current.revision, token } }
|
|
@@ -228,9 +274,9 @@ export class CommentDrafts {
|
|
|
228
274
|
const thread = this.#document.comments?.[created ? record.pending.threadId ?? '' : target.threadId]
|
|
229
275
|
const comment = thread?.comments.find(value => value.id === record.pending!.commentId)
|
|
230
276
|
return Boolean(thread && !thread.deletedAt && thread.createdAt === (created ? record.pending.threadCreatedAt : target.threadCreatedAt)
|
|
231
|
-
&& (!created ||
|
|
277
|
+
&& (!created || documentAnchorKey(thread.anchor) === documentAnchorKey(target.anchor)) && comment && !comment.deletedAt && committedValue(comment) === record.pending.value)
|
|
232
278
|
}
|
|
233
|
-
synchronize(document:
|
|
279
|
+
synchronize(document: PresmiumDocument, version: string | undefined, acknowledged = false): void {
|
|
234
280
|
this.#document = document; this.#version = version; this.#acknowledged = acknowledged
|
|
235
281
|
for (const value of this.#writing.values()) if (this.#isCommitted(value.record)) void this.clearOwn(value.record)
|
|
236
282
|
if (this.#started) void this.refresh()
|
|
@@ -240,7 +286,7 @@ export class CommentDrafts {
|
|
|
240
286
|
const known = previous && this.#writing.get(previous.id)
|
|
241
287
|
if (previous && (known && known.record.revision !== previous.revision || previous.owner !== this.#owner)) return
|
|
242
288
|
const branched = known?.store.conflicted(keyOf(this.#scope, known.record.id))
|
|
243
|
-
const record: CommentDraftRecord = { format: 1, scope: this.#scope, id: !branched && known ? known.record.id :
|
|
289
|
+
const record: CommentDraftRecord = { format: 1, scope: this.#scope, id: !branched && known ? known.record.id : randomUUID(), owner: this.#owner,
|
|
244
290
|
revision: !branched && known ? known.record.revision + 1 : 1, updatedAt: Date.now(), target: structuredClone(target), version, content: structuredClone(content), composing }
|
|
245
291
|
return this.#put(record, !branched ? known : undefined)
|
|
246
292
|
}
|
|
@@ -294,19 +340,21 @@ export class CommentDrafts {
|
|
|
294
340
|
this.#settling++; this.#touch()
|
|
295
341
|
try {
|
|
296
342
|
if (this.#closed || !this.#reader) return false
|
|
297
|
-
const values = await this.#reader.read([
|
|
343
|
+
const values = await this.#reader.read([keyOf(this.#scope, reference.id)], operation?.signal), writing = this.#writing.get(reference.id)
|
|
298
344
|
const raw = writing && writing.record.revision === reference.revision && await tokenOf(writing.raw) === reference.token ? writing.raw : values.get(keyOf(this.#scope, reference.id))
|
|
299
345
|
if (this.#closed || typeof raw !== 'string' || await tokenOf(raw) !== reference.token) return false
|
|
300
346
|
const value: unknown = JSON.parse(raw)
|
|
301
347
|
if (!valid(value, this.#scope) || value.revision !== reference.revision || this.#closed) return false
|
|
302
348
|
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
303
|
-
const committed = await this.#reader!.mark([[markerOf(this.#scope, reference), reference.token]])
|
|
349
|
+
const committed = await this.#reader!.mark([[markerOf(this.#scope, reference), reference.token]], operation)
|
|
350
|
+
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
351
|
+
const writtenToken = writing ? await tokenOf(writing.raw) : undefined
|
|
304
352
|
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
305
353
|
if (!this.#closed) {
|
|
306
354
|
if (committed) this.#touch()
|
|
307
|
-
if (committed && writing && this.#writing.get(reference.id) === writing && writing.record.revision === reference.revision &&
|
|
355
|
+
if (committed && writing && this.#writing.get(reference.id) === writing && writing.record.revision === reference.revision && writtenToken === reference.token) { this.#writing.delete(reference.id); writing.store.close() }
|
|
308
356
|
if (!committed) this.#admissionFailure = true
|
|
309
|
-
this.#pending();
|
|
357
|
+
this.#pending(); void this.refresh()
|
|
310
358
|
}
|
|
311
359
|
return committed
|
|
312
360
|
} catch (error) { if (operation) throw error; this.#readFailure = true; this.#pending(); return false }
|
|
@@ -317,15 +365,15 @@ export class CommentDrafts {
|
|
|
317
365
|
if (this.#closed || !this.#reader) return
|
|
318
366
|
this.#settling++; this.#touch()
|
|
319
367
|
try {
|
|
320
|
-
const values = await this.#reader.read([
|
|
368
|
+
const values = await this.#reader.read([keyOf(this.#scope, reference.id), markerOf(this.#scope, reference)], operation?.signal), writing = this.#writing.get(reference.id)
|
|
321
369
|
const raw = writing && writing.record.revision === reference.revision && await tokenOf(writing.raw) === reference.token ? writing.raw : values.get(keyOf(this.#scope, reference.id))
|
|
322
370
|
if (this.#closed || typeof raw !== 'string' || await tokenOf(raw) !== reference.token || values.get(markerOf(this.#scope, reference)) === reference.token) return
|
|
323
371
|
const value: unknown = JSON.parse(raw)
|
|
324
372
|
if (!valid(value, this.#scope) || value.revision !== reference.revision || !sameCommentDraftTarget(value.target, target) || !this.#validContent(value) || this.#closed) return
|
|
325
373
|
operation?.signal?.throwIfAborted(); operation?.guard?.()
|
|
326
|
-
const record: CommentDraftRecord = { ...value, target: isNewCommentDraft(target) ? structuredClone(target) : value.target, id:
|
|
374
|
+
const record: CommentDraftRecord = { ...value, target: isNewCommentDraft(target) ? structuredClone(target) : value.target, id: randomUUID(), owner: this.#owner, revision: 1, updatedAt: Date.now(), version, composing: false, pending: undefined }
|
|
327
375
|
const store = new DocumentDraftStore(this.#scope, undefined, { family: 'comment', owner: this.#owner }), next = JSON.stringify(record)
|
|
328
|
-
if (next.length > MAX_CHARS || !await store.create(keyOf(this.#scope, record.id), next) || this.#closed) { store.close(); if (!this.#closed) { this.#admissionFailure = true; this.#pending() }; return }
|
|
376
|
+
if (next.length > MAX_CHARS || !await store.create(keyOf(this.#scope, record.id), next, operation) || this.#closed) { store.close(); if (!this.#closed) { this.#admissionFailure = true; this.#pending() }; return }
|
|
329
377
|
try { operation?.signal?.throwIfAborted(); operation?.guard?.() } catch (error) { store.close(); throw error }
|
|
330
378
|
this.#writing.set(record.id, { record, raw: next, store, generation: 0, pending: false, failed: false, done: Promise.resolve('committed') })
|
|
331
379
|
this.#touch(); void this.refresh()
|
|
@@ -4,8 +4,8 @@ import type { BlockNoteEditor } from '@blocknote/core'
|
|
|
4
4
|
import type { CommentData, ThreadData } from '@blocknote/core/comments'
|
|
5
5
|
import { AddMarkStep, RemoveMarkStep } from '@tiptap/pm/transform'
|
|
6
6
|
import { Plugin } from '@tiptap/pm/state'
|
|
7
|
-
import { applyDocumentCommentAction, hasRole, LOCAL_AUTHOR, validateDocumentCommentAnchor } from '@lincyaw/kernel'
|
|
8
|
-
import type { DocumentComment, DocumentCommentAction, DocumentThread, Member, RichTextNode,
|
|
7
|
+
import { applyDocumentCommentAction, degradeDocumentCommentAnchor, hasRole, isDocumentPlaceAnchor, isDocumentTextAnchor, LOCAL_AUTHOR, randomUUID, validateDocumentCommentAnchor } from '@lincyaw/kernel'
|
|
8
|
+
import type { DocumentComment, DocumentCommentAction, DocumentPlaceAnchor, DocumentThread, DocumentThreadAnchor, Member, RichTextNode, PresmiumDocument } from '@lincyaw/kernel'
|
|
9
9
|
import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
|
|
10
10
|
import type { RichProjection } from './rich-text.ts'
|
|
11
11
|
import type { Transaction } from '@tiptap/pm/state'
|
|
@@ -16,7 +16,7 @@ import type { CommentComposerTarget, CommentDraftTarget, NewCommentDraftTarget }
|
|
|
16
16
|
import { nativeProductText, nativeTextPoint, nativeTextPosition, nativeTextPositionInDocument } from './selection.ts'
|
|
17
17
|
|
|
18
18
|
type NewComment = { body: unknown, metadata?: unknown }
|
|
19
|
-
type Threads = NonNullable<
|
|
19
|
+
type Threads = NonNullable<PresmiumDocument['comments']>
|
|
20
20
|
const date = (value: string) => new Date(value)
|
|
21
21
|
const jsonObject = (value: unknown) => value && typeof value === 'object' && !Array.isArray(value) ? structuredClone(value) as DocumentThread['metadata'] : undefined
|
|
22
22
|
const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
|
|
@@ -70,7 +70,7 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
70
70
|
#threads = new Map<string, ThreadData>()
|
|
71
71
|
#canonical: Threads = {}
|
|
72
72
|
#version?: string
|
|
73
|
-
#document:
|
|
73
|
+
#document: PresmiumDocument
|
|
74
74
|
#synchronizing = false
|
|
75
75
|
readonly #edits = new Map<string, CommentEditing>()
|
|
76
76
|
#submitting?: CommentEditing
|
|
@@ -78,13 +78,16 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
78
78
|
readonly #rich: RichProjection = createRichProjection()
|
|
79
79
|
readonly #anchors = new Map<string, DocumentThread['anchor']>()
|
|
80
80
|
readonly #initialBodies = new Map<string, { body: unknown, content: RichTextNode[] }>()
|
|
81
|
-
constructor(document:
|
|
81
|
+
constructor(document: PresmiumDocument, member?: Member, version?: string, identity?: string, drafts?: CommentDrafts) {
|
|
82
82
|
super(new DocumentThreadAuth(member)); this.member = member; this.#version = version; this.#document = document; this.#replace(document.comments ?? {})
|
|
83
83
|
this.#ownsDrafts = !drafts
|
|
84
84
|
if (drafts || identity && member?.id) { this.drafts = drafts ?? new CommentDrafts(identity!, member!.id) }
|
|
85
85
|
}
|
|
86
86
|
get version(): string | undefined { return this.#version }
|
|
87
|
+
get document(): PresmiumDocument { return this.#document }
|
|
87
88
|
threadSnapshot(threadId: string): DocumentThread | undefined { return this.#canonical[threadId] }
|
|
89
|
+
anchorOf(threadId: string): DocumentThreadAnchor | undefined { const anchor = this.#anchors.get(threadId); return anchor ? structuredClone(anchor) : undefined }
|
|
90
|
+
placeAnchorOf(threadId: string): DocumentPlaceAnchor | undefined { const anchor = this.#anchors.get(threadId); return anchor && isDocumentPlaceAnchor(anchor) ? structuredClone(anchor) : undefined }
|
|
88
91
|
refreshEditorCallbacks(): void { this.#publishView() }
|
|
89
92
|
draftTargetState(target: CommentComposerTarget): 'current' | 'changed' | 'unavailable' {
|
|
90
93
|
if (isNewCommentDraft(target)) {
|
|
@@ -96,7 +99,7 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
96
99
|
if (!thread || thread.deletedAt || thread.createdAt !== target.threadCreatedAt || target.commentId && (!comment || comment.deletedAt || comment.createdAt !== target.commentCreatedAt)) return 'unavailable'
|
|
97
100
|
return comment && target.baseline !== commentDraftBaseline(comment) ? 'changed' : 'current'
|
|
98
101
|
}
|
|
99
|
-
newDraftTarget(editor: NativeDocumentEditor, intentId =
|
|
102
|
+
newDraftTarget(editor: NativeDocumentEditor, intentId = randomUUID()): NewCommentDraftTarget {
|
|
100
103
|
this.beforeAction?.()
|
|
101
104
|
const target: NewCommentDraftTarget = { kind: 'create', intentId, documentId: this.#document.id }
|
|
102
105
|
const selection = editor.prosemirrorState.selection
|
|
@@ -109,7 +112,7 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
109
112
|
}
|
|
110
113
|
/** Verify both the canonical range and the actual native projection before a selection command. */
|
|
111
114
|
newDraftPositions(target: NewCommentDraftTarget, editor: NativeDocumentEditor): { from: number, to: number } | undefined {
|
|
112
|
-
if (editor.prosemirrorView.isDestroyed || this.draftTargetState(target) !== 'current' || !target.anchor || !target.signature) return
|
|
115
|
+
if (editor.prosemirrorView.isDestroyed || this.draftTargetState(target) !== 'current' || !target.anchor || !isDocumentTextAnchor(target.anchor) || !target.signature) return
|
|
113
116
|
const positions = (point: { blockId: string, offset: number }) => {
|
|
114
117
|
const value = nativeTextPosition(editor, point)
|
|
115
118
|
if (value === undefined) return
|
|
@@ -162,7 +165,7 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
162
165
|
#content(comment: NewComment): RichTextNode[] { return nativeRichTextToProduct(comment.body as DocumentEditorBlock[], this.#rich) }
|
|
163
166
|
#act(action: DocumentCommentAction, nativeBody?: unknown) {
|
|
164
167
|
this.beforeAction?.()
|
|
165
|
-
const answer = applyDocumentCommentAction(this.#canonical, action, { member: this.member, now: new Date().toISOString(), allocate: () =>
|
|
168
|
+
const answer = applyDocumentCommentAction(this.#canonical, action, { member: this.member, now: new Date().toISOString(), allocate: () => randomUUID() })
|
|
166
169
|
if (answer.effect.changed) {
|
|
167
170
|
this.#replace(answer.threads, answer.effect.commentId && nativeBody !== undefined ? { id: answer.effect.commentId, body: nativeBody } : undefined)
|
|
168
171
|
this.#notify()
|
|
@@ -173,6 +176,14 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
173
176
|
const effect = this.#act({ type: 'comment.create', content: this.#content(initialComment), metadata: jsonObject(metadata), commentMetadata: jsonObject(initialComment.metadata) }, initialComment.body)
|
|
174
177
|
return this.getThread(effect.threadId)
|
|
175
178
|
}
|
|
179
|
+
/** A block, optionally at one step; the same canonical action as a text comment, with a place anchor. */
|
|
180
|
+
createPlaceThread = async ({ blockId, stepId, body }: { blockId: string, stepId?: string, body: unknown }): Promise<ThreadData> => {
|
|
181
|
+
this.beforeAction?.()
|
|
182
|
+
const anchor: DocumentPlaceAnchor = { blockId, ...stepId === undefined ? {} : { stepId } }
|
|
183
|
+
validateDocumentCommentAnchor(this.#document, anchor)
|
|
184
|
+
const effect = this.#act({ type: 'comment.create', content: this.#content({ body }), anchor }, body)
|
|
185
|
+
return this.getThread(effect.threadId)
|
|
186
|
+
}
|
|
176
187
|
addComment = async ({ threadId, comment }: { threadId: string, comment: NewComment }): Promise<CommentData> => {
|
|
177
188
|
const effect = this.#act({ type: 'comment.reply', threadId, content: this.#content(comment), metadata: jsonObject(comment.metadata) }, comment.body)
|
|
178
189
|
return this.getThread(threadId).comments.find(value => value.id === effect.commentId)!
|
|
@@ -266,7 +277,7 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
266
277
|
}
|
|
267
278
|
|
|
268
279
|
/** Source adoption is not another native edit; preserve selected thread and unchanged comment bodies. */
|
|
269
|
-
synchronize(document:
|
|
280
|
+
synchronize(document: PresmiumDocument, version: string | undefined, editor: NativeDocumentEditor, transaction?: Transaction, acknowledged = false): void {
|
|
270
281
|
if (this.#synchronizing) return
|
|
271
282
|
this.#document = document
|
|
272
283
|
this.drafts?.synchronize(document, version, acknowledged)
|
|
@@ -286,7 +297,7 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
286
297
|
restoreAnchors(editor: NativeDocumentEditor, transaction?: Transaction): void {
|
|
287
298
|
const extension = editor.getExtension(CommentsExtension)!, name = extension.tiptapExtensions[0].name
|
|
288
299
|
const ranges = [...this.#anchors].flatMap(([threadId, anchor]) => {
|
|
289
|
-
if (!anchor) return []
|
|
300
|
+
if (!anchor || !isDocumentTextAnchor(anchor)) return []
|
|
290
301
|
try { validateDocumentCommentAnchor(this.#document, anchor) } catch { return [] }
|
|
291
302
|
const position = (point: { blockId: string, offset: number }, association: number) => {
|
|
292
303
|
if (!transaction) return nativeTextPosition(editor, point)
|
|
@@ -303,12 +314,21 @@ export class DocumentThreadStore extends ThreadStore {
|
|
|
303
314
|
transaction.setMeta('addToHistory', false)
|
|
304
315
|
})
|
|
305
316
|
}
|
|
306
|
-
snapshot(editor: NativeDocumentEditor): Threads {
|
|
317
|
+
snapshot(editor: NativeDocumentEditor, source: PresmiumDocument = this.#document): Threads {
|
|
307
318
|
const positions = editor.getExtension(CommentsExtension)!.store.state.threadPositions
|
|
308
319
|
const result = Object.fromEntries([...this.#threads.values()].map(thread => {
|
|
309
|
-
const
|
|
310
|
-
|
|
311
|
-
|
|
320
|
+
const stored = this.#anchors.get(thread.id)
|
|
321
|
+
let anchor: DocumentThreadAnchor | undefined
|
|
322
|
+
if (stored && isDocumentPlaceAnchor(stored)) {
|
|
323
|
+
const degraded = degradeDocumentCommentAnchor(source, stored)
|
|
324
|
+
anchor = degraded && isDocumentPlaceAnchor(degraded) ? degraded : undefined
|
|
325
|
+
} else {
|
|
326
|
+
const position = positions.get(thread.id)
|
|
327
|
+
const from = position ? nativeTextPoint(editor, position.from) : undefined, to = position ? nativeTextPoint(editor, position.to) : undefined
|
|
328
|
+
anchor = from && to ? { from: { blockId: from.blockId, offset: from.offset }, to: { blockId: to.blockId, offset: to.offset } } : undefined
|
|
329
|
+
}
|
|
330
|
+
if (anchor) this.#anchors.set(thread.id, structuredClone(anchor))
|
|
331
|
+
else this.#anchors.delete(thread.id)
|
|
312
332
|
const value: DocumentThread = {
|
|
313
333
|
id: thread.id, type: 'thread', createdAt: thread.createdAt.toISOString(), updatedAt: thread.updatedAt.toISOString(), resolved: thread.resolved,
|
|
314
334
|
...thread.resolvedUpdatedAt ? { resolvedUpdatedAt: thread.resolvedUpdatedAt.toISOString() } : {}, ...thread.resolvedBy ? { resolvedBy: thread.resolvedBy } : {},
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Definition } from '@lincyaw/kernel'
|
|
2
|
+
|
|
3
|
+
/** What an author calls a component: their title, otherwise a readable implementation name, never source code. */
|
|
4
|
+
export function componentDefinitionLabel(definition: Definition): string {
|
|
5
|
+
const title = typeof definition.parameterSchema === 'object' && typeof definition.parameterSchema.title === 'string' ? definition.parameterSchema.title.trim() : ''
|
|
6
|
+
if (title) return Array.from(title).slice(0, 80).join('')
|
|
7
|
+
const implementation = definition.implementation
|
|
8
|
+
const name = implementation.type === 'file' ? implementation.path.split('/').at(-1)?.replace(/\.(tsx?|jsx?|mjs|cjs)$/, '')
|
|
9
|
+
: implementation.type === 'plugin' ? implementation.name : implementation.specifier.split('/').at(-1)
|
|
10
|
+
return Array.from(name || definition.kind).slice(0, 80).join('')
|
|
11
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createExtension, getBlockInfoNearPos, getNodeId } from '@blocknote/core'
|
|
2
2
|
import { FileHandler } from '@tiptap/extension-file-handler'
|
|
3
|
-
import { DOCUMENT_IMAGE_MEDIA_TYPES } from '@lincyaw/kernel'
|
|
3
|
+
import { DOCUMENT_IMAGE_MEDIA_TYPES, randomUUID } from '@lincyaw/kernel'
|
|
4
4
|
import { isObservedWorkspaceFailure, WorkspaceServerError } from '../workspace-client.ts'
|
|
5
5
|
import type { NativeDocumentEditor } from './schema.tsx'
|
|
6
6
|
|
|
@@ -34,7 +34,7 @@ export const imageFileInput = createExtension(({ editor, options }: { editor: Na
|
|
|
34
34
|
const state = editor.prosemirrorState, info = getBlockInfoNearPos(state, position)
|
|
35
35
|
const anchor = editor.getBlock(getNodeId(info.block.node, state.doc))
|
|
36
36
|
if (!anchor) throw new Error('document-file-position')
|
|
37
|
-
const blocks = accepted.map(file => ({ id:
|
|
37
|
+
const blocks = accepted.map(file => ({ id: randomUUID(), type: 'image' as const, props: { name: file.name } }))
|
|
38
38
|
const before = anchor.type !== 'presmiumPage' && position <= (info.contentStart ?? info.block.beforePos)
|
|
39
39
|
const inserted = editor.insertBlocks(blocks, anchor, before ? 'before' : 'after')
|
|
40
40
|
pending = inserted.map((block, index) => ({ file: accepted[index]!, id: block.id }))
|
|
@@ -43,6 +43,7 @@ function label(node: InlineNode): string {
|
|
|
43
43
|
if (node.type === 'math') return node.value
|
|
44
44
|
if (node.type === 'break') return '\n'
|
|
45
45
|
if (node.type === 'extension') return node.fallback
|
|
46
|
+
if (node.type === 'reference') return node.label ?? node.fallback
|
|
46
47
|
return node.children.map(label).join('') || node.href
|
|
47
48
|
}
|
|
48
49
|
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { DocumentProjection } from './projection.ts'
|
|
2
|
+
import type { DocumentEditorBlock, NativeDocumentEditor } from './schema.tsx'
|
|
3
|
+
|
|
4
|
+
/** Where the caret is in the document, as a place for new content that the author and the AI can both name. */
|
|
5
|
+
export interface DocumentInsertionPlace {
|
|
6
|
+
sectionId: string
|
|
7
|
+
/** The block (its document ID) the caret is in, then the blocks holding it, innermost first. */
|
|
8
|
+
blocks: string[]
|
|
9
|
+
/** The text of the paragraph the caret is in, when it has any. */
|
|
10
|
+
text?: string
|
|
11
|
+
/**
|
|
12
|
+
* What new content follows: the caret's paragraph, or the content before it when the paragraph is empty, by its text
|
|
13
|
+
* ('' when that content has none). None at the start of the page.
|
|
14
|
+
*/
|
|
15
|
+
after?: string
|
|
16
|
+
/** Nothing else follows on the page. */
|
|
17
|
+
end: boolean
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
type Inline = { type: string, text?: string, content?: unknown, props?: { label?: string } }
|
|
21
|
+
|
|
22
|
+
function inlineText(content: unknown): string {
|
|
23
|
+
if (typeof content === 'string') return content
|
|
24
|
+
if (!Array.isArray(content)) return ''
|
|
25
|
+
return (content as Inline[]).map(item => item.type === 'text' ? item.text ?? '' : item.type === 'presmiumInline' ? item.props?.label ?? '' : inlineText(item.content)).join('')
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function textOf(block: DocumentEditorBlock): string {
|
|
29
|
+
const text = block.type === 'image' ? block.props.caption || block.props.name
|
|
30
|
+
: block.type === 'presmiumAtom' ? block.props.label
|
|
31
|
+
: block.type === 'presmiumContainer' ? block.props.title
|
|
32
|
+
: inlineText(block.content)
|
|
33
|
+
return text.replace(/\s+/g, ' ').trim()
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// An empty paragraph (or heading, list item…) is where content can go, not content to follow.
|
|
37
|
+
const filled = (block: DocumentEditorBlock) => !Array.isArray(block.content) || block.content.length > 0
|
|
38
|
+
|
|
39
|
+
/** The place of the caret's block, as the slash menu opened in it; none on a page title. */
|
|
40
|
+
export function documentInsertionPlace(editor: NativeDocumentEditor, projection: Pick<DocumentProjection, 'owners' | 'pages'>): DocumentInsertionPlace | undefined {
|
|
41
|
+
const at = editor.getTextCursorPosition().block as DocumentEditorBlock
|
|
42
|
+
if (at.type === 'presmiumPage') return undefined
|
|
43
|
+
const order: DocumentEditorBlock[] = []
|
|
44
|
+
const visit = (blocks: readonly DocumentEditorBlock[]) => { for (const block of blocks) { order.push(block); visit(block.children) } }
|
|
45
|
+
visit(editor.document)
|
|
46
|
+
const index = order.findIndex(block => block.id === at.id)
|
|
47
|
+
const start = order.findLastIndex((block, i) => i < index && block.type === 'presmiumPage')
|
|
48
|
+
const page = order[start]
|
|
49
|
+
if (index < 0 || page?.type !== 'presmiumPage') return undefined
|
|
50
|
+
const next = order.findIndex((block, i) => i > index && block.type === 'presmiumPage')
|
|
51
|
+
const holders: DocumentEditorBlock[] = []
|
|
52
|
+
for (let block = editor.getParentBlock(at); block; block = editor.getParentBlock(block)) holders.push(block as DocumentEditorBlock)
|
|
53
|
+
const anchor = filled(at) ? at : order.slice(start + 1, index).reverse().find(block => filled(block) && !holders.some(holder => holder.id === block.id))
|
|
54
|
+
const text = textOf(at)
|
|
55
|
+
const blocks = [...new Set([at, ...holders].flatMap(block => projection.owners.get(block.id) ?? []))]
|
|
56
|
+
return {
|
|
57
|
+
sectionId: projection.pages.get(page.id) ?? page.props.sectionId, blocks, ...text ? { text } : {},
|
|
58
|
+
...anchor ? { after: textOf(anchor) } : {}, end: !order.slice(index + 1, next < 0 ? undefined : next).some(filled),
|
|
59
|
+
}
|
|
60
|
+
}
|
|
@@ -4,11 +4,11 @@ export const IMAGE_IMPORT_MESSAGES = {
|
|
|
4
4
|
}
|
|
5
5
|
|
|
6
6
|
export const DOCUMENT_EDITOR_MESSAGES = {
|
|
7
|
-
'zh-CN': { colors: '颜色', textColor: '文字颜色', backgroundColor: '背景颜色', colorDefault: '默认', backgroundDefault: '无底色', colorNames: { muted: '灰色 · 次要', accent: '青色 · 强调', ok: '绿色 · 通过', warn: '橙色 · 提醒', danger: '红色 · 警示' }, backgroundNames: { muted: '灰底', accent: '青底', ok: '绿底', warn: '橙底', danger: '红底' }, formula: '公式', formulaInline: '行内公式', formulaBlock: '公式块', formulaInlineHint: '在文字中插入 LaTeX 公式', formulaBlockHint: '单独一行显示的 LaTeX 公式', openLink: '打开链接', goToSection: (title: string) => `跳到“${title}”`, mathEmpty: '插入公式', mathInvalid: '公式无法识别', mathPlaceholder: '输入 LaTeX 公式', commentRecoveryChanged: '已取消恢复草稿,当前输入已保留。', commentNewDraft: '新建批注', commentsEmpty: '
|
|
8
|
-
en: { colors: 'Colors', textColor: 'Text color', backgroundColor: 'Highlight', colorDefault: 'Default', backgroundDefault: 'No highlight', colorNames: { muted: 'Gray · subtle', accent: 'Teal · accent', ok: 'Green · success', warn: 'Amber · caution', danger: 'Red · alert' }, backgroundNames: { muted: 'Gray', accent: 'Teal', ok: 'Green', warn: 'Amber', danger: 'Red' }, formula: 'Formula', formulaInline: 'Inline Formula', formulaBlock: 'Formula Block', formulaInlineHint: 'A LaTeX formula within the text', formulaBlockHint: 'A LaTeX formula on its own line', openLink: 'Open Link', goToSection: (title: string) => `Go to “${title}”`, mathEmpty: 'Insert Formula', mathInvalid: 'Formula not recognized', mathPlaceholder: 'Enter a LaTeX formula', commentRecoveryChanged: 'Draft recovery canceled. Your current input is kept.', commentNewDraft: 'New Comment', commentsEmpty: 'No comments yet. Select text in the document,
|
|
7
|
+
'zh-CN': { colors: '颜色', textColor: '文字颜色', backgroundColor: '背景颜色', colorDefault: '默认', backgroundDefault: '无底色', colorNames: { muted: '灰色 · 次要', accent: '青色 · 强调', ok: '绿色 · 通过', warn: '橙色 · 提醒', danger: '红色 · 警示' }, backgroundNames: { muted: '灰底', accent: '青底', ok: '绿底', warn: '橙底', danger: '红底' }, formula: '公式', formulaInline: '行内公式', formulaBlock: '公式块', formulaInlineHint: '在文字中插入 LaTeX 公式', formulaBlockHint: '单独一行显示的 LaTeX 公式', openLink: '打开链接', goToSection: (title: string) => `跳到“${title}”`, mathEmpty: '插入公式', mathInvalid: '公式无法识别', mathPlaceholder: '输入 LaTeX 公式', commentRecoveryChanged: '已取消恢复草稿,当前输入已保留。', commentNewDraft: '新建批注', commentsEmpty: '还没有批注。选中正文中的文字,或在动画、图表的工具栏里选“本步批注”。', commentTargetUnavailable: '原选区已改变或不可用,草稿仍可恢复。', commentSessionOnly: '仅本次会话', commentDrafts: '批注草稿', commentChooseDraft: '请选择草稿', commentEditDraft: '编辑稿', commentReplyDraft: '回复稿', commentRecover: '恢复草稿', commentDiscard: '放弃草稿', commentBackupFailed: '最新的批注草稿只在本次会话中保留,请发布后再关闭窗口。', stepNarration: '讲稿', stepCaptions: '字幕', previousStep: '上一步', nextStep: '下一步', narrationStep: (step: number, total: number, title: string) => `第 ${step} / ${total} 步${title ? ` · ${title}` : ''}`, previewFailure: '预览失败', previewLoading: '正在更新预览…', previewPrevious: '上次已保存的预览', previewSnapshot: '文稿内预览', previewRetry: '重试', previewRefresh: '刷新', previewTitle: '内容块只读预览', comment: '新建批注', stepComment: (step: number) => `在第 ${step} 步批注`, stepCommentHint: (step: number, count: number) => count ? `第 ${step} 步 · ${count} 条未解决批注` : `在第 ${step} 步批注`, stepCommentFailed: '无法保存这条批注,请重试。', stepCommentStep: '批注位置', stepCommentWhole: '整个内容块', stepCommentOption: (step: number, title: string) => title ? `第 ${step} 步 · ${title}` : `第 ${step} 步`, placeCommentReference: (label: string, step?: number) => step ? `“${label}” · 第 ${step} 步` : `“${label}”`, block: '内容块', commentChanged: '这条批注已在别处修改。请先复制草稿,再取消以查看已保存的内容。', commentUnavailable: '无法确认这条批注的版本。请先复制草稿,再关闭并重新打开。', author: '作者', page: '新页面', document: '文稿', untitledPage: '未命名页面', opaque: '组件', animation: (title: string) => `动画:${title}`, component: (title: string) => `组件:${title}`, codeReference: (title: string) => `引用代码:${title}`, syncedBlock: (source: string) => `同步块:来自 ${source},将在后续版本中显示`, diagram: (title: string) => title ? `图表:${title}` : '图表', adapterError: '无法保存这次编辑。请保持页面打开,并查看诊断。', conflict: '文稿已在别处修改。草稿已保留,请先核对当前文稿,再重试或放弃草稿。', saveFailure: '文稿尚未确认保存,草稿已保留。请保持页面打开后重试。', restored: '已恢复尚未保存的草稿,请检查后重新保存或放弃。', loading: '正在加载文稿…', unavailable: '暂时无法加载文稿,请重试。', diagnostics: (count: number) => `${count} 项诊断`, formulaBlockAliases: '公式|数学', formulaInlineAliases: '行内公式|公式', pageAliases: '页面|章节', animateWithAI: '用 AI 插入动画…', animateWithAIHint: '告诉 AI 这里的动画要演示什么', animateWithAIAliases: '动画|场景|演示' },
|
|
8
|
+
en: { colors: 'Colors', textColor: 'Text color', backgroundColor: 'Highlight', colorDefault: 'Default', backgroundDefault: 'No highlight', colorNames: { muted: 'Gray · subtle', accent: 'Teal · accent', ok: 'Green · success', warn: 'Amber · caution', danger: 'Red · alert' }, backgroundNames: { muted: 'Gray', accent: 'Teal', ok: 'Green', warn: 'Amber', danger: 'Red' }, formula: 'Formula', formulaInline: 'Inline Formula', formulaBlock: 'Formula Block', formulaInlineHint: 'A LaTeX formula within the text', formulaBlockHint: 'A LaTeX formula on its own line', openLink: 'Open Link', goToSection: (title: string) => `Go to “${title}”`, mathEmpty: 'Insert Formula', mathInvalid: 'Formula not recognized', mathPlaceholder: 'Enter a LaTeX formula', commentRecoveryChanged: 'Draft recovery canceled. Your current input is kept.', commentNewDraft: 'New Comment', commentsEmpty: 'No comments yet. Select text in the document, or use Comment on step in an animation or chart toolbar.', commentTargetUnavailable: 'The original selection changed or is unavailable. You can still recover your draft.', commentSessionOnly: 'This session only', commentDrafts: 'Comment drafts', commentChooseDraft: 'Choose a draft', commentEditDraft: 'Comment edit', commentReplyDraft: 'Reply', commentRecover: 'Recover Draft', commentDiscard: 'Discard Draft', commentBackupFailed: 'The latest comment draft is kept in this session only. Post it before closing this window.', stepNarration: 'Script', stepCaptions: 'Captions', previousStep: 'Previous Step', nextStep: 'Next Step', narrationStep: (step: number, total: number, title: string) => `Step ${step} / ${total}${title ? ` · ${title}` : ''}`, previewFailure: 'Preview failed', previewLoading: 'Updating preview…', previewPrevious: 'Last saved preview', previewSnapshot: 'Document preview', previewRetry: 'Retry', previewRefresh: 'Refresh', previewTitle: 'Read-only block preview', comment: 'New Comment', stepComment: (step: number) => `Comment on step ${step}`, stepCommentHint: (step: number, count: number) => count ? `Step ${step} · ${count} unresolved` : `Comment on step ${step}`, stepCommentFailed: 'Couldn’t save this comment. Try again.', stepCommentStep: 'Comment on', stepCommentWhole: 'The whole content block', stepCommentOption: (step: number, title: string) => title ? `Step ${step} · ${title}` : `Step ${step}`, placeCommentReference: (label: string, step?: number) => step ? `“${label}” · Step ${step}` : `“${label}”`, block: 'Content block', commentChanged: 'This comment changed elsewhere. Copy your draft, then cancel to view the saved comment.', commentUnavailable: 'Couldn’t confirm this comment’s version. Copy your draft before closing and reopening it.', author: 'Author', page: 'New Page', document: 'Document', untitledPage: 'Untitled page', opaque: 'Component', animation: (title: string) => `Animation: ${title}`, component: (title: string) => `Component: ${title}`, codeReference: (title: string) => `Referenced code: ${title}`, syncedBlock: (source: string) => `Synced block from ${source}. It will be shown in a later version.`, diagram: (title: string) => title ? `Diagram: ${title}` : 'Diagram', adapterError: 'Couldn’t save this edit. Keep this page open and check the diagnostics.', conflict: 'The document changed elsewhere. Your draft is kept; review the current document, then try again or discard your draft.', saveFailure: 'Couldn’t confirm the save. Your draft is kept; keep this page open and try again.', restored: 'A draft that was not saved was recovered. Review it, then save it again or discard it.', loading: 'Loading document…', unavailable: 'Couldn’t load the document. Try again.', diagnostics: (count: number) => `${count} ${count === 1 ? 'diagnostic' : 'diagnostics'}`, formulaBlockAliases: 'formula|math|equation|latex|tex', formulaInlineAliases: 'inline formula|inline math|latex|tex', pageAliases: 'page|section', animateWithAI: 'Insert Animation with AI…', animateWithAIHint: 'Tell the AI what the animation here should show', animateWithAIAliases: 'animation|animate|scene|motion' },
|
|
9
9
|
}
|
|
10
10
|
|
|
11
11
|
/** Slash-menu search words (`|`-separated): an author finds an item by its name in either language, whatever the interface's. */
|
|
12
|
-
export function slashAliases(key: 'formulaBlockAliases' | 'formulaInlineAliases' | 'pageAliases'): string[] {
|
|
12
|
+
export function slashAliases(key: 'formulaBlockAliases' | 'formulaInlineAliases' | 'pageAliases' | 'animateWithAIAliases'): string[] {
|
|
13
13
|
return [...new Set([...DOCUMENT_EDITOR_MESSAGES.en[key].split('|'), ...DOCUMENT_EDITOR_MESSAGES['zh-CN'][key].split('|')])]
|
|
14
14
|
}
|
|
@@ -6,6 +6,7 @@ import { Extension } from '@tiptap/core'
|
|
|
6
6
|
import { Plugin } from '@tiptap/pm/state'
|
|
7
7
|
import { Fragment, Slice } from '@tiptap/pm/model'
|
|
8
8
|
import type { Node } from '@tiptap/pm/model'
|
|
9
|
+
import { randomUUID } from '@lincyaw/kernel'
|
|
9
10
|
import { PmButton, PmDialog, PmInput } from '../components.tsx'
|
|
10
11
|
import type { Locale } from '../messages.ts'
|
|
11
12
|
|
|
@@ -49,36 +50,41 @@ const atom = createReactInlineContentSpec({
|
|
|
49
50
|
},
|
|
50
51
|
})
|
|
51
52
|
|
|
52
|
-
|
|
53
|
+
export function createNarrationExtensions(owners: () => ReadonlyMap<string, string>, copied: (from: string, to: string) => void) {
|
|
54
|
+
const copyId = (id: string) => { const next = randomUUID(); copied(id, next); return next }
|
|
55
|
+
return [createExtension({
|
|
53
56
|
key: 'presmium-narration-cue-identities',
|
|
54
57
|
tiptapExtensions: [Extension.create({ name: 'presmiumNarrationCueIdentities', addProseMirrorPlugins: () => [new Plugin({
|
|
55
58
|
props: { transformPasted: slice => {
|
|
56
59
|
const copied = (fragment: Fragment): Fragment => {
|
|
57
60
|
const nodes: Node[] = []
|
|
58
61
|
fragment.forEach(node => nodes.push(node.type.name === 'narrationAtom' && node.attrs.kind === 'cue'
|
|
59
|
-
? node.type.create({ ...node.attrs, cueId:
|
|
62
|
+
? node.type.create({ ...node.attrs, cueId: copyId(node.attrs.cueId as string) }, node.content, node.marks)
|
|
60
63
|
: node.isLeaf ? node : node.copy(copied(node.content))))
|
|
61
64
|
return Fragment.fromArray(nodes)
|
|
62
65
|
}
|
|
63
66
|
return new Slice(copied(slice.content), slice.openStart, slice.openEnd)
|
|
64
67
|
} },
|
|
65
68
|
appendTransaction: (_transactions, _old, state) => {
|
|
66
|
-
const seen = new Set<string>(), transaction = state.tr
|
|
69
|
+
const seen = new Set<string>(), transaction = state.tr, external = owners()
|
|
67
70
|
state.doc.descendants((node, position) => {
|
|
68
71
|
if (node.type.name !== 'narrationAtom' || node.attrs.kind !== 'cue') return
|
|
69
72
|
const id = node.attrs.cueId as string
|
|
70
|
-
|
|
73
|
+
const location = state.doc.resolve(position)
|
|
74
|
+
let blockId: string | undefined
|
|
75
|
+
for (let depth = location.depth; depth > 0; depth--) if (location.node(depth).type.name === 'blockContainer') { blockId = location.node(depth).attrs.id as string; break }
|
|
76
|
+
if (!id || seen.has(id) || external.has(id) && external.get(id) !== blockId) transaction.setNodeMarkup(position, undefined, { ...node.attrs, cueId: copyId(id) })
|
|
71
77
|
else seen.add(id)
|
|
72
78
|
})
|
|
73
79
|
return transaction.docChanged ? transaction : null
|
|
74
80
|
},
|
|
75
81
|
})] })],
|
|
76
|
-
})
|
|
82
|
+
})]
|
|
83
|
+
}
|
|
77
84
|
export const narrationSchema = BlockNoteSchema.create({
|
|
78
85
|
blockSpecs: { paragraph: defaultBlockSpecs.paragraph },
|
|
79
86
|
inlineContentSpecs: { ...defaultInlineContentSpecs, narrationAtom: atom }, styleSpecs: {},
|
|
80
87
|
})
|
|
81
|
-
export const narrationExtensions = [cueIdentities]
|
|
82
88
|
export type NativeNarrationEditor = BlockNoteEditor<typeof narrationSchema.blockSchema, typeof narrationSchema.inlineContentSchema, typeof narrationSchema.styleSchema>
|
|
83
89
|
export type NativeNarrationBlock = Block<typeof narrationSchema.blockSchema, typeof narrationSchema.inlineContentSchema, typeof narrationSchema.styleSchema>
|
|
84
90
|
export type NativeNarrationInput = PartialBlock<typeof narrationSchema.blockSchema, typeof narrationSchema.inlineContentSchema, typeof narrationSchema.styleSchema>
|
|
@@ -1,18 +1,34 @@
|
|
|
1
|
-
import type { NarrationNode } from '@lincyaw/kernel'
|
|
1
|
+
import type { Narration, NarrationNode } from '@lincyaw/kernel'
|
|
2
2
|
import type { NativeNarrationBlock, NativeNarrationInput, NativeNarrationInline } from './narration-schema.tsx'
|
|
3
3
|
import type { NativeNarrationEditor } from './narration-schema.tsx'
|
|
4
4
|
import { nativeFieldFocus } from './focus.ts'
|
|
5
5
|
|
|
6
|
-
export const narrationFieldFocus = (editor: NativeNarrationEditor) => nativeFieldFocus(editor, () => JSON.stringify(
|
|
6
|
+
export const narrationFieldFocus = (editor: NativeNarrationEditor) => nativeFieldFocus(editor, () => JSON.stringify(nativeToNarrations(editor.document)))
|
|
7
7
|
|
|
8
8
|
export function narrationToNative(id: string, content: readonly NarrationNode[]): NativeNarrationInput[] {
|
|
9
|
-
return [{ id
|
|
9
|
+
return [{ id, type: 'paragraph', content: content.map((node): NativeNarrationInline => {
|
|
10
10
|
if (node.type === 'text') return { type: 'text', text: node.text, styles: {} }
|
|
11
11
|
return { type: 'narrationAtom', content: undefined, props: node.type === 'pronunciation'
|
|
12
12
|
? { kind: 'pronunciation', display: node.display, spoken: node.spoken, cueId: '', payload: '' }
|
|
13
13
|
: { kind: 'cue', cueId: node.id, payload: JSON.stringify(node), display: '', spoken: '' } }
|
|
14
14
|
}) }]
|
|
15
15
|
}
|
|
16
|
+
|
|
17
|
+
export function narrationsToNative(narrations: readonly Narration[], emptyId: string): NativeNarrationInput[] {
|
|
18
|
+
return narrations.length ? narrations.flatMap(narration => narrationToNative(narration.id, narration.content)) : narrationToNative(emptyId, [])
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function nativeToNarrations(blocks: readonly NativeNarrationBlock[]): Narration[] {
|
|
22
|
+
const narrations: Narration[] = []
|
|
23
|
+
const visit = (blocks: readonly NativeNarrationBlock[]) => {
|
|
24
|
+
for (const block of blocks) {
|
|
25
|
+
narrations.push({ id: block.id, content: nativeToNarration([{ ...block, children: [] }]) })
|
|
26
|
+
visit(block.children)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
visit(blocks)
|
|
30
|
+
return narrations.length === 1 && !narrations[0]!.content.length ? [] : narrations
|
|
31
|
+
}
|
|
16
32
|
export function nativeToNarration(blocks: readonly NativeNarrationBlock[]): NarrationNode[] {
|
|
17
33
|
const content: NarrationNode[] = []
|
|
18
34
|
const text = (value: string) => {
|