@lincyaw/workbench 0.2.0-rc.3 → 0.2.0-rc.31

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 (57) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +1 -1
  3. package/src/authoring-client.ts +3 -3
  4. package/src/authoring-draft-fragment.ts +3 -1
  5. package/src/component-property-drafts.ts +5 -5
  6. package/src/components.tsx +10 -28
  7. package/src/document-drafts.ts +6 -7
  8. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  9. package/src/document-editor/ComponentMaterials.tsx +3 -9
  10. package/src/document-editor/ComponentPropertiesDialog.tsx +3 -3
  11. package/src/document-editor/DocumentBlockPreview.tsx +2 -0
  12. package/src/document-editor/DocumentComments.tsx +58 -9
  13. package/src/document-editor/DocumentEditor.tsx +44 -7
  14. package/src/document-editor/DocumentStepNarration.tsx +24 -19
  15. package/src/document-editor/NarrationEditor.tsx +54 -20
  16. package/src/document-editor/NewCommentDrafts.tsx +4 -3
  17. package/src/document-editor/PlaceComment.tsx +150 -0
  18. package/src/document-editor/comment-drafts.ts +16 -14
  19. package/src/document-editor/comments.ts +30 -10
  20. package/src/document-editor/component-label.ts +11 -0
  21. package/src/document-editor/file-input.ts +2 -2
  22. package/src/document-editor/focus.ts +0 -2
  23. package/src/document-editor/insertion-place.ts +60 -0
  24. package/src/document-editor/messages.ts +3 -3
  25. package/src/document-editor/narration-schema.tsx +12 -6
  26. package/src/document-editor/narration.ts +19 -3
  27. package/src/document-editor/page-body.ts +60 -0
  28. package/src/document-editor/projection.ts +2 -2
  29. package/src/document-editor/rich-text.ts +3 -2
  30. package/src/document-editor/selection.ts +13 -0
  31. package/src/document-editor/style.css +12 -1
  32. package/src/document-editor/table-identities.ts +2 -1
  33. package/src/document-session.ts +50 -16
  34. package/src/history.ts +2 -2
  35. package/src/index.ts +0 -3
  36. package/src/messages.ts +19 -4
  37. package/src/panels/DocumentView.tsx +10 -10
  38. package/src/panels/ExportPanel.tsx +1 -6
  39. package/src/panels/PreviewPanel.tsx +1 -4
  40. package/src/panels/ProductionCaptionSize.tsx +20 -0
  41. package/src/panels/ProductionCaptionTiming.tsx +3 -3
  42. package/src/panels/ProductionMediaClips.tsx +2 -1
  43. package/src/panels/ProductionPanel.tsx +5 -1
  44. package/src/panels/ProductionRecordingRange.tsx +2 -2
  45. package/src/panels/ProductionTimeline.tsx +6 -1
  46. package/src/panels/ProductionTranscription.tsx +2 -1
  47. package/src/panels/SourceDocumentPanel.tsx +3 -6
  48. package/src/panels/TranscriptionAdoption.tsx +7 -6
  49. package/src/places.ts +1 -36
  50. package/src/production-messages.ts +6 -0
  51. package/src/sha256.ts +9 -0
  52. package/src/styles.css +16 -41
  53. package/src/workbench.ts +124 -88
  54. package/src/workspace-client.ts +2 -1
  55. package/src/assistant-mascot.ts +0 -62
  56. package/src/mascot-preference.ts +0 -37
  57. package/src/panels/ChangeTrail.tsx +0 -79
@@ -1,7 +1,8 @@
1
1
  import { useEffect, useMemo, useRef } from 'react'
2
2
  import type { Transaction } from '@tiptap/pm/state'
3
+ import { TextSelection } from '@tiptap/pm/state'
3
4
  import { closeHistory } from '@tiptap/pm/history'
4
- import { allocateDocumentPage } from '@lincyaw/kernel'
5
+ import { allocateDocumentPage, randomUUID } from '@lincyaw/kernel'
5
6
  import type { Member, TeachingDocument } from '@lincyaw/kernel'
6
7
  import type { Locale } from '../messages.ts'
7
8
  import { BlockNoteSurface } from './BlockNoteSurface.tsx'
@@ -12,17 +13,25 @@ import type { NativePageCreation } from './projection.ts'
12
13
  import { captureRichBaseline } from './rich-text.ts'
13
14
  import { captureTableIdentities, seedTableIdentities } from './table-identities.ts'
14
15
  import type { DocumentNodeViews, NativeDocumentEditor } from './schema.tsx'
15
- import { nativeEditingCursor } from './selection.ts'
16
- import type { NativeDocumentSelection } from './selection.ts'
16
+ import { nativeEditingCursor, nativeTextPoint, nativeTextPosition } from './selection.ts'
17
+ import type { NativeDocumentSelection, NativeTextPoint } from './selection.ts'
18
+ import { documentInsertionPlace } from './insertion-place.ts'
19
+ import type { DocumentInsertionPlace } from './insertion-place.ts'
17
20
 
18
21
  export interface DocumentEditingPosition {
19
22
  nativeBlockId: string
20
23
  sectionId: string
21
24
  position: number
22
25
  }
26
+ /** Who takes the slash menu's request for an animation where it was opened; while none is available the menu has no such item. */
27
+ export interface DocumentAnimationRequests {
28
+ available(): boolean
29
+ request(place: DocumentInsertionPlace): void
30
+ }
23
31
  export interface DocumentEditorCommands {
24
32
  insertPage(after: string | undefined, title: string): NativePageCreation
25
33
  rememberComponentConfiguration(document: TeachingDocument): void
34
+ handleAnimationRequests(requests: DocumentAnimationRequests | undefined): void
26
35
  }
27
36
 
28
37
  export interface DocumentEditorProps {
@@ -56,6 +65,7 @@ export interface DocumentEditorProps {
56
65
  onError?(error: Error): void
57
66
  commentsPortal?: HTMLElement | null
58
67
  onCommentDraftRestore?(): void
68
+ onOpenComments?(): void
59
69
  }
60
70
 
61
71
  /** A source version reset replaces the editor; its own save receipts never replace it. */
@@ -73,11 +83,19 @@ export function DocumentEditor(props: DocumentEditorProps) {
73
83
  return () => comments.close()
74
84
  }, [comments])
75
85
  const current = useRef(props), editor = useRef<NativeDocumentEditor>(), unsubscribe = useRef<() => void>()
86
+ const animationRequests = useRef<DocumentAnimationRequests>()
76
87
  const projectedDocument = useRef<NativeDocumentEditor['prosemirrorState']['doc']>()
77
88
  const pendingTransaction = useRef<Transaction>()
78
89
  const focusFrame = useRef<number>()
79
90
  const binding = useRef(projection)
80
91
  const active = useRef(projection)
92
+ const editorIdentity = useRef(props.identity)
93
+ const retainedSelection = useRef<{ from: NativeTextPoint, to: NativeTextPoint }>()
94
+ const previous = editor.current
95
+ if (binding.current !== projection && editorIdentity.current === props.identity && previous?.isFocused() && !previous.prosemirrorView.composing) {
96
+ const from = nativeTextPoint(previous, previous.prosemirrorState.selection.anchor), to = nativeTextPoint(previous, previous.prosemirrorState.selection.head)
97
+ if (from && to) retainedSelection.current = { from, to }
98
+ }
81
99
  active.current = projection
82
100
  current.current = props
83
101
  const cancelFocus = () => { if (focusFrame.current !== undefined) cancelAnimationFrame(focusFrame.current); focusFrame.current = undefined }
@@ -113,7 +131,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
113
131
  if (!latest || current.current.getDocumentVersion && current.current.getDocumentVersion() === undefined) return
114
132
  syncComments()
115
133
  const document = nativeDocumentToProduct(editor.current.document, projection, latest)
116
- const threads = comments.snapshot(editor.current)
134
+ const threads = comments.snapshot(editor.current, document)
117
135
  if (Object.keys(threads).length) document.comments = threads
118
136
  else delete document.comments
119
137
  current.current.onChange(document)
@@ -125,7 +143,16 @@ export function DocumentEditor(props: DocumentEditorProps) {
125
143
  }
126
144
  return <BlockNoteSurface identity={props.identity} reset={props.reset} initialContent={projection.content} locale={props.locale} contentLang={props.document.metadata.lang || 'zh-CN'} readOnly={props.readOnly}
127
145
  resolveAssetURL={props.resolveAssetURL} uploadImage={props.uploadImage}
128
- comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection} onSectionLink={sectionId => {
146
+ comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} onOpenComments={() => current.current.onOpenComments?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection}
147
+ animationRequest={{
148
+ available: () => !current.current.readOnly && binding.current === projection && active.current === projection && Boolean(animationRequests.current?.available()),
149
+ request: value => {
150
+ if (value !== editor.current || binding.current !== projection || active.current !== projection) return
151
+ const place = documentInsertionPlace(value, projection)
152
+ if (place) animationRequests.current?.request(place)
153
+ },
154
+ }}
155
+ onSectionLink={sectionId => {
129
156
  if (!current.current.onSectionLink?.(sectionId)) return false
130
157
  // The click placed the caret in the link; it follows the reader to the page they asked for.
131
158
  const value = editor.current
@@ -147,7 +174,17 @@ export function DocumentEditor(props: DocumentEditorProps) {
147
174
  comments.restoreAnchors(value)
148
175
  binding.current = projection
149
176
  editor.current = value
177
+ editorIdentity.current = props.identity
150
178
  projectedDocument.current = value.prosemirrorState.doc
179
+ const selection = retainedSelection.current
180
+ retainedSelection.current = undefined
181
+ if (selection) {
182
+ const from = nativeTextPosition(value, selection.from), to = nativeTextPosition(value, selection.to)
183
+ if (from !== undefined && to !== undefined) {
184
+ value.transact(transaction => transaction.setSelection(TextSelection.create(transaction.doc, from, to)).setMeta('addToHistory', false))
185
+ value.focus()
186
+ }
187
+ }
151
188
  const stopBefore = value.onBeforeChange(({ tr }) => { if (!comments.synchronizing && tr.docChanged) pendingTransaction.current = tr })
152
189
  const stopComments = comments.subscribe(emit)
153
190
  const stopSelection = value.onSelectionChange(() => { cancelFocus(); reportPosition() })
@@ -162,7 +199,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
162
199
  })
163
200
  unsubscribe.current = () => { stopBefore(); stopComments(); stopSelection(); stopFocus(); cancelFocus() }
164
201
  }
165
- const commands: DocumentEditorCommands | undefined = value ? { rememberComponentConfiguration: document => {
202
+ const commands: DocumentEditorCommands | undefined = value ? { handleAnimationRequests: requests => { animationRequests.current = requests }, rememberComponentConfiguration: document => {
166
203
  if (editor.current === value && active.current === projection && binding.current === projection && !value.prosemirrorView.isDestroyed) rememberComponentConfiguration(projection, document)
167
204
  }, insertPage: (after, title) => {
168
205
  if (current.current.readOnly || editor.current !== value || active.current !== projection || binding.current !== projection || value.prosemirrorView.isDestroyed) throw new Error('page-context-changed')
@@ -171,7 +208,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
171
208
  const next = after ? blocks.slice(index + 1).find(block => block.type === 'presmiumPage') : undefined
172
209
  const latest = current.current.getDocument ? current.current.getDocument() : current.current.document
173
210
  if (!latest) throw new Error('page-context-changed')
174
- const creation = allocateDocumentPage(latest, () => crypto.randomUUID())
211
+ const creation = allocateDocumentPage(latest, () => randomUUID())
175
212
  projection.createdPages.set(creation.sectionId, creation)
176
213
  try {
177
214
  value.transact(transaction => {
@@ -1,11 +1,12 @@
1
1
  import { useRef, useState } from 'react'
2
- import type { NarrationNode, TeachingDocument } from '@lincyaw/kernel'
2
+ import type { Narration, NarrationNode, TeachingDocument } from '@lincyaw/kernel'
3
+ import { randomUUID } from '@lincyaw/kernel'
3
4
  import { PmIconButton } from '../components.tsx'
4
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
5
6
  import { isAgentChanging } from '../workbench.ts'
6
7
  import { NarrationEditor } from './NarrationEditor.tsx'
7
8
  import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
8
- import { narrationFieldFocus } from './narration.ts'
9
+ import { narrationFieldFocus, narrationsToNative, nativeToNarrations } from './narration.ts'
9
10
  import type { NativeNarrationEditor } from './narration-schema.tsx'
10
11
  import { StepProductionEditor } from '../StepProductionEditor.tsx'
11
12
 
@@ -23,28 +24,32 @@ export function narrationDisplay(content: readonly NarrationNode[]): string {
23
24
  return content.map(node => node.type === 'text' ? node.text : node.type === 'pronunciation' ? node.display : '').join('')
24
25
  }
25
26
 
26
- function NarrationField({ identity, reset, blockId, stepId, slot, narrationId, content, readOnly, advanced, onPause }: {
27
- identity: string, reset: number, blockId?: string, stepId: string, slot: number, narrationId?: string, content: NarrationNode[], readOnly: boolean, advanced: boolean, onPause(): void,
27
+ function NarrationField({ identity, reset, blockId, stepId, content, readOnly, advanced, onPause }: {
28
+ identity: string, reset: number, blockId?: string, stepId: string, content: Narration[], readOnly: boolean, advanced: boolean, onPause(): void,
28
29
  }) {
29
30
  const workbench = useWorkbench(), locale = useWorkbenchState(state => state.locale)
30
- // Reserving an identity does not create an entity. The first actual input commits it.
31
- const [reservedId] = useState(() => {
32
- const pending = workbench.pendingDocumentField(blockId, identity)
33
- return narrationId ?? (pending?.stepId === stepId ? pending.narrationId : undefined) ?? crypto.randomUUID()
34
- })
35
- const id = narrationId ?? reservedId
36
- const target = () => narrationId ?? workbench.getDocument(identity)?.steps[stepId]?.narrationIds[slot] ?? id
31
+ const [emptyId] = useState(() => randomUUID())
32
+ const read = () => {
33
+ const document = workbench.getDocument(identity), step = document?.steps[stepId]
34
+ return step ? step.narrationIds.map(id => ({ id, content: document!.narrations[id]!.content })) : undefined
35
+ }
37
36
  const registration = useRef<() => void>()
38
37
  const fieldEditor = useRef<NativeNarrationEditor>()
39
- const owner = `narration:${identity}:${reset}:${JSON.stringify(blockId ?? null)}:${stepId}:${slot}:${id}`
40
- return <NarrationEditor identity={identity} reset={reset} narrationId={id} content={content} locale={locale} readOnly={readOnly} advanced={advanced}
41
- getContent={() => { const document = workbench.getDocument(identity); return document ? document.narrations[target()]?.content ?? [] : undefined }}
38
+ const owner = `narration:${identity}:${reset}:${JSON.stringify(blockId ?? null)}:${stepId}`
39
+ return <NarrationEditor identity={identity} reset={reset} fieldId={stepId} content={content} locale={locale} readOnly={readOnly} advanced={advanced} blockMenu
40
+ getContent={read} toNative={value => narrationsToNative(value, emptyId)} fromNative={nativeToNarrations}
41
+ cueOwners={() => {
42
+ const document = workbench.getDocument(identity)
43
+ const retained = new Set(Object.values(document?.steps ?? {}).filter(step => step.id !== stepId).flatMap(step => step.narrationIds))
44
+ return new Map([...retained].flatMap(id => document!.narrations[id]!.content.flatMap(node => node.type === 'cue' ? [[node.id, id] as const] : [])))
45
+ }}
46
+ onCueCopy={(from, to) => workbench.copyNarrationCueTiming(from, to, identity)}
42
47
  onReady={editor => {
43
48
  registration.current?.()
44
49
  fieldEditor.current = editor
45
- registration.current = editor ? workbench.registerDocumentField({ identity, reset, blockId, stepId, narrationId: id, slot, focus: narrationFieldFocus(editor), editor }) : undefined
50
+ registration.current = editor ? workbench.registerDocumentField({ identity, reset, blockId, stepId, focus: narrationFieldFocus(editor), editor }) : undefined
46
51
  }}
47
- onFocus={() => { workbench.documentInteraction(); if (fieldEditor.current) workbench.activateDocumentHistory(fieldEditor.current); onPause() }} onChange={value => workbench.setDocumentNarration(stepId, target(), value, identity)}
52
+ onFocus={() => { workbench.documentInteraction(); if (fieldEditor.current) workbench.activateDocumentHistory(fieldEditor.current); onPause() }} onChange={value => workbench.setDocumentNarrations(stepId, value, identity)}
48
53
  onComposition={composing => workbench.documentComposition(composing, owner, identity)}
49
54
  onError={error => workbench.documentError(error)} />
50
55
  }
@@ -78,9 +83,9 @@ export function DocumentStepNarration({ blockId, sectionId, stepId, expanded, ad
78
83
  {!expanded && text && <p className="pm-ui-block-preview__caption" data-step-caption={stepId}>{text}</p>}
79
84
  {expanded && <div id={panelId} className="pm-ui-block-preview__narration-fields">
80
85
  {showLabel && <span className="pm-ui-block-preview__step-label">{fieldLabel}</span>}
81
- {(ids.length ? ids : [undefined]).map((id, slot) => <NarrationField key={`${source.identity}:${source.reset}:${stepId}:${slot}`}
82
- identity={source.identity!} reset={source.reset} blockId={blockId} stepId={stepId} slot={slot} narrationId={id}
83
- content={id ? document.narrations[id]?.content ?? [] : []} readOnly={readOnly} advanced={advanced} onPause={onPause} />)}
86
+ <NarrationField key={`${source.identity}:${source.reset}:${stepId}`}
87
+ identity={source.identity!} reset={source.reset} blockId={blockId} stepId={stepId}
88
+ content={ids.map(id => ({ id, content: document.narrations[id]!.content }))} readOnly={readOnly} advanced={advanced} onPause={onPause} />
84
89
  <StepProductionEditor key={`${source.identity}:${source.reset}:${stepId}`} document={document} stepId={stepId} locale={locale} readOnly={readOnly} advanced={advanced}
85
90
  onPause={onPause} onInteraction={() => workbench.documentInteraction()}
86
91
  onChange={patch => workbench.setDocumentStepProduction(stepId, patch, source.identity)}
@@ -1,26 +1,31 @@
1
1
  import { useEffect, useMemo, useRef, useState } from 'react'
2
2
  import { createRoot } from 'react-dom/client'
3
- import type { NarrationNode } from '@lincyaw/kernel'
4
3
  import { blockNoteDictionary } from './blocknote-messages.ts'
5
4
  import { BlockNoteView } from '@blocknote/mantine'
6
- import { useCreateBlockNote } from '@blocknote/react'
7
- import { PmButton, PmDialog, PmInput } from '../components.tsx'
5
+ import { SideMenuExtension } from '@blocknote/core/extensions'
6
+ import { DragHandleMenu, RemoveBlockItem, SideMenu, SideMenuController, useBlockNoteEditor, useComponentsContext, useCreateBlockNote, useDictionary, useExtension, useExtensionState, usePortalElement } from '@blocknote/react'
7
+ import type { SideMenuProps } from '@blocknote/react'
8
+ import { PmButton, PmDialog, PmIcon, PmInput } from '../components.tsx'
8
9
  import type { Locale } from '../messages.ts'
9
10
  import { DOCUMENT_EDITOR_THEME } from './BlockNoteSurface.tsx'
10
- import { narrationToNative, nativeToNarration } from './narration.ts'
11
- import { NARRATION_CONTEXT, NARRATION_MESSAGES, narrationExtensions, narrationSchema } from './narration-schema.tsx'
12
- import type { NativeNarrationEditor } from './narration-schema.tsx'
11
+ import { NARRATION_CONTEXT, NARRATION_MESSAGES, createNarrationExtensions, narrationSchema } from './narration-schema.tsx'
12
+ import type { NativeNarrationBlock, NativeNarrationEditor, NativeNarrationInput } from './narration-schema.tsx'
13
13
 
14
- export interface NarrationEditorProps {
14
+ export interface NarrationEditorProps<T> {
15
15
  identity: string
16
- narrationId: string
17
- content: NarrationNode[]
18
- getContent?(): NarrationNode[] | undefined
16
+ fieldId: string
17
+ content: T
18
+ getContent?(): T | undefined
19
+ toNative(content: T): NativeNarrationInput[]
20
+ fromNative(blocks: readonly NativeNarrationBlock[]): T
21
+ blockMenu?: boolean
22
+ cueOwners?(): ReadonlyMap<string, string>
23
+ onCueCopy?(from: string, to: string): void
19
24
  locale: Locale
20
25
  reset?: number
21
26
  readOnly?: boolean
22
27
  advanced?: boolean
23
- onChange(content: NarrationNode[]): void
28
+ onChange(content: T): void
24
29
  onComposition?(composing: boolean): void
25
30
  onFocus?(): void
26
31
  onError?(error: Error): void
@@ -28,7 +33,7 @@ export interface NarrationEditorProps {
28
33
  }
29
34
 
30
35
  /** A native field can live inside an opaque body node without sharing its DOM event root. */
31
- export function NarrationEditor(props: NarrationEditorProps) {
36
+ export function NarrationEditor<T>(props: NarrationEditorProps<T>) {
32
37
  const mount = useRef<HTMLDivElement>(null), root = useRef<ReturnType<typeof createRoot>>(), current = useRef(props)
33
38
  current.current = props
34
39
  useEffect(() => {
@@ -50,14 +55,40 @@ export function NarrationEditor(props: NarrationEditorProps) {
50
55
  }
51
56
  }, [])
52
57
  useEffect(() => { root.current?.render(<NarrationSurface {...props} />) })
53
- return <div ref={mount} contentEditable={false} data-narration-editor={props.narrationId} />
58
+ return <div ref={mount} contentEditable={false} data-narration-editor={props.fieldId} />
54
59
  }
55
60
 
56
- function NarrationSurface(props: NarrationEditorProps) {
61
+ function NarrationBlockMenu() {
62
+ const components = useComponentsContext()!, dictionary = useDictionary(), portalElement = usePortalElement()
63
+ const sideMenu = useExtension(SideMenuExtension)
64
+ return <components.Generic.Menu.Root position="left" portalElement={portalElement} onOpenChange={open => {
65
+ if (open) sideMenu.freezeMenu()
66
+ else sideMenu.unfreezeMenu()
67
+ }}>
68
+ <components.Generic.Menu.Trigger><components.SideMenu.Button label={dictionary.side_menu.drag_handle_label} icon={<PmIcon name="more" />} /></components.Generic.Menu.Trigger>
69
+ <DragHandleMenu><RemoveBlockItem>{dictionary.drag_handle.delete_menuitem}</RemoveBlockItem></DragHandleMenu>
70
+ </components.Generic.Menu.Root>
71
+ }
72
+
73
+ function InsertNarrationBlock() {
74
+ const editor = useBlockNoteEditor(), components = useComponentsContext()!, dictionary = useDictionary()
75
+ const block = useExtensionState(SideMenuExtension, { selector: state => state?.block })
76
+ if (!block) return null
77
+ return <components.SideMenu.Button label={dictionary.side_menu.add_block_label} icon={<PmIcon name="plus" />} onClick={() => {
78
+ const [inserted] = editor.insertBlocks([{ type: 'paragraph' }], block, 'after')
79
+ editor.setTextCursorPosition(inserted!, 'start'); editor.focus()
80
+ }} />
81
+ }
82
+
83
+ function NarrationSideMenu(props: SideMenuProps) {
84
+ return <SideMenu {...props}><InsertNarrationBlock /><NarrationBlockMenu /></SideMenu>
85
+ }
86
+
87
+ function NarrationSurface<T>(props: NarrationEditorProps<T>) {
57
88
  const current = useRef(props), pending = useRef<string[]>([])
58
89
  current.current = props
59
90
  const canonical = props.getContent?.() ?? props.content
60
- const incoming = JSON.stringify(canonical), sourceKey = JSON.stringify([props.identity, props.narrationId, props.reset])
91
+ const incoming = JSON.stringify(canonical), sourceKey = JSON.stringify([props.identity, props.fieldId, props.reset])
61
92
  const version = useRef({ key: sourceKey, incoming, epoch: 0 })
62
93
  if (version.current.key !== sourceKey) {
63
94
  version.current.epoch++; version.current.key = sourceKey; pending.current = []
@@ -70,10 +101,11 @@ function NarrationSurface(props: NarrationEditorProps) {
70
101
  const instance = useMemo(() => ({ content: structuredClone(canonical), emitted: incoming }), [sourceKey, version.current.epoch])
71
102
  const active = useRef(instance); active.current = instance
72
103
  const t = NARRATION_MESSAGES[props.locale]
73
- const editor = useCreateBlockNote({ schema: narrationSchema, initialContent: narrationToNative(props.narrationId, instance.content),
104
+ const editor = useCreateBlockNote({ schema: narrationSchema, initialContent: props.toNative(instance.content),
74
105
  trailingBlock: false,
75
106
  dictionary: { ...blockNoteDictionary(props.locale), placeholders: { ...blockNoteDictionary(props.locale).placeholders, default: props.advanced === false ? t.emptyCaptions : t.empty } },
76
- extensions: narrationExtensions, domAttributes: { editor: { 'aria-label': props.advanced === false ? t.captions : t.field } },
107
+ extensions: createNarrationExtensions(() => current.current.cueOwners?.() ?? new Map(), (from, to) => current.current.onCueCopy?.(from, to)),
108
+ domAttributes: { editor: { 'aria-label': props.advanced === false ? t.captions : t.field } },
77
109
  }, [instance, props.advanced])
78
110
  const baseline = useMemo(() => JSON.stringify(editor.document), [editor])
79
111
  const [open, setOpen] = useState(false), [display, setDisplay] = useState(''), [spoken, setSpoken] = useState('')
@@ -85,7 +117,7 @@ function NarrationSurface(props: NarrationEditorProps) {
85
117
  if (active.current !== instance) return
86
118
  if (current.current.getContent && current.current.getContent() === undefined) return
87
119
  try {
88
- const content = JSON.stringify(editor.document) === baseline ? structuredClone(instance.content) : nativeToNarration(editor.document)
120
+ const content = JSON.stringify(editor.document) === baseline ? structuredClone(instance.content) : current.current.fromNative(editor.document)
89
121
  const serialized = JSON.stringify(content)
90
122
  if (serialized === instance.emitted) return
91
123
  instance.emitted = serialized; pending.current.push(serialized)
@@ -93,10 +125,12 @@ function NarrationSurface(props: NarrationEditorProps) {
93
125
  } catch (error) { current.current.onError?.(error instanceof Error ? error : new Error(String(error))) }
94
126
  }
95
127
  return <NARRATION_CONTEXT.Provider value={{ locale: props.locale, readOnly: props.readOnly, advanced: props.advanced }}>
96
- <div className="pm-ui-narration-editor pm-ui-block-editor pm-ui" onFocus={() => current.current.onFocus?.()}
128
+ <div className="pm-ui-narration-editor pm-ui-block-editor pm-ui" data-block-menu={props.blockMenu || undefined} onFocus={() => current.current.onFocus?.()}
97
129
  onCompositionStart={() => current.current.onComposition?.(true)}
98
130
  onCompositionEnd={() => queueMicrotask(() => { if (active.current === instance) current.current.onComposition?.(false) })}>
99
- <BlockNoteView editor={editor} editable={!props.readOnly} theme={DOCUMENT_EDITOR_THEME} formattingToolbar={false} sideMenu={false} slashMenu={false} linkToolbar={false} comments={false} onChange={change} />
131
+ <BlockNoteView editor={editor} editable={!props.readOnly} theme={DOCUMENT_EDITOR_THEME} formattingToolbar={false} sideMenu={false} slashMenu={false} linkToolbar={false} comments={false} onChange={change}>
132
+ {props.blockMenu && <SideMenuController sideMenu={NarrationSideMenu} />}
133
+ </BlockNoteView>
100
134
  {props.advanced !== false && <div className="pm-ui-narration-editor__actions"><PmButton small variant="ghost" disabled={props.readOnly} onClick={() => { setDisplay(editor.getSelectedText()); setSpoken(''); setOpen(true) }}>{t.pronunciation}</PmButton></div>}
101
135
  <PmDialog open={open} label={t.pronunciation} closeLabel={t.cancel} onClose={() => setOpen(false)} actions={<>
102
136
  <PmButton small onClick={() => setOpen(false)}>{t.cancel}</PmButton>
@@ -5,6 +5,7 @@ import { components } from '@blocknote/mantine'
5
5
  import { ComponentsContext, FloatingComposer, PositionPopover, useBlockNoteEditor, useComponentsContext, useCreateBlockNote, useDictionary, useEditorState, useExtension, useExtensionState } from '@blocknote/react'
6
6
  import type { ComponentProps } from '@blocknote/react'
7
7
  import type { BlockNoteEditor } from '@blocknote/core'
8
+ import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
8
9
  import { TextSelection } from '@tiptap/pm/state'
9
10
  import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
10
11
  import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
@@ -60,7 +61,7 @@ export function NewCommentDraftProvider({ children }: { children?: ReactNode })
60
61
  && editor.prosemirrorState.doc === native.doc && editor.prosemirrorState.selection === native.selection && comments.store.state === extensionState
61
62
  && (!binding || latest.current === binding && binding.input === input && binding.record === record && !binding.composing)
62
63
  if (record && !await drafts.confirm(record) || !owns()) return
63
- const nextTarget = { ...target, intentId: crypto.randomUUID() }, next = await drafts.recover(candidate, nextTarget, version)
64
+ const nextTarget = { ...target, intentId: randomUUID() }, next = await drafts.recover(candidate, nextTarget, version)
64
65
  store.beforeAction?.()
65
66
  if (!next || !owns()) return
66
67
  const positions = store.newDraftPositions(nextTarget, editor)
@@ -185,7 +186,7 @@ function NewCommentEditor(props: ComponentProps['Comments']['Editor']) {
185
186
  })
186
187
  return () => { stop(); stopEnter(); if (original && guarded && !props.editor.prosemirrorView.isDestroyed && props.editor.getExtension(CommentEditorSubmitExtension) === guarded) props.editor.replaceExtension(guarded, original) }
187
188
  }, [binding, drafts, props.editor])
188
- const composerId = useRef(crypto.randomUUID())
189
+ const composerId = useRef(randomUUID())
189
190
  useLayoutEffect(() => {
190
191
  if (!binding || !drafts || !context) return
191
192
  return drafts.registerComposer({ id: composerId.current, target: binding.target,
@@ -211,7 +212,7 @@ export function DocumentNewCommentRecovery() {
211
212
  const active = useRef(true)
212
213
  useLayoutEffect(() => { active.current = true; return () => { active.current = false } }, [owner?.editor])
213
214
  const state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState)), t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
214
- const candidates = state.candidates.filter(value => isNewCommentDraft(value.target))
215
+ const candidates = state.candidates.filter(value => isNewCommentDraft(value.target) && !(value.target.anchor && isDocumentPlaceAnchor(value.target.anchor)))
215
216
  if (!drafts || !owner) return null
216
217
  return <>{owner.failure && <PmNotice tone="warn">{t.commentTargetUnavailable}</PmNotice>}<DraftChoices candidates={candidates} preview
217
218
  canRecover={candidate => isNewCommentDraft(candidate.target) && Boolean(context?.store.newDraftPositions(candidate.target, owner.editor))}
@@ -0,0 +1,150 @@
1
+ import { useContext, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
+ import type { ContextType } from 'react'
3
+ import type { BlockNoteEditor } from '@blocknote/core'
4
+ import { CommentEditorSubmitExtension } from '@blocknote/core/comments'
5
+ import { components } from '@blocknote/mantine'
6
+ import { useCreateBlockNote, useDictionary, useEditorState, useThreads } from '@blocknote/react'
7
+ import { randomUUID } from '@lincyaw/kernel'
8
+ import { PmButton, PmIconButton, PmNotice, PmPopover, PmSelect } from '../components.tsx'
9
+ import { useWorkbench, useWorkbenchState } from '../context.tsx'
10
+ import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
11
+ import { isNewCommentDraft, newCommentDraftSignature, sameCommentDraftTarget } from './comment-drafts.ts'
12
+ import type { CommentDraftCandidate, CommentDraftRecord, NewCommentDraftTarget } from './comment-drafts.ts'
13
+ import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
14
+ import { commentEditorSchema } from './schema.tsx'
15
+ import type { DocumentEditorBlock } from './schema.tsx'
16
+ import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
17
+
18
+ const MantineCommentEditor = components.Comments.Editor
19
+ const emptyDrafts = { candidates: [], pending: false, failed: false, reading: false } as const
20
+ const subscribeEmpty = () => () => {}
21
+ type CommentContext = NonNullable<ContextType<typeof COMMENT_EDITOR_CONTEXT>>
22
+
23
+ /** The step's place anchor: the whole block when no step is chosen. */
24
+ function placeOf(blockId: string, stepId: string | undefined) {
25
+ return stepId === undefined ? { blockId } : { blockId, stepId }
26
+ }
27
+
28
+ /**
29
+ * A block preview's own comment entry. The button belongs to the preview header; the composer reuses the canonical
30
+ * comment editor and draft bank instead of inventing a second comment flow.
31
+ */
32
+ export function PlaceCommentButton(props: {
33
+ blockId: string, sectionId: string, stepId: string, stepIndex: number, onPause(): void,
34
+ }) {
35
+ const context = useContext(COMMENT_EDITOR_CONTEXT)
36
+ if (!context || context.readOnly || !context.store.auth.canCreateThread()) return null
37
+ return <PlaceCommentButtonContent {...props} context={context} />
38
+ }
39
+
40
+ function PlaceCommentButtonContent({ blockId, sectionId, stepId, stepIndex, onPause, context }: {
41
+ blockId: string, sectionId: string, stepId: string, stepIndex: number, onPause(): void, context: CommentContext,
42
+ }) {
43
+ const threads = useThreads(), workbench = useWorkbench()
44
+ const t = DOCUMENT_EDITOR_MESSAGES[context.locale]
45
+ const [open, setOpen] = useState(false), [selected, setSelected] = useState<string | undefined>(stepId)
46
+ const count = useMemo(() => [...threads.values()].filter(thread => {
47
+ if (thread.deletedAt || thread.resolved) return false
48
+ const anchor = context.store.placeAnchorOf(thread.id)
49
+ return anchor?.blockId === blockId && anchor.stepId === stepId
50
+ }).length, [threads, context, blockId, stepId])
51
+ const change = (next: boolean) => {
52
+ setOpen(next)
53
+ if (next) setSelected(stepId)
54
+ }
55
+ return <PmPopover open={open} label={t.stepComment(stepIndex)} name="pm-document-place-comment" placement="below-end" onOpenChange={change}
56
+ trigger={<PmIconButton tooltip={false} small icon="comment-add" label={t.stepCommentHint(stepIndex, count)} onClick={onPause} />}>
57
+ {open && <PlaceCommentComposer key={selected ?? 'block'} context={context} blockId={blockId} sectionId={sectionId} stepId={selected}
58
+ onSelect={next => { setSelected(next); if (next !== undefined) workbench.observeDocumentStep(sectionId, next) }} onClose={() => setOpen(false)} />}
59
+ </PmPopover>
60
+ }
61
+
62
+ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, onClose }: {
63
+ context: CommentContext, blockId: string, sectionId: string, stepId: string | undefined, onSelect(stepId: string | undefined): void, onClose(): void,
64
+ }) {
65
+ const workbench = useWorkbench()
66
+ const fallback = context.store.document
67
+ const document = useWorkbenchState(state => state.authoring?.content) ?? fallback
68
+ const section = document?.sections[sectionId]
69
+ const t = DOCUMENT_EDITOR_MESSAGES[context.locale]
70
+ const store = context.store, drafts = store.drafts, dictionary = useDictionary()
71
+ const rich = useMemo(() => createRichProjection(), [])
72
+ const [target] = useState<NewCommentDraftTarget>(() => {
73
+ const anchor = placeOf(blockId, stepId)
74
+ return { kind: 'create', intentId: randomUUID(), documentId: document!.id, anchor, signature: newCommentDraftSignature(document!, anchor) }
75
+ })
76
+ const [busy, setBusy] = useState(false), [failure, setFailure] = useState(false)
77
+ const record = useRef<CommentDraftRecord>(), composing = useRef(false), submitting = useRef(false), composer = useRef(randomUUID())
78
+ const submitRef = useRef<() => Promise<void>>(() => Promise.resolve())
79
+ const editor: BlockNoteEditor<any, any, any> = useCreateBlockNote({
80
+ schema: commentEditorSchema, trailingBlock: false,
81
+ dictionary: { ...dictionary, placeholders: { ...dictionary.placeholders, emptyDocument: t.stepCommentPlaceholder } },
82
+ extensions: [CommentEditorSubmitExtension({ onSubmit: async () => submitRef.current() })],
83
+ }, [blockId, stepId])
84
+ const empty = useEditorState({ editor, selector: ({ editor }) => editor.isEmpty })
85
+ const write = (composingNow: boolean) => {
86
+ const version = store.version, current = record.current
87
+ if (!drafts || !version) return
88
+ if (editor.isEmpty) {
89
+ if (current) { record.current = undefined; void drafts.clearOwn(current) }
90
+ return
91
+ }
92
+ const next = drafts.write(current?.target ?? target, current?.version ?? version, nativeRichTextToProduct(editor.document as DocumentEditorBlock[], rich), composingNow, current)
93
+ if (next) record.current = next
94
+ }
95
+ useLayoutEffect(() => {
96
+ if (!drafts) return
97
+ const stop = editor.onChange(() => { if (!submitting.current) write(composing.current) })
98
+ return stop
99
+ }, [drafts, editor, target, rich])
100
+ useLayoutEffect(() => {
101
+ if (!drafts) return
102
+ return drafts.registerComposer({ id: composer.current, target,
103
+ snapshot: () => ({ record: record.current, composing: composing.current || editor.prosemirrorView.composing, available: !editor.prosemirrorView.isDestroyed }),
104
+ targetState: () => store.draftTargetState(target) })
105
+ }, [drafts, store, target, editor])
106
+ const composition = (value: boolean) => { composing.current = value; write(value) }
107
+ const submit = async () => {
108
+ if (submitting.current || busy || editor.isEmpty || editor.prosemirrorView.composing) return
109
+ if (!store.auth.canCreateThread() || store.draftTargetState(target) !== 'current') { setFailure(true); return }
110
+ setBusy(true); setFailure(false); submitting.current = true
111
+ try {
112
+ store.beforeAction?.()
113
+ const thread = await store.createPlaceThread({ blockId, stepId, body: editor.document })
114
+ const actual = store.threadSnapshot(thread.id)
115
+ if (actual) { const current = record.current; if (current) { drafts?.submitted(current, actual.comments[0]!, actual); record.current = undefined } }
116
+ context?.openComments?.()
117
+ onClose()
118
+ } catch { setFailure(true) } finally { submitting.current = false; setBusy(false) }
119
+ }
120
+ submitRef.current = submit
121
+ const draftsState = useSyncExternalStore(drafts?.subscribe ?? subscribeEmpty, drafts?.snapshot ?? (() => emptyDrafts))
122
+ const candidates = draftsState.candidates.filter(candidate => isNewCommentDraft(candidate.target) && sameCommentDraftTarget(candidate.target, target))
123
+ const recover = async (candidate: CommentDraftCandidate) => {
124
+ const version = store.version
125
+ if (!drafts || !version) return
126
+ const next = await drafts.recover(candidate, target, version)
127
+ if (!next) return
128
+ // Keep the recovered record current before the editor publishes its content, then retire the old copy.
129
+ record.current = next
130
+ void drafts.discard(candidate)
131
+ editor.replaceBlocks(editor.document, productRichTextToNative(next.content, rich))
132
+ }
133
+ const discard = async (candidate: CommentDraftCandidate) => { await drafts?.discard(candidate) }
134
+ return <div className="pm-document-place-comment__body pm-ui-block-editor">
135
+ <PmSelect label={t.stepCommentStep} value={stepId ?? ''} disabled={busy || !empty} onChange={event => onSelect(event.currentTarget.value || undefined)}>
136
+ <option value="">{t.stepCommentWhole}</option>
137
+ {section?.stepOrder.map((id, index) => <option key={id} value={id}>{t.stepCommentOption(index + 1, document?.steps[id]?.title ?? '')}</option>)}
138
+ </PmSelect>
139
+ <div className="pm-document-place-comment__editor" onCompositionStart={() => composition(true)} onCompositionEnd={() => composition(false)}>
140
+ <MantineCommentEditor editor={editor} editable autoFocus />
141
+ </div>
142
+ {failure && <PmNotice tone="warn">{t.stepCommentFailed}</PmNotice>}
143
+ {candidates.length > 0 && <DraftChoices candidates={candidates} preview disabled={busy} canRecover={() => store.draftTargetState(target) === 'current'}
144
+ unavailableMessage={t.commentTargetUnavailable} onRecover={recover} onDiscard={discard} />}
145
+ <div className="pm-document-place-comment__actions">
146
+ <PmButton small disabled={busy} onClick={onClose}>{t.stepCommentCancel}</PmButton>
147
+ <PmButton small variant="primary" loading={busy} disabled={busy || empty} onClick={() => void submit()}>{t.stepCommentSave}</PmButton>
148
+ </div>
149
+ </div>
150
+ }
@@ -1,16 +1,19 @@
1
- import { documentCommentTargets, isRecord, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
2
- import type { DocumentComment, DocumentThread, RichTextNode, TeachingDocument } from '@lincyaw/kernel'
1
+ import { documentAnchorKey, documentCommentTargets, isDocumentPlaceAnchor, isRecord, randomUUID, validateDocument, validateDocumentCommentAnchor } from '@lincyaw/kernel'
2
+ import type { DocumentComment, DocumentThread, DocumentThreadAnchor, RichTextNode, TeachingDocument } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } 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 }
@@ -50,18 +53,17 @@ const markerOf = (scope: string, value: CommentDraftReference) => `${SETTLED}${J
50
53
  export const commentDraftBaseline = (comment: DocumentComment) => JSON.stringify({ userId: comment.userId, content: comment.content })
51
54
  const committedValue = (comment: DocumentComment) => JSON.stringify({ id: comment.id, userId: comment.userId, createdAt: comment.createdAt, updatedAt: comment.updatedAt, content: comment.content })
52
55
  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)
56
+ ? isNewCommentDraft(a) && isNewCommentDraft(b) && a.documentId === b.documentId && a.signature === b.signature && documentAnchorKey(a.anchor) === documentAnchorKey(b.anchor)
54
57
  : 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
58
  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
59
+ const place = (value: unknown): boolean => isRecord(value) && typeof value.blockId === 'string' && value.blockId.length > 0 && value.blockId.length <= 205
60
+ && (value.stepId === undefined || typeof value.stepId === 'string' && value.stepId.length > 0 && value.stepId.length <= 205)
60
61
  function targetShape(value: unknown): boolean {
61
62
  if (!isRecord(value)) return false
62
63
  if (value.kind === 'create') return typeof value.intentId === 'string' && value.intentId.length > 0 && value.intentId.length <= 200
63
64
  && 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')
65
+ && (value.anchor === undefined && value.signature === undefined || isRecord(value.anchor) && typeof value.signature === 'string'
66
+ && (point(value.anchor.from) && point(value.anchor.to) || place(value.anchor)))
65
67
  return typeof value.threadId === 'string' && typeof value.threadCreatedAt === 'string'
66
68
  && (value.commentId === undefined || typeof value.commentId === 'string' && typeof value.commentCreatedAt === 'string' && typeof value.baseline === 'string')
67
69
  }
@@ -77,7 +79,7 @@ function valid(value: unknown, scope: string): value is CommentDraftRecord {
77
79
  /** Native composer backups use the document backup owner's strict transactions, never the source writer. */
78
80
  export class CommentDrafts {
79
81
  readonly #scope: string
80
- readonly #owner = crypto.randomUUID()
82
+ readonly #owner = randomUUID()
81
83
  #reader?: DocumentDraftStore
82
84
  readonly #listeners = new Set<() => void>()
83
85
  readonly #writing = new Map<string, Writing>()
@@ -228,7 +230,7 @@ export class CommentDrafts {
228
230
  const thread = this.#document.comments?.[created ? record.pending.threadId ?? '' : target.threadId]
229
231
  const comment = thread?.comments.find(value => value.id === record.pending!.commentId)
230
232
  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)
233
+ && (!created || documentAnchorKey(thread.anchor) === documentAnchorKey(target.anchor)) && comment && !comment.deletedAt && committedValue(comment) === record.pending.value)
232
234
  }
233
235
  synchronize(document: TeachingDocument, version: string | undefined, acknowledged = false): void {
234
236
  this.#document = document; this.#version = version; this.#acknowledged = acknowledged
@@ -240,7 +242,7 @@ export class CommentDrafts {
240
242
  const known = previous && this.#writing.get(previous.id)
241
243
  if (previous && (known && known.record.revision !== previous.revision || previous.owner !== this.#owner)) return
242
244
  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,
245
+ const record: CommentDraftRecord = { format: 1, scope: this.#scope, id: !branched && known ? known.record.id : randomUUID(), owner: this.#owner,
244
246
  revision: !branched && known ? known.record.revision + 1 : 1, updatedAt: Date.now(), target: structuredClone(target), version, content: structuredClone(content), composing }
245
247
  return this.#put(record, !branched ? known : undefined)
246
248
  }
@@ -323,7 +325,7 @@ export class CommentDrafts {
323
325
  const value: unknown = JSON.parse(raw)
324
326
  if (!valid(value, this.#scope) || value.revision !== reference.revision || !sameCommentDraftTarget(value.target, target) || !this.#validContent(value) || this.#closed) return
325
327
  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 }
328
+ 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
329
  const store = new DocumentDraftStore(this.#scope, undefined, { family: 'comment', owner: this.#owner }), next = JSON.stringify(record)
328
330
  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 }
329
331
  try { operation?.signal?.throwIfAborted(); operation?.guard?.() } catch (error) { store.close(); throw error }