@lincyaw/workbench 0.2.0-rc.5 → 0.2.0-rc.50

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 (79) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +1 -1
  3. package/src/audio-recording.ts +27 -5
  4. package/src/authoring-client.ts +10 -10
  5. package/src/authoring-draft-fragment.ts +3 -1
  6. package/src/body-draft-actions.ts +60 -0
  7. package/src/component-property-drafts.ts +5 -5
  8. package/src/components.tsx +10 -28
  9. package/src/context.tsx +2 -1
  10. package/src/diagnostics.ts +1 -1
  11. package/src/document-draft-store.ts +45 -18
  12. package/src/document-drafts.ts +28 -19
  13. package/src/document-editing.ts +484 -0
  14. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  15. package/src/document-editor/ComponentMaterials.tsx +3 -9
  16. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  17. package/src/document-editor/DocumentBlockPreview.tsx +4 -2
  18. package/src/document-editor/DocumentComments.tsx +58 -9
  19. package/src/document-editor/DocumentEditor.tsx +44 -7
  20. package/src/document-editor/DocumentStepNarration.tsx +30 -25
  21. package/src/document-editor/NarrationEditor.tsx +54 -20
  22. package/src/document-editor/NewCommentDrafts.tsx +4 -3
  23. package/src/document-editor/PlaceComment.tsx +150 -0
  24. package/src/document-editor/comment-drafts.ts +16 -14
  25. package/src/document-editor/comments.ts +30 -10
  26. package/src/document-editor/component-label.ts +11 -0
  27. package/src/document-editor/file-input.ts +2 -2
  28. package/src/document-editor/focus.ts +0 -2
  29. package/src/document-editor/insertion-place.ts +60 -0
  30. package/src/document-editor/messages.ts +3 -3
  31. package/src/document-editor/narration-schema.tsx +12 -6
  32. package/src/document-editor/narration.ts +19 -3
  33. package/src/document-editor/page-body.ts +60 -0
  34. package/src/document-editor/projection.ts +2 -2
  35. package/src/document-editor/rich-text.ts +3 -2
  36. package/src/document-editor/selection.ts +13 -0
  37. package/src/document-editor/style.css +12 -1
  38. package/src/document-editor/table-identities.ts +2 -1
  39. package/src/document-production.ts +331 -0
  40. package/src/document-session.ts +190 -51
  41. package/src/history.ts +3 -3
  42. package/src/index.ts +5 -5
  43. package/src/jobs.ts +1 -1
  44. package/src/messages.ts +19 -4
  45. package/src/panels/DocumentView.tsx +66 -26
  46. package/src/panels/DocumentVoiceDialog.tsx +2 -2
  47. package/src/panels/DocumentVoiceField.tsx +1 -1
  48. package/src/panels/ExportPanel.tsx +1 -6
  49. package/src/panels/HistoryPanel.tsx +1 -1
  50. package/src/panels/PageDeleteDialog.tsx +4 -4
  51. package/src/panels/PageRenameDialog.tsx +1 -1
  52. package/src/panels/PreviewPanel.tsx +1 -4
  53. package/src/panels/ProductionCaptionSize.tsx +20 -0
  54. package/src/panels/ProductionCaptionTiming.tsx +7 -7
  55. package/src/panels/ProductionMediaClips.tsx +6 -5
  56. package/src/panels/ProductionPanel.tsx +8 -4
  57. package/src/panels/ProductionRecording.tsx +86 -9
  58. package/src/panels/ProductionRecordingRange.tsx +4 -4
  59. package/src/panels/ProductionTimeline.tsx +6 -1
  60. package/src/panels/ProductionTranscription.tsx +5 -4
  61. package/src/panels/SourceDocumentPanel.tsx +12 -15
  62. package/src/panels/TranscriptionAdoption.tsx +9 -8
  63. package/src/panels/VoiceCloneDialog.tsx +2 -1
  64. package/src/panels/VoiceoverDialog.tsx +1 -1
  65. package/src/places.ts +1 -36
  66. package/src/preview-playback.ts +1 -1
  67. package/src/production-messages.ts +6 -0
  68. package/src/production-playback.ts +1 -1
  69. package/src/production-voice-playback.ts +3 -2
  70. package/src/sha256.ts +9 -0
  71. package/src/styles.css +16 -41
  72. package/src/use-recording-adoption.ts +2 -2
  73. package/src/voiceover-jobs.ts +1 -1
  74. package/src/workbench-state.ts +157 -0
  75. package/src/workbench.ts +177 -943
  76. package/src/workspace-client.ts +6 -5
  77. package/src/assistant-mascot.ts +0 -62
  78. package/src/mascot-preference.ts +0 -37
  79. package/src/panels/ChangeTrail.tsx +0 -79
@@ -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 }
@@ -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
+ }