@lincyaw/workbench 0.2.0-rc.26 → 0.2.0-rc.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.26",
3
+ "version": "0.2.0-rc.28",
4
4
  "description": "Presmium's workbench panels in React (the documents, a document edited on its rendered page with comments and version history) with the workspace service's client and the preview protocol's workbench side; @lincyaw/dsh places them in presmium studio (experimental)",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -31,6 +31,7 @@
31
31
  "src"
32
32
  ],
33
33
  "dependencies": {
34
+ "@noble/hashes": "2.4.0",
34
35
  "@blocknote/core": "0.56.0",
35
36
  "@blocknote/mantine": "0.56.0",
36
37
  "@blocknote/react": "0.56.0",
@@ -39,7 +40,6 @@
39
40
  "@floating-ui/react": "0.27.20",
40
41
  "@mantine/core": "8.3.11",
41
42
  "@mantine/hooks": "8.3.11",
42
- "@noble/hashes": "2.4.0",
43
43
  "@radix-ui/react-dialog": "^1.3.1",
44
44
  "@radix-ui/react-dropdown-menu": "^2.2.1",
45
45
  "@radix-ui/react-popover": "^1.1.15",
@@ -55,8 +55,8 @@
55
55
  "@tiptap/pm": "3.32.0",
56
56
  "katex": "0.18.10",
57
57
  "react-resizable-panels": "4.14.5",
58
- "@lincyaw/design": "1.0.0-rc.27",
59
- "@lincyaw/kernel": "1.0.0-rc.27"
58
+ "@lincyaw/design": "1.0.0-rc.29",
59
+ "@lincyaw/kernel": "1.0.0-rc.29"
60
60
  },
61
61
  "peerDependencies": {
62
62
  "react": "^18.3.1",
@@ -67,6 +67,6 @@
67
67
  "@types/react-dom": "18.3.7",
68
68
  "react": "^18.3.1",
69
69
  "react-dom": "^18.3.1",
70
- "@lincyaw/compiler": "1.0.0-rc.27"
70
+ "@lincyaw/compiler": "1.0.0-rc.29"
71
71
  }
72
72
  }
@@ -93,6 +93,8 @@ export class DocumentDrafts {
93
93
  || typeof value.owner !== 'string' || !value.owner || value.owner.length > 200 || typeof value.updatedAt !== 'number' || !Number.isSafeInteger(value.updatedAt) || value.updatedAt < 0 || Number.isNaN(new Date(value.updatedAt).getTime())) throw new Error('document-draft-data')
94
94
  const draft = documentDraft(value, documentId)
95
95
  if (!draft) throw new Error('document-draft-document')
96
+ if (draft.baseHash.startsWith('json:')) draft.baseHash = await tokenOf(draft.baseHash.slice(5))
97
+ if (draft.pendingHash?.startsWith('json:')) draft.pendingHash = await tokenOf(draft.pendingHash.slice(5))
96
98
  const token = await tokenOf(raw), marker = settledKey(identity, { id: value.id, revision: value.revision, token })
97
99
  if (durable.get(marker) === token) continue
98
100
  if (source === 'rescue' && localStorage.getItem(marker) === token) continue
@@ -82,6 +82,8 @@ export interface BlockNoteSurfaceProps {
82
82
  commentsPortal?: HTMLElement | null
83
83
  getPositionToken?(): string | undefined
84
84
  onCommentDraftRestore?(): void
85
+ /** The author asked to see the comments pane, e.g. after saving a place comment. */
86
+ onOpenComments?(): void
85
87
  onReady?(editor: NativeDocumentEditor | undefined): void
86
88
  onComposition?(composing: boolean): void
87
89
  /** Shows a page of this document from an in-document link; false when none matches. */
@@ -176,7 +178,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
176
178
  stopCommentHistory?.(); current.current.onReady?.(undefined)
177
179
  }
178
180
  }, [editor])
179
- return <DOCUMENT_EDITOR_LOCALE.Provider value={props.locale}><DOCUMENT_LINKS.Provider value={links}><DOCUMENT_NODE_VIEWS.Provider value={props.nodeViews ?? {}}><COMMENT_EDITOR_CONTEXT.Provider value={props.comments ? { store: props.comments, locale: props.locale, sidebar: Boolean(props.commentsPortal), getPositionToken: () => current.current.getPositionToken?.(), onDraftRestore: () => current.current.onCommentDraftRestore?.() } : undefined}>
181
+ return <DOCUMENT_EDITOR_LOCALE.Provider value={props.locale}><DOCUMENT_LINKS.Provider value={links}><DOCUMENT_NODE_VIEWS.Provider value={props.nodeViews ?? {}}><COMMENT_EDITOR_CONTEXT.Provider value={props.comments ? { store: props.comments, locale: props.locale, sidebar: Boolean(props.commentsPortal), readOnly: Boolean(props.readOnly), getPositionToken: () => current.current.getPositionToken?.(), onDraftRestore: () => current.current.onCommentDraftRestore?.(), openComments: () => current.current.onOpenComments?.() } : undefined}>
180
182
  <div className="pm-document-editor pm-ui-block-editor pm-ui" data-document-editor={props.identity}
181
183
  onDragEnter={event => { if (event.dataTransfer.types.includes('Files')) event.stopPropagation() }}
182
184
  onDragOver={event => { if (event.dataTransfer.types.includes('Files')) event.stopPropagation() }}
@@ -1,17 +1,11 @@
1
1
  import { useMemo } from 'react'
2
2
  import { applyDocumentComponentAction } from '@lincyaw/kernel'
3
- import type { Definition, TeachingDocument } from '@lincyaw/kernel'
3
+ import type { TeachingDocument } from '@lincyaw/kernel'
4
4
  import { PmButton, PmMenu, PmSearchList } from '../components.tsx'
5
5
  import type { ComponentPropertyMessages } from '../component-property-messages.ts'
6
+ import { componentDefinitionLabel } from './component-label.ts'
6
7
 
7
- export function componentDefinitionLabel(definition: Definition): string {
8
- const title = typeof definition.parameterSchema === 'object' && typeof definition.parameterSchema.title === 'string' ? definition.parameterSchema.title.trim() : ''
9
- if (title) return Array.from(title).slice(0, 80).join('')
10
- const implementation = definition.implementation
11
- const name = implementation.type === 'file' ? implementation.path.split('/').at(-1)?.replace(/\.(tsx?|jsx?|mjs|cjs)$/, '')
12
- : implementation.type === 'plugin' ? implementation.name : implementation.specifier.split('/').at(-1)
13
- return Array.from(name || definition.kind).slice(0, 80).join('')
14
- }
8
+ export { componentDefinitionLabel } from './component-label.ts'
15
9
 
16
10
  /** Selection is a proposal; only the caller's source-bound Apply changes a binding. */
17
11
  export function ComponentMaterials({ document, blockId, selected, onSelect, onLocate, disabled, messages: t }: {
@@ -10,6 +10,7 @@ import { BLOCK_PREVIEW_MESSAGES } from './block-preview-messages.ts'
10
10
  import { documentBlockSection, DocumentStepNarration } from './DocumentStepNarration.tsx'
11
11
  import { DocumentBlockPlayback } from './block-playback.ts'
12
12
  import { ComponentPropertiesDialog } from './ComponentPropertiesDialog.tsx'
13
+ import { PlaceCommentButton } from './PlaceComment.tsx'
13
14
  import { COMPONENT_PROPERTY_MESSAGES } from '../component-property-messages.ts'
14
15
 
15
16
  interface Snapshot { address: string, revision: string }
@@ -216,6 +217,7 @@ export function DocumentBlockPreview({ blockId, fallback }: { blockId: string, f
216
217
  return <section ref={root} className="pm-ui-block-preview" data-block-preview={blockId} data-status={state.status} contentEditable={false}>
217
218
  <header className="pm-ui-block-preview__header"><span className="pm-ui-block-preview__label" role={state.status === 'failed' ? 'status' : undefined}><PmIcon name="slides" />{state.status === 'failed' ? t.previewFailure : old && state.snapshot ? t.previewPrevious : state.status === 'preparing' ? p.preparing : state.status === 'loading' ? t.previewLoading : t.previewSnapshot}</span>
218
219
  <span className="pm-ui-block-preview__actions">
220
+ {sectionId && stepId && <PlaceCommentButton blockId={blockId} sectionId={sectionId} stepId={stepId} stepIndex={section ? section.stepOrder.indexOf(stepId) + 1 : 1} onPause={pause} />}
219
221
  {source?.content?.blocks[blockId]?.type === 'component' && <PmIconButton small icon="sliders" label={COMPONENT_PROPERTY_MESSAGES[locale].properties}
220
222
  data-component-properties={blockId} disabled={!source.identity || workbench.client.capabilities?.readOnly} onClick={() => { if (source.identity && !workbench.client.capabilities?.readOnly) setProperties({ identity: source.identity, stepId }) }} />}
221
223
  {workbench.client.capabilities?.narration !== false && <PmIconButton small icon="captions" label={t.stepCaptions} aria-expanded={narrationOpen} aria-controls={narrationOpen ? narrationPanel : undefined} aria-pressed={narrationOpen} disabled={!stepId} onClick={() => {
@@ -1,23 +1,26 @@
1
1
  import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
2
  import type { FocusEvent, ReactNode } from 'react'
3
- import { randomUUID } from '@lincyaw/kernel'
3
+ import { documentAnchorOrder, isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
4
+ import type { DocumentPlaceAnchor, TeachingDocument } from '@lincyaw/kernel'
4
5
  import { CommentEditorSubmitExtension, CommentsExtension } from '@blocknote/core/comments'
5
6
  import { components } from '@blocknote/mantine'
6
7
  import { FloatingThreadController, getReferenceText, Thread, useBlockNoteEditor, useCreateBlockNote, useEditorState, useExtension, useExtensionState, useThreads } from '@blocknote/react'
7
8
  import type { ComponentProps, ThreadProps } from '@blocknote/react'
8
9
  import type { Locale } from '../messages.ts'
9
10
  import { PmButton, PmEmpty, PmNotice, PmSelect } from '../components.tsx'
11
+ import { useWorkbenchState } from '../context.tsx'
10
12
  import { enterSubmits } from './comments.ts'
11
13
  import type { DocumentCommentEditorHandle, DocumentThreadStore } from './comments.ts'
12
14
  import type { CommentDrafts, CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, CommentDraftOperation } from './comment-drafts.ts'
13
15
  import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
14
- import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
16
+ import { createRichProjection, fallbackText, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
15
17
  import { commentEditorSchema } from './schema.tsx'
16
18
  import type { DocumentEditorBlock } from './schema.tsx'
17
19
  import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
20
+ import { componentDefinitionLabel } from './component-label.ts'
18
21
  import { commentFloating } from './popover.tsx'
19
22
 
20
- export const COMMENT_EDITOR_CONTEXT = createContext<{ store: DocumentThreadStore, locale: Locale, sidebar: boolean, getPositionToken?(): string | undefined, onDraftRestore?(): void } | undefined>(undefined)
23
+ export const COMMENT_EDITOR_CONTEXT = createContext<{ store: DocumentThreadStore, locale: Locale, sidebar: boolean, readOnly?: boolean, getPositionToken?(): string | undefined, onDraftRestore?(): void, openComments?(): void } | undefined>(undefined)
21
24
  const THREAD_CONTEXT = createContext<string | undefined>(undefined)
22
25
  const emptySubscribe = () => () => {}
23
26
  const emptyState = { candidates: [], pending: false, failed: false, reading: false } as const
@@ -33,12 +36,14 @@ export function DocumentCommentThread(props: ThreadProps) {
33
36
 
34
37
  /** Keep the native controller and reply editor while body selection owns the pointer. */
35
38
  export function DocumentFloatingThreadController() {
36
- const editor = useBlockNoteEditor(), { selectedThreadId } = useExtensionState(CommentsExtension)
39
+ const editor = useBlockNoteEditor(), { selectedThreadId, threadPositions } = useExtensionState(CommentsExtension)
37
40
  const empty = useEditorState({ editor, on: 'selection', selector: ({ editor }) => editor.prosemirrorState.selection.empty })
38
41
  const [selecting, setSelecting] = useState(false)
39
42
  const blocked = selecting || !empty
43
+ // A place thread has no text mark; it belongs to the sidebar only and must not open a floating card.
44
+ const positioned = Boolean(selectedThreadId && threadPositions.has(selectedThreadId))
40
45
  const shown = useRef(false), thread = useRef(selectedThreadId)
41
- shown.current = Boolean(selectedThreadId) && !blocked
46
+ shown.current = positioned && !blocked
42
47
  thread.current = selectedThreadId
43
48
  // The pointer that last pressed commented text, and the line of the thread chosen from it (the first line without one).
44
49
  const point = useRef<{ x: number, y: number }>(), line = useRef<{ thread: string, index: number }>()
@@ -102,16 +107,60 @@ export function DocumentFloatingThreadController() {
102
107
  return rects[Math.min(line.current.index, rects.length - 1)]
103
108
  }), [editor])
104
109
  return <FloatingThreadController floatingThread={DocumentCommentThread} floatingUIOptions={{
105
- useFloatingOptions: { ...floating, open: Boolean(selectedThreadId) && !blocked },
110
+ useFloatingOptions: { ...floating, open: positioned && !blocked },
106
111
  elementProps: { className: blocked ? 'pm-ui-comment-hidden' : undefined },
107
112
  }} />
108
113
  }
109
114
 
115
+ function placeReference(document: TeachingDocument | undefined, anchor: DocumentPlaceAnchor, t: typeof DOCUMENT_EDITOR_MESSAGES['zh-CN']): string {
116
+ if (!document) return ''
117
+ const block = document.blocks[anchor.blockId]
118
+ let label: string
119
+ if (block?.type === 'component') {
120
+ const definition = document.definitions[block.definitionId]
121
+ const author = typeof block.parameters.title === 'string' ? block.parameters.title.trim() : ''
122
+ const data = definition?.data && typeof definition.data.title === 'string' ? definition.data.title.trim() : ''
123
+ const schema = definition && typeof definition.parameterSchema === 'object' && typeof definition.parameterSchema.title === 'string' ? definition.parameterSchema.title.trim() : ''
124
+ const name = author || data || schema || (definition ? componentDefinitionLabel(definition) : block.definitionId)
125
+ label = definition?.kind === 'scene' ? t.animation(name) : t.component(name)
126
+ } else if (block?.type === 'code') label = t.codeReference(block.title ?? block.origin?.anchor ?? block.language)
127
+ else if (block?.type === 'image') label = block.alt || t.block
128
+ else if (block?.type === 'text') label = (block.content[0] ? Array.from(fallbackText(block.content[0]).replace(/\s+/g, ' ').trim()).slice(0, 40).join('') : '') || t.block
129
+ else if (block?.type === 'container') label = block.properties.title || t.block
130
+ else label = t.block
131
+ if (anchor.stepId === undefined) return t.placeCommentReference(label)
132
+ const step = document.steps[anchor.stepId], section = step ? document.sections[step.sectionId] : undefined
133
+ return t.placeCommentReference(label, step && section ? section.stepOrder.indexOf(step.id) + 1 : 0)
134
+ }
135
+
110
136
  /** Native Thread composition, with the same public focus/blur and position ordering as the sidebar. */
111
137
  export function DocumentThreadsSidebar({ children }: { children?: ReactNode }) {
112
138
  const editor = useBlockNoteEditor(), comments = useExtension(CommentsExtension), threads = useThreads()
113
139
  const { selectedThreadId, threadPositions } = useExtensionState(CommentsExtension)
114
- const ordered = [...threads.values()].sort((a, b) => (threadPositions.get(a.id)?.from ?? Number.MAX_VALUE) - (threadPositions.get(b.id)?.from ?? Number.MAX_VALUE))
140
+ const context = useContext(COMMENT_EDITOR_CONTEXT), t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
141
+ const document = useWorkbenchState(state => state.authoring?.content) ?? context?.store.document
142
+ const places = useMemo(() => document ? documentAnchorOrder(document) : new Map<string, number>(), [document])
143
+ const place = (threadId: string): number => {
144
+ const anchor = context?.store.anchorOf(threadId)
145
+ if (!anchor) return Number.MAX_VALUE
146
+ if (isDocumentPlaceAnchor(anchor)) {
147
+ const order = places.get(anchor.blockId)
148
+ const step = anchor.stepId === undefined ? undefined : document?.steps[anchor.stepId]
149
+ const section = step && document ? document.sections[step.sectionId] : undefined
150
+ return order === undefined ? Number.MAX_VALUE : order * 1_000_000 + (step && section ? section.stepOrder.indexOf(step.id) : 0)
151
+ }
152
+ const order = places.get(anchor.from.blockId)
153
+ return order === undefined ? Number.MAX_VALUE : order * 1_000_000 + Math.min(999_999, anchor.from.offset)
154
+ }
155
+ const reference = (threadId: string): string | undefined => {
156
+ const anchor = context?.store.anchorOf(threadId)
157
+ return anchor && isDocumentPlaceAnchor(anchor) ? placeReference(document, anchor, t) : getReferenceText(editor, threadPositions.get(threadId))
158
+ }
159
+ const orphaned = (threadId: string): boolean => {
160
+ const anchor = context?.store.anchorOf(threadId)
161
+ return !(anchor && isDocumentPlaceAnchor(anchor)) && !threadPositions.has(threadId)
162
+ }
163
+ const ordered = [...threads.values()].sort((a, b) => place(a.id) - place(b.id) || a.createdAt.getTime() - b.createdAt.getTime())
115
164
  const focus = (id: string, event: FocusEvent) => { if (!(event.target as HTMLElement).closest('.bn-action-toolbar')) comments.selectThread(id) }
116
165
  const blur = (event: FocusEvent) => {
117
166
  const next = event.relatedTarget
@@ -119,9 +168,8 @@ export function DocumentThreadsSidebar({ children }: { children?: ReactNode }) {
119
168
  const parent = next.closest('.bn-thread')
120
169
  if (!parent || !(event.target instanceof Node) || !parent.contains(event.target)) comments.selectThread(undefined)
121
170
  }
122
- const context = useContext(COMMENT_EDITOR_CONTEXT), t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
123
171
  return <div className="bn-threads-sidebar">{children}<CommentDraftRetrieval />{!ordered.length && <PmEmpty icon="comment">{t.commentsEmpty}</PmEmpty>}{ordered.map(thread => <DocumentCommentThread key={thread.id} thread={thread}
124
- selected={selectedThreadId === thread.id} orphaned={!threadPositions.has(thread.id)} referenceText={getReferenceText(editor, threadPositions.get(thread.id))}
172
+ selected={selectedThreadId === thread.id} orphaned={orphaned(thread.id)} referenceText={reference(thread.id)}
125
173
  onFocus={event => focus(thread.id, event)} onBlur={blur} tabIndex={0} />)}</div>
126
174
  }
127
175
 
@@ -1,5 +1,6 @@
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
5
  import { allocateDocumentPage, randomUUID } from '@lincyaw/kernel'
5
6
  import type { Member, TeachingDocument } from '@lincyaw/kernel'
@@ -12,8 +13,8 @@ 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'
17
18
  import { documentInsertionPlace } from './insertion-place.ts'
18
19
  import type { DocumentInsertionPlace } from './insertion-place.ts'
19
20
 
@@ -64,6 +65,7 @@ export interface DocumentEditorProps {
64
65
  onError?(error: Error): void
65
66
  commentsPortal?: HTMLElement | null
66
67
  onCommentDraftRestore?(): void
68
+ onOpenComments?(): void
67
69
  }
68
70
 
69
71
  /** A source version reset replaces the editor; its own save receipts never replace it. */
@@ -87,6 +89,13 @@ export function DocumentEditor(props: DocumentEditorProps) {
87
89
  const focusFrame = useRef<number>()
88
90
  const binding = useRef(projection)
89
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
+ }
90
99
  active.current = projection
91
100
  current.current = props
92
101
  const cancelFocus = () => { if (focusFrame.current !== undefined) cancelAnimationFrame(focusFrame.current); focusFrame.current = undefined }
@@ -122,7 +131,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
122
131
  if (!latest || current.current.getDocumentVersion && current.current.getDocumentVersion() === undefined) return
123
132
  syncComments()
124
133
  const document = nativeDocumentToProduct(editor.current.document, projection, latest)
125
- const threads = comments.snapshot(editor.current)
134
+ const threads = comments.snapshot(editor.current, document)
126
135
  if (Object.keys(threads).length) document.comments = threads
127
136
  else delete document.comments
128
137
  current.current.onChange(document)
@@ -134,7 +143,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
134
143
  }
135
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}
136
145
  resolveAssetURL={props.resolveAssetURL} uploadImage={props.uploadImage}
137
- comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection}
146
+ comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} onOpenComments={() => current.current.onOpenComments?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection}
138
147
  animationRequest={{
139
148
  available: () => !current.current.readOnly && binding.current === projection && active.current === projection && Boolean(animationRequests.current?.available()),
140
149
  request: value => {
@@ -165,7 +174,17 @@ export function DocumentEditor(props: DocumentEditorProps) {
165
174
  comments.restoreAnchors(value)
166
175
  binding.current = projection
167
176
  editor.current = value
177
+ editorIdentity.current = props.identity
168
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
+ }
169
188
  const stopBefore = value.onBeforeChange(({ tr }) => { if (!comments.synchronizing && tr.docChanged) pendingTransaction.current = tr })
170
189
  const stopComments = comments.subscribe(emit)
171
190
  const stopSelection = value.onSelectionChange(() => { cancelFocus(); reportPosition() })
@@ -5,7 +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 { randomUUID } from '@lincyaw/kernel'
8
+ import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
9
9
  import { TextSelection } from '@tiptap/pm/state'
10
10
  import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
11
11
  import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
@@ -212,7 +212,7 @@ export function DocumentNewCommentRecovery() {
212
212
  const active = useRef(true)
213
213
  useLayoutEffect(() => { active.current = true; return () => { active.current = false } }, [owner?.editor])
214
214
  const state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState)), t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
215
- 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)))
216
216
  if (!drafts || !owner) return null
217
217
  return <>{owner.failure && <PmNotice tone="warn">{t.commentTargetUnavailable}</PmNotice>}<DraftChoices candidates={candidates} preview
218
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,17 +1,19 @@
1
- import { documentCommentTargets, isRecord, randomUUID, 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
4
  import { sha256 as tokenOf } from '../sha256.ts'
5
5
  import type { DraftStoreResult } from '../document-draft-store.ts'
6
6
 
7
7
  export interface CommentDraftTarget { threadId: string, commentId?: string, threadCreatedAt: string, commentCreatedAt?: string, baseline?: string }
8
- 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 }
9
9
  export type CommentComposerTarget = CommentDraftTarget | NewCommentDraftTarget
10
10
  export const isNewCommentDraft = (target: CommentComposerTarget): target is NewCommentDraftTarget => 'kind' in target && target.kind === 'create'
11
- export function newCommentDraftSignature(document: TeachingDocument, anchor: DocumentThread['anchor']): string | undefined {
11
+ export function newCommentDraftSignature(document: TeachingDocument, anchor: DocumentThreadAnchor | undefined): string | undefined {
12
12
  if (!anchor) return
13
13
  try {
14
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)
15
17
  const targets = documentCommentTargets(document), from = targets.get(anchor.from.blockId)!, to = targets.get(anchor.to.blockId)!
16
18
  return JSON.stringify([...targets].filter(([, value]) => value.order >= from.order && value.order <= to.order).map(([id, value]) => ({ id, text: value.text })))
17
19
  } catch { return }
@@ -51,14 +53,17 @@ const markerOf = (scope: string, value: CommentDraftReference) => `${SETTLED}${J
51
53
  export const commentDraftBaseline = (comment: DocumentComment) => JSON.stringify({ userId: comment.userId, content: comment.content })
52
54
  const committedValue = (comment: DocumentComment) => JSON.stringify({ id: comment.id, userId: comment.userId, createdAt: comment.createdAt, updatedAt: comment.updatedAt, content: comment.content })
53
55
  export const sameCommentDraftTarget = (a: CommentComposerTarget, b: CommentComposerTarget) => isNewCommentDraft(a) || isNewCommentDraft(b)
54
- ? 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)
55
57
  : a.threadId === b.threadId && a.commentId === b.commentId && a.threadCreatedAt === b.threadCreatedAt && a.commentCreatedAt === b.commentCreatedAt
56
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)
57
61
  function targetShape(value: unknown): boolean {
58
62
  if (!isRecord(value)) return false
59
63
  if (value.kind === 'create') return typeof value.intentId === 'string' && value.intentId.length > 0 && value.intentId.length <= 200
60
64
  && typeof value.documentId === 'string' && value.documentId.length > 0 && value.documentId.length <= 200
61
- && (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)))
62
67
  return typeof value.threadId === 'string' && typeof value.threadCreatedAt === 'string'
63
68
  && (value.commentId === undefined || typeof value.commentId === 'string' && typeof value.commentCreatedAt === 'string' && typeof value.baseline === 'string')
64
69
  }
@@ -225,7 +230,7 @@ export class CommentDrafts {
225
230
  const thread = this.#document.comments?.[created ? record.pending.threadId ?? '' : target.threadId]
226
231
  const comment = thread?.comments.find(value => value.id === record.pending!.commentId)
227
232
  return Boolean(thread && !thread.deletedAt && thread.createdAt === (created ? record.pending.threadCreatedAt : target.threadCreatedAt)
228
- && (!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)
229
234
  }
230
235
  synchronize(document: TeachingDocument, version: string | undefined, acknowledged = false): void {
231
236
  this.#document = document; this.#version = version; this.#acknowledged = acknowledged
@@ -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, randomUUID, 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)) {
@@ -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
@@ -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
+ }
@@ -4,8 +4,8 @@ export const IMAGE_IMPORT_MESSAGES = {
4
4
  }
5
5
 
6
6
  export const DOCUMENT_EDITOR_MESSAGES = {
7
- 'zh-CN': { colors: '颜色', textColor: '文字颜色', backgroundColor: '背景颜色', colorDefault: '默认', backgroundDefault: '无底色', colorNames: { muted: '灰色 · 次要', accent: '青色 · 强调', ok: '绿色 · 通过', warn: '橙色 · 提醒', danger: '红色 · 警示' }, backgroundNames: { muted: '灰底', accent: '青底', ok: '绿底', warn: '橙底', danger: '红底' }, formula: '公式', formulaInline: '行内公式', formulaBlock: '公式块', formulaInlineHint: '在文字中插入 LaTeX 公式', formulaBlockHint: '单独一行显示的 LaTeX 公式', openLink: '打开链接', goToSection: (title: string) => `跳到“${title}”`, mathEmpty: '插入公式', mathInvalid: '公式无法识别', mathPlaceholder: '输入 LaTeX 公式', commentRecoveryChanged: '已取消恢复草稿,当前输入已保留。', commentNewDraft: '新建批注', commentsEmpty: '还没有批注。选中正文中的文字,再选“新建批注”。', commentTargetUnavailable: '原选区已改变或不可用,草稿仍可恢复。', commentSessionOnly: '仅本次会话', commentDrafts: '批注草稿', commentChooseDraft: '请选择草稿', commentEditDraft: '编辑稿', commentReplyDraft: '回复稿', commentRecover: '恢复草稿', commentDiscard: '放弃草稿', commentBackupFailed: '最新的批注草稿只在本次会话中保留,请发布后再关闭窗口。', stepNarration: '讲稿', stepCaptions: '字幕', previousStep: '上一步', nextStep: '下一步', narrationStep: (step: number, total: number, title: string) => `第 ${step} / ${total} 步${title ? ` · ${title}` : ''}`, previewFailure: '预览失败', previewLoading: '正在更新预览…', previewPrevious: '上次已保存的预览', previewSnapshot: '文稿内预览', previewRetry: '重试', previewRefresh: '刷新', previewTitle: '内容块只读预览', comment: '新建批注', commentChanged: '这条批注已在别处修改。请先复制草稿,再取消以查看已保存的内容。', commentUnavailable: '无法确认这条批注的版本。请先复制草稿,再关闭并重新打开。', author: '作者', page: '新页面', document: '文稿', untitledPage: '未命名页面', opaque: '组件', animation: (title: string) => `动画:${title}`, component: (title: string) => `组件:${title}`, codeReference: (title: string) => `引用代码:${title}`, diagram: (title: string) => title ? `图表:${title}` : '图表', adapterError: '无法保存这次编辑。请保持页面打开,并查看诊断。', conflict: '文稿已在别处修改。草稿已保留,请先核对当前文稿,再重试或放弃草稿。', saveFailure: '文稿尚未确认保存,草稿已保留。请保持页面打开后重试。', restored: '已恢复尚未保存的草稿,请检查后重新保存或放弃。', loading: '正在加载文稿…', unavailable: '暂时无法加载文稿,请重试。', diagnostics: (count: number) => `${count} 项诊断`, formulaBlockAliases: '公式|数学', formulaInlineAliases: '行内公式|公式', pageAliases: '页面|章节', animateWithAI: '用 AI 插入动画…', animateWithAIHint: '告诉 AI 这里的动画要演示什么', animateWithAIAliases: '动画|场景|演示' },
8
- en: { colors: 'Colors', textColor: 'Text color', backgroundColor: 'Highlight', colorDefault: 'Default', backgroundDefault: 'No highlight', colorNames: { muted: 'Gray · subtle', accent: 'Teal · accent', ok: 'Green · success', warn: 'Amber · caution', danger: 'Red · alert' }, backgroundNames: { muted: 'Gray', accent: 'Teal', ok: 'Green', warn: 'Amber', danger: 'Red' }, formula: 'Formula', formulaInline: 'Inline Formula', formulaBlock: 'Formula Block', formulaInlineHint: 'A LaTeX formula within the text', formulaBlockHint: 'A LaTeX formula on its own line', openLink: 'Open Link', goToSection: (title: string) => `Go to “${title}”`, mathEmpty: 'Insert Formula', mathInvalid: 'Formula not recognized', mathPlaceholder: 'Enter a LaTeX formula', commentRecoveryChanged: 'Draft recovery canceled. Your current input is kept.', commentNewDraft: 'New Comment', commentsEmpty: 'No comments yet. Select text in the document, then choose New Comment.', commentTargetUnavailable: 'The original selection changed or is unavailable. You can still recover your draft.', commentSessionOnly: 'This session only', commentDrafts: 'Comment drafts', commentChooseDraft: 'Choose a draft', commentEditDraft: 'Comment edit', commentReplyDraft: 'Reply', commentRecover: 'Recover Draft', commentDiscard: 'Discard Draft', commentBackupFailed: 'The latest comment draft is kept in this session only. Post it before closing this window.', stepNarration: 'Script', stepCaptions: 'Captions', previousStep: 'Previous Step', nextStep: 'Next Step', narrationStep: (step: number, total: number, title: string) => `Step ${step} / ${total}${title ? ` · ${title}` : ''}`, previewFailure: 'Preview failed', previewLoading: 'Updating preview…', previewPrevious: 'Last saved preview', previewSnapshot: 'Document preview', previewRetry: 'Retry', previewRefresh: 'Refresh', previewTitle: 'Read-only block preview', comment: 'New Comment', commentChanged: 'This comment changed elsewhere. Copy your draft, then cancel to view the saved comment.', commentUnavailable: 'Couldn’t confirm this comment’s version. Copy your draft before closing and reopening it.', author: 'Author', page: 'New Page', document: 'Document', untitledPage: 'Untitled page', opaque: 'Component', animation: (title: string) => `Animation: ${title}`, component: (title: string) => `Component: ${title}`, codeReference: (title: string) => `Referenced code: ${title}`, diagram: (title: string) => title ? `Diagram: ${title}` : 'Diagram', adapterError: 'Couldn’t save this edit. Keep this page open and check the diagnostics.', conflict: 'The document changed elsewhere. Your draft is kept; review the current document, then try again or discard your draft.', saveFailure: 'Couldn’t confirm the save. Your draft is kept; keep this page open and try again.', restored: 'A draft that was not saved was recovered. Review it, then save it again or discard it.', loading: 'Loading document…', unavailable: 'Couldn’t load the document. Try again.', diagnostics: (count: number) => `${count} ${count === 1 ? 'diagnostic' : 'diagnostics'}`, formulaBlockAliases: 'formula|math|equation|latex|tex', formulaInlineAliases: 'inline formula|inline math|latex|tex', pageAliases: 'page|section', animateWithAI: 'Insert Animation with AI…', animateWithAIHint: 'Tell the AI what the animation here should show', animateWithAIAliases: 'animation|animate|scene|motion' },
7
+ 'zh-CN': { colors: '颜色', textColor: '文字颜色', backgroundColor: '背景颜色', colorDefault: '默认', backgroundDefault: '无底色', colorNames: { muted: '灰色 · 次要', accent: '青色 · 强调', ok: '绿色 · 通过', warn: '橙色 · 提醒', danger: '红色 · 警示' }, backgroundNames: { muted: '灰底', accent: '青底', ok: '绿底', warn: '橙底', danger: '红底' }, formula: '公式', formulaInline: '行内公式', formulaBlock: '公式块', formulaInlineHint: '在文字中插入 LaTeX 公式', formulaBlockHint: '单独一行显示的 LaTeX 公式', openLink: '打开链接', goToSection: (title: string) => `跳到“${title}”`, mathEmpty: '插入公式', mathInvalid: '公式无法识别', mathPlaceholder: '输入 LaTeX 公式', commentRecoveryChanged: '已取消恢复草稿,当前输入已保留。', commentNewDraft: '新建批注', commentsEmpty: '还没有批注。选中正文中的文字,或在动画、图表的工具栏里选“本步批注”。', commentTargetUnavailable: '原选区已改变或不可用,草稿仍可恢复。', commentSessionOnly: '仅本次会话', commentDrafts: '批注草稿', commentChooseDraft: '请选择草稿', commentEditDraft: '编辑稿', commentReplyDraft: '回复稿', commentRecover: '恢复草稿', commentDiscard: '放弃草稿', commentBackupFailed: '最新的批注草稿只在本次会话中保留,请发布后再关闭窗口。', stepNarration: '讲稿', stepCaptions: '字幕', previousStep: '上一步', nextStep: '下一步', narrationStep: (step: number, total: number, title: string) => `第 ${step} / ${total} 步${title ? ` · ${title}` : ''}`, previewFailure: '预览失败', previewLoading: '正在更新预览…', previewPrevious: '上次已保存的预览', previewSnapshot: '文稿内预览', previewRetry: '重试', previewRefresh: '刷新', previewTitle: '内容块只读预览', comment: '新建批注', stepComment: (step: number) => `在第 ${step} 步批注`, stepCommentHint: (step: number, count: number) => count ? `第 ${step} 步 · ${count} 条未解决批注` : `在第 ${step} 步批注`, stepCommentSave: '保存批注', stepCommentCancel: '取消', stepCommentFailed: '无法保存这条批注,请重试。', stepCommentPlaceholder: '写下这里要改的地方', stepCommentStep: '批注位置', stepCommentWhole: '整个内容块', stepCommentOption: (step: number, title: string) => title ? `第 ${step} 步 · ${title}` : `第 ${step} 步`, placeCommentReference: (label: string, step?: number) => step ? `“${label}” · 第 ${step} 步` : `“${label}”`, block: '内容块', commentChanged: '这条批注已在别处修改。请先复制草稿,再取消以查看已保存的内容。', commentUnavailable: '无法确认这条批注的版本。请先复制草稿,再关闭并重新打开。', author: '作者', page: '新页面', document: '文稿', untitledPage: '未命名页面', opaque: '组件', animation: (title: string) => `动画:${title}`, component: (title: string) => `组件:${title}`, codeReference: (title: string) => `引用代码:${title}`, diagram: (title: string) => title ? `图表:${title}` : '图表', adapterError: '无法保存这次编辑。请保持页面打开,并查看诊断。', conflict: '文稿已在别处修改。草稿已保留,请先核对当前文稿,再重试或放弃草稿。', saveFailure: '文稿尚未确认保存,草稿已保留。请保持页面打开后重试。', restored: '已恢复尚未保存的草稿,请检查后重新保存或放弃。', loading: '正在加载文稿…', unavailable: '暂时无法加载文稿,请重试。', diagnostics: (count: number) => `${count} 项诊断`, formulaBlockAliases: '公式|数学', formulaInlineAliases: '行内公式|公式', pageAliases: '页面|章节', animateWithAI: '用 AI 插入动画…', animateWithAIHint: '告诉 AI 这里的动画要演示什么', animateWithAIAliases: '动画|场景|演示' },
8
+ en: { colors: 'Colors', textColor: 'Text color', backgroundColor: 'Highlight', colorDefault: 'Default', backgroundDefault: 'No highlight', colorNames: { muted: 'Gray · subtle', accent: 'Teal · accent', ok: 'Green · success', warn: 'Amber · caution', danger: 'Red · alert' }, backgroundNames: { muted: 'Gray', accent: 'Teal', ok: 'Green', warn: 'Amber', danger: 'Red' }, formula: 'Formula', formulaInline: 'Inline Formula', formulaBlock: 'Formula Block', formulaInlineHint: 'A LaTeX formula within the text', formulaBlockHint: 'A LaTeX formula on its own line', openLink: 'Open Link', goToSection: (title: string) => `Go to “${title}”`, mathEmpty: 'Insert Formula', mathInvalid: 'Formula not recognized', mathPlaceholder: 'Enter a LaTeX formula', commentRecoveryChanged: 'Draft recovery canceled. Your current input is kept.', commentNewDraft: 'New Comment', commentsEmpty: 'No comments yet. Select text in the document, or use Comment on step in an animation or chart toolbar.', commentTargetUnavailable: 'The original selection changed or is unavailable. You can still recover your draft.', commentSessionOnly: 'This session only', commentDrafts: 'Comment drafts', commentChooseDraft: 'Choose a draft', commentEditDraft: 'Comment edit', commentReplyDraft: 'Reply', commentRecover: 'Recover Draft', commentDiscard: 'Discard Draft', commentBackupFailed: 'The latest comment draft is kept in this session only. Post it before closing this window.', stepNarration: 'Script', stepCaptions: 'Captions', previousStep: 'Previous Step', nextStep: 'Next Step', narrationStep: (step: number, total: number, title: string) => `Step ${step} / ${total}${title ? ` · ${title}` : ''}`, previewFailure: 'Preview failed', previewLoading: 'Updating preview…', previewPrevious: 'Last saved preview', previewSnapshot: 'Document preview', previewRetry: 'Retry', previewRefresh: 'Refresh', previewTitle: 'Read-only block preview', comment: 'New Comment', stepComment: (step: number) => `Comment on step ${step}`, stepCommentHint: (step: number, count: number) => count ? `Step ${step} · ${count} unresolved` : `Comment on step ${step}`, stepCommentSave: 'Save Comment', stepCommentCancel: 'Cancel', stepCommentFailed: 'Couldn’t save this comment. Try again.', stepCommentPlaceholder: 'Write what should change here', stepCommentStep: 'Comment on', stepCommentWhole: 'The whole content block', stepCommentOption: (step: number, title: string) => title ? `Step ${step} · ${title}` : `Step ${step}`, placeCommentReference: (label: string, step?: number) => step ? `“${label}” · Step ${step}` : `“${label}”`, block: 'Content block', commentChanged: 'This comment changed elsewhere. Copy your draft, then cancel to view the saved comment.', commentUnavailable: 'Couldn’t confirm this comment’s version. Copy your draft before closing and reopening it.', author: 'Author', page: 'New Page', document: 'Document', untitledPage: 'Untitled page', opaque: 'Component', animation: (title: string) => `Animation: ${title}`, component: (title: string) => `Component: ${title}`, codeReference: (title: string) => `Referenced code: ${title}`, diagram: (title: string) => title ? `Diagram: ${title}` : 'Diagram', adapterError: 'Couldn’t save this edit. Keep this page open and check the diagnostics.', conflict: 'The document changed elsewhere. Your draft is kept; review the current document, then try again or discard your draft.', saveFailure: 'Couldn’t confirm the save. Your draft is kept; keep this page open and try again.', restored: 'A draft that was not saved was recovered. Review it, then save it again or discard it.', loading: 'Loading document…', unavailable: 'Couldn’t load the document. Try again.', diagnostics: (count: number) => `${count} ${count === 1 ? 'diagnostic' : 'diagnostics'}`, formulaBlockAliases: 'formula|math|equation|latex|tex', formulaInlineAliases: 'inline formula|inline math|latex|tex', pageAliases: 'page|section', animateWithAI: 'Insert Animation with AI…', animateWithAIHint: 'Tell the AI what the animation here should show', animateWithAIAliases: 'animation|animate|scene|motion' },
9
9
  }
10
10
 
11
11
  /** Slash-menu search words (`|`-separated): an author finds an item by its name in either language, whatever the interface's. */
@@ -11,3 +11,10 @@
11
11
  .pm-document-editor__fallback { display: grid; gap: var(--pm-space-2); min-width: 0; }
12
12
  .pm-document-editor__fallback p { margin: 0; white-space: pre-wrap; }
13
13
  .pm-document-editor__comment-tools { position: sticky; top: var(--pm-space-2); z-index: var(--pm-z-site-header); width: fit-content; margin-inline-start: var(--pm-space-5); }
14
+
15
+ /* A place comment's popover: the comment editor, a position picker and its actions. */
16
+ .pm-document-place-comment { width: min(var(--pm-comment-width), calc(100vw - var(--pm-space-8))); }
17
+ .pm-document-place-comment__body { display: grid; gap: var(--pm-space-2); min-width: 0; }
18
+ .pm-document-place-comment__editor { min-width: 0; }
19
+ .pm-document-place-comment__editor .bn-editor { max-height: min(var(--pm-comment-editor-max-height), 45vh); overflow-y: auto; overflow-wrap: anywhere; }
20
+ .pm-document-place-comment__actions { display: flex; justify-content: end; gap: var(--pm-space-2); }
@@ -1,4 +1,4 @@
1
- import { hasRole, randomUUID, validateDocument } from '@lincyaw/kernel'
1
+ import { hasRole, isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
2
  import type { DocumentAnswer, DocumentChangeAnswer, DocumentImageImportAnswer, DocumentIssue, Member, TeachingDocument } from '@lincyaw/kernel'
3
3
  import { WorkspaceServerError } from './workspace-client.ts'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
@@ -35,6 +35,7 @@ interface Slot {
35
35
  compositions: Set<string>
36
36
  input: number
37
37
  baseHash: string
38
+ baseContent: TeachingDocument
38
39
  storage: string
39
40
  drafts: DocumentDrafts
40
41
  backup?: DocumentDraftCommit
@@ -92,6 +93,20 @@ async function digest(value: TeachingDocument): Promise<string> {
92
93
  return sha256(serialize(value))
93
94
  }
94
95
 
96
+ /** Replay pending author input on a newer saved document; an overlapping value belongs to the author. */
97
+ function rebaseDocument(base: TeachingDocument, local: TeachingDocument, remote: TeachingDocument): TeachingDocument {
98
+ const merge = (before: unknown, author: unknown, saved: unknown): unknown => {
99
+ if (serialize(author) === serialize(before)) return structuredClone(saved)
100
+ if (serialize(saved) === serialize(before) || serialize(author) === serialize(saved)) return structuredClone(author)
101
+ if (isRecord(before) && isRecord(author) && isRecord(saved)) return Object.fromEntries([...new Set([...Object.keys(before), ...Object.keys(author), ...Object.keys(saved)])]
102
+ .map(key => [key, merge(before[key], author[key], saved[key])] as const).filter(([, value]) => value !== undefined))
103
+ return structuredClone(author)
104
+ }
105
+ const merged = validateDocument(merge(base, local, remote))
106
+ // A structural conflict is one document operation: preserve the author's valid complete document.
107
+ return merged.document && !merged.issues.some(issue => issue.severity === 'error') ? merged.document : structuredClone(local)
108
+ }
109
+
95
110
  /** One source actor per document. Runtime compilation and iframe lifecycle never own its input. */
96
111
  export class DocumentSession {
97
112
  readonly #client: WorkspaceClient
@@ -140,7 +155,7 @@ export class DocumentSession {
140
155
  const baseHash = await digest(answer.content)
141
156
  if (this.#disposed || this.#active !== directory || opening !== this.#opening) return
142
157
  const drafts = new DocumentDrafts(() => { if (slot && !this.#disposed) void this.#readDrafts(slot) })
143
- slot = { input: 0, read: 0, compositions: new Set(), drafts, baseHash, storage: `presmium.document.v1:${JSON.stringify([info.root, answer.content.id])}`, state: { directory, member: info.member, identity: JSON.stringify([info.root, answer.content.id]), content: answer.content, version: answer.version, fingerprint: answer.fingerprint, loading: true, dirty: false, saving: false, restored: false, composing: false, storageFailure: false, reset: 0, issues: answer.issues } }
158
+ slot = { input: 0, read: 0, compositions: new Set(), drafts, baseHash, baseContent: structuredClone(answer.content), storage: `presmium.document.v1:${JSON.stringify([info.root, answer.content.id])}`, state: { directory, member: info.member, identity: JSON.stringify([info.root, answer.content.id]), content: answer.content, version: answer.version, fingerprint: answer.fingerprint, loading: true, dirty: false, saving: false, restored: false, composing: false, storageFailure: false, reset: 0, issues: answer.issues } }
144
159
  this.#slots.set(directory, slot)
145
160
  await this.#restore(slot, answer)
146
161
  } else {
@@ -233,11 +248,19 @@ export class DocumentSession {
233
248
  slot.baseHash = remoteHash; slot.pendingHash = undefined
234
249
  slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, error: undefined, issues: answer.issues }
235
250
  } else if (remoteHash === slot.baseHash) slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, issues: answer.issues }
236
- else slot.state = { ...slot.state, error: 'document-version-changed', issues: answer.issues }
251
+ else if (!slot.state.composing) {
252
+ const content = rebaseDocument(slot.baseContent, slot.state.content!, answer.content)
253
+ const reset = slot.state.reset + (keepsEditorContent(slot.state.content!, content) ? 0 : 1)
254
+ slot.baseHash = remoteHash
255
+ slot.pendingHash = undefined
256
+ slot.state = { ...slot.state, content, reset, version: answer.version, fingerprint: answer.fingerprint, error: undefined, dirty: true, issues: answer.issues }
257
+ }
258
+ if (slot.state.version === answer.version) slot.baseContent = structuredClone(answer.content)
237
259
  return
238
260
  }
239
261
  const reset = slot.state.reset + (keepsEditorContent(slot.state.content!, answer.content) ? 0 : 1)
240
262
  slot.baseHash = remoteHash
263
+ slot.baseContent = structuredClone(answer.content)
241
264
  slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, content: answer.content, reset, error: undefined, issues: answer.issues }
242
265
  }
243
266
 
@@ -297,7 +320,12 @@ export class DocumentSession {
297
320
  if (answer.changeId !== flight.id || answer.document !== slot.state.directory || answer.content.id !== flight.content.id) throw new Error('document-confirmation')
298
321
  this.#ack(slot, flight, answer)
299
322
  } catch (error) {
300
- slot.state = { ...slot.state, saving: false, error: this.#error(error), issues: this.#issues(error) }
323
+ if (this.#error(error) === 'document-version-changed' && !slot.state.composing) {
324
+ try {
325
+ await this.#adopt(slot, await this.#client.readDocument(slot.state.directory))
326
+ slot.state = { ...slot.state, saving: false }
327
+ } catch (refreshError) { slot.state = { ...slot.state, saving: false, error: this.#error(refreshError), issues: this.#issues(refreshError) } }
328
+ } else slot.state = { ...slot.state, saving: false, error: this.#error(error), issues: this.#issues(error) }
301
329
  } finally {
302
330
  if (slot.flight === flight) slot.flight = undefined
303
331
  this.#persist(slot); this.#emit(slot)
@@ -308,6 +336,7 @@ export class DocumentSession {
308
336
  }
309
337
  #ack(slot: Slot, flight: NonNullable<Slot['flight']>, answer: DocumentChangeAnswer): void {
310
338
  slot.baseHash = flight.hash!
339
+ slot.baseContent = structuredClone(answer.content)
311
340
  slot.pendingHash = undefined
312
341
  const same = slot.input === flight.input
313
342
  slot.state = { ...slot.state, version: answer.version, fingerprint: answer.fingerprint, ...(same ? { content: answer.content } : {}), dirty: !same, saving: false, error: undefined, issues: answer.issues }
@@ -326,6 +355,7 @@ export class DocumentSession {
326
355
  const same = slot.input === input, content = same ? answer.content : structuredClone(current)
327
356
  if (!same) for (const [id, asset] of added) content.assets[id] = structuredClone(asset)
328
357
  slot.baseHash = baseHash
358
+ slot.baseContent = structuredClone(answer.content)
329
359
  slot.state = { ...slot.state, content, version: answer.version, fingerprint: answer.fingerprint, dirty: !same, error: undefined, issues: answer.issues }
330
360
  return true
331
361
  }
@@ -340,6 +370,7 @@ export class DocumentSession {
340
370
  const checked = validateDocument(content)
341
371
  if (!checked.document || checked.issues.some(issue => issue.severity === 'error')) return false
342
372
  slot.baseHash = baseHash
373
+ slot.baseContent = structuredClone(answer.content)
343
374
  slot.pendingHash = undefined
344
375
  slot.state = { ...slot.state, content: structuredClone(checked.document), version: answer.version, fingerprint: answer.fingerprint,
345
376
  dirty: slot.input !== input || slot.state.composing || serialize(content) !== serialize(answer.content), error: undefined, issues: answer.issues }
@@ -198,7 +198,7 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
198
198
  <DocumentNotices />
199
199
  <div className="pmw-document__body" role="region" aria-label={producing ? PRODUCTION_MESSAGES[workbench.getState().locale].title : presenting ? t.presentationPreview : reading ? t.readDocument : t.documentEditor}>
200
200
  {!presenting && !producing && !reading && navigation && <NavigationPane onClose={() => setNavigation(false)} onSelect={() => { if (matchMedia('(max-width: 1279px)').matches) setNavigation(false) }} />}
201
- <div className="pmw-document__main"><div className="pmw-document__source" hidden={presenting || producing || reading}><SourceDocumentPanel commentsPortal={commentsPortal} onCommentDraftRestore={() => setAside(current => current === 'comments' ? null : current)} /></div>{producing && <ProductionPanel active={active} closing={changingView} onClose={() => void exitPresent()} />}{presenting && <PreviewPanel presentation active={active} onPresentationAction={action => { if (action === 'refresh') void compilePresentation(); else void exitPresent() }} />}{reading && <PreviewPanel active={active} />}</div>
201
+ <div className="pmw-document__main"><div className="pmw-document__source" hidden={presenting || producing || reading}><SourceDocumentPanel commentsPortal={commentsPortal} onCommentDraftRestore={() => setAside(current => current === 'comments' ? null : current)} onOpenComments={() => setAside('comments')} /></div>{producing && <ProductionPanel active={active} closing={changingView} onClose={() => void exitPresent()} />}{presenting && <PreviewPanel presentation active={active} onPresentationAction={action => { if (action === 'refresh') void compilePresentation(); else void exitPresent() }} />}{reading && <PreviewPanel active={active} />}</div>
202
202
  {!presenting && !producing && !reading && aside && (
203
203
  <aside className="pmw-document__aside pm-ui-block-editor" aria-label={{ narration: t.documentNarration, comments: t.comments, export: t.exportPane, history: t.versionHistory }[aside]}>
204
204
  {aside === 'comments' ? <section className="pmw-pane"><header className="pmw-pane__header"><h2 className="pmw-pane__title">{t.comments}</h2><PmIconButton small icon="close" label={t.close} onClick={() => setAside(null)} /></header><div ref={setCommentsPortal} /></section> : aside === 'narration' ? <DocumentNarrationPanel onClose={() => setAside(null)} /> : aside === 'export' ? <ExportPanel documentOnly onClose={() => setAside(null)} /> : <HistoryPanel onClose={() => setAside(null)} revisionAction={historyRevisionAction} />}
@@ -12,7 +12,7 @@ import type { NativeDocumentEditor } from '../document-editor/schema.tsx'
12
12
  import { isAgentChanging } from '../workbench.ts'
13
13
 
14
14
  /** Source editing is available before the first successful runtime compilation. */
15
- export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore }: { commentsPortal?: HTMLElement | null, onCommentDraftRestore?(): void }) {
15
+ export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore, onOpenComments }: { commentsPortal?: HTMLElement | null, onCommentDraftRestore?(): void, onOpenComments?(): void }) {
16
16
  const workbench = useWorkbench(), t = useMessages()
17
17
  const source = useWorkbenchState(state => state.authoring)
18
18
  const sourceAcknowledged = () => {
@@ -175,7 +175,7 @@ export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore }: {
175
175
  {!source?.content || !source.identity ? source?.loading
176
176
  ? <div className="pmw-source-document__sheet pmw-source-document__sheet--loading"><PmSkeleton label={messages.loading} /></div>
177
177
  : <PmNotice tone="warn"><span>{messages.unavailable}</span><span className="pmw-notice__actions"><PmButton small onClick={() => void workbench.retryDocument()}>{t.retry}</PmButton></span></PmNotice> : <div className="pmw-source-document__sheet">
178
- <DocumentEditor acknowledged={sourceAcknowledged()} getDocumentAcknowledged={sourceAcknowledged} onCommentDraftRestore={onCommentDraftRestore} commentDrafts={workbench.documentCommentDrafts(source.identity)} identity={source.identity} document={source.content} version={source.version} member={source.member} getDocument={() => workbench.getDocument(source.identity)}
178
+ <DocumentEditor acknowledged={sourceAcknowledged()} getDocumentAcknowledged={sourceAcknowledged} onCommentDraftRestore={onCommentDraftRestore} onOpenComments={onOpenComments} commentDrafts={workbench.documentCommentDrafts(source.identity)} identity={source.identity} document={source.content} version={source.version} member={source.member} getDocument={() => workbench.getDocument(source.identity)}
179
179
  getDocumentVersion={() => { const current = workbench.getState().authoring; return current && current.identity === source.identity && current.reset === source.reset ? current.version : undefined }} reset={source.reset} locale={locale} readOnly={readOnly}
180
180
  uploadImage={(file, signal) => workbench.importDocumentImage(file, source.identity!, signal)}
181
181
  getPositionToken={() => workbench.getState().documentPositionToken}
package/src/workbench.ts CHANGED
@@ -217,7 +217,7 @@ export function selectedDocument(state: WorkbenchState): string | null {
217
217
 
218
218
  /** Whether the AI is changing the workspace now, or its change waits for the author. */
219
219
  export function isAgentChanging(state: WorkbenchState): boolean {
220
- return Boolean(state.review && (state.review.running || state.review.changes.length > 0))
220
+ return Boolean(state.review?.engine === 'git' && (state.review.running || state.review.changes.length > 0))
221
221
  }
222
222
 
223
223
  /** Whether the document has a slides form (no renderers listed: every form). */