@lincyaw/workbench 0.2.0-rc.8 → 0.2.0-rc.80

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.
Files changed (90) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +4 -3
  3. package/src/StepProductionEditor.tsx +13 -4
  4. package/src/approvals.tsx +6 -1
  5. package/src/audio-recording.ts +27 -5
  6. package/src/authoring-client.ts +10 -10
  7. package/src/authoring-draft-fragment.ts +3 -1
  8. package/src/authoring-window.ts +100 -0
  9. package/src/body-draft-actions.ts +60 -0
  10. package/src/caption-timing-drafts.ts +18 -1
  11. package/src/component-property-drafts.ts +5 -5
  12. package/src/components.tsx +22 -31
  13. package/src/context.tsx +5 -3
  14. package/src/diagnostics.ts +1 -1
  15. package/src/document-draft-store.ts +45 -18
  16. package/src/document-drafts.ts +28 -19
  17. package/src/document-editing.ts +484 -0
  18. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  19. package/src/document-editor/ComponentMaterials.tsx +3 -9
  20. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  21. package/src/document-editor/DocumentBlockPreview.tsx +4 -2
  22. package/src/document-editor/DocumentComments.tsx +85 -14
  23. package/src/document-editor/DocumentEditor.tsx +44 -7
  24. package/src/document-editor/DocumentStepNarration.tsx +33 -25
  25. package/src/document-editor/NarrationEditor.tsx +54 -20
  26. package/src/document-editor/NewCommentDrafts.tsx +114 -31
  27. package/src/document-editor/PlaceComment.tsx +228 -0
  28. package/src/document-editor/comment-draft-actions.ts +40 -20
  29. package/src/document-editor/comment-draft-inspection.ts +2 -2
  30. package/src/document-editor/comment-drafts.ts +73 -25
  31. package/src/document-editor/comments.ts +30 -10
  32. package/src/document-editor/component-label.ts +11 -0
  33. package/src/document-editor/file-input.ts +2 -2
  34. package/src/document-editor/focus.ts +0 -2
  35. package/src/document-editor/insertion-place.ts +60 -0
  36. package/src/document-editor/messages.ts +3 -3
  37. package/src/document-editor/narration-schema.tsx +12 -6
  38. package/src/document-editor/narration.ts +19 -3
  39. package/src/document-editor/page-body.ts +60 -0
  40. package/src/document-editor/projection.ts +2 -2
  41. package/src/document-editor/rich-text.ts +3 -2
  42. package/src/document-editor/selection.ts +13 -0
  43. package/src/document-editor/style.css +12 -1
  44. package/src/document-editor/table-identities.ts +2 -1
  45. package/src/document-production.ts +491 -0
  46. package/src/document-session.ts +202 -56
  47. package/src/document-timing-drafts.ts +22 -2
  48. package/src/history.ts +5 -5
  49. package/src/index.ts +6 -5
  50. package/src/jobs.ts +1 -1
  51. package/src/media-drafts.ts +43 -1
  52. package/src/messages.ts +31 -14
  53. package/src/panels/DocumentView.tsx +71 -28
  54. package/src/panels/DocumentVoiceDialog.tsx +25 -9
  55. package/src/panels/DocumentVoiceField.tsx +1 -1
  56. package/src/panels/ExportPanel.tsx +1 -6
  57. package/src/panels/HistoryPanel.tsx +32 -2
  58. package/src/panels/PageDeleteDialog.tsx +4 -4
  59. package/src/panels/PageRenameDialog.tsx +1 -1
  60. package/src/panels/PreviewPanel.tsx +1 -4
  61. package/src/panels/ProductionCaptionSize.tsx +20 -0
  62. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  63. package/src/panels/ProductionMediaClips.tsx +23 -7
  64. package/src/panels/ProductionPanel.tsx +8 -4
  65. package/src/panels/ProductionRecording.tsx +86 -9
  66. package/src/panels/ProductionRecordingRange.tsx +21 -19
  67. package/src/panels/ProductionTimeline.tsx +6 -1
  68. package/src/panels/ProductionTranscription.tsx +5 -4
  69. package/src/panels/SourceDocumentPanel.tsx +16 -36
  70. package/src/panels/TranscriptionAdoption.tsx +40 -34
  71. package/src/panels/VoiceCloneDialog.tsx +2 -1
  72. package/src/panels/VoiceoverDialog.tsx +1 -1
  73. package/src/places.ts +1 -36
  74. package/src/preview-playback.ts +1 -1
  75. package/src/production-draft-actions.ts +37 -0
  76. package/src/production-messages.ts +6 -0
  77. package/src/production-playback.ts +1 -1
  78. package/src/production-voice-playback.ts +3 -2
  79. package/src/sha256.ts +9 -0
  80. package/src/styles.css +21 -43
  81. package/src/transcription-drafts.ts +124 -0
  82. package/src/use-recording-adoption.ts +2 -2
  83. package/src/voice-drafts.ts +32 -8
  84. package/src/voiceover-jobs.ts +1 -1
  85. package/src/workbench-state.ts +157 -0
  86. package/src/workbench.ts +258 -951
  87. package/src/workspace-client.ts +21 -11
  88. package/src/assistant-mascot.ts +0 -62
  89. package/src/mascot-preference.ts +0 -37
  90. 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, TeachingDocument } from '@lincyaw/kernel'
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, TeachingDocument } 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?: DocumentThread['anchor'], signature?: string }
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: TeachingDocument, anchor: DocumentThread['anchor']): string | undefined {
11
+ export function newCommentDraftSignature(document: TeachingDocument, 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 && JSON.stringify(a.anchor) === JSON.stringify(b.anchor)
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) && point(value.anchor.from) && point(value.anchor.to) && typeof value.signature === 'string')
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 = crypto.randomUUID()
84
+ readonly #owner = randomUUID()
81
85
  #reader?: DocumentDraftStore
82
86
  readonly #listeners = new Set<() => void>()
83
87
  readonly #writing = new Map<string, Writing>()
@@ -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 || isNewCommentDraft(candidate.target) || candidate.storage !== 'durable' || candidate.composing || candidate.pending) return
120
- const matching = [...this.#composers.values()].filter(value => value.restore && sameCommentDraftTarget(value.target, candidate.target) && value.snapshot().available && !value.snapshot().composing && value.targetState() !== 'unavailable')
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 || writing.pending || writing.failed || !writing.store.owns(keyOf(this.#scope, current.id), writing.raw)) return
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,7 +274,7 @@ 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 || JSON.stringify(thread.anchor) === JSON.stringify(target.anchor)) && comment && !comment.deletedAt && committedValue(comment) === record.pending.value)
277
+ && (!created || documentAnchorKey(thread.anchor) === documentAnchorKey(target.anchor)) && comment && !comment.deletedAt && committedValue(comment) === record.pending.value)
232
278
  }
233
279
  synchronize(document: TeachingDocument, version: string | undefined, acknowledged = false): void {
234
280
  this.#document = document; this.#version = version; this.#acknowledged = acknowledged
@@ -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 : crypto.randomUUID(), owner: this.#owner,
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([prefix(this.#scope)], operation?.signal), writing = this.#writing.get(reference.id)
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 && await tokenOf(writing.raw) === reference.token) { this.#writing.delete(reference.id); writing.store.close() }
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(); await this.refresh()
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([prefix(this.#scope)], operation?.signal), writing = this.#writing.get(reference.id)
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: crypto.randomUUID(), owner: this.#owner, revision: 1, updatedAt: Date.now(), version, composing: false, pending: undefined }
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, TeachingDocument } from '@lincyaw/kernel'
7
+ import { applyDocumentCommentAction, degradeDocumentCommentAnchor, hasRole, isDocumentPlaceAnchor, isDocumentTextAnchor, LOCAL_AUTHOR, randomUUID, validateDocumentCommentAnchor } from '@lincyaw/kernel'
8
+ import type { DocumentComment, DocumentCommentAction, DocumentPlaceAnchor, DocumentThread, DocumentThreadAnchor, Member, RichTextNode, TeachingDocument } 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'
@@ -84,7 +84,10 @@ export class DocumentThreadStore extends ThreadStore {
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(): TeachingDocument { 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 = crypto.randomUUID()): NewCommentDraftTarget {
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: () => crypto.randomUUID() })
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)!
@@ -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: TeachingDocument = 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 position = positions.get(thread.id)
310
- const from = position ? nativeTextPoint(editor, position.from) : undefined, to = position ? nativeTextPoint(editor, position.to) : undefined
311
- const anchor = from && to ? { from: { blockId: from.blockId, offset: from.offset }, to: { blockId: to.blockId, offset: to.offset } } : undefined
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: crypto.randomUUID(), type: 'image' as const, props: { name: file.name } }))
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 }))
@@ -25,8 +25,6 @@ export interface DocumentFieldRegistration {
25
25
  reset: number
26
26
  blockId?: string
27
27
  stepId: string
28
- narrationId: string
29
- slot: number
30
28
  focus: DocumentFieldFocus
31
29
  editor?: DocumentHistoryEditor
32
30
  }
@@ -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: '还没有批注。选中正文中的文字,再选“新建批注”。', 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: '新建批注', commentChanged: '这条批注已在别处修改。请先复制草稿,再取消以查看已保存的内容。', commentUnavailable: '无法确认这条批注的版本。请先复制草稿,再关闭并重新打开。', author: '作者', page: '新页面', document: '文稿', untitledPage: '未命名页面', opaque: '组件', animation: (title: string) => `动画:${title}`, component: (title: string) => `组件:${title}`, codeReference: (title: string) => `引用代码:${title}`, diagram: (title: string) => title ? `图表:${title}` : '图表', adapterError: '无法保存这次编辑。请保持页面打开,并查看诊断。', conflict: '文稿已在别处修改。草稿已保留,请先核对当前文稿,再重试或放弃草稿。', saveFailure: '文稿尚未确认保存,草稿已保留。请保持页面打开后重试。', restored: '已恢复尚未保存的草稿,请检查后重新保存或放弃。', loading: '正在加载文稿…', unavailable: '暂时无法加载文稿,请重试。', diagnostics: (count: number) => `${count} 项诊断`, formulaBlockAliases: '公式|数学', formulaInlineAliases: '行内公式|公式', pageAliases: '页面|章节' },
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, then choose New Comment.', 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', 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}`, 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' },
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} 步批注`, stepCommentSave: '保存批注', stepCommentCancel: '取消', stepCommentFailed: '无法保存这条批注,请重试。', stepCommentPlaceholder: '写下这里要改的地方', 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}`, 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}`, stepCommentSave: 'Save Comment', stepCommentCancel: 'Cancel', stepCommentFailed: 'Couldn’t save this comment. Try again.', stepCommentPlaceholder: 'Write what should change here', 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}`, 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
- const cueIdentities = createExtension({
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: crypto.randomUUID() }, node.content, node.marks)
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
- if (!id || seen.has(id)) transaction.setNodeMarkup(position, undefined, { ...node.attrs, cueId: crypto.randomUUID() })
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(nativeToNarration(editor.document)))
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: `narration:${id}`, type: 'paragraph', content: content.map((node): NativeNarrationInline => {
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) => {
@@ -0,0 +1,60 @@
1
+ import { createExtension } from '@blocknote/core'
2
+ import { Plugin, TextSelection } from '@tiptap/pm/state'
3
+ import type { EditorState } from '@tiptap/pm/state'
4
+ import { Decoration, DecorationSet } from '@tiptap/pm/view'
5
+ import type { Node } from '@tiptap/pm/model'
6
+ import type { NativeDocumentEditor } from './schema.tsx'
7
+
8
+ // Pages are top-level blocks: doc > blockGroup > blockContainer > (content, children?).
9
+ function emptyParagraph(container: Node | null | undefined): boolean {
10
+ return container?.childCount === 1 && container.firstChild!.type.name === 'paragraph' && container.firstChild!.content.size === 0
11
+ }
12
+
13
+ function pageEnds(doc: Node, placeholder: string): DecorationSet {
14
+ const group = doc.firstChild, found: Decoration[] = []
15
+ if (!group) return DecorationSet.empty
16
+ group.forEach((container, offset, index) => {
17
+ const next = index + 1 < group.childCount ? group.child(index + 1) : undefined
18
+ if (!emptyParagraph(container) || next && next.firstChild?.type.name !== 'presmiumPage') return
19
+ const start = 1 + offset + 1
20
+ found.push(Decoration.node(start, start + container.firstChild!.nodeSize, { 'data-page-end': '', 'data-placeholder': placeholder }))
21
+ })
22
+ return DecorationSet.create(doc, found)
23
+ }
24
+
25
+ /**
26
+ * A page's empty last paragraph shows the editor's placeholder even without the caret, so an empty body is visible;
27
+ * Enter at the end of a title goes into that paragraph instead of adding another one before it.
28
+ */
29
+ export const documentPageBodies = createExtension(({ editor }: { editor: NativeDocumentEditor }) => ({
30
+ key: 'presmium-document-page-bodies',
31
+ prosemirrorPlugins: [new Plugin<DecorationSet>({
32
+ state: {
33
+ init: (_, state: EditorState) => pageEnds(state.doc, editor.dictionary.placeholders.default ?? ''),
34
+ apply: (transaction, value) => transaction.docChanged ? pageEnds(transaction.doc, editor.dictionary.placeholders.default ?? '') : value,
35
+ },
36
+ props: { decorations(state) { return editor.isEditable ? this.getState(state) : undefined } },
37
+ })],
38
+ keyboardShortcuts: {
39
+ Enter: () => {
40
+ const { selection } = editor.prosemirrorState, { $head } = selection
41
+ if (!editor.isEditable || !selection.empty || $head.parent.type.name !== 'presmiumPage' || $head.parentOffset !== $head.parent.content.size) return false
42
+ const after = $head.after($head.depth - 1)
43
+ if (!emptyParagraph(editor.prosemirrorState.doc.resolve(after).nodeAfter)) return false
44
+ editor.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, after + 2)).scrollIntoView())
45
+ return true
46
+ },
47
+ },
48
+ }))
49
+
50
+ /** The caret at the end of the document: in its empty last paragraph, or in a new one after the last block. */
51
+ export function focusDocumentEnd(editor: NativeDocumentEditor): void {
52
+ const last = editor.document.at(-1)
53
+ if (!last) return
54
+ editor.transact(transaction => {
55
+ if (last.type === 'paragraph' && !last.children.length && !last.content.length) editor.setTextCursorPosition(last, 'end')
56
+ else editor.setTextCursorPosition(editor.insertBlocks([{ type: 'paragraph' }], last, 'after')[0]!, 'start')
57
+ transaction.scrollIntoView()
58
+ })
59
+ editor.focus()
60
+ }