@lincyaw/workbench 0.2.0-rc.6 → 0.2.0-rc.60

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 (90) hide show
  1. package/package.json +5 -4
  2. package/src/MediaClipEditor.tsx +4 -3
  3. package/src/StepProductionEditor.tsx +13 -4
  4. package/src/approvals.tsx +6 -1
  5. package/src/audio-recording.ts +27 -5
  6. package/src/authoring-client.ts +10 -10
  7. package/src/authoring-draft-fragment.ts +3 -1
  8. package/src/authoring-window.ts +100 -0
  9. package/src/body-draft-actions.ts +60 -0
  10. package/src/caption-timing-drafts.ts +18 -1
  11. package/src/component-property-drafts.ts +5 -5
  12. package/src/components.tsx +22 -31
  13. package/src/context.tsx +5 -3
  14. package/src/diagnostics.ts +1 -1
  15. package/src/document-draft-store.ts +45 -18
  16. package/src/document-drafts.ts +28 -19
  17. package/src/document-editing.ts +484 -0
  18. package/src/document-editor/BlockNoteSurface.tsx +25 -9
  19. package/src/document-editor/ComponentMaterials.tsx +3 -9
  20. package/src/document-editor/ComponentPropertiesDialog.tsx +4 -4
  21. package/src/document-editor/DocumentBlockPreview.tsx +4 -2
  22. package/src/document-editor/DocumentComments.tsx +85 -14
  23. package/src/document-editor/DocumentEditor.tsx +44 -7
  24. package/src/document-editor/DocumentStepNarration.tsx +33 -25
  25. package/src/document-editor/NarrationEditor.tsx +54 -20
  26. package/src/document-editor/NewCommentDrafts.tsx +114 -31
  27. package/src/document-editor/PlaceComment.tsx +228 -0
  28. package/src/document-editor/comment-draft-actions.ts +40 -20
  29. package/src/document-editor/comment-draft-inspection.ts +2 -2
  30. package/src/document-editor/comment-drafts.ts +73 -25
  31. package/src/document-editor/comments.ts +30 -10
  32. package/src/document-editor/component-label.ts +11 -0
  33. package/src/document-editor/file-input.ts +2 -2
  34. package/src/document-editor/focus.ts +0 -2
  35. package/src/document-editor/insertion-place.ts +60 -0
  36. package/src/document-editor/messages.ts +3 -3
  37. package/src/document-editor/narration-schema.tsx +12 -6
  38. package/src/document-editor/narration.ts +19 -3
  39. package/src/document-editor/page-body.ts +60 -0
  40. package/src/document-editor/projection.ts +2 -2
  41. package/src/document-editor/rich-text.ts +3 -2
  42. package/src/document-editor/selection.ts +13 -0
  43. package/src/document-editor/style.css +12 -1
  44. package/src/document-editor/table-identities.ts +2 -1
  45. package/src/document-production.ts +491 -0
  46. package/src/document-session.ts +193 -53
  47. package/src/document-timing-drafts.ts +22 -2
  48. package/src/history.ts +5 -5
  49. package/src/index.ts +6 -5
  50. package/src/jobs.ts +1 -1
  51. package/src/media-drafts.ts +43 -1
  52. package/src/messages.ts +19 -4
  53. package/src/panels/DocumentView.tsx +66 -26
  54. package/src/panels/DocumentVoiceDialog.tsx +25 -9
  55. package/src/panels/DocumentVoiceField.tsx +1 -1
  56. package/src/panels/ExportPanel.tsx +1 -6
  57. package/src/panels/HistoryPanel.tsx +1 -1
  58. package/src/panels/PageDeleteDialog.tsx +4 -4
  59. package/src/panels/PageRenameDialog.tsx +1 -1
  60. package/src/panels/PreviewPanel.tsx +1 -4
  61. package/src/panels/ProductionCaptionSize.tsx +20 -0
  62. package/src/panels/ProductionCaptionTiming.tsx +12 -9
  63. package/src/panels/ProductionMediaClips.tsx +23 -7
  64. package/src/panels/ProductionPanel.tsx +8 -4
  65. package/src/panels/ProductionRecording.tsx +86 -9
  66. package/src/panels/ProductionRecordingRange.tsx +21 -19
  67. package/src/panels/ProductionTimeline.tsx +6 -1
  68. package/src/panels/ProductionTranscription.tsx +5 -4
  69. package/src/panels/SourceDocumentPanel.tsx +12 -15
  70. package/src/panels/TranscriptionAdoption.tsx +40 -34
  71. package/src/panels/VoiceCloneDialog.tsx +2 -1
  72. package/src/panels/VoiceoverDialog.tsx +1 -1
  73. package/src/places.ts +1 -36
  74. package/src/preview-playback.ts +1 -1
  75. package/src/production-draft-actions.ts +37 -0
  76. package/src/production-messages.ts +6 -0
  77. package/src/production-playback.ts +1 -1
  78. package/src/production-voice-playback.ts +3 -2
  79. package/src/sha256.ts +9 -0
  80. package/src/styles.css +16 -41
  81. package/src/transcription-drafts.ts +124 -0
  82. package/src/use-recording-adoption.ts +2 -2
  83. package/src/voice-drafts.ts +32 -8
  84. package/src/voiceover-jobs.ts +1 -1
  85. package/src/workbench-state.ts +157 -0
  86. package/src/workbench.ts +254 -950
  87. package/src/workspace-client.ts +21 -11
  88. package/src/assistant-mascot.ts +0 -62
  89. package/src/mascot-preference.ts +0 -37
  90. package/src/panels/ChangeTrail.tsx +0 -79
@@ -1,17 +1,14 @@
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'
7
5
  import * as Tabs from '@radix-ui/react-tabs'
8
6
  import * as Toolbar from '@radix-ui/react-toolbar'
9
7
  import * as RadioGroup from '@radix-ui/react-radio-group'
10
- import { forwardRef, useEffect, useId, useMemo, useRef, useState } from 'react'
8
+ import { createContext, forwardRef, useContext, 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'
@@ -289,8 +286,13 @@ export function PmWorkspaceSwitcher({ label, value, items, onValueChange, placeh
289
286
  export type PopoverPlacement = 'below-end' | 'below-start' | 'above-end' | 'above-start'
290
287
  const placementOf = (placement: PopoverPlacement) => ({ side: placement.startsWith('above') ? 'top' as const : 'bottom' as const, align: placement.endsWith('start') ? 'start' as const : 'end' as const })
291
288
 
289
+ /** Host controls remain reachable inside the active modal without weakening its focus boundary. */
290
+ export const PmDialogActionsContext = createContext<ReactNode>(undefined)
291
+ const PmDialogLayerContext = createContext(false)
292
+
292
293
  export function PmDialog({ open, label, closeLabel, name, actions, description, footer, busy, onClose, onOpenAutoFocus, onCloseAutoFocus, children }: { open: boolean, label: string, closeLabel: string, name?: string, actions?: ReactNode, description?: string, footer?: ReactNode, busy?: boolean, onClose(): void, onOpenAutoFocus?(event: Event): void, onCloseAutoFocus?(event: Event): void, children?: ReactNode }) {
293
294
  const id = useId()
295
+ const hostActions = useContext(PmDialogActionsContext)
294
296
  // A descendant's React autoFocus runs before Radix's open-focus event.
295
297
  const trigger = useRef<HTMLElement | null>(typeof document === 'undefined' ? null : document.activeElement as HTMLElement)
296
298
  useEffect(() => {
@@ -321,14 +323,17 @@ export function PmDialog({ open, label, closeLabel, name, actions, description,
321
323
  const target = available(trigger.current) ? trigger.current : [...document.querySelectorAll<HTMLElement>('[role="toolbar"] button, main button')].find(available)
322
324
  target?.focus()
323
325
  }}>
326
+ <PmDialogLayerContext.Provider value>
324
327
  <div className="pm-ui-dialog__header">
325
328
  <Dialog.Title className="pm-ui-dialog__title">{label}</Dialog.Title>
326
329
  {actions}
330
+ {hostActions}
327
331
  <Dialog.Close asChild><PmIconButton icon="close" label={closeLabel} small disabled={busy} /></Dialog.Close>
328
332
  </div>
329
333
  {description && <Dialog.Description className="pm-ui-dialog__description">{description}</Dialog.Description>}
330
334
  <div className="pm-ui-dialog__body">{children}</div>
331
335
  {footer && <div className="pm-ui-dialog__footer">{footer}</div>}
336
+ </PmDialogLayerContext.Provider>
332
337
  </Dialog.Content>
333
338
  </Dialog.Portal>
334
339
  </Dialog.Root>
@@ -336,12 +341,13 @@ export function PmDialog({ open, label, closeLabel, name, actions, description,
336
341
  }
337
342
 
338
343
  /** A non-modal floating panel on its trigger, with the shared `pm-ui-popover` surface (host's PmPopover for React pages). */
339
- export function PmPopover({ open, label, name, placement = 'below-end', trigger, onOpenChange, children }: { open: boolean, label: string, name?: string, placement?: PopoverPlacement, trigger: ReactNode, onOpenChange(open: boolean): void, children?: ReactNode }) {
344
+ export function PmPopover({ open, label, name, placement = 'below-end', trigger, onOpenChange, onInteractOutside, children }: { open: boolean, label: string, name?: string, placement?: PopoverPlacement, trigger: ReactNode, onOpenChange(open: boolean): void, onInteractOutside?: ComponentProps<typeof Popover.Content>['onInteractOutside'], children?: ReactNode }) {
345
+ const inDialog = useContext(PmDialogLayerContext)
340
346
  return (
341
347
  <Popover.Root open={open} onOpenChange={onOpenChange}>
342
348
  <Popover.Trigger asChild>{trigger}</Popover.Trigger>
343
349
  <Popover.Portal>
344
- <Popover.Content className={cls('pm-ui-popover', 'pm-ui-floating', 'pm-ui', name)} aria-label={label} {...placementOf(placement)} sideOffset={6} collisionPadding={16} onEscapeKeyDown={event => event.stopPropagation()}>
350
+ <Popover.Content className={cls('pm-ui-popover', 'pm-ui-floating', 'pm-ui', name)} data-layer={inDialog ? 'dialog' : undefined} aria-label={label} {...placementOf(placement)} sideOffset={6} collisionPadding={16} onInteractOutside={onInteractOutside} onEscapeKeyDown={event => event.stopPropagation()}>
345
351
  {children}
346
352
  </Popover.Content>
347
353
  </Popover.Portal>
@@ -413,26 +419,6 @@ export function PmNotice({ tone = 'neutral', children }: { tone?: 'neutral' | 'a
413
419
  return <div className={cls('pm-ui-notice', tone !== 'neutral' && `pm-ui-notice--${tone}`)} role={tone === 'danger' ? 'alert' : 'status'}>{children}</div>
414
420
  }
415
421
 
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
422
  export interface RangeProps {
437
423
  label: string
438
424
  value: number
@@ -526,6 +512,10 @@ export interface TimelineProps {
526
512
  showSteps?: boolean
527
513
  /** A flush docked editor, with status and zoom in the same tool row. */
528
514
  variant?: 'default' | 'editor'
515
+ /** The page has no place on this timeline (the lecture leaves it out): its status and notice say so, with no tracks to seek. */
516
+ excluded?: { status: string, notice: string }
517
+ /** A note about the selected step, under the tracks. */
518
+ notice?: string
529
519
  }
530
520
 
531
521
  const timelineTime = (ms: number) => `${String(Math.floor(ms / 60000)).padStart(2, '0')}:${(ms % 60000 / 1000).toFixed(3).padStart(6, '0')}`
@@ -540,11 +530,11 @@ function waveformPath(samples: readonly number[] | undefined): string | undefine
540
530
  }
541
531
 
542
532
  /** 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) {
533
+ 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
534
  const hintId = useId()
545
535
  const viewport = useRef<HTMLDivElement>(null), tick = useRef<HTMLSpanElement>(null), composing = useRef(false)
546
536
  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
537
+ const span = !excluded && Number.isFinite(durationMs) && durationMs! >= 0 ? durationMs : undefined
548
538
  const timing = durationStatus ?? (span === undefined ? 'unknown' : 'confirmed')
549
539
  const timed = span !== undefined && span > 0 && timing !== 'unknown'
550
540
  const blocked = Boolean(disabled || loading), cannotSeek = Boolean(blocked || seeking || seekDisabled || !timed || timing !== 'confirmed')
@@ -585,10 +575,10 @@ export function PmTimeline({ label, tracks, labels, durationMs, durationStatus,
585
575
  const marks = Array.from({ length: Math.min(200, Math.floor(span / unit) + 1) }, (_, index) => index * unit)
586
576
  return [0, ...marks.filter(time => time > 0 && time < span && Math.min(time, span - time) / span * width * scale >= tickWidth), span]
587
577
  }, [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>
578
+ 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
579
  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
580
  <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}
581
+ <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
582
  onChange={event => setRaw(event.target.value)} onBlur={commitPosition}
593
583
  onCompositionStart={() => { composing.current = true }} onCompositionEnd={() => { composing.current = false }}
594
584
  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 +615,8 @@ export function PmTimeline({ label, tracks, labels, durationMs, durationStatus,
625
615
  <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
616
  </PmSelect></div>}
627
617
  {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>}
618
+ {(excluded || !tracks.some(track => track.segments.length)) && <PmNotice>{excluded?.notice ?? labels.empty}</PmNotice>}
619
+ {notice && <PmNotice>{notice}</PmNotice>}
629
620
  <p id={hintId} className="pm-ui-sr-only">{labels.seekHint}</p>
630
621
  </section>
631
622
  }
package/src/context.tsx CHANGED
@@ -2,13 +2,15 @@ import { createContext, useContext, useSyncExternalStore } from 'react'
2
2
  import type { ReactNode } from 'react'
3
3
  import { MESSAGES } from './messages.ts'
4
4
  import type { WorkbenchMessages } from './messages.ts'
5
- import type { Workbench, WorkbenchState } from './workbench.ts'
5
+ import type { Workbench } from './workbench.ts'
6
+ import type { WorkbenchState } from './workbench-state.ts'
7
+ import { PmDialogActionsContext } from './components.tsx'
6
8
 
7
9
  const WORKBENCH = createContext<Workbench | undefined>(undefined)
8
10
 
9
11
  /** Gives the panels drawn in it one workbench. */
10
- export function WorkbenchProvider({ workbench, children }: { workbench: Workbench, children?: ReactNode }) {
11
- return <WORKBENCH.Provider value={workbench}>{children}</WORKBENCH.Provider>
12
+ export function WorkbenchProvider({ workbench, children, dialogActions }: { workbench: Workbench, children?: ReactNode, dialogActions?: ReactNode }) {
13
+ return <WORKBENCH.Provider value={workbench}>{dialogActions === undefined ? children : <PmDialogActionsContext.Provider value={dialogActions}>{children}</PmDialogActionsContext.Provider>}</WORKBENCH.Provider>
12
14
  }
13
15
 
14
16
  export function useWorkbench(): Workbench {
@@ -1,6 +1,6 @@
1
1
  import { errorMessage } from '@lincyaw/kernel'
2
2
  import type { Diagnostic, DiagnosticSnapshot, PreviewDiagnostics } from '@lincyaw/kernel'
3
- import type { WorkbenchStore } from './workbench.ts'
3
+ import type { WorkbenchStore } from './workbench-state.ts'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
5
 
6
6
  type Repairer = (diagnostics: readonly Diagnostic[]) => void | Promise<void>
@@ -1,3 +1,14 @@
1
+ export interface DraftStoreOperation { signal?: AbortSignal, guard?(): void }
2
+ export async function waitForDraft<T>(work: Promise<T>, signal?: AbortSignal): Promise<T> {
3
+ signal?.throwIfAborted()
4
+ if (!signal) return work
5
+ return new Promise<T>((resolve, reject) => {
6
+ const abort = () => { signal.removeEventListener('abort', abort); reject(signal.reason) }
7
+ signal.addEventListener('abort', abort, { once: true })
8
+ work.then(value => { signal.removeEventListener('abort', abort); signal.aborted ? reject(signal.reason) : resolve(value) }, error => { signal.removeEventListener('abort', abort); reject(error) })
9
+ })
10
+ }
11
+
1
12
  export type DraftStoreResult = 'committed' | 'superseded' | 'failed'
2
13
  export interface DraftStoreCommit { generation: number, done: Promise<DraftStoreResult> }
3
14
  interface Operation extends DraftStoreCommit {
@@ -98,31 +109,47 @@ export class DocumentDraftStore {
98
109
 
99
110
  #notify(): void { if (!this.#closing) this.#channel?.postMessage({ scope: this.#scope, ...this.#writerOwner ? { owner: this.#writerOwner } : {}, ...this.#family ? { family: this.#family } : {} }) }
100
111
 
101
- async #commit(key: string | undefined, raw: string | undefined, markers: readonly [string, string][]): Promise<{ committed: boolean, foreign: boolean }> {
112
+ async #commit(key: string | undefined, raw: string | undefined, markers: readonly [string, string][], operation?: DraftStoreOperation): Promise<{ committed: boolean, foreign: boolean }> {
102
113
  try {
103
- const db = await this.#db()
104
- return await new Promise(resolve => {
114
+ operation?.signal?.throwIfAborted(); operation?.guard?.()
115
+ const db = await waitForDraft(this.#db(), operation?.signal)
116
+ operation?.signal?.throwIfAborted(); operation?.guard?.()
117
+ return await new Promise((resolve, reject) => {
105
118
  const tx = db.transaction(ENTRIES, 'readwrite', { durability: 'strict' }), store = tx.objectStore(ENTRIES)
106
- let foreign = false
107
- tx.oncomplete = () => resolve({ committed: true, foreign })
108
- tx.onabort = () => resolve({ committed: false, foreign })
119
+ let foreign = false, failure: unknown
120
+ const abort = () => { try { tx.abort() } catch {} }
121
+ const stop = () => operation?.signal?.removeEventListener('abort', abort)
122
+ operation?.signal?.addEventListener('abort', abort, { once: true })
123
+ tx.oncomplete = () => { stop(); resolve({ committed: true, foreign }) }
124
+ tx.onabort = () => { stop(); failure || operation?.signal?.aborted ? reject(failure ?? operation?.signal?.reason) : resolve({ committed: false, foreign }) }
109
125
  tx.onerror = () => { /* The abort event delivers the terminal transaction result. */ }
110
126
  if (tx.durability !== 'strict') { tx.abort(); return }
127
+ const check = () => { operation?.signal?.throwIfAborted(); operation?.guard?.() }
111
128
  const apply = () => {
129
+ check()
112
130
  for (const [marker, value] of markers) store.put(value, marker)
113
131
  }
114
- if (key === undefined) { apply(); return }
132
+ if (key === undefined) {
133
+ if (operation) {
134
+ const gate = store.get(markers[0]?.[0] ?? 'presmium-draft-guard')
135
+ gate.onsuccess = () => { try { apply() } catch (error) { failure = error; abort() } }
136
+ } else { try { apply() } catch (error) { failure = error; abort() } }
137
+ return
138
+ }
115
139
  const request = store.get(key), expected = this.#confirmed.get(key)
116
140
  request.onsuccess = () => {
117
- foreign = request.result !== expected
118
- if (raw !== undefined) {
119
- if (foreign) { tx.abort(); return }
120
- store.put(raw, key)
121
- } else if (!foreign) store.delete(key)
122
- apply()
141
+ try {
142
+ check()
143
+ foreign = request.result !== expected
144
+ if (raw !== undefined) {
145
+ if (foreign) { tx.abort(); return }
146
+ store.put(raw, key)
147
+ } else if (!foreign) store.delete(key)
148
+ apply()
149
+ } catch (error) { failure = error; abort() }
123
150
  }
124
151
  })
125
- } catch { return { committed: false, foreign: false } }
152
+ } catch (error) { if (operation) throw error; return { committed: false, foreign: false } }
126
153
  }
127
154
 
128
155
  #stage(key: string, raw: string | undefined, markers: readonly [string, string][]): DraftStoreCommit | undefined {
@@ -157,16 +184,16 @@ export class DocumentDraftStore {
157
184
  }
158
185
 
159
186
  /** A candidate copy must be strictly committed before the actor switches to it. */
160
- async create(key: string, raw: string): Promise<boolean> {
187
+ async create(key: string, raw: string, operation?: DraftStoreOperation): Promise<boolean> {
161
188
  if (this.#closing) return false
162
- const result = await this.#commit(key, raw, [])
189
+ const result = await this.#commit(key, raw, [], operation)
163
190
  if (result.committed) { this.#confirmed.set(key, raw); this.#notify() }
164
191
  return result.committed
165
192
  }
166
193
 
167
- async mark(markers: readonly [string, string][]): Promise<boolean> {
194
+ async mark(markers: readonly [string, string][], operation?: DraftStoreOperation): Promise<boolean> {
168
195
  if (this.#closing) return false
169
- const result = await this.#commit(undefined, undefined, markers)
196
+ const result = await this.#commit(undefined, undefined, markers, operation)
170
197
  if (result.committed) this.#notify()
171
198
  return result.committed
172
199
  }
@@ -1,7 +1,8 @@
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 type { DraftStoreCommit } from './document-draft-store.ts'
4
+ import { sha256 as tokenOf } from './sha256.ts'
5
+ import type { DraftStoreCommit, DraftStoreOperation } from './document-draft-store.ts'
5
6
 
6
7
  export interface DocumentDraftReference { id: string, revision: number, token: string }
7
8
  export interface DocumentDraft {
@@ -45,36 +46,36 @@ 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
59
56
  #closed = false
57
+ #revision = 0
58
+ get revision(): number { return this.#revision }
59
+ #touch(): void { if (!this.#closed) { this.#revision++; this.#changed?.() } }
60
60
  readonly #changed?: () => void
61
61
  constructor(changed?: () => void) { this.#changed = changed }
62
62
 
63
63
  #storage(identity: string): DocumentDraftStore | undefined {
64
64
  if (this.#closed || this.#identity !== undefined && this.#identity !== identity) return
65
65
  this.#identity = identity
66
- return this.#store ??= new DocumentDraftStore(identity, this.#changed)
66
+ return this.#store ??= new DocumentDraftStore(identity, () => this.#touch())
67
67
  }
68
68
  matches(identity: string, key: string | null): boolean { return key === null || key.startsWith(prefix(identity)) || key.startsWith(markerPrefix(identity)) }
69
69
 
70
- async read(identity: string, documentId: string): Promise<{ records: RecoverableDocumentDraft[], failed: boolean }> {
70
+ async read(identity: string, documentId: string, signal?: AbortSignal): Promise<{ records: RecoverableDocumentDraft[], failed: boolean }> {
71
+ signal?.throwIfAborted()
71
72
  const store = this.#storage(identity), values: { key: string, raw: unknown, source: 'durable' | 'rescue' }[] = []
72
73
  let failed = false, durable = new Map<string, unknown>()
73
74
  if (!store) return { records: [], failed: true }
74
75
  try {
75
- durable = await store.read([prefix(identity), markerPrefix(identity)])
76
+ durable = await store.read([prefix(identity), markerPrefix(identity)], signal, signal ? 2048 : undefined)
76
77
  for (const [key, raw] of durable) if (key.startsWith(prefix(identity))) values.push({ key, raw, source: 'durable' })
77
- } catch { failed = true }
78
+ } catch { signal?.throwIfAborted(); failed = true }
78
79
  // Existing localStorage input is never removed or silently treated as a strict commit.
79
80
  try {
80
81
  const keys: string[] = []
@@ -86,9 +87,10 @@ export class DocumentDrafts {
86
87
  const raw = localStorage.getItem(key)
87
88
  if (raw !== null) values.push({ key, raw, source: 'rescue' })
88
89
  }
89
- } catch { failed = true }
90
+ } catch { signal?.throwIfAborted(); failed = true }
90
91
  const records = new Map<string, RecoverableDocumentDraft>()
91
92
  for (const { key, raw, source } of values) {
93
+ signal?.throwIfAborted()
92
94
  try {
93
95
  if (typeof raw !== 'string' || raw.length > MAX_CHARS) throw new Error('document-draft-size')
94
96
  const value: unknown = JSON.parse(raw)
@@ -96,14 +98,17 @@ export class DocumentDrafts {
96
98
  || 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
99
  const draft = documentDraft(value, documentId)
98
100
  if (!draft) throw new Error('document-draft-document')
101
+ if (draft.baseHash.startsWith('json:')) draft.baseHash = await tokenOf(draft.baseHash.slice(5))
102
+ if (draft.pendingHash?.startsWith('json:')) draft.pendingHash = await tokenOf(draft.pendingHash.slice(5))
99
103
  const token = await tokenOf(raw), marker = settledKey(identity, { id: value.id, revision: value.revision, token })
100
104
  if (durable.get(marker) === token) continue
101
105
  if (source === 'rescue' && localStorage.getItem(marker) === token) continue
102
106
  const id = JSON.stringify([value.id, value.revision, token])
103
107
  if (!records.has(id)) records.set(id, { ...draft, format: 2, identity, id: value.id, owner: value.owner, revision: value.revision, updatedAt: value.updatedAt, token, source,
104
108
  owned: source === 'durable' && value.owner === this.#owner && (this.#owned.get(value.id)?.raw === raw || store.owns(key, raw)) })
105
- } catch { failed = true }
109
+ } catch { signal?.throwIfAborted(); failed = true }
106
110
  }
111
+ signal?.throwIfAborted()
107
112
  return { records: [...records.values()], failed }
108
113
  }
109
114
 
@@ -113,7 +118,7 @@ export class DocumentDrafts {
113
118
  const owned = previous && this.#owned.get(previous.id)
114
119
  if (previous && (!owned || owned.identity !== identity || previous.owner !== this.#owner || previous.revision !== owned.revision)) return
115
120
  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() }
121
+ 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
122
  if (!Number.isSafeInteger(record.revision)) return
118
123
  try { const raw = JSON.stringify(record); return raw.length <= MAX_CHARS ? { record, raw } : undefined }
119
124
  catch { return }
@@ -126,21 +131,25 @@ export class DocumentDrafts {
126
131
  const commit = this.#store!.put(keyOf(identity, next.record.id), next.raw)
127
132
  if (!commit) return
128
133
  this.#owned.set(next.record.id, { identity, revision: next.record.revision, raw: next.raw })
134
+ void commit.done.then(() => this.#touch())
129
135
  if (previous && previous.id !== next.record.id) this.archive(previous)
130
136
  return { ...commit, record: next.record, clearing: false }
131
137
  }
132
138
 
133
- async fork(identity: string, draft: DocumentDraft): Promise<StoredDocumentDraft | undefined> {
139
+ async fork(identity: string, draft: DocumentDraft, operation?: DraftStoreOperation): Promise<StoredDocumentDraft | undefined> {
134
140
  const next = this.#record(identity, draft)
135
- if (!next || !await this.#store!.create(keyOf(identity, next.record.id), next.raw)) return
141
+ if (!next || !await this.#store!.create(keyOf(identity, next.record.id), next.raw, operation)) return
136
142
  this.#owned.set(next.record.id, { identity, revision: next.record.revision, raw: next.raw })
143
+ this.#touch()
137
144
  return next.record
138
145
  }
139
146
 
140
147
  /** Immutable, revision-specific markers never delete another tab's newer record. */
141
- async settle(identity: string, values: readonly DocumentDraftReference[]): Promise<boolean> {
148
+ async settle(identity: string, values: readonly DocumentDraftReference[], operation?: DraftStoreOperation): Promise<boolean> {
142
149
  const store = this.#storage(identity)
143
- return Boolean(store && await store.mark(values.map(value => [settledKey(identity, value), value.token])))
150
+ const done = Boolean(store && await store.mark(values.map(value => [settledKey(identity, value), value.token]), operation))
151
+ if (done) this.#touch()
152
+ return done
144
153
  }
145
154
 
146
155
  remove(identity: string, record: StoredDocumentDraft, origins: readonly DocumentDraftReference[]): DocumentDraftCommit | undefined {
@@ -148,7 +157,7 @@ export class DocumentDrafts {
148
157
  if (!store || !owned || owned.identity !== identity || record.owner !== this.#owner || owned.revision !== record.revision) return
149
158
  const commit = store.remove(keyOf(identity, record.id), origins.map(value => [settledKey(identity, value), value.token]))
150
159
  if (!commit) return
151
- void commit.done.then(result => { if (result === 'committed' && this.#owned.get(record.id)?.revision === record.revision) this.#owned.delete(record.id) })
160
+ void commit.done.then(result => { if (result === 'committed' && this.#owned.get(record.id)?.revision === record.revision) this.#owned.delete(record.id); this.#touch() })
152
161
  return { ...commit, record, clearing: true }
153
162
  }
154
163