@lincyaw/workbench 0.2.0-rc.122 → 0.2.0-rc.123

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.
@@ -0,0 +1,190 @@
1
+ import { useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'
2
+ import type { ReactNode } from 'react'
3
+ import type { EmbedBlock, PresmiumDocument, ReferenceTarget } from '@lincyaw/kernel'
4
+ import { PmButton, PmDocMention, PmDocPeek, PmIcon, PmNotice, PmSkeleton } from '../components.tsx'
5
+ import { useTreeMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
6
+ import { ReadOnlyBlock } from '../document-editor/references.tsx'
7
+ import type { ReadOnlyBlocks } from '../document-editor/references.tsx'
8
+
9
+ /** A burst of saves to the document on the side is read once, after it settles. */
10
+ const RELOAD_DELAY = 300
11
+ /**
12
+ * A long document is drawn over several frames so that none holds the page for long: the first frame draws this
13
+ * many blocks; when drawing them (until the page is painted) was quick the next frame draws twice as many, when it
14
+ * was slow half as many.
15
+ */
16
+ const FIRST_BLOCKS = 60
17
+ const MOST_BLOCKS = 960
18
+ const LEAST_BLOCKS = 15
19
+ const QUICK_DRAW_MS = 12
20
+ const SLOW_DRAW_MS = 30
21
+
22
+ type Read = { state: 'loading' } | { state: 'failed' } | { state: 'ready', document: string, version: string, content: PresmiumDocument }
23
+ type Item = { kind: 'page', id: string, title: string } | { kind: 'block', id: string }
24
+
25
+ /** The pages and their top-level blocks in reading order: what the side draws, a few frames at a time. */
26
+ function itemsOf(content: PresmiumDocument): Item[] {
27
+ return content.sectionOrder.flatMap(id => {
28
+ const section = content.sections[id]
29
+ return section ? [{ kind: 'page' as const, id, title: section.title }, ...section.children.map(child => ({ kind: 'block' as const, id: child }))] : []
30
+ })
31
+ }
32
+
33
+ /** The top-level block that holds `block` (itself when it is one), where the side scrolls to. */
34
+ function topBlockOf(content: PresmiumDocument, block: string): string | undefined {
35
+ const parents = new Map<string, string>()
36
+ for (const item of Object.values(content.blocks)) {
37
+ const children = item.type === 'container' ? item.children : item.type === 'component' ? item.children ?? [] : []
38
+ for (const child of children) parents.set(child, item.id)
39
+ }
40
+ let current = block
41
+ for (let depth = 0; parents.has(current) && depth < 64; depth++) current = parents.get(current)!
42
+ return content.blocks[current] ? current : undefined
43
+ }
44
+
45
+ /**
46
+ * The document a reference leads to, read-only in the right pane beside the open one ("Open on the Side"): its
47
+ * breadcrumb, title, Open and Close, and its pages, scrolled to the page or block of the reference. References in it
48
+ * open their target here in its place; Esc closes it. It is read when it opens and again after its saves settle
49
+ * (`document` events), never while the open document is typed in; a newer target cancels the read in flight.
50
+ */
51
+ export function DocumentPeekPanel({ target }: { target: ReferenceTarget }) {
52
+ const workbench = useWorkbench()
53
+ const t = useTreeMessages()
54
+ const dir = useWorkbenchState(state => state.documents?.documents.find(doc => doc.id === target.document)?.dir ?? state.documentTree?.nodes[target.document]?.path)
55
+ const treeTitle = useWorkbenchState(state => state.documentTree?.nodes[target.document]?.title)
56
+ const trashed = useWorkbenchState(state => Boolean(state.documentTree?.trash.some(entry => entry.id === target.document)))
57
+ const treeKnown = useWorkbenchState(state => Boolean(state.documentTree))
58
+ const pathText = useWorkbenchState(state => state.documentTree && JSON.stringify(workbench.tree.ancestors(target.document)))
59
+ const path = useMemo<{ id: string, title: string }[]>(() => pathText ? JSON.parse(pathText) : [], [pathText])
60
+ // Titles of the references in it follow the tree.
61
+ const tree = useWorkbenchState(state => state.documentTree)
62
+ const [read, setRead] = useState<Read>({ state: 'loading' })
63
+ const [reload, setReload] = useState(0)
64
+ // The version on screen, and the latest one its `document` events announced.
65
+ const loaded = useRef<{ document?: string, version?: string }>({})
66
+ const announced = useRef<{ document?: string, version?: string }>({})
67
+ const reloadTimer = useRef<ReturnType<typeof setTimeout>>()
68
+ const reloadSoon = () => { clearTimeout(reloadTimer.current); reloadTimer.current = setTimeout(() => setReload(value => value + 1), RELOAD_DELAY) }
69
+ useEffect(() => () => clearTimeout(reloadTimer.current), [])
70
+ const frame = useRef<HTMLElement>(null)
71
+ const body = useRef<HTMLDivElement | null>(null)
72
+
73
+ useEffect(() => {
74
+ if (dir === undefined) return
75
+ const controller = new AbortController()
76
+ // The same document read again stays on screen until the new one is there; another one starts from loading.
77
+ setRead(current => current.state === 'ready' && current.document === target.document ? current : { state: 'loading' })
78
+ workbench.client.readDocument(dir, controller.signal).then(answer => {
79
+ if (controller.signal.aborted) return
80
+ loaded.current = { document: target.document, version: answer.version }
81
+ if (announced.current.document === target.document && announced.current.version !== answer.version) reloadSoon()
82
+ setRead({ state: 'ready', document: target.document, version: answer.version, content: answer.content })
83
+ }, () => { if (!controller.signal.aborted) setRead({ state: 'failed' }) })
84
+ return () => controller.abort()
85
+ }, [workbench, dir, target.document, reload])
86
+
87
+ useEffect(() => {
88
+ if (dir === undefined) return
89
+ const stop = workbench.client.subscribeDocument(dir, event => {
90
+ announced.current = { document: target.document, version: event.version }
91
+ // While the document is being read, the read compares when it arrives.
92
+ if (loaded.current.document !== target.document || event.version === loaded.current.version) return
93
+ reloadSoon()
94
+ })
95
+ return () => { clearTimeout(reloadTimer.current); stop() }
96
+ }, [workbench, dir, target.document])
97
+
98
+ // Focus moves into the side when it opens and back where it was when it closes; Esc closes it.
99
+ useEffect(() => {
100
+ const before = document.activeElement
101
+ frame.current?.focus({ preventScroll: true })
102
+ const escape = (event: KeyboardEvent) => {
103
+ if (event.key !== 'Escape' || event.defaultPrevented || event.isComposing) return
104
+ if (document.querySelector('[role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"]')) return
105
+ event.preventDefault()
106
+ workbench.tree.closePeek()
107
+ }
108
+ window.addEventListener('keydown', escape)
109
+ return () => {
110
+ window.removeEventListener('keydown', escape)
111
+ const focused = document.activeElement
112
+ if (before instanceof HTMLElement && before.isConnected && (!focused || focused === document.body || frame.current?.contains(focused))) before.focus({ preventScroll: true })
113
+ }
114
+ }, [workbench])
115
+
116
+ const content = read.state === 'ready' ? read.content : undefined
117
+ const items = useMemo(() => content ? itemsOf(content) : [], [content])
118
+ const targetBlock = useMemo(() => content && target.block ? topBlockOf(content, target.block) : undefined, [content, target.block])
119
+ const targetIndex = useMemo(() => {
120
+ if (targetBlock) return items.findIndex(item => item.kind === 'block' && item.id === targetBlock)
121
+ if (target.section) return items.findIndex(item => item.kind === 'page' && item.id === target.section)
122
+ // The whole document: it opens at its start, with nothing marked.
123
+ return -1
124
+ }, [items, targetBlock, target.section])
125
+
126
+ // Drawn a few frames at a time; a document read again keeps what is drawn.
127
+ const [shown, setShown] = useState(0)
128
+ const pace = useRef({ size: FIRST_BLOCKS, requested: 0 })
129
+ useEffect(() => { setShown(0); pace.current = { size: FIRST_BLOCKS, requested: 0 } }, [read.state === 'ready' ? read.document : undefined])
130
+ useEffect(() => {
131
+ // Effects run after the paint: the time since the request is what drawing the last blocks cost.
132
+ const current = pace.current
133
+ if (current.requested) {
134
+ const cost = performance.now() - current.requested
135
+ current.size = cost > SLOW_DRAW_MS ? Math.max(LEAST_BLOCKS, current.size / 2) : cost < QUICK_DRAW_MS ? Math.min(MOST_BLOCKS, current.size * 2) : current.size
136
+ current.requested = 0
137
+ }
138
+ if (shown >= items.length) return
139
+ const id = requestAnimationFrame(() => {
140
+ current.requested = performance.now()
141
+ setShown(drawn => Math.min(items.length, drawn + current.size))
142
+ })
143
+ return () => cancelAnimationFrame(id)
144
+ }, [shown, items.length])
145
+
146
+ // Scrolled to the reference's place once it is drawn, again for each new target, not for a document read again.
147
+ const scrolled = useRef('')
148
+ const targetKey = JSON.stringify([target.document, target.section ?? '', target.block ?? ''])
149
+ useLayoutEffect(() => {
150
+ if (!content || scrolled.current === targetKey || shown <= Math.max(0, targetIndex)) return
151
+ scrolled.current = targetKey
152
+ const scroller = body.current
153
+ const place = scroller?.querySelector<HTMLElement>('[data-peek-target]')
154
+ if (!scroller) return
155
+ scroller.scrollTop = place ? place.getBoundingClientRect().top - scroller.getBoundingClientRect().top + scroller.scrollTop - scroller.clientHeight / 8 : 0
156
+ }, [content, targetKey, targetIndex, shown])
157
+
158
+ const view = useMemo<ReadOnlyBlocks | undefined>(() => content && dir !== undefined ? {
159
+ blocks: content.blocks,
160
+ asset: id => content.assets[id] ? workbench.client.documentAssetURL(dir, id) : undefined,
161
+ componentLabel: title => t.syncedComponent(title || content.metadata.title),
162
+ title: reference => reference.section || reference.block ? undefined : workbench.tree.title(reference.document),
163
+ onReference: reference => workbench.tree.peek(reference),
164
+ embed: (block: EmbedBlock) => <p className="pmw-peek__synced"><PmIcon name="synced" /><span>{t.syncedFrom}</span>
165
+ <PmDocMention title={workbench.tree.title(block.source.document) ?? t.missingDocument} onActivate={() => workbench.tree.peek({ document: block.source.document, block: block.source.block })} /></p>,
166
+ // The tree is a dependency: the titles of references follow it.
167
+ } : undefined, [content, dir, workbench, t, tree])
168
+
169
+ const missing = treeKnown && dir === undefined && !trashed
170
+ const title = treeTitle ?? content?.metadata.title ?? (trashed ? workbench.getState().documentTree?.trash.find(entry => entry.id === target.document)?.title : undefined) ?? t.untitled
171
+ const notice: ReactNode = trashed ? <PmNotice tone="warn">{t.previewTrashed}</PmNotice>
172
+ : missing ? <PmNotice tone="warn">{t.previewMissing}</PmNotice> : undefined
173
+ const open = () => void workbench.tree.openPlace(target, { focus: 'body' })
174
+ let main: ReactNode
175
+ if (dir === undefined) main = null
176
+ else if (read.state === 'loading') main = <PmSkeleton shape="document" label={t.peekLoading} />
177
+ else if (read.state === 'failed') main = <PmNotice tone="danger" action={<PmButton small onClick={() => setReload(value => value + 1)}>{t.retry}</PmButton>}>{t.peekFailed}</PmNotice>
178
+ else if (!items.length) main = <p className="pmw-muted">{t.peekEmpty}</p>
179
+ else main = <div className="pmw-peek pm-document-editor__synced-content">{view && items.slice(0, shown).map((item, index) => item.kind === 'page'
180
+ ? <h3 key={`page:${item.id}`} className="pmw-peek__page" data-peek-target={index === targetIndex && !targetBlock || undefined}>{item.title || t.untitled}</h3>
181
+ : <div key={item.id} className="pmw-peek__block" data-peek-target={index === targetIndex && targetBlock !== undefined || undefined}><ReadOnlyBlock view={view} id={item.id} /></div>)}</div>
182
+ return (
183
+ <PmDocPeek ref={frame} label={t.peekLabel} path={path} title={title} closeLabel={t.close} onClose={() => workbench.tree.closePeek()}
184
+ onPath={id => workbench.tree.peek({ document: id })} busy={read.state === 'loading' || shown < items.length} notice={notice}
185
+ actions={!missing && !trashed && <PmButton small variant="primary" onClick={open}>{t.open}</PmButton>}
186
+ bodyRef={node => { body.current = node }}>
187
+ {main}
188
+ </PmDocPeek>
189
+ )
190
+ }
@@ -18,8 +18,9 @@ import { PageRenameDialog } from './PageRenameDialog.tsx'
18
18
  import { PageDeleteDialog } from './PageDeleteDialog.tsx'
19
19
  import { SourceDocumentPanel } from './SourceDocumentPanel.tsx'
20
20
  import { DocumentNarrationPanel } from './DocumentNarrationPanel.tsx'
21
+ import { DocumentPeekPanel } from './DocumentPeekPanel.tsx'
21
22
 
22
- export type DocumentAside = 'outline' | 'references' | 'comments' | 'history' | 'export' | 'narration'
23
+ export type DocumentAside = 'outline' | 'references' | 'comments' | 'history' | 'export' | 'narration' | 'peek'
23
24
  /** The right pane's tabs: the page outline, the references and the comments. */
24
25
  const RAIL_TABS: readonly DocumentAside[] = ['outline', 'references', 'comments']
25
26
  const isRail = (aside: DocumentAside | null): aside is 'outline' | 'references' | 'comments' => aside !== null && RAIL_TABS.includes(aside)
@@ -64,6 +65,14 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
64
65
  previousRoomy.current = roomy
65
66
  }, [roomy, container.measured])
66
67
  const navigation = isRail(aside)
68
+ // "Open on the Side" puts another document in the right pane; closing it brings back what the pane showed before.
69
+ const peek = useWorkbenchState(state => state.documentPeek)
70
+ const beforePeek = useRef<DocumentAside | null>(null)
71
+ useEffect(() => {
72
+ if (peek) setAside(current => { if (current !== 'peek') beforePeek.current = current; return 'peek' })
73
+ else setAside(current => current === 'peek' ? beforePeek.current : current)
74
+ }, [peek])
75
+ useEffect(() => { if (aside !== 'peek') workbench.tree.closePeek() }, [aside])
67
76
  const compilePresentation = async (ready?: () => void, forReading = false, signal?: AbortSignal, deadline?: number): Promise<void> => {
68
77
  if (preparing.current || workbench.getState().isPreparingPresentation) return
69
78
  preparing.current = true
@@ -232,7 +241,7 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
232
241
  <div className="pmw-document__body" role="region" aria-label={producing ? PRODUCTION_MESSAGES[workbench.getState().locale].title : presenting ? t.presentationPreview : reading ? t.readDocument : t.documentEditor}>
233
242
  <div className="pmw-document__main"><div className="pmw-document__source" hidden={presenting || producing || reading}><SourceDocumentPanel commentsPortal={commentsPortal} onCommentDraftRestore={() => setAside(current => current === 'comments' ? null : current)} onOpenComments={() => setAside('comments')} after={narrow ? <ReferencesSummary /> : undefined} /></div>{producing && <ProductionPanel actions={actions} active={active} closing={changingView} onClose={() => void exitPresent()} />}{presenting && <PreviewPanel presentation active={active} onPresentationAction={action => { if (action === 'refresh') void compilePresentation(); else void exitPresent() }} />}{reading && <PreviewPanel active={active} />}</div>
234
243
  {!presenting && !producing && !reading && aside && (
235
- <aside className="pmw-document__aside pm-ui-block-editor" aria-label={{ outline: tt.outline, references: tt.references, narration: t.documentNarration, comments: t.comments, export: t.exportPane, history: t.versionHistory }[aside]}>
244
+ <aside className="pmw-document__aside pm-ui-block-editor" aria-label={{ outline: tt.outline, references: tt.references, narration: t.documentNarration, comments: t.comments, export: t.exportPane, history: t.versionHistory, peek: tt.peekLabel }[aside]}>
236
245
  {isRail(aside) ? <section className="pmw-pane pmw-rail">
237
246
  <div className="pmw-rail__header">
238
247
  <PmTabs variant="dock" value={aside} label={tt.rail} tabs={[{ value: 'outline', label: tt.outline }, { value: 'references', label: tt.references }, { value: 'comments', label: t.comments }]} onValueChange={value => setAside(value as DocumentAside)} />
@@ -243,7 +252,7 @@ export function DocumentView({ active = true, framed = false, onBack, actions, h
243
252
  {aside === 'references' && <ReferencesPanel />}
244
253
  {aside === 'comments' && <div ref={setCommentsPortal} />}
245
254
  </div>
246
- </section> : aside === 'narration' ? <DocumentNarrationPanel onClose={() => setAside(null)} /> : aside === 'export' ? <ExportPanel documentOnly onClose={() => setAside(null)} /> : <HistoryPanel onClose={() => setAside(null)} revisionAction={historyRevisionAction} />}
255
+ </section> : aside === 'peek' ? peek && <DocumentPeekPanel target={peek} /> : aside === 'narration' ? <DocumentNarrationPanel onClose={() => setAside(null)} /> : aside === 'export' ? <ExportPanel documentOnly onClose={() => setAside(null)} /> : <HistoryPanel onClose={() => setAside(null)} revisionAction={historyRevisionAction} />}
247
256
  </aside>
248
257
  )}
249
258
  </div>
@@ -14,7 +14,7 @@ export function DocumentVoiceField({ stepId, disabled = false, onGenerate }: { s
14
14
  const locale = useWorkbenchState(state => state.locale)
15
15
  const blocked = useWorkbenchState(state => Boolean(state.authoring?.loading || state.authoring?.composing) || isAgentChanging(state))
16
16
  const [open, setOpen] = useState(false)
17
- const inheritedFrom = useInheritedFrom()
17
+ const inheritedFrom = useInheritedFrom('production.defaults.voiceSource')
18
18
  useEffect(() => { setOpen(false) }, [source?.identity, stepId])
19
19
  const document = source?.content, step = document?.steps[stepId], p = PRODUCTION_MESSAGES[locale]
20
20
  if (!document || !step || !source?.identity) return null
@@ -24,7 +24,7 @@ export function DocumentVoiceField({ stepId, disabled = false, onGenerate }: { s
24
24
  : voice.value?.type === 'none' ? p.none
25
25
  : voice.value?.type === 'recording' ? recording?.title || p.recording : p.unset
26
26
  return <>
27
- <PmField group label={p.voice} hint={voice.inheritedFrom === 'document' && !document.production.defaults.voiceSource && source.inherited?.production?.defaults?.voiceSource ? inheritedFrom : p.inherited[voice.inheritedFrom]}>
27
+ <PmField group label={p.voice} hint={voice.inheritedFrom === 'document' && !document.production.defaults.voiceSource && source.inherited?.production?.defaults?.voiceSource && inheritedFrom || p.inherited[voice.inheritedFrom]}>
28
28
  <span>{label}</span>
29
29
  <div className="pmw-voice__actions">
30
30
  <PmButton small icon="audio" disabled={disabled || blocked} onClick={() => { workbench.pauseDocumentStep(step.sectionId, stepId); workbench.stopAuditions(); setOpen(true) }}>{p.choose}</PmButton>
@@ -0,0 +1,67 @@
1
+ import { useEffect, useRef, useState } from 'react'
2
+ import { DOCUMENT_MATERIALS_MAX_BYTES, DOCUMENT_MATERIALS_MAX_FILES } from '@lincyaw/kernel'
3
+ import { PmButton, PmDialog, PmNotice, PmTextarea } from '../components.tsx'
4
+ import { useMessages, useTreeMessages, useWorkbench } from '../context.tsx'
5
+ import { WorkspaceServerError } from '../workspace-client.ts'
6
+
7
+ const MEBIBYTES = DOCUMENT_MATERIALS_MAX_BYTES / (1 << 20)
8
+ const ACCEPTED = '.pdf,.md,.markdown,.txt,.docx,.doc,.pptx,.ppt,.key,.odt,.odp,.rtf,.html,.htm,.csv,.json,.tex,.bib,image/*'
9
+
10
+ /**
11
+ * Write from Source Material: the author chooses files and may say what they want; the workbench creates the document,
12
+ * keeps the files in its folder, opens it and hands the AI the request.
13
+ */
14
+ export function MaterialsDialog({ onClose }: { onClose(): void }) {
15
+ const t = useMessages()
16
+ const tt = useTreeMessages()
17
+ const workbench = useWorkbench()
18
+ const [files, setFiles] = useState<File[]>([])
19
+ const [note, setNote] = useState('')
20
+ const [working, setWorking] = useState(false)
21
+ const [failure, setFailure] = useState<string>()
22
+ const input = useRef<HTMLInputElement>(null)
23
+ const controller = useRef<AbortController>()
24
+ useEffect(() => () => controller.current?.abort(), [])
25
+ const select = (list: FileList | null) => {
26
+ const selected = [...list ?? []]
27
+ if (selected.length > DOCUMENT_MATERIALS_MAX_FILES || selected.reduce((sum, file) => sum + file.size, 0) > DOCUMENT_MATERIALS_MAX_BYTES) {
28
+ setFailure(tt.materialsLimit(DOCUMENT_MATERIALS_MAX_FILES, MEBIBYTES)); setFiles([])
29
+ } else { setFiles(selected); setFailure(undefined) }
30
+ }
31
+ const submit = async () => {
32
+ if (working || !files.length) return
33
+ const pending = controller.current = new AbortController()
34
+ setWorking(true); setFailure(undefined)
35
+ try {
36
+ const { asked } = await workbench.writeFromMaterials(files, note, pending.signal)
37
+ onClose()
38
+ workbench.tree.toast(asked ? tt.materialsSent : tt.materialsNotSent)
39
+ } catch (error) {
40
+ if (pending.signal.aborted) return
41
+ setFailure(error instanceof WorkspaceServerError && error.status === 413 ? tt.materialsLimit(DOCUMENT_MATERIALS_MAX_FILES, MEBIBYTES) : tt.materialsFailed)
42
+ setWorking(false)
43
+ }
44
+ }
45
+ return (
46
+ <PmDialog open label={tt.fromMaterials} closeLabel={t.close} name="pmw-operation" busy={working} onClose={onClose}>
47
+ <form className="pmw-operation" onSubmit={(event) => { event.preventDefault(); void submit() }}>
48
+ <p>{tt.materialsDescription}</p>
49
+ <p className="pmw-muted">{tt.materialsLimits(DOCUMENT_MATERIALS_MAX_FILES, MEBIBYTES)}</p>
50
+ <input ref={input} type="file" multiple hidden accept={ACCEPTED} onChange={(event) => { select(event.currentTarget.files); event.currentTarget.value = '' }} />
51
+ <div className="pmw-operation__actions">
52
+ <PmButton icon="upload" disabled={working} onClick={() => input.current?.click()}>{tt.materialsChoose}</PmButton>
53
+ </div>
54
+ {files.length > 0 && <>
55
+ <p>{tt.materialsSelected(files.length)}</p>
56
+ <ul className="pmw-materials__files">{files.map((file, index) => <li key={`${file.name}-${index}`}>{file.name}</li>)}</ul>
57
+ </>}
58
+ <PmTextarea label={tt.materialsNote} placeholder={tt.materialsNotePlaceholder} rows={3} value={note} disabled={working} maxLength={2000} onChange={event => setNote(event.target.value)} />
59
+ {failure && <PmNotice tone="danger">{failure}</PmNotice>}
60
+ <div className="pmw-operation__actions">
61
+ <PmButton disabled={working} onClick={onClose}>{t.cancel}</PmButton>
62
+ <PmButton type="submit" variant="primary" loading={working} disabled={!files.length}>{tt.materialsSubmit}</PmButton>
63
+ </div>
64
+ </form>
65
+ </PmDialog>
66
+ )
67
+ }
@@ -13,8 +13,8 @@ export function ProductionCaptionSize({ identity, document, disabled, onChanged
13
13
  // `document` has its inherited settings filled in; the source says whether the size is the document's own.
14
14
  const own = useWorkbenchState(state => state.authoring?.identity === identity ? state.authoring.content?.production.captions?.scale !== undefined : true)
15
15
  const inherits = useWorkbenchState(state => state.authoring?.identity === identity && state.authoring.inherited?.production?.captions?.scale !== undefined)
16
- const inheritedFrom = useInheritedFrom(), tt = useTreeMessages()
17
- return <PmField label={p.captionSize} group hint={own ? p.captionSizeHint : `${inheritedFrom} · ${p.captionSizeHint}`}>
16
+ const inheritedFrom = useInheritedFrom('production.captions'), tt = useTreeMessages()
17
+ return <PmField label={p.captionSize} group hint={own || !inheritedFrom ? p.captionSizeHint : `${inheritedFrom} · ${p.captionSizeHint}`}>
18
18
  <div className="pm-ui-range-row">
19
19
  <PmRange label={p.captionSize} value={percent} min={Math.round(CAPTION_SCALE_MIN * 100)} max={Math.round(CAPTION_SCALE_MAX * 100)} step={10} disabled={disabled} valueText={value => `${Math.round(value)}%`}
20
20
  onPreviewChange={setPreview} onValueCommit={value => { workbench.production.setCaptionScale(value / 100, identity); onChanged() }} />
@@ -5,6 +5,7 @@ import { useMessages, useTreeMessages, useWorkbench, useWorkbenchState } from '.
5
5
  import { IMPORT_MESSAGES } from '../import-messages.ts'
6
6
  import { timeAgo } from '../messages.ts'
7
7
  import { DocumentImportDialog } from './DocumentImportDialog.tsx'
8
+ import { MaterialsDialog } from './MaterialsDialog.tsx'
8
9
  import { SearchDialog } from './WorkspaceSidebar.tsx'
9
10
 
10
11
  /**
@@ -21,16 +22,23 @@ export function WorkspaceHome({ actions }: { actions?: ReactNode }) {
21
22
  const locale = useWorkbenchState(state => state.locale)
22
23
  const busy = useWorkbenchState(state => Boolean(state.isDocumentTreeBusy))
23
24
  const failure = useWorkbenchState(state => state.documentsFailure)
25
+ const attention = useWorkbenchState(state => state.workspaceAttention)
26
+ const canAskAgent = useWorkbenchState(state => Boolean(state.canAskAgent))
27
+ const needsModel = useWorkbenchState(state => state.agentReadiness === 'missing')
24
28
  const importMessages = IMPORT_MESSAGES[locale]
25
29
  const [importing, setImporting] = useState(false)
26
30
  const [searching, setSearching] = useState(false)
27
31
  const [upgrading, setUpgrading] = useState(false)
32
+ const [writing, setWriting] = useState(false)
28
33
  const readOnly = workbench.client.capabilities?.readOnly === true
29
34
  const canImport = Boolean(answer?.git && !answer.single && workbench.client.importDocuments && !readOnly)
35
+ // Only the AI writes from source material: without a conversation there is no card, without a model it says so.
36
+ const canWrite = Boolean(canAskAgent && !answer?.single && workbench.client.addDocumentMaterials && workbench.tree.available && !readOnly)
30
37
  const count = Object.keys(tree.nodes).length
31
38
  const issues = Object.values(tree.nodes).filter(node => node.issues?.length)
32
39
  const pending = answer?.migration?.documents.length ?? 0
33
40
  const shown = recent.filter(entry => tree.nodes[entry.id]).slice(0, 8)
41
+ const { references: brokenReferences, embeds: brokenSynced } = attention ?? {}
34
42
  const create = () => void workbench.tree.create(null)
35
43
  const upgrade = async () => {
36
44
  setUpgrading(true)
@@ -57,12 +65,19 @@ export function WorkspaceHome({ actions }: { actions?: ReactNode }) {
57
65
  <button type="button" className="pm-ui-card__cover" onClick={() => setImporting(true)}>{importMessages.title}</button>
58
66
  <p className="pm-ui-card__hint">{tt.importHint}</p>
59
67
  </PmCard></li>}
68
+ {canWrite && <li><PmCard variant="interactive">
69
+ <span className="pm-ui-card__icon"><PmIcon name="sparkle" /></span>
70
+ <button type="button" className="pm-ui-card__cover" disabled={busy} onClick={() => needsModel ? workbench.openAgentSetup() : setWriting(true)}>{tt.fromMaterials}</button>
71
+ <p className="pm-ui-card__hint">{needsModel ? tt.fromMaterialsNeedsModel : tt.fromMaterialsHint}</p>
72
+ </PmCard></li>}
60
73
  </ul>}
61
- {(pending > 0 || issues.length > 0) && <>
62
- <h2 className="pmw-home__heading">{tt.needsAttention}</h2>
74
+ {(pending > 0 || issues.length > 0 || brokenReferences || brokenSynced) && <>
75
+ <div className="pmw-home__heading-row"><h2 className="pmw-home__heading">{tt.needsAttention}</h2></div>
63
76
  <div className="pmw-workspace-home__attention">
64
77
  {pending > 0 && workbench.client.migrateWorkspace && <PmNotice tone="warn" action={<PmButton small loading={upgrading} onClick={() => void upgrade()}>{tt.upgrade}</PmButton>}>{tt.upgradePending(pending)}</PmNotice>}
65
78
  {issues.length > 0 && <PmNotice tone="warn" action={<PmButton small onClick={() => void workbench.tree.openPlace({ document: issues[0]!.id })}>{tt.show}</PmButton>}>{tt.treeIssues(issues.length)}</PmNotice>}
79
+ {brokenReferences && <PmNotice tone="warn" action={<PmButton small onClick={() => void workbench.tree.openPlace(brokenReferences.first)}>{tt.show}</PmButton>}>{tt.brokenReferences(brokenReferences.places, brokenReferences.documents)}</PmNotice>}
80
+ {brokenSynced && <PmNotice tone="warn" action={<PmButton small onClick={() => void workbench.tree.openPlace(brokenSynced.first)}>{tt.show}</PmButton>}>{tt.brokenSynced(brokenSynced.places, brokenSynced.documents)}</PmNotice>}
66
81
  </div>
67
82
  </>}
68
83
  <div className="pmw-home__heading-row">
@@ -87,6 +102,7 @@ export function WorkspaceHome({ actions }: { actions?: ReactNode }) {
87
102
  {importing && <DocumentImportDialog onClose={() => setImporting(false)} onImported={result => {
88
103
  setImporting(false); workbench.tree.toast(importMessages.done(result.documents.length, result.unresolved, result.warnings)); void workbench.tree.load()
89
104
  }} />}
105
+ {writing && <MaterialsDialog onClose={() => setWriting(false)} />}
90
106
  {searching && <SearchDialog onClose={() => setSearching(false)} onOpen={(id, section, block) => { setSearching(false); void workbench.tree.openPlace({ document: id, ...section ? { section } : {}, ...block ? { block } : {} }) }} />}
91
107
  </section>
92
108
  )
@@ -244,9 +244,9 @@ function TrashDialog({ entries, onClose }: { entries: TrashEntry[], onClose(): v
244
244
  <PmIcon name="document" />
245
245
  <span className="pmw-trash__text">
246
246
  <span className="pmw-trash__title">{entry.title}</span>
247
- <span className="pmw-trash__meta">{[t.deletedAt(timeAgo(entry.deletedAt, locale)), entry.children.length ? t.childCount(entry.children.length) : ''].filter(Boolean).join(' · ')}</span>
247
+ <span className="pmw-trash__meta">{[t.deletedAt(timeAgo(entry.deletedAt, locale)), entry.children.length ? t.childCount(entry.children.length) : '', entry.parentTrashed ? t.parentTrashed : ''].filter(Boolean).join(' · ')}</span>
248
248
  </span>
249
- <PmButton small icon="restore" disabled={busy || readOnly} onClick={async () => { await workbench.tree.restore(entry.id); workbench.tree.toast(t.restored(entry.title)) }}>{t.restore}</PmButton>
249
+ <PmButton small icon="restore" disabled={busy || readOnly} onClick={() => void workbench.tree.restore(entry.id)}>{t.restore}</PmButton>
250
250
  <PmButton small variant="text" disabled={busy || readOnly} onClick={() => setPurging(entry)}>{t.deletePermanently}</PmButton>
251
251
  </li>
252
252
  ))}</ul>}
package/src/styles.css CHANGED
@@ -160,6 +160,25 @@
160
160
  gap: var(--pm-space-2);
161
161
  }
162
162
 
163
+ /* The files chosen as source material: a short list that scrolls when long, each name on one line. */
164
+ .pmw-materials__files {
165
+ display: grid;
166
+ gap: var(--pm-space-1);
167
+ max-height: var(--pm-materials-list-max-height);
168
+ margin: 0;
169
+ padding: 0;
170
+ overflow: auto;
171
+ color: var(--pm-color-muted);
172
+ font-size: var(--pm-text-sm);
173
+ list-style: none;
174
+ }
175
+
176
+ .pmw-materials__files li {
177
+ overflow: hidden;
178
+ text-overflow: ellipsis;
179
+ white-space: nowrap;
180
+ }
181
+
163
182
  /* The open document, as an editor shows it: the command bar, the panes, the page on its canvas, the status bar. */
164
183
 
165
184
  .pmw-document {
@@ -63,6 +63,8 @@ export const DOCUMENT_TREE_MESSAGES = {
63
63
  trashHint: '移到回收站的文稿连同其子文稿保存在这里,可以还原。',
64
64
  restore: '还原',
65
65
  restored: (title: string) => `已还原“${title}”`,
66
+ restoredToTop: (title: string, parent: 'trashed' | 'missing') => parent === 'trashed' ? `已还原“${title}”。它的上级文稿在回收站中,所以放在了顶层。` : `已还原“${title}”。它原来的上级文稿已不存在,所以放在了顶层。`,
67
+ parentTrashed: '上级文稿也在回收站中,单独还原时放在顶层',
66
68
  deletePermanently: '永久删除…',
67
69
  deletePermanentlyTitle: '永久删除',
68
70
  deleteConfirm: (title: string) => `永久删除“${title}”及其子文稿?此操作无法撤消。`,
@@ -102,6 +104,11 @@ export const DOCUMENT_TREE_MESSAGES = {
102
104
  previewMissing: '这份文稿已删除。',
103
105
  previewTrashed: '这份文稿在回收站中。',
104
106
  open: '打开',
107
+ openOnSide: '在右侧打开',
108
+ peekLabel: '右侧的文稿',
109
+ peekLoading: '正在加载文稿…',
110
+ peekFailed: '无法加载这份文稿。',
111
+ peekEmpty: '这份文稿还没有内容。',
105
112
  missingDocument: '文稿已删除',
106
113
  linkHeading: (query: string) => query ? `链接到文稿 · 输入“${query}”` : '链接到文稿',
107
114
  createChildAndLink: (query: string) => `新建子文稿“${query}”并链接`,
@@ -135,7 +142,23 @@ export const DOCUMENT_TREE_MESSAGES = {
135
142
  copyFailed: '无法复制链接,请重试。',
136
143
  blankDocument: '空白文稿',
137
144
  blankDocumentHint: '从标题开始写,随时添加页面和动画',
138
- importHint: '用已有的文件生成文稿',
145
+ importHint: '把已有的文件转成文稿',
146
+ fromMaterials: '从来源材料写作',
147
+ fromMaterialsHint: '选择 PDF、Word、PowerPoint、图片或文本文件,由 AI 写成一份新文稿',
148
+ fromMaterialsNeedsModel: 'AI 助手还没有模型。设置模型之后,AI 才能根据来源材料写文稿。',
149
+ materialsDescription: 'Presmium 新建一份文稿,把来源材料保存在它的文件夹中,再发送给 AI,由它根据材料写出标题、页面与正文。写好之前可以随时在对话中补充要求。',
150
+ materialsChoose: '选择文件',
151
+ materialsSelected: (count: number) => `已选择 ${count} 个文件`,
152
+ materialsLimits: (files: number, mebibytes: number) => `最多 ${files} 个文件,合计 ${mebibytes} MiB。`,
153
+ materialsNote: '想要怎样的文稿(可选)',
154
+ materialsNotePlaceholder: '例如:给研究生的 20 分钟报告,每页一个要点',
155
+ materialsSubmit: '新建并发送给 AI',
156
+ materialsSent: '已新建文稿,AI 正在根据来源材料写作。',
157
+ materialsNotSent: '已新建文稿并保存了来源材料,但请求没有发给 AI。',
158
+ materialsFailed: '无法保存来源材料。新建的文稿已移到回收站,请重试。',
159
+ materialsLimit: (files: number, mebibytes: number) => `来源材料超过 ${files} 个文件或合计 ${mebibytes} MiB 的限制,请减少文件后重试。`,
160
+ brokenReferences: (places: number, documents: number) => `${places} 处引用的目标已删除或在回收站中${documents > 1 ? `,分布在 ${documents} 份文稿中` : ''}。`,
161
+ brokenSynced: (places: number, documents: number) => `${places} 个同步块的原内容已删除或在回收站中${documents > 1 ? `,分布在 ${documents} 份文稿中` : ''}。`,
139
162
  needsAttention: '需要处理',
140
163
  treeIssues: (count: number) => `${count} 份文稿的上级无效,暂时显示在顶层。请把它们移到正确的位置。`,
141
164
  show: '查看',
@@ -210,6 +233,8 @@ export const DOCUMENT_TREE_MESSAGES = {
210
233
  trashHint: 'Documents moved to the trash stay here with their child documents until you restore or delete them.',
211
234
  restore: 'Restore',
212
235
  restored: (title: string) => `Restored “${title}”.`,
236
+ restoredToTop: (title: string, parent: 'trashed' | 'missing') => parent === 'trashed' ? `Restored “${title}” to the top level because its parent document is in the trash.` : `Restored “${title}” to the top level because its parent document no longer exists.`,
237
+ parentTrashed: 'Its parent document is also in the trash; restored alone, it goes to the top level',
213
238
  deletePermanently: 'Delete Permanently…',
214
239
  deletePermanentlyTitle: 'Delete Permanently',
215
240
  deleteConfirm: (title: string) => `Delete “${title}” and its child documents permanently? You can’t undo this.`,
@@ -249,6 +274,11 @@ export const DOCUMENT_TREE_MESSAGES = {
249
274
  previewMissing: 'This document was deleted.',
250
275
  previewTrashed: 'This document is in the trash.',
251
276
  open: 'Open',
277
+ openOnSide: 'Open on the Side',
278
+ peekLabel: 'Document on the Side',
279
+ peekLoading: 'Loading the document…',
280
+ peekFailed: 'Couldn’t load this document.',
281
+ peekEmpty: 'This document has no content yet.',
252
282
  missingDocument: 'Deleted document',
253
283
  linkHeading: (query: string) => query ? `Link to Document · “${query}”` : 'Link to Document',
254
284
  createChildAndLink: (query: string) => `New Child Document “${query}” and Link`,
@@ -282,7 +312,23 @@ export const DOCUMENT_TREE_MESSAGES = {
282
312
  copyFailed: 'Couldn’t copy the link. Try again.',
283
313
  blankDocument: 'Blank Document',
284
314
  blankDocumentHint: 'Start from a title and add pages and animations as you go',
285
- importHint: 'Make documents from files you already have',
315
+ importHint: 'Turn files you already have into documents',
316
+ fromMaterials: 'Write from Source Material',
317
+ fromMaterialsHint: 'Choose PDF, Word, PowerPoint, picture, or text files, and the AI writes a new document from them',
318
+ fromMaterialsNeedsModel: 'The AI Assistant has no model yet. Set one up, and the AI can write documents from source material.',
319
+ materialsDescription: 'Presmium creates a new document, keeps your source material in its folder, and has the AI write the title, pages, and text from it. You can add to the request in the chat at any time.',
320
+ materialsChoose: 'Choose Files',
321
+ materialsSelected: (count: number) => `${count} ${count === 1 ? 'file' : 'files'} selected`,
322
+ materialsLimits: (files: number, mebibytes: number) => `Up to ${files} files and ${mebibytes} MiB in total.`,
323
+ materialsNote: 'What you want (optional)',
324
+ materialsNotePlaceholder: 'For example: a 20-minute talk for graduate students, one point per page',
325
+ materialsSubmit: 'Create and Send to AI',
326
+ materialsSent: 'Created the document. The AI is writing it from your source material.',
327
+ materialsNotSent: 'Created the document and kept the source material, but the request didn’t reach the AI.',
328
+ materialsFailed: 'Couldn’t save the source material. The new document was moved to the trash. Try again.',
329
+ materialsLimit: (files: number, mebibytes: number) => `The source material is over the limit of ${files} files or ${mebibytes} MiB in total. Choose fewer files and try again.`,
330
+ brokenReferences: (places: number, documents: number) => `${places} ${places === 1 ? 'reference points' : 'references point'} to content that was deleted or is in the trash${documents > 1 ? `, in ${documents} documents` : ''}.`,
331
+ brokenSynced: (places: number, documents: number) => `${places} ${places === 1 ? 'synced block shows' : 'synced blocks show'} content that was deleted or is in the trash${documents > 1 ? `, in ${documents} documents` : ''}.`,
286
332
  needsAttention: 'Needs Attention',
287
333
  treeIssues: (count: number) => `${count} ${count === 1 ? 'document has an invalid parent and is' : 'documents have an invalid parent and are'} shown at the top level for now. Move them where they belong.`,
288
334
  show: 'Show',
@@ -75,8 +75,12 @@ export interface WorkbenchState {
75
75
  renamingDocument?: string
76
76
  /** Documents opened recently in this browser, the latest first. */
77
77
  recentDocuments?: import('./document-tree.ts').RecentDocument[]
78
+ /** What needs attention across the workspace: references and synced blocks whose target is gone or in the trash. */
79
+ workspaceAttention?: import('@lincyaw/kernel/contracts').WorkspaceAttention
78
80
  /** Changes when cached reference previews and synced block sources are forgotten. */
79
81
  documentLinksGeneration?: number
82
+ /** The document (and its page or block) shown read-only in the right pane beside the open one. */
83
+ documentPeek?: import('./document-tree.ts').DocumentPlace
80
84
  /** The one message at the bottom that says what an operation did. */
81
85
  toast?: import('./knowledge-components.tsx').ToastMessage
82
86
  /** The workspace's routes answer 404: `@lincyaw/dsh` is turned off on the plugins page. */
@@ -138,6 +142,10 @@ export interface WorkbenchState {
138
142
  isHistoryBusy: boolean
139
143
  isAsking: boolean
140
144
  askFailure?: string
145
+ /** A conversation's agent takes requests (`onAgentRequest`). */
146
+ canAskAgent?: boolean
147
+ /** Whether the agent has a model to run with, as the host says (`setAgentReadiness`); unknown until it does. */
148
+ agentReadiness?: 'ready' | 'missing' | 'unknown'
141
149
  /** What the document can be made into, and its builds and exports (the author's and the AI's). */
142
150
  jobs?: JobsAnswer
143
151
  jobsFailure?: string