@lincyaw/workbench 0.2.0-rc.95 → 0.2.0-rc.98

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.95",
3
+ "version": "0.2.0-rc.98",
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": {
@@ -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.95",
59
- "@lincyaw/kernel": "1.0.0-rc.95"
58
+ "@lincyaw/design": "1.0.0-rc.98",
59
+ "@lincyaw/kernel": "1.0.0-rc.98"
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.95"
70
+ "@lincyaw/compiler": "1.0.0-rc.98"
71
71
  }
72
72
  }
@@ -0,0 +1,24 @@
1
+ import { createContext, useContext, useMemo } from 'react'
2
+ import type { ComponentType, ReactNode } from 'react'
3
+ import { components } from '@blocknote/mantine'
4
+ import { ComponentsContext, FloatingComposer, useComponentsContext } from '@blocknote/react'
5
+ import type { ComponentProps } from '@blocknote/react'
6
+ import type { BlockNoteEditor } from '@blocknote/core'
7
+
8
+ const COMPOSER_CARD = createContext<{ Card: ComponentType<ComponentProps['Comments']['Card']>, header?: ReactNode } | undefined>(undefined)
9
+
10
+ function ComposerCard(props: ComponentProps['Comments']['Card']) {
11
+ const { Card, header } = useContext(COMPOSER_CARD)!
12
+ return <Card {...props}>{header && <div className="pm-ui-comment-target">{header}</div>}{props.children}</Card>
13
+ }
14
+
15
+ /** Text selections and block/step anchors share the native card, editor and Post action. */
16
+ export function CommentComposer({ editor, editorComponent = components.Comments.Editor, children }: {
17
+ editor: BlockNoteEditor<any, any, any>, editorComponent?: ComponentType<ComponentProps['Comments']['Editor']>, children?: ReactNode,
18
+ }) {
19
+ const native = useComponentsContext()!
20
+ const value = useMemo(() => ({ ...native, Comments: { ...native.Comments, Card: ComposerCard, Editor: editorComponent } }), [native, editorComponent])
21
+ return <COMPOSER_CARD.Provider value={{ Card: native.Comments.Card, header: children }}><ComponentsContext.Provider value={value}>
22
+ <FloatingComposer newCommentEditor={editor} />
23
+ </ComponentsContext.Provider></COMPOSER_CARD.Provider>
24
+ }
@@ -27,6 +27,8 @@ export function DocumentBlockPreview({ blockId, fallback }: { blockId: string, f
27
27
  const position = useWorkbenchState(state => state.position)
28
28
  const navigation = useWorkbenchState(state => state.documentPositionToken)
29
29
  const navigationIntent = useWorkbenchState(state => state.documentPositionIntent)
30
+ const block = source?.content?.blocks[blockId]
31
+ const definition = block?.type === 'component' ? source?.content?.definitions[block.definitionId] : undefined
30
32
  const sectionId = source?.content && documentBlockSection(source.content, blockId)
31
33
  const section = sectionId ? source?.content?.sections[sectionId] : undefined
32
34
  const stepId = section?.stepOrder[position && position.section === sectionId ? position.step : 0] ?? section?.stepOrder[0]
@@ -218,7 +220,7 @@ export function DocumentBlockPreview({ blockId, fallback }: { blockId: string, f
218
220
  <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>
219
221
  <span className="pm-ui-block-preview__actions">
220
222
  {sectionId && stepId && <PlaceCommentButton blockId={blockId} sectionId={sectionId} stepId={stepId} stepIndex={section ? section.stepOrder.indexOf(stepId) + 1 : 1} onPause={pause} />}
221
- {source?.content?.blocks[blockId]?.type === 'component' && <PmIconButton small icon="sliders" label={COMPONENT_PROPERTY_MESSAGES[locale].properties}
223
+ {source && block?.type === 'component' && definition?.kind !== 'scene' && <PmIconButton small icon="sliders" label={COMPONENT_PROPERTY_MESSAGES[locale].properties}
222
224
  data-component-properties={blockId} disabled={!source.identity || workbench.client.capabilities?.readOnly} onClick={() => { if (source.identity && !workbench.client.capabilities?.readOnly) setProperties({ identity: source.identity, stepId }) }} />}
223
225
  {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={() => {
224
226
  pause()
@@ -115,7 +115,7 @@ export function DocumentFloatingThreadController() {
115
115
  }} />
116
116
  }
117
117
 
118
- function placeReference(document: TeachingDocument | undefined, anchor: DocumentPlaceAnchor, t: typeof DOCUMENT_EDITOR_MESSAGES['zh-CN']): string {
118
+ export function placeReference(document: TeachingDocument | undefined, anchor: DocumentPlaceAnchor, t: typeof DOCUMENT_EDITOR_MESSAGES['zh-CN']): string {
119
119
  if (!document) return ''
120
120
  const block = document.blocks[anchor.blockId]
121
121
  let label: string
@@ -2,7 +2,7 @@ import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef,
2
2
  import type { ReactNode } from 'react'
3
3
  import { CommentEditorSubmitExtension, CommentsExtension } from '@blocknote/core/comments'
4
4
  import { components } from '@blocknote/mantine'
5
- import { ComponentsContext, FloatingComposer, PositionPopover, useBlockNoteEditor, useComponentsContext, useCreateBlockNote, useDictionary, useEditorState, useExtension, useExtensionState } from '@blocknote/react'
5
+ import { PositionPopover, useBlockNoteEditor, 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
8
  import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
@@ -19,6 +19,7 @@ import type { DocumentEditorBlock, NativeDocumentEditor } from './schema.tsx'
19
19
  import { PmNotice } from '../components.tsx'
20
20
  import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
21
21
  import { commentFloating } from './popover.tsx'
22
+ import { CommentComposer } from './CommentComposer.tsx'
22
23
 
23
24
  type CommentEditor = BlockNoteEditor<any, any, any>
24
25
  interface ComposerBinding {
@@ -167,7 +168,7 @@ export function DocumentNewCommentController() {
167
168
  const COMPOSER_LAYER = 60
168
169
 
169
170
  function DocumentNewCommentComposer({ newCommentEditor }: { newCommentEditor: CommentEditor }) {
170
- const owner = useContext(NEW_DRAFT_OWNER), context = useContext(COMMENT_EDITOR_CONTEXT), nativeComponents = useComponentsContext()!
171
+ const owner = useContext(NEW_DRAFT_OWNER), context = useContext(COMMENT_EDITOR_CONTEXT)
171
172
  const [binding, setBinding] = useState<ComposerBinding>(), [, render] = useState(0)
172
173
  useLayoutEffect(() => {
173
174
  if (!owner || !context) return
@@ -188,10 +189,9 @@ function DocumentNewCommentComposer({ newCommentEditor }: { newCommentEditor: Co
188
189
  return () => { value.active = false }
189
190
  } catch { /* The unchanged native form remains available when no authoritative target can be confirmed. */ }
190
191
  }, [newCommentEditor, context?.store, owner?.editor, owner?.generation])
191
- const value = useMemo(() => ({ ...nativeComponents, Comments: { ...nativeComponents.Comments, Editor: NewCommentEditor } }), [nativeComponents])
192
- return <NEW_COMPOSER_BINDING.Provider value={{ binding, ready: () => render(value => value + 1) }}><ComponentsContext.Provider value={value}>
193
- <FloatingComposer newCommentEditor={newCommentEditor} />
194
- </ComponentsContext.Provider></NEW_COMPOSER_BINDING.Provider>
192
+ return <NEW_COMPOSER_BINDING.Provider value={{ binding, ready: () => render(value => value + 1) }}>
193
+ <CommentComposer editor={newCommentEditor} editorComponent={NewCommentEditor} />
194
+ </NEW_COMPOSER_BINDING.Provider>
195
195
  }
196
196
  const NEW_COMPOSER_BINDING = createContext<{ binding?: ComposerBinding, ready(): void } | undefined>(undefined)
197
197
 
@@ -1,13 +1,12 @@
1
- import { useContext, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
1
+ import { useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
2
  import type { ContextType } from 'react'
3
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'
4
+ import { CommentEditorSubmitExtension, CommentsExtension } from '@blocknote/core/comments'
5
+ import { GenericPopover, useCreateBlockNote, useDictionary, useEditorState, useExtension, useExtensionState, useThreads } from '@blocknote/react'
7
6
  import { isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
8
- import { PmButton, PmIconButton, PmNotice, PmPopover, PmSelect } from '../components.tsx'
7
+ import { PmButton, PmIconButton, PmNotice, PmSelect } from '../components.tsx'
9
8
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
10
- import { COMMENT_EDITOR_CONTEXT, DraftChoices } from './DocumentComments.tsx'
9
+ import { COMMENT_EDITOR_CONTEXT, DocumentCommentThread, DraftChoices, placeReference } from './DocumentComments.tsx'
11
10
  import { isNewCommentDraft, newCommentDraftSignature, sameCommentDraftTarget } from './comment-drafts.ts'
12
11
  import type { CommentDraftCandidate, CommentDraftRecord, CommentDraftOperation, CommentDraftComposer, NewCommentDraftTarget } from './comment-drafts.ts'
13
12
  import { discardNativeCommentDraft } from './comment-draft-actions.ts'
@@ -17,8 +16,9 @@ import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
17
16
  import { commentEditorSchema } from './schema.tsx'
18
17
  import type { DocumentEditorBlock } from './schema.tsx'
19
18
  import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
20
-
21
- const MantineCommentEditor = components.Comments.Editor
19
+ import { CommentComposer } from './CommentComposer.tsx'
20
+ import { commentFloating } from './popover.tsx'
21
+ import { enterSubmits } from './comments.ts'
22
22
  const emptyDrafts = { candidates: [], pending: false, failed: false, reading: false } as const
23
23
  const subscribeEmpty = () => () => {}
24
24
  type CommentContext = NonNullable<ContextType<typeof COMMENT_EDITOR_CONTEXT>>
@@ -43,7 +43,11 @@ export function PlaceCommentButton(props: {
43
43
  function PlaceCommentButtonContent({ blockId, sectionId, stepId, stepIndex, onPause, context }: {
44
44
  blockId: string, sectionId: string, stepId: string, stepIndex: number, onPause(): void, context: CommentContext,
45
45
  }) {
46
- const threads = useThreads(), workbench = useWorkbench()
46
+ const threads = useThreads(), workbench = useWorkbench(), comments = useExtension(CommentsExtension)
47
+ const { selectedThreadId } = useExtensionState(CommentsExtension)
48
+ const [trigger, setTrigger] = useState<HTMLSpanElement | null>(null)
49
+ const threadComposing = useRef(false)
50
+ const floating = useMemo(() => commentFloating(), [])
47
51
  const t = DOCUMENT_EDITOR_MESSAGES[context.locale]
48
52
  const [open, setOpen] = useState(false), [selected, setSelected] = useState<string | undefined>(stepId)
49
53
  const drafts = context.store.drafts, native = useRef<CommentDraftComposer>(), composerId = useRef(randomUUID()), revision = useRef(0)
@@ -88,28 +92,52 @@ function PlaceCommentButtonContent({ blockId, sectionId, stepId, stepIndex, onPa
88
92
  targetState: target => target && accept(target) ? 'current' : 'unavailable', restore })
89
93
  return () => { alive.current = false; revision.current++; opening.current?.ready?.(); opening.current = undefined; stop() }
90
94
  }, [drafts, context.store, blockId, sectionId, needed])
91
- const count = useMemo(() => [...threads.values()].filter(thread => {
92
- if (thread.deletedAt || thread.resolved) return false
95
+ const anchored = [...threads.values()].filter(thread => {
93
96
  const anchor = context.store.placeAnchorOf(thread.id)
94
- return anchor?.blockId === blockId && anchor.stepId === stepId
95
- }).length, [threads, context, blockId, stepId])
97
+ return !thread.deletedAt && !thread.resolved && anchor?.blockId === blockId && (anchor.stepId === undefined || anchor.stepId === stepId)
98
+ })
99
+ const selectedAnchor = selectedThreadId ? context.store.placeAnchorOf(selectedThreadId) : undefined
100
+ const selectedThread = selectedAnchor?.blockId === blockId ? threads.get(selectedThreadId!) : undefined
101
+ useEffect(() => {
102
+ if (!selectedThread || !selectedAnchor?.stepId) return
103
+ onPause(); workbench.observeDocumentStep(sectionId, selectedAnchor.stepId)
104
+ }, [selectedThreadId, selectedAnchor?.stepId])
96
105
  const change = (next: boolean) => {
97
106
  revision.current++; opening.current?.ready?.()
98
107
  setOpen(next)
99
- if (next) setSelected(stepId)
108
+ if (next) { comments.stopPendingComment(); comments.selectThread(undefined); setSelected(stepId); onPause() }
109
+ }
110
+ const close = (next: boolean, event?: Event) => {
111
+ if (next || isApprovalTarget(event?.target ?? document.activeElement) || native.current?.snapshot().composing || threadComposing.current
112
+ || event instanceof KeyboardEvent && (event.isComposing || event.keyCode === 229)) return
113
+ change(false); comments.selectThread(undefined)
114
+ if (event instanceof KeyboardEvent && event.key === 'Escape') trigger?.querySelector('button')?.focus()
100
115
  }
101
- return <PmPopover open={open} label={t.stepComment(stepIndex)} name="pm-document-place-comment" placement="below-end" onOpenChange={change}
102
- onInteractOutside={event => { if (isApprovalTarget(event.detail.originalEvent.target)) event.preventDefault() }}
103
- trigger={<PmIconButton tooltip={false} small icon="comment-add" label={t.stepCommentHint(stepIndex, count)} onClick={onPause} />}>
104
- {open && <PlaceCommentComposer key={selected ?? 'block'} context={context} blockId={blockId} sectionId={sectionId} stepId={selected}
105
- onReady={ready} onSelect={next => { revision.current++; setSelected(next); if (next !== undefined) workbench.observeDocumentStep(sectionId, next) }} onClose={() => change(false)} />}
106
- </PmPopover>
116
+ const shown = !context.sidebar && !open && selectedThread && !selectedThread.deletedAt && (selectedAnchor?.stepId === undefined || selectedAnchor.stepId === stepId)
117
+ return <>
118
+ <span ref={setTrigger} className="pm-document-place-comment__trigger">
119
+ <PmIconButton small icon="comment-add" label={t.stepComment(stepIndex)} onClick={() => change(!open)} />
120
+ {anchored.length > 0 && <PmButton small icon="comment" aria-label={t.stepCommentHint(stepIndex, anchored.length)} onClick={() => {
121
+ change(false); comments.stopPendingComment(); onPause(); comments.selectThread(anchored[0]!.id, false)
122
+ }}>{anchored.length}</PmButton>}
123
+ </span>
124
+ <GenericPopover reference={trigger ? { element: trigger } : undefined} focusManagerProps={{ disabled: true }}
125
+ elementProps={{ style: { zIndex: 60 }, 'aria-label': open ? t.stepComment(stepIndex) : t.stepCommentHint(stepIndex, anchored.length) }}
126
+ useFloatingOptions={{ ...floating, placement: 'bottom-start', open: Boolean(open || shown), onOpenChange: close }}>
127
+ {open && <PlaceCommentComposer key={selected ?? 'block'} context={context} blockId={blockId} sectionId={sectionId} stepId={selected}
128
+ onReady={ready} onSelect={next => { revision.current++; setSelected(next); if (next !== undefined) workbench.observeDocumentStep(sectionId, next) }} onClose={threadId => {
129
+ change(false); comments.selectThread(threadId, false)
130
+ }} />}
131
+ {shown && <div className="pm-ui-comment-threads" onCompositionStart={() => { threadComposing.current = true }} onCompositionEnd={() => { threadComposing.current = false }}>{(anchored.some(thread => thread.id === selectedThread.id) ? anchored : [selectedThread]).map(thread => <DocumentCommentThread key={thread.id} thread={thread}
132
+ selected={selectedThreadId === thread.id} referenceText={placeReference(context.store.document, context.store.placeAnchorOf(thread.id)!, t)}
133
+ onFocus={() => comments.selectThread(thread.id, false)} tabIndex={0} />)}</div>}
134
+ </GenericPopover>
135
+ </>
107
136
  }
108
137
 
109
138
  function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, onClose, onReady }: {
110
- context: CommentContext, blockId: string, sectionId: string, stepId: string | undefined, onSelect(stepId: string | undefined): void, onClose(): void, onReady(owner?: CommentDraftComposer): void,
139
+ context: CommentContext, blockId: string, sectionId: string, stepId: string | undefined, onSelect(stepId: string | undefined): void, onClose(threadId: string): void, onReady(owner?: CommentDraftComposer): void,
111
140
  }) {
112
- const workbench = useWorkbench()
113
141
  const fallback = context.store.document
114
142
  const document = useWorkbenchState(state => state.authoring?.content) ?? fallback
115
143
  const section = document?.sections[sectionId]
@@ -126,7 +154,7 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
126
154
  const submitRef = useRef<() => Promise<void>>(() => Promise.resolve())
127
155
  const editor: BlockNoteEditor<any, any, any> = useCreateBlockNote({
128
156
  schema: commentEditorSchema, trailingBlock: false,
129
- dictionary: { ...dictionary, placeholders: { ...dictionary.placeholders, emptyDocument: t.stepCommentPlaceholder } },
157
+ dictionary: { ...dictionary, placeholders: { ...dictionary.placeholders, emptyDocument: dictionary.placeholders.new_comment } },
130
158
  extensions: [CommentEditorSubmitExtension({ onSubmit: async () => submitRef.current() })],
131
159
  }, [blockId, stepId])
132
160
  const empty = useEditorState({ editor, selector: ({ editor }) => editor.isEmpty })
@@ -143,8 +171,9 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
143
171
  useLayoutEffect(() => {
144
172
  if (!drafts) return
145
173
  active.current = true
174
+ const stopEnter = enterSubmits(editor, () => submitRef.current())
146
175
  const stop = editor.onChange(() => { if (!submitting.current && !suppress.current) { input.current++; write(composing.current) } })
147
- return () => { active.current = false; input.current++; stop() }
176
+ return () => { active.current = false; input.current++; stop(); stopEnter() }
148
177
  }, [drafts, editor, target, rich])
149
178
  useLayoutEffect(() => {
150
179
  if (!drafts) return
@@ -156,7 +185,7 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
156
185
  }, [drafts, store, target, editor])
157
186
  const composition = (value: boolean) => { composing.current = value; input.current++; write(value) }
158
187
  const submit = async () => {
159
- if (submitting.current || busy || editor.isEmpty || editor.prosemirrorView.composing) return
188
+ if (!active.current || composing.current || submitting.current || busy || editor.isEmpty || editor.prosemirrorView.composing) return
160
189
  if (!store.auth.canCreateThread() || store.draftTargetState(target) !== 'current') { setFailure(true); return }
161
190
  setBusy(true); setFailure(false); submitting.current = true
162
191
  try {
@@ -164,13 +193,12 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
164
193
  const thread = await store.createPlaceThread({ blockId, stepId, body: editor.document })
165
194
  const actual = store.threadSnapshot(thread.id)
166
195
  if (actual) { const current = record.current; if (current) { drafts?.submitted(current, actual.comments[0]!, actual); record.current = undefined } }
167
- context?.openComments?.()
168
- onClose()
196
+ onClose(thread.id)
169
197
  } catch { setFailure(true) } finally { submitting.current = false; setBusy(false) }
170
198
  }
171
199
  submitRef.current = submit
172
200
  const draftsState = useSyncExternalStore(drafts?.subscribe ?? subscribeEmpty, drafts?.snapshot ?? (() => emptyDrafts))
173
- const candidates = draftsState.candidates.filter(candidate => isNewCommentDraft(candidate.target) && sameCommentDraftTarget(candidate.target, target))
201
+ const candidates = draftsState.candidates.filter(candidate => isNewCommentDraft(candidate.target) && sameCommentDraftTarget(candidate.target, target) && candidate.id !== record.current?.id)
174
202
  const nativeGuard = () => {
175
203
  const version = store.version, before = input.current, own = record.current, native = editor.prosemirrorState, position = context.getPositionToken?.()
176
204
  return () => {
@@ -209,20 +237,16 @@ function PlaceCommentComposer({ context, blockId, sectionId, stepId, onSelect, o
209
237
  })
210
238
  }
211
239
  const discard = async (candidate: CommentDraftCandidate) => { await drafts?.discardProposal(candidate) }
212
- return <div className="pm-document-place-comment__body pm-ui-block-editor">
213
- <PmSelect label={t.stepCommentStep} value={stepId ?? ''} disabled={busy || !empty} onChange={event => onSelect(event.currentTarget.value || undefined)}>
214
- <option value="">{t.stepCommentWhole}</option>
215
- {section?.stepOrder.map((id, index) => <option key={id} value={id}>{t.stepCommentOption(index + 1, document?.steps[id]?.title ?? '')}</option>)}
216
- </PmSelect>
217
- <div className="pm-document-place-comment__editor" onCompositionStart={() => composition(true)} onCompositionEnd={() => composition(false)}>
218
- <MantineCommentEditor editor={editor} editable autoFocus />
219
- </div>
240
+ return <div onCompositionStart={() => composition(true)} onCompositionEnd={() => composition(false)}>
241
+ <CommentComposer editor={editor}>
242
+ <PmSelect label={t.stepCommentStep} value={stepId ?? ''} disabled={busy || !empty} onChange={event => onSelect(event.currentTarget.value || undefined)}>
243
+ <option value="">{t.stepCommentWhole}</option>
244
+ {section?.stepOrder.map((id, index) => <option key={id} value={id}>{t.stepCommentOption(index + 1, document?.steps[id]?.title ?? '')}</option>)}
245
+ </PmSelect>
246
+ </CommentComposer>
220
247
  {failure && <PmNotice tone="warn">{t.stepCommentFailed}</PmNotice>}
248
+ {draftsState.failed && <PmNotice tone="warn">{t.commentBackupFailed}</PmNotice>}
221
249
  {candidates.length > 0 && <DraftChoices candidates={candidates} preview disabled={busy} canRecover={() => store.draftTargetState(target) === 'current'}
222
250
  unavailableMessage={t.commentTargetUnavailable} onRecover={async candidate => { await recover(candidate) }} onDiscard={discard} />}
223
- <div className="pm-document-place-comment__actions">
224
- <PmButton small disabled={busy} onClick={onClose}>{t.stepCommentCancel}</PmButton>
225
- <PmButton small variant="primary" loading={busy} disabled={busy || empty} onClick={() => void submit()}>{t.stepCommentSave}</PmButton>
226
- </div>
227
251
  </div>
228
252
  }
@@ -35,6 +35,7 @@ export const BLOCKNOTE_MESSAGES: Record<Locale, Overrides<Dictionary>> = {
35
35
  file_panel: { upload: { file_placeholder: kinds('上传图片', '上传视频', '上传音频', '上传文件'), upload_error: '无法上传文件' }, embed: { embed_button: kinds('嵌入图片', '嵌入视频', '嵌入音频', '嵌入文件'), url_placeholder: '输入网址' } },
36
36
  link_toolbar: { delete: { tooltip: '移除链接' }, edit: { text: '编辑链接' }, open: { tooltip: '在新标签页中打开' }, form: { title_placeholder: '链接文字', url_placeholder: '链接地址' } },
37
37
  comments: {
38
+ save_button_text: '发布',
38
39
  discard_pending_comment: '要放弃这条批注吗?',
39
40
  actions: { add_reaction: '添加回应', edit_comment: '编辑批注', delete_comment: '删除批注', more_actions: '更多' },
40
41
  },
@@ -70,6 +71,7 @@ export const BLOCKNOTE_MESSAGES: Record<Locale, Overrides<Dictionary>> = {
70
71
  file_panel: { upload: { file_placeholder: kinds('Upload Picture', 'Upload Video', 'Upload Audio', 'Upload File'), upload_error: 'Couldn’t upload the file' }, embed: { embed_button: kinds('Embed Picture', 'Embed Video', 'Embed Audio', 'Embed File'), url_placeholder: 'Enter an address' } },
71
72
  link_toolbar: { delete: { tooltip: 'Remove Link' }, edit: { text: 'Edit Link' }, open: { tooltip: 'Open in New Tab' }, form: { title_placeholder: 'Link text', url_placeholder: 'Link address' } },
72
73
  comments: {
74
+ save_button_text: 'Post',
73
75
  discard_pending_comment: 'Discard this comment?',
74
76
  actions: { add_reaction: 'Add Reaction', edit_comment: 'Edit Comment', delete_comment: 'Delete Comment', more_actions: 'More' },
75
77
  },
@@ -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: '新建批注', 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' },
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} 步批注`, stepCommentFailed: '无法保存这条批注,请重试。', 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}`, stepCommentFailed: 'Couldn’t save this comment. Try again.', 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. */
@@ -2,7 +2,7 @@ import { useLayoutEffect } from 'react'
2
2
  import { Menu } from '@mantine/core'
3
3
  import { components } from '@blocknote/mantine'
4
4
  import type { ComponentProps, FloatingUIOptions } from '@blocknote/react'
5
- import { autoUpdate, computePosition, flip, offset, shift } from '@floating-ui/react'
5
+ import { autoUpdate, computePosition, flip, offset, shift, size } from '@floating-ui/react'
6
6
 
7
7
  /** A length token in CSS pixels, for positioning code that only takes numbers. */
8
8
  function tokenPixels(name: string, element: Element = document.documentElement): number {
@@ -73,7 +73,9 @@ export function commentFloating(line?: () => DOMRect | undefined): NonNullable<F
73
73
  const padding = edge()
74
74
  return {
75
75
  ...line ? { placement: 'bottom-start' as const } : {},
76
- middleware: [...line ? [commentLine(line)] : [], offset(COMMENT_GAP), flip({ padding, flipAlignment: false }), shift({ padding })],
76
+ middleware: [...line ? [commentLine(line)] : [], offset(COMMENT_GAP), flip({ padding, flipAlignment: false }), shift({ padding }), size({ padding, apply: ({ availableHeight, elements }) => {
77
+ elements.floating.style.setProperty('--pm-comment-available-height', `${Math.max(0, availableHeight)}px`)
78
+ } })],
77
79
  }
78
80
  }
79
81
 
@@ -12,9 +12,4 @@
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
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); }
15
+ .pm-document-place-comment__trigger { display: inline-flex; align-items: center; gap: var(--pm-space-1); }
@@ -210,10 +210,11 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
210
210
  <div ref={container.ref} className="pmw-document" data-roomy={roomy || undefined} data-narrow={narrow || undefined} data-workspace={producing ? 'production' : presenting ? 'presentation' : reading ? 'reading' : 'content'} data-presenting={presenting || undefined} data-aside={aside ?? undefined} data-navigation={navigation || undefined}>
211
211
  {reading && <PmToolbar variant="workspace" className="pmw-toolbar" label={t.commands}>
212
212
  <span className="pmw-toolbar__title">{t.readDocument}</span>
213
- {actions}
213
+ <span className="pmw-spacer" />
214
214
  <PmToolbarButton asChild><PmIconButton small icon="edit" label={t.editDocument} disabled={changingView} onClick={() => void exitPresent()} /></PmToolbarButton>
215
215
  <PmToolbarButton asChild><PmIconButton small icon="refresh" label={t.reloadPreview} loading={changingView} onClick={() => void compilePresentation(() => workbench.reloadPreview(), true)} /></PmToolbarButton>
216
216
  <PmToolbarButton asChild><PmIconButton small icon="slides" label={t.present} disabled={changingView} onClick={() => void compilePresentation(() => { workbench.setWebView('present'); setWorkspace('presentation') })} /></PmToolbarButton>
217
+ {actions}
217
218
  </PmToolbar>}
218
219
  {!producing && !presenting && !reading && <DocumentToolbar narrow={narrow} presentButton={presentButton} framed={framed} onBack={onBack} actions={actions} aside={aside} navigation={navigation} changingView={changingView} onProduction={() => void openProduction()} onRead={() => void compilePresentation(() => {
219
220
  workbench.setMode('viewing')