@lincyaw/workbench 0.2.0-rc.25 → 0.2.0-rc.27

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.25",
3
+ "version": "0.2.0-rc.27",
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": {
@@ -39,6 +39,7 @@
39
39
  "@floating-ui/react": "0.27.20",
40
40
  "@mantine/core": "8.3.11",
41
41
  "@mantine/hooks": "8.3.11",
42
+ "@noble/hashes": "2.4.0",
42
43
  "@radix-ui/react-dialog": "^1.3.1",
43
44
  "@radix-ui/react-dropdown-menu": "^2.2.1",
44
45
  "@radix-ui/react-popover": "^1.1.15",
@@ -54,8 +55,8 @@
54
55
  "@tiptap/pm": "3.32.0",
55
56
  "katex": "0.18.10",
56
57
  "react-resizable-panels": "4.14.5",
57
- "@lincyaw/design": "1.0.0-rc.26",
58
- "@lincyaw/kernel": "1.0.0-rc.26"
58
+ "@lincyaw/design": "1.0.0-rc.28",
59
+ "@lincyaw/kernel": "1.0.0-rc.28"
59
60
  },
60
61
  "peerDependencies": {
61
62
  "react": "^18.3.1",
@@ -66,6 +67,6 @@
66
67
  "@types/react-dom": "18.3.7",
67
68
  "react": "^18.3.1",
68
69
  "react-dom": "^18.3.1",
69
- "@lincyaw/compiler": "1.0.0-rc.26"
70
+ "@lincyaw/compiler": "1.0.0-rc.28"
70
71
  }
71
72
  }
@@ -1,9 +1,11 @@
1
1
  import type { AuthoringClientActionResult } from '@lincyaw/kernel'
2
+ import { sha256 as draftContentHash } from './sha256.ts'
3
+
4
+ export { draftContentHash }
2
5
 
3
6
  type Fragment = Extract<AuthoringClientActionResult, { jsonText: string }>
4
7
  type Fields = 'offset' | 'endOffset' | 'totalUtf16' | 'totalUtf8' | 'sha256' | 'jsonText'
5
8
  type FragmentBase = Fragment extends infer Value ? Value extends Fragment ? Omit<Value, Fields> : never : never
6
- export const draftContentHash = async (text: string): Promise<string> => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))].map(value => value.toString(16).padStart(2, '0')).join('')
7
9
  const boundary = (text: string, offset: number) => !(offset > 0 && offset < text.length && /[\uD800-\uDBFF]/.test(text[offset - 1]!) && /[\uDC00-\uDFFF]/.test(text[offset]!))
8
10
 
9
11
  /** Budget the complete client receipt and WS frame, preserving exact JSON text and Unicode progress. */
@@ -1,6 +1,7 @@
1
1
  import { isRecord, randomUUID } from '@lincyaw/kernel'
2
2
  import type { CanonicalSource, ClientComponentDraftReference, JsonObject } from '@lincyaw/kernel'
3
3
  import { DocumentDraftStore } from './document-draft-store.ts'
4
+ import { sha256 as tokenOf } from './sha256.ts'
4
5
  import type { DraftStoreCommit } from './document-draft-store.ts'
5
6
 
6
7
  export interface ComponentPropertyTarget { identity: string, memberId: string, blockId: string, stepId?: string }
@@ -32,7 +33,6 @@ const scopedPrefix = (kind: string, identity: string, memberId: string) => `${ki
32
33
  const markerOf = (target: ComponentPropertyTarget, reference: { id: string, revision: number, token: string }) => `${markerPrefix(target)}${JSON.stringify([reference.id, reference.revision, reference.token])}`
33
34
  const marker = (backup: ComponentPropertyBackup) => markerOf(backup.record.target, { id: backup.record.id, revision: backup.record.revision, token: backup.token })
34
35
  const keyOf = (record: ComponentPropertyDraft) => `${prefix(record.target)}${record.id}`
35
- const tokenOf = async (raw: string) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw)))].map(byte => byte.toString(16).padStart(2, '0')).join('')
36
36
 
37
37
  function valid(value: unknown, target: ComponentPropertyTarget): value is ComponentPropertyDraft {
38
38
  return isRecord(value) && value.format === 1 && typeof value.id === 'string' && value.id.length > 0
@@ -1,6 +1,7 @@
1
1
  import { isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
2
  import type { 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 { DraftStoreCommit } from './document-draft-store.ts'
5
6
 
6
7
  export interface DocumentDraftReference { id: string, revision: number, token: string }
@@ -45,10 +46,6 @@ function documentDraft(value: unknown, documentId: string): DocumentDraft | unde
45
46
  return { content: checked.document, baseVersion: value.baseVersion, baseHash: value.baseHash, input: value.input,
46
47
  pendingHash: value.pendingHash, composing: value.composing, origins: value.origins }
47
48
  }
48
- async function tokenOf(raw: string): Promise<string> {
49
- const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(raw))
50
- return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
51
- }
52
49
 
53
50
  /** Strictly committed document backups, with old localStorage copies identified as unconfirmed rescue material. */
54
51
  export class DocumentDrafts {
@@ -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
 
@@ -64,6 +64,7 @@ export interface DocumentEditorProps {
64
64
  onError?(error: Error): void
65
65
  commentsPortal?: HTMLElement | null
66
66
  onCommentDraftRestore?(): void
67
+ onOpenComments?(): void
67
68
  }
68
69
 
69
70
  /** A source version reset replaces the editor; its own save receipts never replace it. */
@@ -122,7 +123,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
122
123
  if (!latest || current.current.getDocumentVersion && current.current.getDocumentVersion() === undefined) return
123
124
  syncComments()
124
125
  const document = nativeDocumentToProduct(editor.current.document, projection, latest)
125
- const threads = comments.snapshot(editor.current)
126
+ const threads = comments.snapshot(editor.current, document)
126
127
  if (Object.keys(threads).length) document.comments = threads
127
128
  else delete document.comments
128
129
  current.current.onChange(document)
@@ -134,7 +135,7 @@ export function DocumentEditor(props: DocumentEditorProps) {
134
135
  }
135
136
  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
137
  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}
138
+ comments={comments} commentsPortal={props.commentsPortal} onCommentDraftRestore={() => current.current.onCommentDraftRestore?.()} onOpenComments={() => current.current.onOpenComments?.()} nodeViews={props.nodeViews} onComposition={props.onComposition} onSelection={props.onSelection}
138
139
  animationRequest={{
139
140
  available: () => !current.current.readOnly && binding.current === projection && active.current === projection && Boolean(animationRequests.current?.available()),
140
141
  request: value => {
@@ -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,16 +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
+ 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
  }
@@ -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
@@ -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); }
@@ -3,6 +3,7 @@ import type { DocumentAnswer, DocumentChangeAnswer, DocumentImageImportAnswer, D
3
3
  import { WorkspaceServerError } from './workspace-client.ts'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
5
  import { DocumentDrafts } from './document-drafts.ts'
6
+ import { sha256 } from './sha256.ts'
6
7
  import type { DocumentDraftChoice, DocumentDraftCommit, DocumentDraftReference, StoredDocumentDraft } from './document-drafts.ts'
7
8
 
8
9
  export interface DocumentSessionState {
@@ -88,10 +89,7 @@ function keepsEditorContent(before: TeachingDocument, after: TeachingDocument):
88
89
  }
89
90
 
90
91
  async function digest(value: TeachingDocument): Promise<string> {
91
- const text = serialize(value)
92
- if (!globalThis.crypto?.subtle) return `json:${text}`
93
- const bytes = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
94
- return [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join('')
92
+ return sha256(serialize(value))
95
93
  }
96
94
 
97
95
  /** One source actor per document. Runtime compilation and iframe lifecycle never own its input. */
@@ -609,7 +607,12 @@ export class DocumentSession {
609
607
  const answer = await this.#client.readDocument(slot.state.directory)
610
608
  if (!current()) return
611
609
  if (answer.document !== slot.state.directory || answer.content.id !== documentId) { slot.state = { ...slot.state, error: 'document-identity-changed' }; return }
612
- const [localHash, remoteHash] = await Promise.all([digest(candidate.content), digest(answer.content)])
610
+ // Older LAN HTTP drafts stored canonical JSON in place of a SHA-256 fingerprint.
611
+ const [localHash, remoteHash, candidateBaseHash, pendingHash] = await Promise.all([
612
+ digest(candidate.content), digest(answer.content),
613
+ candidate.baseHash.startsWith('json:') ? sha256(candidate.baseHash.slice(5)) : candidate.baseHash,
614
+ candidate.pendingHash?.startsWith('json:') ? sha256(candidate.pendingHash.slice(5)) : candidate.pendingHash,
615
+ ])
613
616
  if (!current()) return
614
617
  const origins = [...new Map([...(candidate.origins ?? []), { id: candidate.id, revision: candidate.revision, token: candidate.token }].map(value => [JSON.stringify([value.id, value.revision, value.token]), value])).values()]
615
618
  if (localHash === remoteHash && !candidate.composing) {
@@ -618,16 +621,16 @@ export class DocumentSession {
618
621
  slot.persistFailure = !settled
619
622
  return
620
623
  }
621
- const conflict = answer.version !== candidate.baseVersion && remoteHash !== candidate.baseHash && remoteHash !== candidate.pendingHash
622
- const version = remoteHash === candidate.pendingHash || remoteHash === candidate.baseHash ? answer.version : candidate.baseVersion
623
- const baseHash = remoteHash === candidate.pendingHash ? remoteHash : candidate.baseHash
624
+ const conflict = answer.version !== candidate.baseVersion && remoteHash !== candidateBaseHash && remoteHash !== pendingHash
625
+ const version = remoteHash === pendingHash || remoteHash === candidateBaseHash ? answer.version : candidate.baseVersion
626
+ const baseHash = remoteHash === pendingHash ? remoteHash : candidateBaseHash
624
627
  const record = await slot.drafts.fork(identity, { content: candidate.content, baseVersion: version, baseHash, input: input + 1,
625
- pendingHash: candidate.pendingHash, composing: Boolean(candidate.composing), origins })
628
+ pendingHash, composing: Boolean(candidate.composing), origins })
626
629
  if (!current()) { if (record) slot.drafts.archive(record); return }
627
630
  if (!record) { slot.persistFailure = true; slot.state = { ...slot.state, storageFailure: true }; return }
628
631
  clearTimeout(slot.timer); slot.timer = undefined
629
632
  if (slot.draft) slot.drafts.archive(slot.draft)
630
- slot.input = input + 1; slot.baseHash = baseHash; slot.pendingHash = candidate.pendingHash; slot.draft = record; slot.draftOrigins = origins
633
+ slot.input = input + 1; slot.baseHash = baseHash; slot.pendingHash = pendingHash; slot.draft = record; slot.draftOrigins = origins
631
634
  slot.backup = undefined; slot.persistFailure = false
632
635
  adopted = true
633
636
  slot.compositions.clear()
@@ -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/sha256.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { sha256 as hash } from '@noble/hashes/sha2.js'
2
+ import { bytesToHex } from '@noble/hashes/utils.js'
3
+
4
+ /** The same SHA-256 fingerprint on HTTPS, localhost and LAN HTTP. */
5
+ export async function sha256(value: string | ArrayBuffer): Promise<string> {
6
+ const bytes = typeof value === 'string' ? new TextEncoder().encode(value) : new Uint8Array(value)
7
+ const subtle = globalThis.crypto?.subtle
8
+ return bytesToHex(subtle ? new Uint8Array(await subtle.digest('SHA-256', bytes)) : hash(bytes))
9
+ }
package/src/workbench.ts CHANGED
@@ -15,6 +15,7 @@ import { mutateCommentDrafts } from './document-editor/comment-draft-actions.ts'
15
15
  import { inspectComponentDrafts } from './component-draft-inspection.ts'
16
16
  import { mutateComponentDrafts } from './component-draft-actions.ts'
17
17
  import { DocumentSession } from './document-session.ts'
18
+ import { sha256 } from './sha256.ts'
18
19
  import { reconcileRecordingAdoption } from './recording-adoption.ts'
19
20
  import { disposeTranscriptionSessions } from './transcription-session.ts'
20
21
  import { documentRecordingActive, disposeDocumentRecordings } from './audio-recording.ts'
@@ -1420,7 +1421,7 @@ export class Workbench {
1420
1421
  if (!file.size || file.size > DOCUMENT_AUDIO_MAX_BYTES) throw new Error('production.asset-size')
1421
1422
  let pending = this.#audioFingerprints.get(file)
1422
1423
  if (!pending) {
1423
- pending = file.arrayBuffer().then(bytes => crypto.subtle.digest('SHA-256', bytes)).then(bytes => [...new Uint8Array(bytes)].map(value => value.toString(16).padStart(2, '0')).join(''))
1424
+ pending = file.arrayBuffer().then(sha256)
1424
1425
  this.#audioFingerprints.set(file, pending)
1425
1426
  }
1426
1427
  const hash = await pending