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

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/src/knowledge.css CHANGED
@@ -195,6 +195,18 @@
195
195
  gap: var(--pm-space-px);
196
196
  }
197
197
 
198
+ .pmw-references__row {
199
+ display: flex;
200
+ align-items: center;
201
+ gap: var(--pm-space-1);
202
+ min-width: 0;
203
+ }
204
+
205
+ .pmw-references__link {
206
+ flex: 1;
207
+ min-width: 0;
208
+ }
209
+
198
210
  .pmw-references__link:not([aria-disabled]) {
199
211
  color: var(--pm-color-accent);
200
212
  }
@@ -318,3 +330,37 @@
318
330
  text-overflow: ellipsis;
319
331
  white-space: nowrap;
320
332
  }
333
+
334
+ /* The right pane with a document on the side is wider: the page beside it keeps the rest. */
335
+ .pmw-document[data-aside="peek"] .pmw-document__aside {
336
+ flex-basis: min(var(--pm-peek-width), 50%);
337
+ }
338
+
339
+ .pmw-document:not([data-roomy])[data-aside="peek"] .pmw-document__aside {
340
+ width: min(100%, var(--pm-peek-width));
341
+ }
342
+
343
+ .pmw-peek__page {
344
+ margin: var(--pm-space-6) 0 var(--pm-space-2);
345
+ font-size: var(--pm-text-lg);
346
+ }
347
+
348
+ .pmw-peek__page:first-child {
349
+ margin-top: 0;
350
+ }
351
+
352
+ .pmw-peek__block {
353
+ min-width: 0;
354
+ }
355
+
356
+ .pmw-peek__block > :first-child { margin-top: 0; }
357
+ .pmw-peek__block > :last-child { margin-bottom: 0; }
358
+ .pmw-peek__block + .pmw-peek__block { margin-top: var(--pm-space-3); }
359
+
360
+ .pmw-peek__synced {
361
+ display: flex;
362
+ flex-wrap: wrap;
363
+ align-items: center;
364
+ gap: var(--pm-space-1);
365
+ color: var(--pm-color-muted);
366
+ }
package/src/messages.ts CHANGED
@@ -365,6 +365,11 @@ const zh = {
365
365
  place.quote ? `\n原文:“${place.quote}”` : '',
366
366
  ].join('')).filter(Boolean),
367
367
  ].join('\n\n'),
368
+ materialsRequest: (files: string[], note: string) => [
369
+ '根据这份文稿文件夹中的来源材料写这份文稿:先读完材料,再定标题,写出页面与正文。',
370
+ `来源材料:\n${files.map(file => `- ${file}`).join('\n')}`,
371
+ note.trim() ? `作者的要求:${note.trim()}` : '',
372
+ ].filter(Boolean).join('\n\n'),
368
373
  animationRequest: (page: number, title: string, place: AgentInsertion) => {
369
374
  const at = `第 ${page} 页${title ? `“${title}”` : ''}`
370
375
  return place.end ? `在${at}的末尾加一个动画:` : place.after === undefined ? `在${at}的开头加一个动画:`
@@ -738,6 +743,11 @@ const en: WorkbenchMessages = {
738
743
  place.quote ? `\nText: “${place.quote}”` : '',
739
744
  ].join('')).filter(Boolean),
740
745
  ].join('\n\n'),
746
+ materialsRequest: (files: string[], note: string) => [
747
+ 'Write this document from the source material in its folder: read all of it first, then choose a title and write the pages and their text.',
748
+ `Source material:\n${files.map(file => `- ${file}`).join('\n')}`,
749
+ note.trim() ? `What the author wants: ${note.trim()}` : '',
750
+ ].filter(Boolean).join('\n\n'),
741
751
  animationRequest: (page: number, title: string, place: AgentInsertion) => {
742
752
  const at = `page ${page}${title ? `, “${title}”` : ''}`
743
753
  return place.end ? `Add an animation at the end of ${at}: ` : place.after === undefined ? `Add an animation at the start of ${at}: `
@@ -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() }} />
@@ -1,6 +1,6 @@
1
1
  import { useEffect, useState } from 'react'
2
2
  import type { DocumentCitation, DocumentLinks, OutgoingLink } from '@lincyaw/kernel/contracts'
3
- import { PmBacklinkItem, PmButton, PmIcon, PmNotice, PmSkeleton } from '../components.tsx'
3
+ import { PmBacklinkItem, PmButton, PmIcon, PmIconButton, PmNotice, PmSkeleton } from '../components.tsx'
4
4
  import { useTreeMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
5
5
 
6
6
  type Links = { state: 'loading' } | { state: 'failed' } | { state: 'unavailable' } | { state: 'ready', links: DocumentLinks }
@@ -35,6 +35,8 @@ function groupCitations(citations: readonly DocumentCitation[]): { document: str
35
35
  return [...groups.values()]
36
36
  }
37
37
 
38
+ const placeOf = (citation: DocumentCitation) => ({ document: citation.document, ...citation.section ? { section: citation.section } : {}, block: citation.block })
39
+
38
40
  /** Several references to one target are one row with their count. */
39
41
  function sameTargets(links: readonly OutgoingLink[]): { link: OutgoingLink, count: number }[] {
40
42
  const rows = new Map<string, { link: OutgoingLink, count: number }>()
@@ -51,12 +53,13 @@ function OutgoingItem({ link, count }: { link: OutgoingLink, count: number }) {
51
53
  const t = useTreeMessages()
52
54
  const workbench = useWorkbench()
53
55
  const gone = link.missing || link.trashed
54
- return <li>
56
+ return <li className="pmw-references__row">
55
57
  <button type="button" className="pm-ui-nav-item pmw-references__link" title={link.title} disabled={link.missing} aria-disabled={gone || undefined} onClick={() => void workbench.tree.openPlace(link.target)}>
56
58
  <PmIcon name={link.kind === 'embed' ? 'synced' : 'document'} />
57
59
  <span className="pmw-references__title">{link.title}</span>
58
60
  {gone ? <span className="pm-ui-nav-item__count">{link.missing ? t.missingTarget : t.trashedTarget}</span> : count > 1 && <span className="pm-ui-nav-item__count">{t.placeCount(count)}</span>}
59
61
  </button>
62
+ {!link.missing && <PmIconButton small icon="rail" label={t.openOnSide} onClick={() => workbench.tree.peek(link.target)} />}
60
63
  </li>
61
64
  }
62
65
 
@@ -84,7 +87,7 @@ function ReferencesView({ read }: { read: ReturnType<typeof useDocumentLinks> })
84
87
  <PmBacklinkItem title={group.title} count={group.citations.length > 1 ? t.placeCount(group.citations.length) : undefined} syncedLabel={t.syncedLabel}
85
88
  places={group.citations.map((citation, index) => ({ id: String(index), excerpt: citation.excerpt, synced: citation.kind === 'embed',
86
89
  meta: group.citations.length > 1 ? `${citation.kind === 'embed' ? t.syncedLabel : t.referenceLabel} · ${t.placeIndex(index + 1)}` : undefined }))}
87
- onActivate={id => { const citation = group.citations[Number(id)]!; void workbench.tree.openPlace({ document: citation.document, ...citation.section ? { section: citation.section } : {}, block: citation.block }) }} />
90
+ peekLabel={t.openOnSide} onActivate={id => void workbench.tree.openPlace(placeOf(group.citations[Number(id)]!))} onPeek={id => workbench.tree.peek(placeOf(group.citations[Number(id)]!))} />
88
91
  </li>
89
92
  ))}</ul> : <p className="pmw-muted">{t.noCitations}</p>}
90
93
  </section>
@@ -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 {