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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +1 -1
  3. package/src/authoring-client.ts +3 -3
  4. package/src/authoring-draft-fragment.ts +3 -1
  5. package/src/component-property-drafts.ts +5 -5
  6. package/src/components.tsx +10 -28
  7. package/src/document-drafts.ts +6 -7
  8. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  9. package/src/document-editor/ComponentMaterials.tsx +3 -9
  10. package/src/document-editor/ComponentPropertiesDialog.tsx +3 -3
  11. package/src/document-editor/DocumentBlockPreview.tsx +2 -0
  12. package/src/document-editor/DocumentComments.tsx +58 -9
  13. package/src/document-editor/DocumentEditor.tsx +44 -7
  14. package/src/document-editor/DocumentStepNarration.tsx +2 -1
  15. package/src/document-editor/NewCommentDrafts.tsx +4 -3
  16. package/src/document-editor/PlaceComment.tsx +150 -0
  17. package/src/document-editor/comment-drafts.ts +16 -14
  18. package/src/document-editor/comments.ts +30 -10
  19. package/src/document-editor/component-label.ts +11 -0
  20. package/src/document-editor/file-input.ts +2 -2
  21. package/src/document-editor/insertion-place.ts +60 -0
  22. package/src/document-editor/messages.ts +3 -3
  23. package/src/document-editor/narration-schema.tsx +3 -2
  24. package/src/document-editor/page-body.ts +60 -0
  25. package/src/document-editor/projection.ts +2 -2
  26. package/src/document-editor/rich-text.ts +3 -2
  27. package/src/document-editor/selection.ts +13 -0
  28. package/src/document-editor/style.css +12 -1
  29. package/src/document-editor/table-identities.ts +2 -1
  30. package/src/document-session.ts +50 -16
  31. package/src/history.ts +2 -2
  32. package/src/index.ts +0 -3
  33. package/src/messages.ts +19 -4
  34. package/src/panels/DocumentView.tsx +10 -10
  35. package/src/panels/ExportPanel.tsx +1 -6
  36. package/src/panels/PreviewPanel.tsx +1 -4
  37. package/src/panels/ProductionCaptionSize.tsx +20 -0
  38. package/src/panels/ProductionCaptionTiming.tsx +3 -3
  39. package/src/panels/ProductionMediaClips.tsx +2 -1
  40. package/src/panels/ProductionPanel.tsx +5 -1
  41. package/src/panels/ProductionRecordingRange.tsx +2 -2
  42. package/src/panels/ProductionTimeline.tsx +6 -1
  43. package/src/panels/ProductionTranscription.tsx +2 -1
  44. package/src/panels/SourceDocumentPanel.tsx +3 -6
  45. package/src/panels/TranscriptionAdoption.tsx +4 -4
  46. package/src/places.ts +1 -36
  47. package/src/production-messages.ts +6 -0
  48. package/src/sha256.ts +9 -0
  49. package/src/styles.css +16 -41
  50. package/src/workbench.ts +80 -33
  51. package/src/workspace-client.ts +2 -1
  52. package/src/assistant-mascot.ts +0 -62
  53. package/src/mascot-preference.ts +0 -37
  54. package/src/panels/ChangeTrail.tsx +0 -79
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.3",
3
+ "version": "0.2.0-rc.30",
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.4",
58
- "@lincyaw/kernel": "1.0.0-rc.4"
58
+ "@lincyaw/design": "1.0.0-rc.30",
59
+ "@lincyaw/kernel": "1.0.0-rc.30"
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.4"
70
+ "@lincyaw/compiler": "1.0.0-rc.30"
70
71
  }
71
72
  }
@@ -101,7 +101,7 @@ export function MediaClipEditor(props: MediaClipEditorProps) {
101
101
  {rangeError && <span id={rangeErrorId} className="pm-ui-field__error" role="alert">{rangeError}</span>}
102
102
  <PmInput label={t.offset} density={density} width="number" inputMode="decimal" maxLength={32} value={draft.offsetText ?? (clip.attachment.offsetMs / 1000).toFixed(3)}
103
103
  readOnly={disabled || !inspected} error={offsetMs === undefined ? t.invalidOffset : undefined} onChange={event => change({ offsetText: event.target.value })} {...composition('offset')} />
104
- <PmField label={t.volume} density={density} group><div className="pm-ui-media-clip-editor__volume">
104
+ <PmField label={t.volume} density={density} group><div className="pm-ui-range-row">
105
105
  <PmRange label={t.volume} density={density} value={clip.volume * 100} max={100} disabled={disabled || !inspected} valueText={value => `${Math.round(value)}%`} onPreviewChange={setVolumePreview}
106
106
  onValueCommit={value => change({ clip: { ...clip, volume: value / 100 } })} />
107
107
  <output>{Math.round(volumePreview ?? clip.volume * 100)}%</output><PmButton density={density} aria-pressed={Boolean(clip.muted)} disabled={disabled || !inspected} onClick={() => change({ clip: { ...clip, muted: !clip.muted } })}>{clip.muted ? t.unmute : t.mute}</PmButton>
@@ -1,4 +1,4 @@
1
- import { authoringClientResultFits } from '@lincyaw/kernel'
1
+ import { authoringClientResultFits, randomUUID } from '@lincyaw/kernel'
2
2
  import type { AuthoringClientActionResult, AuthoringClientEvent, AuthoringClientSnapshot, CanonicalSource } from '@lincyaw/kernel'
3
3
  import type { Workbench } from './workbench.ts'
4
4
  import type { AuthoringClientChannel } from './workspace-client.ts'
@@ -13,7 +13,7 @@ type Attachment = { directory: string, identity: string, epoch: string, channel:
13
13
  export function connectAuthoringClient(workbench: Workbench): () => void {
14
14
  const open = workbench.client.openAuthoringClient
15
15
  if (!open) return () => {}
16
- const clientId = crypto.randomUUID()
16
+ const clientId = randomUUID()
17
17
  let closed = false, revision = 0, sequence = 0
18
18
  let attached: Attachment | undefined
19
19
  let lastSignature: string | undefined, lastContent: object | undefined
@@ -120,7 +120,7 @@ export function connectAuthoringClient(workbench: Workbench): () => void {
120
120
  if (!value) { detach(); return }
121
121
  if (attached && (attached.directory !== state.document || attached.identity !== source.identity)) detach()
122
122
  if (!attached) {
123
- const epoch = crypto.randomUUID()
123
+ const epoch = randomUUID()
124
124
  // Callbacks run after the channel has been installed; the socket implementation is asynchronous.
125
125
  const owner = { directory: state.document, identity: source.identity, epoch } as Attachment
126
126
  owner.channel = open(state.document, { clientId, epoch, snapshot: value }, event => { void received(owner, event) }, () => {
@@ -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
- import { isRecord } from '@lincyaw/kernel'
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
@@ -50,7 +50,7 @@ export class ComponentPropertyDrafts {
50
50
  readonly #revisions = new Map<string, number>()
51
51
  readonly #settling = new Map<string, number>()
52
52
  #agentReader?: { identity: string, memberId: string, store: DocumentDraftStore }
53
- readonly #writerOwner = crypto.randomUUID()
53
+ readonly #writerOwner = randomUUID()
54
54
  #revision = 0
55
55
  #closed = false
56
56
  readonly #leave = (event: BeforeUnloadEvent) => {
@@ -149,7 +149,7 @@ export class ComponentPropertyDrafts {
149
149
  if (this.#closed) throw new Error('component-draft-closed')
150
150
  const key = targetKey(target), previous = this.#entries.get(key)
151
151
  if (!previous && this.#entries.size >= 512) throw new Error('component-draft-limit')
152
- const record: ComponentPropertyDraft = { format: 1, id: previous?.record.id ?? crypto.randomUUID(), revision: (previous?.record.revision ?? 0) + 1,
152
+ const record: ComponentPropertyDraft = { format: 1, id: previous?.record.id ?? randomUUID(), revision: (previous?.record.revision ?? 0) + 1,
153
153
  target: structuredClone(target), source: structuredClone(value.source), definitionId: value.definitionId, baseline: structuredClone(value.baseline), value: structuredClone(value.value),
154
154
  reset: Boolean(value.reset), composing: Boolean(value.composing), updatedAt: new Date().toISOString() }
155
155
  const entry: Entry = previous ?? { record, store: new DocumentDraftStore(scope(target), undefined, { owner: this.#writerOwner, family: 'component' }), failed: false, origins: [] }
@@ -213,7 +213,7 @@ export class ComponentPropertyDrafts {
213
213
  try { value = JSON.parse(raw) } catch { return false }
214
214
  if (!valid(value, target) || backup.key !== keyOf(value)) return false
215
215
  guard?.()
216
- const record: ComponentPropertyDraft = { ...structuredClone(value), id: crypto.randomUUID(), revision: 1, composing: false, updatedAt: new Date().toISOString() }
216
+ const record: ComponentPropertyDraft = { ...structuredClone(value), id: randomUUID(), revision: 1, composing: false, updatedAt: new Date().toISOString() }
217
217
  const fork = JSON.stringify(record)
218
218
  if (fork.length > MAX_CHARS) return false
219
219
  const operation = store.put(keyOf(record), fork)
@@ -1,6 +1,4 @@
1
1
  import type { IconName } from '@lincyaw/design'
2
- import { mountMascot } from '@lincyaw/design/mascot'
3
- import type { MascotAction } from '@lincyaw/design/mascot'
4
2
  import * as Dialog from '@radix-ui/react-dialog'
5
3
  import * as DropdownMenu from '@radix-ui/react-dropdown-menu'
6
4
  import * as Popover from '@radix-ui/react-popover'
@@ -11,7 +9,6 @@ import { forwardRef, useEffect, useId, useMemo, useRef, useState } from 'react'
11
9
  import type { ComponentProps, CSSProperties, InputHTMLAttributes, ReactNode, Ref, SelectHTMLAttributes, TextareaHTMLAttributes } from 'react'
12
10
  import { Group as ResizableGroup, Panel as ResizablePanel, Separator as ResizableSeparator } from 'react-resizable-panels'
13
11
  import { PmButton, PmIcon, PmIconButton, PmTooltip } from './base-controls.tsx'
14
- import { useMascotEnabled } from './mascot-preference.ts'
15
12
  import type { ControlDensity } from './base-controls.tsx'
16
13
  export { PmButton, PmIcon, PmIconButton, PmTooltip } from './base-controls.tsx'
17
14
  export type { ButtonVariant, ControlDensity } from './base-controls.tsx'
@@ -413,26 +410,6 @@ export function PmNotice({ tone = 'neutral', children }: { tone?: 'neutral' | 'a
413
410
  return <div className={cls('pm-ui-notice', tone !== 'neutral' && `pm-ui-notice--${tone}`)} role={tone === 'danger' ? 'alert' : 'status'}>{children}</div>
414
411
  }
415
412
 
416
- /** The Presmium kitten acting out what the assistant or a long task is doing. It is decoration: the text beside it
417
- * says the same thing for everyone, so it is hidden from assistive technology. Nothing shows when the author turned
418
- * the kitten off in Settings. */
419
- export function PmMascot(props: { action: MascotAction, size?: 'small' | 'regular' }) {
420
- return useMascotEnabled() ? <MascotPlayer {...props} /> : null
421
- }
422
-
423
- function MascotPlayer({ action, size = 'regular' }: { action: MascotAction, size?: 'small' | 'regular' }) {
424
- const ref = useRef<HTMLSpanElement>(null)
425
- const player = useRef<ReturnType<typeof mountMascot>>(undefined)
426
- const first = useRef(action)
427
- useEffect(() => {
428
- const mounted = mountMascot(ref.current!, first.current)
429
- player.current = mounted
430
- return () => mounted.stop()
431
- }, [])
432
- useEffect(() => { player.current?.set(action) }, [action])
433
- return <span ref={ref} className={cls('pm-ui-mascot', size === 'small' && 'pm-ui-mascot--sm')} data-pm-mascot={action} aria-hidden="true" />
434
- }
435
-
436
413
  export interface RangeProps {
437
414
  label: string
438
415
  value: number
@@ -526,6 +503,10 @@ export interface TimelineProps {
526
503
  showSteps?: boolean
527
504
  /** A flush docked editor, with status and zoom in the same tool row. */
528
505
  variant?: 'default' | 'editor'
506
+ /** The page has no place on this timeline (the lecture leaves it out): its status and notice say so, with no tracks to seek. */
507
+ excluded?: { status: string, notice: string }
508
+ /** A note about the selected step, under the tracks. */
509
+ notice?: string
529
510
  }
530
511
 
531
512
  const timelineTime = (ms: number) => `${String(Math.floor(ms / 60000)).padStart(2, '0')}:${(ms % 60000 / 1000).toFixed(3).padStart(6, '0')}`
@@ -540,11 +521,11 @@ function waveformPath(samples: readonly number[] | undefined): string | undefine
540
521
  }
541
522
 
542
523
  /** Data-only timeline; source, playback, seeking authority and all labels remain with its caller. */
543
- export function PmTimeline({ label, tracks, labels, durationMs, durationStatus, currentTimeMs, selectedStepId, zoom, onZoomChange, onSelectStep, onSelectSegment, segmentPicker, onSeek, seekDisabled, disabled, loading, seeking, density = 'compact', showSteps = true, variant = 'default' }: TimelineProps) {
524
+ export function PmTimeline({ label, tracks, labels, durationMs, durationStatus, currentTimeMs, selectedStepId, zoom, onZoomChange, onSelectStep, onSelectSegment, segmentPicker, onSeek, seekDisabled, disabled, loading, seeking, density = 'compact', showSteps = true, variant = 'default', excluded, notice }: TimelineProps) {
544
525
  const hintId = useId()
545
526
  const viewport = useRef<HTMLDivElement>(null), tick = useRef<HTMLSpanElement>(null), composing = useRef(false)
546
527
  const [width, setWidth] = useState(0), [tickWidth, setTickWidth] = useState(1), [localZoom, setLocalZoom] = useState(1), [raw, setRaw] = useState<string>(), [previewTime, setPreviewTime] = useState<number>()
547
- const span = Number.isFinite(durationMs) && durationMs! >= 0 ? durationMs : undefined
528
+ const span = !excluded && Number.isFinite(durationMs) && durationMs! >= 0 ? durationMs : undefined
548
529
  const timing = durationStatus ?? (span === undefined ? 'unknown' : 'confirmed')
549
530
  const timed = span !== undefined && span > 0 && timing !== 'unknown'
550
531
  const blocked = Boolean(disabled || loading), cannotSeek = Boolean(blocked || seeking || seekDisabled || !timed || timing !== 'confirmed')
@@ -585,10 +566,10 @@ export function PmTimeline({ label, tracks, labels, durationMs, durationStatus,
585
566
  const marks = Array.from({ length: Math.min(200, Math.floor(span / unit) + 1) }, (_, index) => index * unit)
586
567
  return [0, ...marks.filter(time => time > 0 && time < span && Math.min(time, span - time) / span * width * scale >= tickWidth), span]
587
568
  }, [span, timed, width, scale, tickWidth])
588
- const status = <div className="pm-ui-timeline__status" role="status">{loading ? labels.loading : timing === 'unknown' || span === undefined ? labels.unknown : `${timing === 'estimated' ? `${labels.estimated} · ` : ''}${timelineTime(span)}`}</div>
569
+ const status = <div className="pm-ui-timeline__status" role="status">{loading ? labels.loading : excluded ? excluded.status : timing === 'unknown' || span === undefined ? labels.unknown : `${timing === 'estimated' ? `${labels.estimated} · ` : ''}${timelineTime(span)}`}</div>
589
570
  return <section className="pm-ui-timeline" data-variant={variant} data-density={density} data-disabled={blocked || undefined} data-segment-picker={segmentPicker?.track} aria-label={label} aria-busy={loading || seeking || undefined}>
590
571
  <div className="pm-ui-timeline__tools">
591
- <PmInput label={`${labels.position} (${labels.seconds})`} labelHidden={variant === 'editor'} width="time" density={density} inputMode="decimal" maxLength={32} value={raw ?? (position === undefined ? '' : (position / 1000).toFixed(3))} placeholder={labels.unknown} error={invalid ? labels.invalidPosition : undefined} disabled={cannotSeek}
572
+ <PmInput label={`${labels.position} (${labels.seconds})`} labelHidden={variant === 'editor'} width="time" density={density} inputMode="decimal" maxLength={32} value={raw ?? (position === undefined ? '' : (position / 1000).toFixed(3))} placeholder={excluded ? undefined : labels.unknown} error={invalid ? labels.invalidPosition : undefined} disabled={cannotSeek}
592
573
  onChange={event => setRaw(event.target.value)} onBlur={commitPosition}
593
574
  onCompositionStart={() => { composing.current = true }} onCompositionEnd={() => { composing.current = false }}
594
575
  onKeyDown={event => { if (event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return; if (event.key === 'Enter') { event.preventDefault(); commitPosition() } else if (event.key === 'Escape') setRaw(undefined) }} />
@@ -625,7 +606,8 @@ export function PmTimeline({ label, tracks, labels, durationMs, durationStatus,
625
606
  <option value="">{segmentPicker.placeholder}</option>{pickerSegments.map(segment => <option key={segment.id} value={segment.id} disabled={segment.disabled}>{timelineTime(segment.startMs!)} · {segment.label}</option>)}
626
607
  </PmSelect></div>}
627
608
  {showSteps && <div className="pm-ui-timeline__steps">{steps.map(segment => <PmButton key={segment.stepId} density={density} disabled={blocked || segment.disabled} aria-pressed={segment.stepId === selectedStepId} variant={segment.stepId === selectedStepId ? 'accent' : 'default'} onClick={() => onSelectStep(segment.stepId!)}>{segment.label}</PmButton>)}</div>}
628
- {!tracks.some(track => track.segments.length) && <PmNotice>{labels.empty}</PmNotice>}
609
+ {(excluded || !tracks.some(track => track.segments.length)) && <PmNotice>{excluded?.notice ?? labels.empty}</PmNotice>}
610
+ {notice && <PmNotice>{notice}</PmNotice>}
629
611
  <p id={hintId} className="pm-ui-sr-only">{labels.seekHint}</p>
630
612
  </section>
631
613
  }
@@ -1,6 +1,7 @@
1
- import { isRecord, validateDocument } from '@lincyaw/kernel'
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,14 +46,10 @@ 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 {
55
- readonly #owner = crypto.randomUUID()
52
+ readonly #owner = randomUUID()
56
53
  readonly #owned = new Map<string, { identity: string, revision: number, raw: string }>()
57
54
  #store?: DocumentDraftStore
58
55
  #identity?: string
@@ -96,6 +93,8 @@ export class DocumentDrafts {
96
93
  || typeof value.owner !== 'string' || !value.owner || value.owner.length > 200 || typeof value.updatedAt !== 'number' || !Number.isSafeInteger(value.updatedAt) || value.updatedAt < 0 || Number.isNaN(new Date(value.updatedAt).getTime())) throw new Error('document-draft-data')
97
94
  const draft = documentDraft(value, documentId)
98
95
  if (!draft) throw new Error('document-draft-document')
96
+ if (draft.baseHash.startsWith('json:')) draft.baseHash = await tokenOf(draft.baseHash.slice(5))
97
+ if (draft.pendingHash?.startsWith('json:')) draft.pendingHash = await tokenOf(draft.pendingHash.slice(5))
99
98
  const token = await tokenOf(raw), marker = settledKey(identity, { id: value.id, revision: value.revision, token })
100
99
  if (durable.get(marker) === token) continue
101
100
  if (source === 'rescue' && localStorage.getItem(marker) === token) continue
@@ -113,7 +112,7 @@ export class DocumentDrafts {
113
112
  const owned = previous && this.#owned.get(previous.id)
114
113
  if (previous && (!owned || owned.identity !== identity || previous.owner !== this.#owner || previous.revision !== owned.revision)) return
115
114
  const changed = previous && store.conflicted(keyOf(identity, previous.id))
116
- const record: StoredDocumentDraft = { ...draft, format: 2, identity, id: !changed && previous ? previous.id : crypto.randomUUID(), owner: this.#owner, revision: changed ? 1 : (owned?.revision ?? 0) + 1, updatedAt: Date.now() }
115
+ const record: StoredDocumentDraft = { ...draft, format: 2, identity, id: !changed && previous ? previous.id : randomUUID(), owner: this.#owner, revision: changed ? 1 : (owned?.revision ?? 0) + 1, updatedAt: Date.now() }
117
116
  if (!Number.isSafeInteger(record.revision)) return
118
117
  try { const raw = JSON.stringify(record); return raw.length <= MAX_CHARS ? { record, raw } : undefined }
119
118
  catch { return }
@@ -1,12 +1,13 @@
1
1
  import { forwardRef, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
2
2
  import type { ForwardRefExoticComponent, ReactNode, RefAttributes } from 'react'
3
+ import { randomUUID } from '@lincyaw/kernel'
3
4
  import { filterSuggestionItems } from '@blocknote/core'
4
5
  import { BlockNoteView, components } from '@blocknote/mantine'
5
6
  import { AddCommentButton, BasicTextStyleButton, BlockNoteViewEditor, BlockTypeSelect, ComponentsContext, CreateLinkButton, FormattingToolbar, FormattingToolbarController, getDefaultReactSlashMenuItems, LinkToolbarController, NestBlockButton, RenderInPortalElement, SideMenuController, SuggestionMenuController, TableCellMergeButton, TableHandlesController, TextAlignButton, UnnestBlockButton, useBlockNoteEditor, useCreateBlockNote, useEditorState } from '@blocknote/react'
6
7
  import type { ComponentProps, FormattingToolbarProps } from '@blocknote/react'
7
8
  import { useMediaQuery } from '@mantine/hooks'
8
9
  import type { Locale } from '../messages.ts'
9
- import { PmIconButton, PmNotice, PmTooltip } from '../components.tsx'
10
+ import { PmIcon, PmIconButton, PmNotice, PmTooltip } from '../components.tsx'
10
11
  import { DOCUMENT_NODE_VIEWS, documentEditorSchema } from './schema.tsx'
11
12
  import type { DocumentEditorBlock, DocumentEditorInput, DocumentNodeViews, NativeDocumentEditor } from './schema.tsx'
12
13
  import { documentSelection } from './selection.ts'
@@ -16,6 +17,7 @@ import { blockNoteDictionary } from './blocknote-messages.ts'
16
17
  import { imageFileInput } from './file-input.ts'
17
18
  import type { ImageImportFailure } from './file-input.ts'
18
19
  import { nativeTextClipboard } from './clipboard.ts'
20
+ import { documentPageBodies, focusDocumentEnd } from './page-body.ts'
19
21
  import { documentBlockColors } from './colors.ts'
20
22
  import { DOCUMENT_EDITOR_LOCALE } from './math.tsx'
21
23
  import { DOCUMENT_LINKS, DocumentColorButton, DocumentLinkToolbar, DocumentSideMenu, DocumentTableCellButton, DocumentTableHandle, FormulaToolbarButton, formulaSlashItems, openDocumentLink } from './authoring.tsx'
@@ -80,10 +82,14 @@ export interface BlockNoteSurfaceProps {
80
82
  commentsPortal?: HTMLElement | null
81
83
  getPositionToken?(): string | undefined
82
84
  onCommentDraftRestore?(): void
85
+ /** The author asked to see the comments pane, e.g. after saving a place comment. */
86
+ onOpenComments?(): void
83
87
  onReady?(editor: NativeDocumentEditor | undefined): void
84
88
  onComposition?(composing: boolean): void
85
89
  /** Shows a page of this document from an in-document link; false when none matches. */
86
90
  onSectionLink?(sectionId: string): boolean
91
+ /** The slash menu's request to the AI for an animation where it was opened: it inserts nothing itself. */
92
+ animationRequest?: { available(): boolean, request(editor: NativeDocumentEditor): void }
87
93
  children?: ReactNode
88
94
  }
89
95
 
@@ -113,10 +119,11 @@ function PlainContentComments({ editor }: { editor: NativeDocumentEditor }) {
113
119
  return show && editor.getExtension('comments') ? <div className="pm-document-editor__comment-tools"><FormattingToolbar><AddCommentButton /></FormattingToolbar></div> : null
114
120
  }
115
121
 
116
- // Formulas join the group that holds tables so the menu keeps one heading per group.
117
- function withFormulas<Item extends { group?: string }>(items: Item[], formulas: Item[]): Item[] {
118
- const index = items.findLastIndex(item => item.group === formulas[0]?.group)
119
- return index < 0 ? [...items, ...formulas] : [...items.slice(0, index + 1), ...formulas, ...items.slice(index + 1)]
122
+ // Added items join the end of their group (formulas the one that holds tables, the animation request the one that holds
123
+ // pictures) so the menu keeps one heading per group.
124
+ function withGroupItems<Item extends { group?: string }>(items: Item[], added: Item[]): Item[] {
125
+ const index = items.findLastIndex(item => item.group === added[0]?.group)
126
+ return index < 0 ? [...items, ...added] : [...items.slice(0, index + 1), ...added, ...items.slice(index + 1)]
120
127
  }
121
128
 
122
129
  /** One native editor owns selection, transactions and history across the complete document. */
@@ -156,7 +163,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
156
163
  dictionary, tables: { splitCells: true, cellBackgroundColor: true, cellTextColor: true, headers: true },
157
164
  // The surface's own click handler opens links in editable and read-only states alike.
158
165
  links: { onClick: () => true },
159
- extensions: [nativeTextClipboard, documentBlockColors, imageFileInput({
166
+ extensions: [nativeTextClipboard, documentBlockColors, documentPageBodies(), imageFileInput({
160
167
  onStart: () => { if (current.current.identity === props.identity) setFileErrors(undefined) },
161
168
  onFailure: failure => { if (current.current.identity === props.identity) setFileErrors(value => ({ identity: props.identity, failures: [...(value?.identity === props.identity ? value.failures : []), failure] })) },
162
169
  }), ...props.comments ? [nativeCommentSelection(), nativeComments(props.comments, t.author)] : []],
@@ -171,7 +178,7 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
171
178
  stopCommentHistory?.(); current.current.onReady?.(undefined)
172
179
  }
173
180
  }, [editor])
174
- 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}>
175
182
  <div className="pm-document-editor pm-ui-block-editor pm-ui" data-document-editor={props.identity}
176
183
  onDragEnter={event => { if (event.dataTransfer.types.includes('Files')) event.stopPropagation() }}
177
184
  onDragOver={event => { if (event.dataTransfer.types.includes('Files')) event.stopPropagation() }}
@@ -196,14 +203,23 @@ export function BlockNoteSurface(props: BlockNoteSurfaceProps) {
196
203
  <LinkToolbarController linkToolbar={DocumentLinkToolbar} floatingUIOptions={linkToolbarOptions} />
197
204
  <SideMenuController sideMenu={DocumentSideMenu} />
198
205
  <TableHandlesController tableHandle={DocumentTableHandle} tableCellHandle={DocumentTableCellButton} />
199
- <SuggestionMenuController triggerCharacter="/" getItems={async query => editor.getTextCursorPosition().block.type === 'presmiumPage' ? [] : filterSuggestionItems([...withFormulas(getDefaultReactSlashMenuItems(editor), formulaSlashItems(editor, props.locale, dictionary.slash_menu.table.group)), {
206
+ <SuggestionMenuController triggerCharacter="/" getItems={async query => editor.getTextCursorPosition().block.type === 'presmiumPage' ? [] : filterSuggestionItems([...withGroupItems(withGroupItems(getDefaultReactSlashMenuItems(editor), formulaSlashItems(editor, props.locale, dictionary.slash_menu.table.group)), current.current.animationRequest?.available() ? [{
207
+ title: t.animateWithAI, subtext: t.animateWithAIHint, group: dictionary.slash_menu.image.group, icon: <PmIcon name="sparkle" />, aliases: slashAliases('animateWithAIAliases'),
208
+ // The menu has already taken back the typed “/” and query; the AI is asked, the document stays as it was.
209
+ onItemClick: () => current.current.animationRequest?.request(editor),
210
+ }] : []), {
200
211
  title: t.page, aliases: slashAliases('pageAliases'), group: t.document,
201
- onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId: crypto.randomUUID() }, content: t.untitledPage }], current, 'after') },
212
+ onItemClick: () => { const current = editor.getTextCursorPosition().block; editor.insertBlocks([{ type: 'presmiumPage', props: { sectionId: randomUUID() }, content: t.untitledPage }], current, 'after') },
202
213
  }], query)} />
203
214
  {props.children}
204
215
  </NewCommentDraftProvider></BlockNoteViewEditor>
205
216
  </ComponentsContext.Provider>
206
217
  </BlockNoteView>
218
+ <div className="pm-document-editor__end" aria-hidden="true" data-editable={props.readOnly ? undefined : ''} onMouseDown={event => {
219
+ if (event.button !== 0 || !editor.isEditable || editor.prosemirrorView.composing) return
220
+ event.preventDefault()
221
+ focusDocumentEnd(editor)
222
+ }} />
207
223
  </div>
208
224
  </COMMENT_EDITOR_CONTEXT.Provider></DOCUMENT_NODE_VIEWS.Provider></DOCUMENT_LINKS.Provider></DOCUMENT_EDITOR_LOCALE.Provider>
209
225
  }
@@ -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 }: {
@@ -1,5 +1,5 @@
1
1
  import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
2
- import { applyDocumentComponentAction, effectiveComponentParameters, isRecord, validateDocumentParameters } from '@lincyaw/kernel'
2
+ import { applyDocumentComponentAction, effectiveComponentParameters, isRecord, randomUUID, validateDocumentParameters } from '@lincyaw/kernel'
3
3
  import type { CanonicalSource, DocumentComponentAction, DocumentParameterValidation, JsonObject, TeachingDocument } from '@lincyaw/kernel'
4
4
  import { PmButton, PmDialog, PmNotice, PmSelect } from '../components.tsx'
5
5
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
@@ -17,7 +17,7 @@ function fresh(document: TeachingDocument, source: CanonicalSource, target: Comp
17
17
  const block = document.blocks[target.blockId]
18
18
  if (block?.type !== 'component') throw new Error('component-block-missing')
19
19
  const value = effectiveComponentParameters(document, block.id, target.stepId).parameters
20
- return { format: 1, id: crypto.randomUUID(), revision: 0, target, source, definitionId: block.definitionId, baseline: value, value,
20
+ return { format: 1, id: randomUUID(), revision: 0, target, source, definitionId: block.definitionId, baseline: value, value,
21
21
  composing: false, reset: false, updatedAt: new Date().toISOString() }
22
22
  }
23
23
  function message(error: unknown, t: ComponentPropertyMessages): string {
@@ -164,7 +164,7 @@ export function ComponentPropertiesDialog({ identity, blockId, stepId, onClose }
164
164
  const submit = async (action: DocumentComponentAction, submitted?: ComponentPropertyDraft) => {
165
165
  if (!canonical || !source?.version || !clean || current.current.busy) return
166
166
  const expected = { identity, version: source.version, fingerprint: source.fingerprint! }, signature = JSON.stringify([canonical, action])
167
- if (!intent.current || intent.current.signature !== signature || intent.current.draft !== submitted) intent.current = { signature, draft: submitted, id: crypto.randomUUID() }
167
+ if (!intent.current || intent.current.signature !== signature || intent.current.draft !== submitted) intent.current = { signature, draft: submitted, id: randomUUID() }
168
168
  const captured = intent.current, controller = new AbortController(), submittedKey = key
169
169
  flight.current = controller; current.current.busy = true; setBusy(true); setError(undefined)
170
170
  try {
@@ -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,22 +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 { documentAnchorOrder, isDocumentPlaceAnchor, randomUUID } from '@lincyaw/kernel'
4
+ import type { DocumentPlaceAnchor, TeachingDocument } from '@lincyaw/kernel'
3
5
  import { CommentEditorSubmitExtension, CommentsExtension } from '@blocknote/core/comments'
4
6
  import { components } from '@blocknote/mantine'
5
7
  import { FloatingThreadController, getReferenceText, Thread, useBlockNoteEditor, useCreateBlockNote, useEditorState, useExtension, useExtensionState, useThreads } from '@blocknote/react'
6
8
  import type { ComponentProps, ThreadProps } from '@blocknote/react'
7
9
  import type { Locale } from '../messages.ts'
8
10
  import { PmButton, PmEmpty, PmNotice, PmSelect } from '../components.tsx'
11
+ import { useWorkbenchState } from '../context.tsx'
9
12
  import { enterSubmits } from './comments.ts'
10
13
  import type { DocumentCommentEditorHandle, DocumentThreadStore } from './comments.ts'
11
14
  import type { CommentDrafts, CommentDraftCandidate, CommentDraftRecord, CommentDraftReference, CommentDraftOperation } from './comment-drafts.ts'
12
15
  import { isNewCommentDraft, sameCommentDraftTarget } from './comment-drafts.ts'
13
- import { createRichProjection, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
16
+ import { createRichProjection, fallbackText, nativeRichTextToProduct, productRichTextToNative } from './rich-text.ts'
14
17
  import { commentEditorSchema } from './schema.tsx'
15
18
  import type { DocumentEditorBlock } from './schema.tsx'
16
19
  import { DOCUMENT_EDITOR_MESSAGES } from './messages.ts'
20
+ import { componentDefinitionLabel } from './component-label.ts'
17
21
  import { commentFloating } from './popover.tsx'
18
22
 
19
- 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)
20
24
  const THREAD_CONTEXT = createContext<string | undefined>(undefined)
21
25
  const emptySubscribe = () => () => {}
22
26
  const emptyState = { candidates: [], pending: false, failed: false, reading: false } as const
@@ -32,12 +36,14 @@ export function DocumentCommentThread(props: ThreadProps) {
32
36
 
33
37
  /** Keep the native controller and reply editor while body selection owns the pointer. */
34
38
  export function DocumentFloatingThreadController() {
35
- const editor = useBlockNoteEditor(), { selectedThreadId } = useExtensionState(CommentsExtension)
39
+ const editor = useBlockNoteEditor(), { selectedThreadId, threadPositions } = useExtensionState(CommentsExtension)
36
40
  const empty = useEditorState({ editor, on: 'selection', selector: ({ editor }) => editor.prosemirrorState.selection.empty })
37
41
  const [selecting, setSelecting] = useState(false)
38
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))
39
45
  const shown = useRef(false), thread = useRef(selectedThreadId)
40
- shown.current = Boolean(selectedThreadId) && !blocked
46
+ shown.current = positioned && !blocked
41
47
  thread.current = selectedThreadId
42
48
  // The pointer that last pressed commented text, and the line of the thread chosen from it (the first line without one).
43
49
  const point = useRef<{ x: number, y: number }>(), line = useRef<{ thread: string, index: number }>()
@@ -101,16 +107,60 @@ export function DocumentFloatingThreadController() {
101
107
  return rects[Math.min(line.current.index, rects.length - 1)]
102
108
  }), [editor])
103
109
  return <FloatingThreadController floatingThread={DocumentCommentThread} floatingUIOptions={{
104
- useFloatingOptions: { ...floating, open: Boolean(selectedThreadId) && !blocked },
110
+ useFloatingOptions: { ...floating, open: positioned && !blocked },
105
111
  elementProps: { className: blocked ? 'pm-ui-comment-hidden' : undefined },
106
112
  }} />
107
113
  }
108
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
+
109
136
  /** Native Thread composition, with the same public focus/blur and position ordering as the sidebar. */
110
137
  export function DocumentThreadsSidebar({ children }: { children?: ReactNode }) {
111
138
  const editor = useBlockNoteEditor(), comments = useExtension(CommentsExtension), threads = useThreads()
112
139
  const { selectedThreadId, threadPositions } = useExtensionState(CommentsExtension)
113
- 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())
114
164
  const focus = (id: string, event: FocusEvent) => { if (!(event.target as HTMLElement).closest('.bn-action-toolbar')) comments.selectThread(id) }
115
165
  const blur = (event: FocusEvent) => {
116
166
  const next = event.relatedTarget
@@ -118,9 +168,8 @@ export function DocumentThreadsSidebar({ children }: { children?: ReactNode }) {
118
168
  const parent = next.closest('.bn-thread')
119
169
  if (!parent || !(event.target instanceof Node) || !parent.contains(event.target)) comments.selectThread(undefined)
120
170
  }
121
- const context = useContext(COMMENT_EDITOR_CONTEXT), t = DOCUMENT_EDITOR_MESSAGES[context?.locale ?? 'en']
122
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}
123
- 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)}
124
173
  onFocus={event => focus(thread.id, event)} onBlur={blur} tabIndex={0} />)}</div>
125
174
  }
126
175
 
@@ -174,7 +223,7 @@ export function DocumentCommentEditor(props: ComponentProps['Comments']['Editor'
174
223
  return value
175
224
  }, [props.editor, drafts])
176
225
  const rich = useMemo(() => ({ current: record.rich }), [record])
177
- const composerId = useRef(crypto.randomUUID())
226
+ const composerId = useRef(randomUUID())
178
227
  const state = useSyncExternalStore(drafts?.subscribe ?? emptySubscribe, drafts?.snapshot ?? (() => emptyState))
179
228
  useLayoutEffect(() => {
180
229
  if (!context || !threadId) return