@lincyaw/workbench 0.2.0-rc.54 → 0.2.0-rc.56

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.54",
3
+ "version": "0.2.0-rc.56",
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.54",
59
- "@lincyaw/kernel": "1.0.0-rc.54"
58
+ "@lincyaw/design": "1.0.0-rc.56",
59
+ "@lincyaw/kernel": "1.0.0-rc.56"
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.54"
70
+ "@lincyaw/compiler": "1.0.0-rc.56"
71
71
  }
72
72
  }
@@ -45,6 +45,7 @@ export interface MediaClipEditorProps {
45
45
  onReview(): void
46
46
  onApply(clip: MediaClip): void
47
47
  onRemove(): void
48
+ onInteraction?(busy: boolean): void
48
49
  onEditStart(): void
49
50
  }
50
51
 
@@ -72,7 +73,7 @@ export function MediaClipEditor(props: MediaClipEditorProps) {
72
73
  props.onApply({ ...clip, sourceRange: { startMs: startMs!, endMs: endMs! }, attachment: { ...clip.attachment, offsetMs: offsetMs! } })
73
74
  }
74
75
  const change = (patch: Partial<MediaClipDraft>) => props.onChange({ ...draft, ...patch })
75
- const composition = (field: string) => ({ onCompositionStart: () => composing.current.add(field), onCompositionEnd: () => { composing.current.delete(field) } })
76
+ const composition = (field: string) => ({ onCompositionStart: () => { composing.current.add(field); props.onInteraction?.(true) }, onCompositionEnd: () => { composing.current.delete(field); props.onInteraction?.(composing.current.size > 0 || volumePreview !== undefined) } })
76
77
  return <section className="pm-ui-media-clip-editor" aria-label={t.title} data-density={density} onFocusCapture={props.onEditStart} onPointerDownCapture={props.onEditStart}
77
78
  onKeyDown={event => {
78
79
  event.stopPropagation()
@@ -102,7 +103,7 @@ export function MediaClipEditor(props: MediaClipEditorProps) {
102
103
  <PmInput label={t.offset} density={density} width="number" inputMode="decimal" maxLength={32} value={draft.offsetText ?? (clip.attachment.offsetMs / 1000).toFixed(3)}
103
104
  readOnly={disabled || !inspected} error={offsetMs === undefined ? t.invalidOffset : undefined} onChange={event => change({ offsetText: event.target.value })} {...composition('offset')} />
104
105
  <PmField label={t.volume} density={density} group><div className="pm-ui-range-row">
105
- <PmRange label={t.volume} density={density} value={clip.volume * 100} max={100} disabled={disabled || !inspected} valueText={value => `${Math.round(value)}%`} onPreviewChange={setVolumePreview}
106
+ <PmRange label={t.volume} density={density} value={clip.volume * 100} max={100} disabled={disabled || !inspected} valueText={value => `${Math.round(value)}%`} onPreviewChange={value => { setVolumePreview(value); props.onInteraction?.(value !== undefined || composing.current.size > 0) }}
106
107
  onValueCommit={value => change({ clip: { ...clip, volume: value / 100 } })} />
107
108
  <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>
108
109
  </div></PmField>
@@ -5,7 +5,7 @@ import * as Popover from '@radix-ui/react-popover'
5
5
  import * as Tabs from '@radix-ui/react-tabs'
6
6
  import * as Toolbar from '@radix-ui/react-toolbar'
7
7
  import * as RadioGroup from '@radix-ui/react-radio-group'
8
- import { forwardRef, useEffect, useId, useMemo, useRef, useState } from 'react'
8
+ import { createContext, forwardRef, useContext, useEffect, useId, useMemo, useRef, useState } from 'react'
9
9
  import type { ComponentProps, CSSProperties, InputHTMLAttributes, ReactNode, Ref, SelectHTMLAttributes, TextareaHTMLAttributes } from 'react'
10
10
  import { Group as ResizableGroup, Panel as ResizablePanel, Separator as ResizableSeparator } from 'react-resizable-panels'
11
11
  import { PmButton, PmIcon, PmIconButton, PmTooltip } from './base-controls.tsx'
@@ -286,8 +286,13 @@ export function PmWorkspaceSwitcher({ label, value, items, onValueChange, placeh
286
286
  export type PopoverPlacement = 'below-end' | 'below-start' | 'above-end' | 'above-start'
287
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 })
288
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
+
289
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 }) {
290
294
  const id = useId()
295
+ const hostActions = useContext(PmDialogActionsContext)
291
296
  // A descendant's React autoFocus runs before Radix's open-focus event.
292
297
  const trigger = useRef<HTMLElement | null>(typeof document === 'undefined' ? null : document.activeElement as HTMLElement)
293
298
  useEffect(() => {
@@ -318,14 +323,17 @@ export function PmDialog({ open, label, closeLabel, name, actions, description,
318
323
  const target = available(trigger.current) ? trigger.current : [...document.querySelectorAll<HTMLElement>('[role="toolbar"] button, main button')].find(available)
319
324
  target?.focus()
320
325
  }}>
326
+ <PmDialogLayerContext.Provider value>
321
327
  <div className="pm-ui-dialog__header">
322
328
  <Dialog.Title className="pm-ui-dialog__title">{label}</Dialog.Title>
323
329
  {actions}
330
+ {hostActions}
324
331
  <Dialog.Close asChild><PmIconButton icon="close" label={closeLabel} small disabled={busy} /></Dialog.Close>
325
332
  </div>
326
333
  {description && <Dialog.Description className="pm-ui-dialog__description">{description}</Dialog.Description>}
327
334
  <div className="pm-ui-dialog__body">{children}</div>
328
335
  {footer && <div className="pm-ui-dialog__footer">{footer}</div>}
336
+ </PmDialogLayerContext.Provider>
329
337
  </Dialog.Content>
330
338
  </Dialog.Portal>
331
339
  </Dialog.Root>
@@ -334,11 +342,12 @@ export function PmDialog({ open, label, closeLabel, name, actions, description,
334
342
 
335
343
  /** A non-modal floating panel on its trigger, with the shared `pm-ui-popover` surface (host's PmPopover for React pages). */
336
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)
337
346
  return (
338
347
  <Popover.Root open={open} onOpenChange={onOpenChange}>
339
348
  <Popover.Trigger asChild>{trigger}</Popover.Trigger>
340
349
  <Popover.Portal>
341
- <Popover.Content className={cls('pm-ui-popover', 'pm-ui-floating', 'pm-ui', name)} aria-label={label} {...placementOf(placement)} sideOffset={6} collisionPadding={16} onInteractOutside={onInteractOutside} 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()}>
342
351
  {children}
343
352
  </Popover.Content>
344
353
  </Popover.Portal>
package/src/context.tsx CHANGED
@@ -4,12 +4,13 @@ import { MESSAGES } from './messages.ts'
4
4
  import type { WorkbenchMessages } from './messages.ts'
5
5
  import type { Workbench } from './workbench.ts'
6
6
  import type { WorkbenchState } from './workbench-state.ts'
7
+ import { PmDialogActionsContext } from './components.tsx'
7
8
 
8
9
  const WORKBENCH = createContext<Workbench | undefined>(undefined)
9
10
 
10
11
  /** Gives the panels drawn in it one workbench. */
11
- export function WorkbenchProvider({ workbench, children }: { workbench: Workbench, children?: ReactNode }) {
12
- 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>
13
14
  }
14
15
 
15
16
  export function useWorkbench(): Workbench {
@@ -17,6 +17,10 @@ import { DocumentTimingDrafts } from './document-timing-drafts.ts'
17
17
  import { CaptionTimingDrafts } from './caption-timing-drafts.ts'
18
18
  import type { CaptionTimingDraft } from './caption-timing-drafts.ts'
19
19
  import type { ClientProductionDraftMetadata } from '@lincyaw/kernel'
20
+ import { clearVoiceDraft, keepVoiceDraft, voiceDraftSnapshot } from './voice-drafts.ts'
21
+ import type { VoiceDraft } from './voice-drafts.ts'
22
+ import { discardMediaDraft, keepMediaDrafts, mediaDraftSnapshot } from './media-drafts.ts'
23
+ import type { MediaDrafts } from './media-drafts.ts'
20
24
 
21
25
  interface ProductionOptions {
22
26
  store: WorkbenchStore
@@ -96,6 +100,18 @@ export class DocumentProduction {
96
100
  this.#draftViews.add(view); this.#draftChanged()
97
101
  return () => { if (closed) return; closed = true; this.#draftViews.delete(view); this.#draftChanged() }
98
102
  }
103
+ keepVoiceDraft(identity: string, stepId: string, value: VoiceDraft): boolean {
104
+ const kept = keepVoiceDraft(this.#options.client, identity, stepId, value)
105
+ this.#draftChanged(); return kept
106
+ }
107
+ clearVoiceDraft(identity: string, stepId: string, expected: VoiceDraft): boolean {
108
+ const cleared = clearVoiceDraft(this.#options.client, identity, stepId, expected)
109
+ this.#draftChanged(); return cleared
110
+ }
111
+ keepMediaDrafts(identity: string, stepId: string, value: MediaDrafts): boolean {
112
+ const kept = keepMediaDrafts(this.#options.client, identity, stepId, value)
113
+ this.#draftChanged(); return kept
114
+ }
99
115
  /** Native pending range input survives mode and document changes within this workbench. */
100
116
  recordingRangeDrafts(identity: string): ReadonlyMap<string, RecordingRangeDraft> {
101
117
  let values = this.#recordingRangeDrafts.get(identity)
@@ -128,7 +144,7 @@ export class DocumentProduction {
128
144
  || current.loading || revision !== this.#draftRevision || viewState() !== blocked) throw new Error('client-production-drafts-changed')
129
145
  }
130
146
  const candidates: ProductionDraftSnapshot['candidates'] = []
131
- const add = (kind: ClientProductionDraftMetadata['kind'], key: string, stepId: string, value: unknown, requiresReview: boolean, storage: 'tab' | 'memory', remove: () => boolean, extra: { field?: StepDurationKey, assetId?: string } = {}, readable = true) => {
147
+ const add = (kind: ClientProductionDraftMetadata['kind'], key: string, stepId: string, value: unknown, requiresReview: boolean, storage: 'tab' | 'memory', remove: () => boolean, extra: { field?: StepDurationKey, assetId?: string, clipId?: string } = {}, readable = true) => {
132
148
  const matches = views.filter(view => view.kind === kind && view.has(key))
133
149
  const discardable = readable && clean() && !this.#unknownDraftViews && !matches.some(view => view.blocked())
134
150
  candidates.push({ key: JSON.stringify([kind, key]), metadata: { kind, stepId, ...extra, targetAvailable: Object.hasOwn(content.steps, stepId), requiresReview, storage, discardable }, value,
@@ -155,9 +171,19 @@ export class DocumentProduction {
155
171
  const [stepId] = JSON.parse(key) as [string]
156
172
  add('recording-range', key, stepId, value, value.version !== version, 'memory', () => this.#recordingRangeDrafts.get(identity)!.delete(key), { assetId: value.voice.assetId })
157
173
  }
174
+ const voices = voiceDraftSnapshot(this.#options.client, identity)
175
+ for (const { stepId, value, persisted } of voices.entries) {
176
+ add('voice', stepId, stepId, value, value.version !== version, persisted ? 'tab' : 'memory', () => clearVoiceDraft(this.#options.client, identity, stepId, value), {}, !voices.partial)
177
+ }
178
+ const media = mediaDraftSnapshot(this.#options.client, identity)
179
+ for (const { stepId, value, persisted } of media.entries) for (const [name, draft] of Object.entries(value.entries)) {
180
+ const original = content.production.mediaClips.find(clip => clip.id === draft.clip.id)
181
+ add('media-clip', JSON.stringify([stepId, name]), stepId, draft, draft.version !== version || Boolean(draft.baseClip && JSON.stringify(draft.baseClip) !== JSON.stringify(original)), persisted ? 'tab' : 'memory',
182
+ () => discardMediaDraft(this.#options.client, identity, stepId, name, value), { clipId: draft.clip.id, ...draft.clip.assetId ? { assetId: draft.clip.assetId } : {} }, !media.partial)
183
+ }
158
184
  candidates.sort((a, b) => a.key.localeCompare(b.key))
159
185
  guard()
160
- return { stamp: JSON.stringify([this.#draftSalt, identity, memberId, version, reset, revision]), coverage: timingPartial || captionPartial ? 'partial' : 'tab-state', candidates, guard }
186
+ return { stamp: JSON.stringify([this.#draftSalt, identity, memberId, version, reset, revision]), coverage: timingPartial || captionPartial || voices.partial || media.partial ? 'partial' : 'tab-state', candidates, guard }
161
187
  }
162
188
 
163
189
  source(expected: { identity: string, version: string }): DocumentSessionState {
@@ -4,7 +4,7 @@ import type { MediaClipDraft } from './MediaClipEditor.tsx'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
5
 
6
6
  export interface MediaDrafts { selectedClipId?: string, entries: Record<string, MediaClipDraft> }
7
- interface Entry { value: MediaDrafts, failed: boolean, volatile: boolean, unreadable?: string }
7
+ interface Entry { value: MediaDrafts, failed: boolean, volatile: boolean, unreadable?: string, raw?: string | null }
8
8
  const memory = new WeakMap<WorkspaceClient, Map<string, Entry>>()
9
9
  const prefix = 'presmium.media-drafts.v1:', limit = 64
10
10
  const keyOf = (identity: string, stepId: string) => prefix + JSON.stringify([identity, stepId])
@@ -38,6 +38,7 @@ function load(client: WorkspaceClient, key: string): Entry {
38
38
  const entry: Entry = { value: { entries: {} }, failed: false, volatile: false }
39
39
  try {
40
40
  const raw = sessionStorage.getItem(key)
41
+ entry.raw = raw
41
42
  if (raw !== null) {
42
43
  entry.unreadable = raw
43
44
  if (raw.length > 131072) throw new Error('media-drafts-size')
@@ -68,6 +69,7 @@ export function keepMediaDrafts(client: WorkspaceClient, identity: string, stepI
68
69
  if (raw.length > 131072) throw new Error('media-drafts-size')
69
70
  if (entry.unreadable !== undefined) sessionStorage.setItem(`${key}:unreadable`, entry.unreadable)
70
71
  sessionStorage.setItem(key, raw)
72
+ entry.raw = raw
71
73
  const keys = Array.from({ length: sessionStorage.length }, (_, index) => sessionStorage.key(index)!).filter(name => name.startsWith(prefix) && !name.endsWith(':unreadable') && name !== key)
72
74
  let excess = keys.length - limit + 1
73
75
  for (const old of keys) {
@@ -81,3 +83,43 @@ export function keepMediaDrafts(client: WorkspaceClient, identity: string, stepI
81
83
  return true
82
84
  } catch { entry.failed = true; trim(known); return false }
83
85
  }
86
+
87
+ /** This is the same step/form bank used when the author reopens Media, including session-only input. */
88
+ export function mediaDraftSnapshot(client: WorkspaceClient, identity: string): { entries: { stepId: string, value: MediaDrafts, persisted: boolean }[], partial: boolean } {
89
+ const scoped = `${prefix}${JSON.stringify([identity]).slice(0, -1)},`
90
+ const keys = new Set([...store(client).keys()].filter(key => key.startsWith(scoped)))
91
+ let partial = false
92
+ try {
93
+ for (let index = 0; index < sessionStorage.length; index++) {
94
+ const key = sessionStorage.key(index)
95
+ if (key?.startsWith(scoped) && !key.endsWith(':unreadable')) keys.add(key)
96
+ }
97
+ } catch { partial = true }
98
+ const entries: { stepId: string, value: MediaDrafts, persisted: boolean }[] = []
99
+ for (const key of keys) {
100
+ let target: unknown
101
+ try { target = JSON.parse(key.slice(prefix.length)) } catch { partial = true; continue }
102
+ if (!Array.isArray(target) || target.length !== 2 || target[0] !== identity || typeof target[1] !== 'string') { partial = true; continue }
103
+ const entry = load(client, key)
104
+ let persisted = false
105
+ try { const raw = sessionStorage.getItem(key); persisted = !entry.failed && raw === entry.raw; if (raw !== entry.raw) partial = true } catch { partial = true }
106
+ if (entry.unreadable !== undefined || entry.raw === undefined) partial = true
107
+ if (Object.keys(entry.value.entries).length) entries.push({ stepId: target[1], value: structuredClone(entry.value), persisted })
108
+ }
109
+ return { entries, partial }
110
+ }
111
+
112
+ /** Retire one exact clip proposal, preserving sibling forms and any independently changed storage. */
113
+ export function discardMediaDraft(client: WorkspaceClient, identity: string, stepId: string, name: string, expected: MediaDrafts): boolean {
114
+ const key = keyOf(identity, stepId), entry = load(client, key)
115
+ if (!Object.hasOwn(expected.entries, name) || JSON.stringify(entry.value) !== JSON.stringify(expected)) return false
116
+ try {
117
+ if (entry.raw === undefined || entry.unreadable !== undefined || sessionStorage.getItem(key) !== entry.raw) return false
118
+ const next = structuredClone(entry.value)
119
+ delete next.entries[name]
120
+ const raw = JSON.stringify(next)
121
+ sessionStorage.setItem(key, raw)
122
+ entry.value = next; entry.raw = raw; entry.failed = false; entry.volatile = false
123
+ return true
124
+ } catch { entry.failed = true; return false }
125
+ }
@@ -4,7 +4,7 @@ import { PmButton, PmDialog, PmField, PmInput, PmNotice, PmSearchList, PmSegment
4
4
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
5
5
  import { documentVoiceStepIds, previewDocumentVoiceChange, resolveDocumentStepVoice } from '../document-voices.ts'
6
6
  import type { DocumentVoiceImpact } from '../document-voices.ts'
7
- import { clearVoiceDraft, keepVoiceDraft, readVoiceDraft, voiceDraftStorageStatus } from '../voice-drafts.ts'
7
+ import { readVoiceDraft, voiceDraftStorageStatus } from '../voice-drafts.ts'
8
8
  import type { VoiceDraft } from '../voice-drafts.ts'
9
9
  import { PRODUCTION_MESSAGES } from '../production-messages.ts'
10
10
  import { VOICE_CLONE_MESSAGES } from '../voice-clone-messages.ts'
@@ -26,13 +26,14 @@ export function DocumentVoiceDialog({ stepId, onClose }: { stepId: string, onClo
26
26
  const t = VOICE_MESSAGES[locale], p = PRODUCTION_MESSAGES[locale], c = VOICE_CLONE_MESSAGES[locale]
27
27
  const serviceVersion = useWorkbenchState(state => state.voiceServiceVersion)
28
28
  const identity = useRef(actor!.identity!).current, directory = useRef(actor!.directory).current
29
- const [restored] = useState(() => readVoiceDraft(workbench.client, identity, stepId))
29
+ const [restored, setRestored] = useState(() => readVoiceDraft(workbench.client, identity, stepId))
30
30
  const [draft, setDraft] = useState<VoiceDraft>(() => restored ?? { version: actor!.version!, scope: { kind: 'step', stepId }, source: resolveDocumentStepVoice(actor!.content!, stepId).value ?? null, replaceOverrides: false })
31
31
  const [storageFailed, setStorageFailed] = useState(() => voiceDraftStorageStatus(workbench.client, identity, stepId) !== 'available')
32
32
  const [engineFilter, setEngineFilter] = useState(draft.source?.type === 'tts' ? draft.source.voice.engine : undefined)
33
33
  const [language, setLanguage] = useState(''), [query, setQuery] = useState(''), [catalog, setCatalog] = useState<VoiceCatalogAnswer>()
34
34
  const [catalogBusy, setCatalogBusy] = useState(true), [catalogFailure, setCatalogFailure] = useState<string>(), [reload, setReload] = useState(0)
35
- const [busy, setBusy] = useState(false), [failure, setFailure] = useState<string>(), [review, setReview] = useState<Review>()
35
+ const pending = useRef(false), composing = useRef(false)
36
+ const [busy, renderBusy] = useState(false), [failure, setFailure] = useState<string>(), [review, setReview] = useState<Review>()
36
37
  const [preview, setPreview] = useState<{ quote: VoicePreviewQuote, snapshot: VoiceSnapshot }>(), [cloning, setCloning] = useState(false)
37
38
  const owner = useRef({ active: true, generation: 0 }), request = useRef<AbortController>()
38
39
  useEffect(() => () => { owner.current.active = false; owner.current.generation++; request.current?.abort() }, [])
@@ -57,10 +58,25 @@ export function DocumentVoiceDialog({ stepId, onClose }: { stepId: string, onClo
57
58
  const rateInvalid = draft.rateInput !== undefined && normalizedRate !== undefined && normalizedRate.length > 0 && (!rateRange || !/^\d+(?:\.\d+)?$/.test(normalizedRate) || !Number.isFinite(rate) || rate! < rateRange.min || rate! > rateRange.max)
58
59
  const sourceType = draft.source === null ? 'inherit' : draft.source.type
59
60
  const current = () => owner.current.active && workbench.getState().authoring?.identity === identity
61
+ const unavailable = useRef(false)
62
+ unavailable.current = blocked || cloning || Boolean(preview)
63
+ const setBusy = (value: boolean) => { pending.current = value; renderBusy(value); workbench.refreshAuthoringClientControls() }
64
+ useEffect(() => workbench.production.registerDraftView({ identity, kind: 'voice', has: key => current() && key === stepId,
65
+ blocked: () => composing.current || pending.current || unavailable.current,
66
+ clear: () => {
67
+ const actual = workbench.getState().authoring, content = workbench.getDocument(identity)
68
+ if (!actual?.version || !content) return
69
+ owner.current.generation++; request.current?.abort(); request.current = undefined
70
+ const value: VoiceDraft = { version: actual.version, scope: { kind: 'step', stepId }, source: resolveDocumentStepVoice(content, stepId).value ?? null, replaceOverrides: false }
71
+ setDraft(value); setRestored(undefined); setStorageFailed(false); setReview(undefined); setFailure(undefined)
72
+ setEngineFilter(value.source?.type === 'tts' ? value.source.voice.engine : undefined); setLanguage(''); setQuery('')
73
+ } }), [workbench, identity, stepId])
74
+ useEffect(() => workbench.registerNavigationGuard(() => current() && (composing.current || pending.current || unavailable.current)), [workbench, identity])
75
+ useEffect(() => { workbench.refreshAuthoringClientControls() }, [workbench, blocked, busy, preview, cloning])
60
76
  const edit = (value: VoiceDraft) => {
61
77
  request.current?.abort(); owner.current.generation++
62
78
  setBusy(false); setFailure(undefined); setReview(undefined); setPreview(undefined); workbench.stopAuditions()
63
- setDraft(value); setStorageFailed(!keepVoiceDraft(workbench.client, identity, stepId, value))
79
+ setDraft(value); setStorageFailed(!workbench.production.keepVoiceDraft(identity, stepId, value))
64
80
  }
65
81
  const checkedDraft = (value: VoiceDraft): VoiceDraft => ({ ...value, version: workbench.getState().authoring!.version! })
66
82
  const checkScope = async (value = draft) => {
@@ -73,7 +89,7 @@ export function DocumentVoiceDialog({ stepId, onClose }: { stepId: string, onClo
73
89
  const source = workbench.getState().authoring, latest = workbench.getDocument(identity)
74
90
  if (!source?.version || !source.fingerprint || !latest || source.dirty || source.saving || source.error || source.restored || source.composing) throw new Error('voice-context-changed')
75
91
  const proposal = checkedDraft(value), impact = previewDocumentVoiceChange(latest, proposal.scope, proposal.source, { replaceOverrides: proposal.replaceOverrides })
76
- setDraft(proposal); setStorageFailed(!keepVoiceDraft(workbench.client, identity, stepId, proposal))
92
+ setDraft(proposal); setStorageFailed(!workbench.production.keepVoiceDraft(identity, stepId, proposal))
77
93
  const targets = documentVoiceStepIds(latest, proposal.scope).map(id => { const step = latest.steps[id]!, page = latest.sections[step.sectionId]!; return `${page.title} · ${t.step(latest.sectionOrder.indexOf(page.id) + 1, page.stepOrder.indexOf(id) + 1)}` })
78
94
  setReview({ draft: proposal, impact, scopeLabel: t.scopes[proposal.scope.kind], targets, expected: { identity, version: source.version, fingerprint: source.fingerprint } })
79
95
  } catch (error) { if (current() && generation === owner.current.generation) setFailure(voiceFailure(error, locale)) }
@@ -87,7 +103,7 @@ export function DocumentVoiceDialog({ stepId, onClose }: { stepId: string, onClo
87
103
  const saved = await workbench.production.applyVoice(confirmation.draft.scope, confirmation.draft.source, { replaceOverrides: confirmation.draft.replaceOverrides }, confirmation.expected)
88
104
  if (!current() || generation !== owner.current.generation) return
89
105
  if (!saved) throw new Error('voice-context-changed')
90
- if (!clearVoiceDraft(workbench.client, identity, stepId, confirmation.draft)) { setStorageFailed(true); setReview(undefined); return }
106
+ if (!workbench.production.clearVoiceDraft(identity, stepId, confirmation.draft)) { setStorageFailed(true); setReview(undefined); return }
91
107
  onClose()
92
108
  } catch (error) { if (current() && generation === owner.current.generation) { setReview(undefined); setFailure(voiceFailure(error, locale)) } }
93
109
  finally { if (current() && generation === owner.current.generation) setBusy(false) }
@@ -109,7 +125,7 @@ export function DocumentVoiceDialog({ stepId, onClose }: { stepId: string, onClo
109
125
  if (!document || !validTarget) return <PmDialog open label={t.settings} closeLabel={t.close} onClose={onClose}><PmNotice tone="warn">{p.draftChanged}</PmNotice></PmDialog>
110
126
  return <>
111
127
  <PmDialog open label={t.settings} closeLabel={t.close} onClose={onClose} footer={<><PmButton onClick={onClose}>{t.close}</PmButton><PmButton loading={busy} disabled={blocked || rateInvalid || draft.source?.type === 'tts' && !draft.source.voice.voice.trim() || draft.scope.kind === 'steps' && !draft.scope.stepIds.length} variant="primary" onClick={() => void checkScope()}>{t.check}</PmButton></>}>
112
- <div className="pmw-voice__form">
128
+ <div className="pmw-voice__form" onCompositionStartCapture={() => { composing.current = true; workbench.refreshAuthoringClientControls() }} onCompositionEndCapture={() => { composing.current = false; workbench.refreshAuthoringClientControls() }}>
113
129
  {restored && <PmNotice tone="accent">{t.draftRecovered}</PmNotice>}
114
130
  {storageFailed && <PmNotice tone="warn">{t.recoveryFailed}</PmNotice>}
115
131
  {failure && <PmNotice tone="danger">{failure}</PmNotice>}
@@ -4,7 +4,7 @@ import { randomUUID } from '@lincyaw/kernel'
4
4
  import { MediaClipEditor } from '../MediaClipEditor.tsx'
5
5
  import type { MediaClipDraft } from '../MediaClipEditor.tsx'
6
6
  import { useWorkbench, useWorkbenchState } from '../context.tsx'
7
- import { keepMediaDrafts, mediaDraftStorageFailed, readMediaDrafts } from '../media-drafts.ts'
7
+ import { mediaDraftStorageFailed, readMediaDrafts } from '../media-drafts.ts'
8
8
  import type { MediaDrafts } from '../media-drafts.ts'
9
9
  import { MEDIA_MESSAGES, mediaFailure } from '../media-messages.ts'
10
10
 
@@ -42,9 +42,23 @@ export function ProductionMediaClips({ identity, version, document, sectionId, s
42
42
  snapshot.current = draft; selected.current = key; latest.current = session
43
43
  const assets = Object.values(document.assets).filter(asset => asset.kind === 'audio').map(asset => ({ id: asset.id, label: asset.title || asset.location.split('/').at(-1) || asset.id }))
44
44
  const active = () => owner.current.active && workbench.getState().authoring?.identity === identity
45
+ const interacting = useRef(false), unavailable = useRef(false)
46
+ unavailable.current = disabled || Boolean(busy)
47
+ useEffect(() => workbench.production.registerDraftView({ identity, kind: 'media-clip', has: target => {
48
+ const [ownerStep, name] = JSON.parse(target) as [string, string]
49
+ return active() && ownerStep === stepId && Object.hasOwn(latest.current.entries, name)
50
+ }, blocked: () => interacting.current || Boolean(request.current) || unavailable.current,
51
+ clear: () => {
52
+ owner.current.revision++
53
+ const value = readMediaDrafts(workbench.client, identity, stepId)
54
+ latest.current = value; setSession(value); setStorageFailed(false); setFailure(undefined); setStatus(undefined)
55
+ blank.current = newDraft(workbench.getState().authoring?.version ?? version, stepId)
56
+ } }), [workbench, identity, stepId])
57
+ useEffect(() => workbench.registerNavigationGuard(() => active() && (interacting.current || Boolean(request.current))), [workbench, identity])
58
+ useEffect(() => { workbench.refreshAuthoringClientControls() }, [workbench, disabled, busy])
45
59
  const remember = (value: MediaDrafts) => {
46
60
  latest.current = value; setSession(value)
47
- setStorageFailed(!keepMediaDrafts(workbench.client, identity, stepId, value))
61
+ setStorageFailed(!workbench.production.keepMediaDrafts(identity, stepId, value))
48
62
  }
49
63
  const edit = (value: MediaClipDraft) => {
50
64
  owner.current.revision++; setFailure(undefined); setStatus(undefined)
@@ -138,6 +152,7 @@ export function ProductionMediaClips({ identity, version, document, sectionId, s
138
152
  return <MediaClipEditor locale={locale} assets={assets} clips={clips} selectedClipId={selectedClipId} draft={draft} inspection={inspectCurrent} stepDurationMs={stepDurationMs}
139
153
  disabled={disabled} canApply={Boolean(binding && stepDurationMs !== undefined)} loading={loading} busy={busy} pending={Boolean(ownDraft(session.entries, key))} review={Boolean(ownDraft(session.entries, key) && draft.version !== version)}
140
154
  failure={failure} storageFailed={storageFailed} status={status} retryImport={retryImport}
155
+ onInteraction={value => { if (value === interacting.current) return; interacting.current = value; workbench.refreshAuthoringClientControls() }}
141
156
  onEditStart={pause} onChange={edit} onImport={value => void importAudio(value)} onRetryImport={() => { if (file.current) void importAudio(file.current) }}
142
157
  onRead={() => { setFailure(undefined); setInspection(undefined); setReload(value => value + 1) }}
143
158
  onReview={() => { if (inspectCurrent && (!draft.baseClip || canonical)) edit({ ...draft, version, ...canonical ? { baseClip: structuredClone(canonical) } : {} }) }}
@@ -5,7 +5,7 @@ import type { WorkspaceClient } from './workspace-client.ts'
5
5
 
6
6
  export interface VoiceDraft { version: string, scope: DocumentVoiceScope, source: VoiceSource | null, replaceOverrides: boolean, rateInput?: string }
7
7
  export type VoiceDraftStorageStatus = 'available' | 'unavailable' | 'corrupt'
8
- interface StoredDraft { draft?: VoiceDraft, status: VoiceDraftStorageStatus, unreadable?: string }
8
+ interface StoredDraft { draft?: VoiceDraft, status: VoiceDraftStorageStatus, unreadable?: string, raw?: string | null }
9
9
  const drafts = new WeakMap<WorkspaceClient, Map<string, StoredDraft>>()
10
10
  const keyOf = (identity: string, stepId: string) => JSON.stringify([identity, stepId])
11
11
  const storageKey = (key: string) => `presmium.voice-draft.v2:${key}`
@@ -36,6 +36,7 @@ function load(client: WorkspaceClient, key: string): StoredDraft {
36
36
  known.set(key, entry)
37
37
  try {
38
38
  const raw = sessionStorage.getItem(storageKey(key))
39
+ entry.raw = raw
39
40
  if (raw !== null) {
40
41
  entry.unreadable = raw
41
42
  const value: unknown = JSON.parse(raw)
@@ -64,7 +65,9 @@ export function keepVoiceDraft(client: WorkspaceClient, identity: string, stepId
64
65
  entry.draft = structuredClone(value)
65
66
  try {
66
67
  if (entry.unreadable !== undefined) sessionStorage.setItem(`${storageKey(key)}:unreadable`, entry.unreadable)
67
- sessionStorage.setItem(storageKey(key), JSON.stringify(entry.draft))
68
+ const raw = JSON.stringify(entry.draft)
69
+ sessionStorage.setItem(storageKey(key), raw)
70
+ entry.raw = raw
68
71
  entry.status = 'available'; delete entry.unreadable
69
72
  return true
70
73
  } catch { entry.status = 'unavailable'; return false }
@@ -76,14 +79,35 @@ export function clearVoiceDraft(client: WorkspaceClient, identity: string, stepI
76
79
  if (expected && JSON.stringify(entry.draft) !== JSON.stringify(expected)) return false
77
80
  try {
78
81
  const raw = sessionStorage.getItem(storageKey(key))
79
- if (expected && raw !== null) {
80
- let persisted: unknown
81
- try { persisted = JSON.parse(raw) } catch { entry.status = 'corrupt'; entry.unreadable = raw; return false }
82
- if (!valid(persisted)) { entry.status = 'corrupt'; entry.unreadable = raw; return false }
83
- if (JSON.stringify(persisted) !== JSON.stringify(expected)) return false
84
- }
82
+ if (expected && (entry.unreadable !== undefined || raw !== entry.raw)) return false
85
83
  sessionStorage.removeItem(storageKey(key))
84
+ entry.raw = null
86
85
  delete entry.draft; delete entry.unreadable; entry.status = 'available'
87
86
  return true
88
87
  } catch { entry.status = 'unavailable'; return false }
89
88
  }
89
+
90
+ /** Enumerate this native bank, including offscreen forms; callers receive no second persisted copy. */
91
+ export function voiceDraftSnapshot(client: WorkspaceClient, identity: string): { entries: { stepId: string, value: VoiceDraft, persisted: boolean }[], partial: boolean } {
92
+ const keys = new Set([...store(client).keys()].filter(key => key.startsWith(`${JSON.stringify([identity]).slice(0, -1)},`)))
93
+ let partial = false
94
+ try {
95
+ const prefix = `presmium.voice-draft.v2:${JSON.stringify([identity]).slice(0, -1)},`
96
+ for (let index = 0; index < sessionStorage.length; index++) {
97
+ const key = sessionStorage.key(index)
98
+ if (key?.startsWith(prefix) && !key.endsWith(':unreadable')) keys.add(key.slice('presmium.voice-draft.v2:'.length))
99
+ }
100
+ } catch { partial = true }
101
+ const entries: { stepId: string, value: VoiceDraft, persisted: boolean }[] = []
102
+ for (const key of keys) {
103
+ let target: unknown
104
+ try { target = JSON.parse(key) } catch { partial = true; continue }
105
+ if (!Array.isArray(target) || target.length !== 2 || target[0] !== identity || typeof target[1] !== 'string') { partial = true; continue }
106
+ const entry = load(client, key)
107
+ let persisted = false
108
+ try { const raw = sessionStorage.getItem(storageKey(key)); persisted = entry.status === 'available' && raw === entry.raw; if (raw !== entry.raw) partial = true } catch { partial = true }
109
+ if (entry.status === 'corrupt' || entry.raw === undefined) partial = true
110
+ if (entry.draft) entries.push({ stepId: target[1], value: structuredClone(entry.draft), persisted })
111
+ }
112
+ return { entries, partial }
113
+ }