@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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lincyaw/workbench",
3
- "version": "0.2.0-rc.122",
3
+ "version": "0.2.0-rc.123",
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.121",
59
- "@lincyaw/kernel": "1.0.0-rc.121"
58
+ "@lincyaw/design": "1.0.0-rc.122",
59
+ "@lincyaw/kernel": "1.0.0-rc.122"
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.121"
70
+ "@lincyaw/compiler": "1.0.0-rc.122"
71
71
  }
72
72
  }
@@ -3,7 +3,7 @@ import type { PresmiumDocument } from '@lincyaw/kernel'
3
3
  import { PmButton, PmField, PmInput, PmSegmented } from './components.tsx'
4
4
  import type { Locale } from './messages.ts'
5
5
  import { stepNarrationStarts, stepTimingValue } from './step-production.ts'
6
- import type { ProductionSource, StepDurationDraft, StepDurationKey, StepTimingPatch } from './step-production.ts'
6
+ import type { ProductionSource, StepDurationDraft, StepDurationKey, StepTimingKey, StepTimingPatch } from './step-production.ts'
7
7
 
8
8
  const MESSAGES = {
9
9
  'zh-CN': {
@@ -34,6 +34,8 @@ interface DurationFieldProps {
34
34
  label: string
35
35
  value?: number
36
36
  source: ProductionSource
37
+ /** What `source` says, when it is more than the source's name (the ancestor a document default comes from). */
38
+ sourceLabel?: string
37
39
  locale: Locale
38
40
  readOnly?: boolean
39
41
  draft?: StepDurationDraft
@@ -46,7 +48,7 @@ interface DurationFieldProps {
46
48
  export interface StepDraftControl { composing(): boolean, clear(): void }
47
49
 
48
50
  /** Short author intent, never an estimated timestamp or a second playback clock. */
49
- function DurationField({ label, value, source, locale, readOnly, draft, onDraft, onChange, onComposition, controlKey, registerControl }: DurationFieldProps) {
51
+ function DurationField({ label, value, source, sourceLabel, locale, readOnly, draft, onDraft, onChange, onComposition, controlKey, registerControl }: DurationFieldProps) {
50
52
  const t = MESSAGES[locale], current = useRef({ onComposition, onChange, onDraft, value, registerControl })
51
53
  current.current = { onComposition, onChange, onDraft, value, registerControl }
52
54
  const [text, setText] = useState(draft?.text ?? (value === undefined ? '' : String(value))), [error, setError] = useState(draft?.error ?? false)
@@ -63,7 +65,7 @@ function DurationField({ label, value, source, locale, readOnly, draft, onDraft,
63
65
  setError(false); current.current.onDraft?.(undefined); current.current.onChange(number); return true
64
66
  }
65
67
  return <PmInput label={locale === 'zh-CN' ? `${label}(${t.unit})` : `${label} (${t.unit})`} width="number" inputMode="decimal" maxLength={256} value={text} placeholder={t.automatic}
66
- hint={draft && !error && !draft.review ? `${t.source[source]} · ${t.pending}` : t.source[source]} error={draft?.review ? t.review : error ? t.invalid : undefined} readOnly={readOnly}
68
+ hint={draft && !error && !draft.review ? `${sourceLabel ?? t.source[source]} · ${t.pending}` : sourceLabel ?? t.source[source]} error={draft?.review ? t.review : error ? t.invalid : undefined} readOnly={readOnly}
67
69
  onFocus={() => { focused.current = true }}
68
70
  onChange={event => {
69
71
  setText(event.target.value)
@@ -87,6 +89,8 @@ function DurationField({ label, value, source, locale, readOnly, draft, onDraft,
87
89
  export interface StepProductionEditorProps {
88
90
  document: PresmiumDocument
89
91
  stepId: string
92
+ /** For a document default the document inherits: where it comes from (“Inherited from …”). */
93
+ inheritedFrom?: Partial<Record<StepTimingKey, string>>
90
94
  locale: Locale
91
95
  readOnly?: boolean
92
96
  advanced?: boolean
@@ -102,12 +106,13 @@ export interface StepProductionEditorProps {
102
106
  }
103
107
 
104
108
  /** A reusable view of the canonical step production, including inherited and migrated settings. */
105
- export function StepProductionEditor({ document, stepId, locale, readOnly, advanced = true, onPause, onInteraction, onChange, drafts, onDraft, draftStorageFailure, onComposition, draftControlKey, registerDraftControl }: StepProductionEditorProps) {
109
+ export function StepProductionEditor({ document, stepId, inheritedFrom, locale, readOnly, advanced = true, onPause, onInteraction, onChange, drafts, onDraft, draftStorageFailure, onComposition, draftControlKey, registerDraftControl }: StepProductionEditorProps) {
106
110
  const t = MESSAGES[locale], [unifying, setUnifying] = useState(false)
107
111
  const start = stepTimingValue(document, stepId, 'narrationStart'), minimum = stepTimingValue(document, stepId, 'minimumHoldMs'), trailing = stepTimingValue(document, stepId, 'trailingPauseMs')
108
112
  const narrations = stepNarrationStarts(document, stepId), hasOverrides = narrations.some(value => value.overridden)
109
113
  const mixed = new Set(narrations.map(value => value.value ?? 'with-animation')).size > 1
110
114
  const hasStepTiming = [start, minimum, trailing].some(value => value.source === 'step')
115
+ const sourceOf = (key: StepTimingKey, source: ProductionSource) => source === 'document' && inheritedFrom?.[key] || t.source[source]
111
116
  const apply = (patch: StepTimingPatch) => { if (!readOnly) { onPause(); onChange(patch) } }
112
117
  const options = [{ value: 'with-animation', label: t.during, icon: 'timing-during' as const }, { value: 'after-animation', label: t.after, icon: 'timing-after' as const }]
113
118
  return <section className="pm-ui-step-production" contentEditable={false} data-step-production={stepId} aria-label={t.timing}
@@ -117,19 +122,19 @@ export function StepProductionEditor({ document, stepId, locale, readOnly, advan
117
122
  </div>}
118
123
  {!advanced ? <PmField group label={t.start} density="compact" hint={mixed ? t.mixed : undefined}>
119
124
  <div className="pm-ui-step-production__actions"><PmSegmented label={t.start} value={mixed ? '' : narrations[0]?.value ?? start.value ?? 'with-animation'} options={options} disabled={readOnly} onChange={value => apply({ narrationStart: value as 'with-animation' | 'after-animation' })} /></div>
120
- </PmField> : <><PmField group label={t.start} density="compact" hint={hasOverrides ? (mixed ? t.mixed : t.legacy) : t.source[start.source]}>
125
+ </PmField> : <><PmField group label={t.start} density="compact" hint={hasOverrides ? (mixed ? t.mixed : t.legacy) : sourceOf('narrationStart', start.source)}>
121
126
  {!hasOverrides && <div className="pm-ui-step-production__actions"><PmSegmented label={t.start} value={start.value ?? ''} options={options} disabled={readOnly} onChange={value => apply({ narrationStart: value as 'with-animation' | 'after-animation' })} /></div>}
122
127
  {hasOverrides && <>
123
- <div className="pm-ui-step-production__narration-settings">{narrations.map((entry, index) => <span key={entry.id} className="pm-ui-field__hint">{t.count(index + 1, entry.value === 'after-animation' ? t.after : t.during)}{entry.overridden ? ` · ${t.legacy}` : ` · ${t.source[start.source]}`}</span>)}</div>
128
+ <div className="pm-ui-step-production__narration-settings">{narrations.map((entry, index) => <span key={entry.id} className="pm-ui-field__hint">{t.count(index + 1, entry.value === 'after-animation' ? t.after : t.during)}{entry.overridden ? ` · ${t.legacy}` : ` · ${sourceOf('narrationStart', start.source)}`}</span>)}</div>
124
129
  <div className="pm-ui-step-production__actions"><PmButton small disabled={readOnly} onClick={() => setUnifying(value => !value)} aria-expanded={unifying}>{t.unify}</PmButton></div>
125
130
  {unifying && <><span className="pm-ui-field__hint">{t.unifyHint}</span><div className="pm-ui-step-production__actions"><PmSegmented label={t.unify} value="" options={options} disabled={readOnly} onChange={value => { apply({ narrationStart: value as 'with-animation' | 'after-animation' }); setUnifying(false) }} /></div></>}
126
131
  </>}
127
132
  </PmField>
128
133
  <div className="pm-ui-step-production__durations">
129
- <DurationField label={t.minimum} value={minimum.value} source={minimum.source} locale={locale} readOnly={readOnly} draft={drafts?.minimumHoldMs} onDraft={draft => onDraft?.('minimumHoldMs', draft)}
134
+ <DurationField label={t.minimum} value={minimum.value} source={minimum.source} sourceLabel={sourceOf('minimumHoldMs', minimum.source)} locale={locale} readOnly={readOnly} draft={drafts?.minimumHoldMs} onDraft={draft => onDraft?.('minimumHoldMs', draft)}
130
135
  controlKey={draftControlKey} registerControl={registerDraftControl && (control => registerDraftControl('minimumHoldMs', control))}
131
136
  onChange={value => apply({ minimumHoldMs: value })} onComposition={composing => onComposition?.('minimumHoldMs', composing)} />
132
- <DurationField label={t.trailing} value={trailing.value} source={trailing.source} locale={locale} readOnly={readOnly} draft={drafts?.trailingPauseMs} onDraft={draft => onDraft?.('trailingPauseMs', draft)}
137
+ <DurationField label={t.trailing} value={trailing.value} source={trailing.source} sourceLabel={sourceOf('trailingPauseMs', trailing.source)} locale={locale} readOnly={readOnly} draft={drafts?.trailingPauseMs} onDraft={draft => onDraft?.('trailingPauseMs', draft)}
133
138
  controlKey={draftControlKey} registerControl={registerDraftControl && (control => registerDraftControl('trailingPauseMs', control))}
134
139
  onChange={value => apply({ trailingPauseMs: value })} onComposition={composing => onComposition?.('trailingPauseMs', composing)} />
135
140
  </div></>}
@@ -14,7 +14,7 @@ export { PmButton, PmIcon, PmIconButton, PmTooltip } from './base-controls.tsx'
14
14
  export type { ButtonVariant, ControlDensity } from './base-controls.tsx'
15
15
  export { PmSortableList } from './sortable-list.tsx'
16
16
  export type { SortableListItem, SortableListLabels, SortableListProps } from './sortable-list.tsx'
17
- export { PmBacklinkItem, PmDocMention, PmDocPreviewCard, PmDocTree, PmMentionPicker, PmSyncedBlockFrame, PmToast } from './knowledge-components.tsx'
17
+ export { PmBacklinkItem, PmDocMention, PmDocPeek, PmDocPreviewCard, PmDocTree, PmMentionPicker, PmSyncedBlockFrame, PmToast } from './knowledge-components.tsx'
18
18
  export type { BacklinkPlace, DocPreview, DocTreeDrop, DocTreeLabels, DocTreeNode, DocTreeProps, MentionOption, ToastMessage } from './knowledge-components.tsx'
19
19
 
20
20
  const cls = (...names: (string | false | undefined | null)[]) => names.filter(Boolean).join(' ')
package/src/context.tsx CHANGED
@@ -34,13 +34,26 @@ export function useTreeMessages(): DocumentTreeMessages {
34
34
  return DOCUMENT_TREE_MESSAGES[useWorkbenchState(state => state.locale)]
35
35
  }
36
36
 
37
- /** Where the open document's inherited settings come from: its parent in the document tree, else the workspace defaults. */
38
- export function useInheritedFrom(): string {
37
+ /**
38
+ * Where the open document's inherited setting `key` (a `SettingOrigins` key, such as `production.captions`) comes
39
+ * from: the ancestor that sets it, else the workspace defaults; undefined when nothing above the document sets it. A
40
+ * host that does not say where settings come from names the parent.
41
+ */
42
+ export function useInheritedFrom(key: string): string | undefined {
39
43
  const t = useTreeMessages()
40
- const parent = useWorkbenchState(state => {
41
- const id = state.authoring?.content?.id
44
+ const origin = useWorkbenchState(state => {
42
45
  const nodes = state.documentTree?.nodes
43
- return id && nodes ? nodes[nodes[id]?.parent ?? '']?.title : undefined
46
+ const titleOf = (id: string) => nodes?.[id]?.title ?? state.documents?.documents.find(doc => doc.id === id)?.title
47
+ const from = state.authoring?.inheritedFrom
48
+ if (from) {
49
+ if (!Object.hasOwn(from, key)) return undefined
50
+ const id = from[key] as string | null
51
+ if (id === null) return null
52
+ const title = titleOf(id)
53
+ if (title !== undefined) return title
54
+ }
55
+ const id = state.authoring?.content?.id
56
+ return id && nodes ? nodes[nodes[id]?.parent ?? '']?.title ?? null : null
44
57
  })
45
- return parent ? t.inheritedFrom(parent) : t.inheritedWorkspace
58
+ return origin === undefined ? undefined : origin === null ? t.inheritedWorkspace : t.inheritedFrom(origin)
46
59
  }
@@ -2,7 +2,7 @@ import { useRef, useState } from 'react'
2
2
  import type { Narration, NarrationNode, PresmiumDocument } from '@lincyaw/kernel'
3
3
  import { randomUUID } from '@lincyaw/kernel'
4
4
  import { PmIconButton } from '../components.tsx'
5
- import { useWorkbench, useWorkbenchState } from '../context.tsx'
5
+ import { useInheritedFrom, useWorkbench, useWorkbenchState } from '../context.tsx'
6
6
  import { isAgentChanging } from '../workbench-state.ts'
7
7
  import { latestAgentActivity } from '../agent-activity.ts'
8
8
  import { NarrationEditor } from './NarrationEditor.tsx'
@@ -66,6 +66,7 @@ export function DocumentStepNarration({ blockId, sectionId, stepId, expanded, ad
66
66
  const timingStorageFailure = useWorkbenchState(state => state.documentTimingDraftStorageFailure)
67
67
  const activities = useWorkbenchState(state => state.agentActivities)
68
68
  const activity = latestAgentActivity(activities?.filter(value => value.document === source?.directory && value.targets.some(target => target.step === stepId)))
69
+ const inheritedStart = useInheritedFrom('production.defaults.narrationStart'), inheritedHold = useInheritedFrom('production.defaults.minimumHoldMs'), inheritedPause = useInheritedFrom('production.defaults.trailingPauseMs')
69
70
  if (workbench.client.capabilities?.narration === false) return null
70
71
  const document = source?.content, section = document?.sections[sectionId], step = document?.steps[stepId]
71
72
  if (!source?.identity || !document || !section || !step) return null
@@ -90,7 +91,8 @@ export function DocumentStepNarration({ blockId, sectionId, stepId, expanded, ad
90
91
  <NarrationField key={`narration:${source.identity}:${source.reset}:${stepId}`}
91
92
  identity={source.identity!} reset={source.reset} blockId={blockId} stepId={stepId}
92
93
  content={ids.map(id => ({ id, content: document.narrations[id]!.content }))} readOnly={readOnly} advanced={advanced} onPause={onPause} />
93
- <StepProductionEditor key={`timing:${source.identity}:${source.reset}:${stepId}`} document={effectiveOf(document, source.inherited)} stepId={stepId} locale={locale} readOnly={readOnly} advanced={advanced}
94
+ <StepProductionEditor key={`timing:${source.identity}:${source.reset}:${stepId}`} document={effectiveOf(document, source.inherited)} stepId={stepId}
95
+ inheritedFrom={{ ...document.production.defaults.narrationStart === undefined && inheritedStart ? { narrationStart: inheritedStart } : {}, ...document.production.defaults.minimumHoldMs === undefined && inheritedHold ? { minimumHoldMs: inheritedHold } : {}, ...document.production.defaults.trailingPauseMs === undefined && inheritedPause ? { trailingPauseMs: inheritedPause } : {} }} locale={locale} readOnly={readOnly} advanced={advanced}
94
96
  onPause={onPause} onInteraction={() => workbench.editing.interact()}
95
97
  onChange={patch => workbench.production.setStepTiming(stepId, patch, source.identity)}
96
98
  drafts={{ minimumHoldMs: workbench.production.timingDraft(stepId, 'minimumHoldMs', source.identity, source.reset), trailingPauseMs: workbench.production.timingDraft(stepId, 'trailingPauseMs', source.identity, source.reset) }}
@@ -3,7 +3,7 @@ import type { ReactNode } from 'react'
3
3
  import { SuggestionMenu as SuggestionMenuExtension } from '@blocknote/core/extensions'
4
4
  import { SuggestionMenuController } from '@blocknote/react'
5
5
  import type { DefaultReactSuggestionItem, SuggestionMenuProps } from '@blocknote/react'
6
- import type { DocumentBlock, InlineNode, PresmiumDocument, ReferenceTarget, RichTextNode } from '@lincyaw/kernel'
6
+ import type { DocumentBlock, EmbedBlock, InlineNode, PresmiumDocument, ReferenceTarget, RichTextNode } from '@lincyaw/kernel'
7
7
  import type { DocumentSearchHit, EmbedSource } from '@lincyaw/kernel/contracts'
8
8
  import { PmButton, PmDialog, PmDocMention, PmDocPreviewCard, PmIcon, PmMentionPicker, PmNotice, PmSearchList, PmSkeleton, PmSyncedBlockFrame } from '../components.tsx'
9
9
  import type { DocPreview, MentionOption } from '../components.tsx'
@@ -56,13 +56,26 @@ export const DocumentReference = memo(function DocumentReference({ document, sec
56
56
  const open = () => void workbench.tree.openPlace(target, { focus: 'body' })
57
57
  return (
58
58
  <PmDocPreviewCard label={t.previewLabel} loadingLabel={t.previewLoading} failedLabel={t.previewFailed} load={() => previewOf(t, workbench, target, fallback)}
59
- actions={<PmButton small variant="primary" onClick={open}>{t.open}</PmButton>}>
59
+ actions={<><PmButton small variant="primary" onClick={open}>{t.open}</PmButton><PmButton small icon="rail" onClick={() => workbench.tree.peek(target)}>{t.openOnSide}</PmButton></>}>
60
60
  <PmDocMention title={title} missing={missing} missingLabel={fallback || t.missingDocument} onActivate={open} />
61
61
  </PmDocPreviewCard>
62
62
  )
63
63
  })
64
64
 
65
- function inlineView(nodes: readonly InlineNode[], key = ''): ReactNode[] {
65
+ /**
66
+ * What read-only blocks are drawn from: the blocks by ID, their pictures' addresses, and what a reference does. With
67
+ * `onReference`, references are mentions that call it (the document on the side); otherwise plain mentions.
68
+ */
69
+ export interface ReadOnlyBlocks {
70
+ blocks?: Record<string, DocumentBlock>
71
+ asset(id: string): string | undefined
72
+ componentLabel(title: string): string
73
+ title?(target: ReferenceTarget): string | undefined
74
+ onReference?(target: ReferenceTarget): void
75
+ embed?(block: EmbedBlock): ReactNode
76
+ }
77
+
78
+ function inlineView(nodes: readonly InlineNode[], view: ReadOnlyBlocks, key = ''): ReactNode[] {
66
79
  return nodes.map((node, index) => {
67
80
  const id = `${key}${index}`
68
81
  if (node.type === 'text') {
@@ -78,40 +91,46 @@ function inlineView(nodes: readonly InlineNode[], key = ''): ReactNode[] {
78
91
  }
79
92
  if (node.type === 'break') return <br key={id} />
80
93
  if (node.type === 'math') return <code key={id}>{node.value}</code>
81
- if (node.type === 'link') return <span key={id} className="pm-document-editor__synced-link">{inlineView(node.children, `${id}-`)}</span>
82
- if (node.type === 'reference') return <span key={id} className="pm-ui-doc-mention"><PmIcon name="document" />{node.label ?? node.fallback}</span>
94
+ if (node.type === 'link') return <span key={id} className="pm-document-editor__synced-link">{inlineView(node.children, view, `${id}-`)}</span>
95
+ if (node.type === 'reference') {
96
+ const title = node.label ?? view.title?.(node.target) ?? node.fallback
97
+ const follow = view.onReference
98
+ if (follow) return <PmDocMention key={id} title={title} onActivate={() => follow(node.target)} />
99
+ return <span key={id} className="pm-ui-doc-mention"><PmIcon name="document" />{title}</span>
100
+ }
83
101
  return <span key={id}>{node.fallback}</span>
84
102
  })
85
103
  }
86
104
 
87
- function richView(nodes: readonly RichTextNode[]): ReactNode[] {
105
+ function richView(nodes: readonly RichTextNode[], view: ReadOnlyBlocks): ReactNode[] {
88
106
  return nodes.map(node => {
89
- if (node.type === 'paragraph') return <p key={node.id}>{inlineView(node.children)}</p>
90
- if (node.type === 'heading') { const Heading = `h${Math.min(6, node.level + 1)}` as 'h2'; return <Heading key={node.id}>{inlineView(node.children)}</Heading> }
91
- if (node.type === 'list') { const List = node.ordered ? 'ol' : 'ul'; return <List key={node.id}>{node.children.map(item => <li key={item.id}>{richView(item.children)}</li>)}</List> }
92
- if (node.type === 'blockquote') return <blockquote key={node.id}>{richView(node.children)}</blockquote>
107
+ if (node.type === 'paragraph') return <p key={node.id}>{inlineView(node.children, view)}</p>
108
+ if (node.type === 'heading') { const Heading = `h${Math.min(6, node.level + 1)}` as 'h2'; return <Heading key={node.id}>{inlineView(node.children, view)}</Heading> }
109
+ if (node.type === 'list') { const List = node.ordered ? 'ol' : 'ul'; return <List key={node.id}>{node.children.map(item => <li key={item.id}>{richView(item.children, view)}</li>)}</List> }
110
+ if (node.type === 'blockquote') return <blockquote key={node.id}>{richView(node.children, view)}</blockquote>
93
111
  if (node.type === 'code') return <pre key={node.id}><code>{node.value}</code></pre>
94
112
  if (node.type === 'math') return <pre key={node.id}><code>{node.value}</code></pre>
95
- if (node.type === 'table') return <table key={node.id}><tbody>{node.children.map(row => <tr key={row.id}>{row.children.map(cell => <td key={cell.id}>{inlineView(cell.children)}</td>)}</tr>)}</tbody></table>
96
- return <div key={node.id}>{richView(node.fallback)}</div>
113
+ if (node.type === 'table') return <table key={node.id}><tbody>{node.children.map(row => <tr key={row.id}>{row.children.map(cell => <td key={cell.id}>{inlineView(cell.children, view)}</td>)}</tr>)}</tbody></table>
114
+ return <div key={node.id}>{richView(node.fallback, view)}</div>
97
115
  })
98
116
  }
99
117
 
100
- /** The source block and its content subtree, read-only, as they are in the source document now. */
101
- function SourceBlocks({ source, id, t }: { source: EmbedSource, id: string, t: DocumentTreeMessages }): ReactNode {
102
- const block: DocumentBlock | undefined = source.blocks?.[id]
118
+ /** A block and its content subtree, read-only, as `view` has them: a synced block's source, or the document on the side. */
119
+ export function ReadOnlyBlock({ view, id }: { view: ReadOnlyBlocks, id: string }): ReactNode {
120
+ const block: DocumentBlock | undefined = view.blocks?.[id]
103
121
  if (!block) return null
104
- if (block.type === 'text') return <>{richView(block.content)}</>
122
+ if (block.type === 'text') return <>{richView(block.content, view)}</>
105
123
  if (block.type === 'image') {
106
- const url = block.assetId ? source.assets?.[block.assetId] : undefined
107
- return url ? <img className="pm-document-editor__synced-image" src={url} alt={block.alt} /> : <p>{block.alt}</p>
124
+ const url = block.assetId ? view.asset(block.assetId) : undefined
125
+ return url ? <img className="pm-document-editor__synced-image" src={url} alt={block.alt} loading="lazy" /> : <p>{block.alt}</p>
108
126
  }
109
127
  if (block.type === 'code') return <pre><code>{block.value ?? block.title ?? ''}</code></pre>
110
- if (block.type === 'container') return <>{block.children.map(child => <SourceBlocks key={child} source={source} id={child} t={t} />)}</>
128
+ if (block.type === 'container') return <>{block.children.map(child => <ReadOnlyBlock key={child} view={view} id={child} />)}</>
111
129
  if (block.type === 'component') return <>
112
- <PmNotice>{t.syncedComponent(typeof block.parameters.title === 'string' ? block.parameters.title : source.title)}</PmNotice>
113
- {block.children?.map(child => <SourceBlocks key={child} source={source} id={child} t={t} />)}
130
+ <PmNotice>{view.componentLabel(typeof block.parameters.title === 'string' ? block.parameters.title : '')}</PmNotice>
131
+ {block.children?.map(child => <ReadOnlyBlock key={child} view={view} id={child} />)}
114
132
  </>
133
+ if (block.type === 'embed') return view.embed?.(block) ?? null
115
134
  return null
116
135
  }
117
136
 
@@ -133,6 +152,7 @@ export const SyncedBlock = memo(function SyncedBlock({ id, document, block }: {
133
152
  return () => { active = false }
134
153
  }, [workbench, source.document, source.block, generation])
135
154
  const ready = typeof answer === 'object' ? answer : undefined
155
+ const view = useMemo<ReadOnlyBlocks | undefined>(() => ready && { blocks: ready.blocks, asset: asset => ready.assets?.[asset], componentLabel: title => t.syncedComponent(title || ready.title) }, [ready, t])
136
156
  const missing = Boolean(ready?.missing || ready && !ready.blocks?.[source.block])
137
157
  const state = missing ? 'missing' : ready?.trashed ? 'trashed' : 'default'
138
158
  const documentTitle = ready?.title ?? workbench.tree.title(source.document) ?? ''
@@ -162,7 +182,7 @@ export const SyncedBlock = memo(function SyncedBlock({ id, document, block }: {
162
182
  {answer === 'loading' ? <PmSkeleton shape="list" label={t.syncedLoading} />
163
183
  : answer === 'failed' ? <p className="pmw-muted">{t.syncedFailed}</p>
164
184
  : missing ? <p className="pmw-muted">{t.sourceMissing}</p>
165
- : <div className="pm-document-editor__synced-content"><SourceBlocks source={answer} id={source.block} t={t} /></div>}
185
+ : <div className="pm-document-editor__synced-content">{view && <ReadOnlyBlock view={view} id={source.block} />}</div>}
166
186
  </PmSyncedBlockFrame>
167
187
  )
168
188
  })
@@ -1,5 +1,5 @@
1
1
  import { hasRole, isRecord, randomUUID, validateDocument } from '@lincyaw/kernel'
2
- import type { CanonicalSource, ClientBodyDraftReference, DocumentAnswer, DocumentChangeAnswer, DocumentImageImportAnswer, DocumentIssue, Member, PresmiumDocument, DocumentDefaults } from '@lincyaw/kernel'
2
+ import type { CanonicalSource, ClientBodyDraftReference, DocumentAnswer, DocumentChangeAnswer, DocumentImageImportAnswer, DocumentIssue, Member, PresmiumDocument, DocumentDefaults, SettingOrigins } from '@lincyaw/kernel'
3
3
  import { WorkspaceServerError } from './workspace-client.ts'
4
4
  import type { WorkspaceClient } from './workspace-client.ts'
5
5
  import { waitForDraft } from './document-draft-store.ts'
@@ -14,6 +14,8 @@ export interface DocumentSessionState {
14
14
  content?: PresmiumDocument
15
15
  /** What the document inherits from its ancestors and the workspace defaults; `effectiveOf` fills it into `content`. */
16
16
  inherited?: DocumentDefaults
17
+ /** Which ancestor (or the workspace defaults, null) each inherited setting comes from. */
18
+ inheritedFrom?: SettingOrigins
17
19
  version?: string
18
20
  fingerprint?: string
19
21
  projectRevision?: number
@@ -162,7 +164,7 @@ export class DocumentSession {
162
164
  const baseHash = await digest(answer.content)
163
165
  if (this.#disposed || this.#active !== directory || opening !== this.#opening) return
164
166
  const drafts = new DocumentDrafts(() => { if (slot && !this.#disposed) void this.#readDrafts(slot) })
165
- slot = { observedSource: this.#source(answer), input: 0, read: 0, compositions: new Set(), drafts, baseHash, baseContent: structuredClone(answer.content), storage: `presmium.document.v1:${JSON.stringify([info.root, answer.content.id])}`, state: { directory, member: info.member, identity: JSON.stringify([info.root, answer.content.id]), content: answer.content, ...answer.inherited ? { inherited: answer.inherited } : {}, version: answer.version, fingerprint: answer.fingerprint, loading: true, dirty: false, saving: false, restored: false, composing: false, storageFailure: false, reset: 0, issues: answer.issues } }
167
+ slot = { observedSource: this.#source(answer), input: 0, read: 0, compositions: new Set(), drafts, baseHash, baseContent: structuredClone(answer.content), storage: `presmium.document.v1:${JSON.stringify([info.root, answer.content.id])}`, state: { directory, member: info.member, identity: JSON.stringify([info.root, answer.content.id]), content: answer.content, ...answer.inherited ? { inherited: answer.inherited } : {}, ...answer.inheritedFrom ? { inheritedFrom: answer.inheritedFrom } : {}, version: answer.version, fingerprint: answer.fingerprint, loading: true, dirty: false, saving: false, restored: false, composing: false, storageFailure: false, reset: 0, issues: answer.issues } }
166
168
  this.#slots.set(directory, slot)
167
169
  await this.#restore(slot, answer)
168
170
  } else {
@@ -291,7 +293,7 @@ export class DocumentSession {
291
293
  async #adopt(slot: Slot, answer: DocumentAnswer, current = () => true): Promise<void> {
292
294
  if (!current()) return
293
295
  if (answer.content.id !== slot.state.content?.id) { slot.state = { ...slot.state, error: 'document-identity-changed' }; return }
294
- if (answer.inherited) slot.state = { ...slot.state, inherited: answer.inherited }
296
+ if (answer.inherited) slot.state = { ...slot.state, inherited: answer.inherited, ...answer.inheritedFrom ? { inheritedFrom: answer.inheritedFrom } : {} }
295
297
  slot.observedSource = this.#source(answer)
296
298
  if (answer.version === slot.state.version) {
297
299
  if (answer.fingerprint !== slot.state.fingerprint) slot.state = { ...slot.state, fingerprint: answer.fingerprint, issues: answer.issues }
@@ -26,6 +26,7 @@ export class DocumentTreeActions {
26
26
  readonly #open: (dir: string, focus?: 'body') => Promise<void>
27
27
  readonly #reveal: (section: string, block?: string) => void
28
28
  #reading?: AbortController
29
+ #attention?: AbortController
29
30
  #treeText?: string
30
31
  readonly #previews = new Map<string, Promise<DocumentPreview>>()
31
32
  readonly #embeds = new Map<string, Promise<EmbedSource>>()
@@ -47,7 +48,10 @@ export class DocumentTreeActions {
47
48
  async load(): Promise<void> {
48
49
  if (!this.#client.readTree) return
49
50
  // Other clients' changes (and the AI's) arrive as tree events; the first read starts listening.
50
- this.#unsubscribe ??= this.#client.subscribeTree?.(() => void this.load(), () => {})
51
+ if (!this.#unsubscribe) {
52
+ this.#unsubscribe = this.#client.subscribeTree?.(kind => void (kind === 'attention' ? this.loadAttention() : this.load()), () => {})
53
+ void this.loadAttention()
54
+ }
51
55
  this.#reading?.abort()
52
56
  const reading = this.#reading = new AbortController()
53
57
  if (!this.#store.state.documentTree) this.#store.set({ isDocumentTreeLoading: true })
@@ -62,6 +66,17 @@ export class DocumentTreeActions {
62
66
  }
63
67
  }
64
68
 
69
+ /** Reads what needs attention across the workspace again (on start and when the workspace says it changed). */
70
+ async loadAttention(): Promise<void> {
71
+ if (!this.#client.readAttention) return
72
+ this.#attention?.abort()
73
+ const reading = this.#attention = new AbortController()
74
+ try {
75
+ const attention = await this.#client.readAttention(reading.signal)
76
+ if (!reading.signal.aborted && JSON.stringify(attention) !== JSON.stringify(this.#store.state.workspaceAttention)) this.#store.set({ workspaceAttention: attention })
77
+ } catch { /* The notices stay as they were; the next change reads them again. */ }
78
+ }
79
+
65
80
  /** The folder of the document, as the workbench opens it. */
66
81
  dirOf(id: string): string | undefined {
67
82
  const state = this.#store.state
@@ -96,6 +111,18 @@ export class DocumentTreeActions {
96
111
  return true
97
112
  }
98
113
 
114
+ /** Shows the document of `place` read-only in the right pane, beside the open one, at its page or block. */
115
+ peek(place: DocumentPlace): void {
116
+ const { document, section, block } = place
117
+ const current = this.#store.state.documentPeek
118
+ if (current && current.document === document && current.section === section && current.block === block) return
119
+ this.#store.set({ documentPeek: { document, ...section ? { section } : {}, ...block ? { block } : {} } })
120
+ }
121
+
122
+ closePeek(): void {
123
+ if (this.#store.state.documentPeek) this.#store.set({ documentPeek: undefined })
124
+ }
125
+
99
126
  /** Remembers that the author opened the document. */
100
127
  visited(id: string | undefined): void {
101
128
  if (!id) return
@@ -200,9 +227,14 @@ export class DocumentTreeActions {
200
227
  this.toast(this.#t.trashed(title), 'neutral', { label: this.#t.undo, run: () => void this.restore(id) })
201
228
  }
202
229
 
230
+ /** Restores a document (with the children trashed along with it) and says where it went. */
203
231
  async restore(id: string): Promise<void> {
232
+ const title = this.#store.state.documentTree?.trash.find(entry => entry.id === id)?.title ?? ''
204
233
  const result = await this.operate({ type: 'restore', id })
205
- if (result) this.#store.set({ documents: await this.#client.readDocuments().catch(() => this.#store.state.documents) })
234
+ if (!result) return
235
+ const top = result.toTopLevel?.find(item => item.document === id)
236
+ this.toast(top ? this.#t.restoredToTop(title, top.parent) : this.#t.restored(title))
237
+ this.#store.set({ documents: await this.#client.readDocuments().catch(() => this.#store.state.documents) })
206
238
  }
207
239
 
208
240
  async purge(id: string): Promise<boolean> {
@@ -223,7 +255,7 @@ export class DocumentTreeActions {
223
255
  if (this.#store.state.toast?.id === id) this.#store.set({ toast: undefined })
224
256
  }
225
257
 
226
- dispose(): void { this.#reading?.abort(); this.#unsubscribe?.() }
258
+ dispose(): void { this.#reading?.abort(); this.#attention?.abort(); this.#unsubscribe?.() }
227
259
  }
228
260
 
229
261
  function readRecent(): RecentDocument[] {
@@ -419,7 +419,8 @@ export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actio
419
419
  <p className="pm-ui-doc-preview__title">{preview.title}</p>
420
420
  {preview.excerpt && <p className="pm-ui-doc-preview__excerpt">{preview.excerpt}</p>}
421
421
  <p className="pm-ui-doc-preview__meta">{preview.meta}</p>
422
- {!preview.missing && actions && <div className="pm-ui-doc-preview__actions">{actions}</div>}
422
+ {/* An action leads elsewhere (the document, or the right pane): the card closes behind it. */}
423
+ {!preview.missing && actions && <div className="pm-ui-doc-preview__actions" onClick={() => { clearTimeout(timer.current); setOpen(false) }}>{actions}</div>}
423
424
  </>}
424
425
  </Popover.Content>
425
426
  </Popover.Portal>
@@ -483,6 +484,32 @@ export function PmSyncedBlockFrame({ source, state = 'default', stateLabel, acti
483
484
  )
484
485
  }
485
486
 
487
+ /**
488
+ * Another document shown read-only beside the open one (the right pane's "Open on the Side"): its ancestors as a
489
+ * breadcrumb (each opens there in turn), its title, the actions (Open) and Close, a notice when it is in the trash or
490
+ * gone, and its content, which scrolls on its own. The frame takes focus when it opens.
491
+ */
492
+ export const PmDocPeek = forwardRef<HTMLElement, { label: string, path: readonly { id: string, title: string }[], title: string, actions?: ReactNode, closeLabel: string, onClose(): void, onPath?(id: string): void, notice?: ReactNode, busy?: boolean, children?: ReactNode, bodyRef?: (node: HTMLDivElement | null) => void }>(function PmDocPeek({ label, path, title, actions, closeLabel, onClose, onPath, notice, busy, children, bodyRef }, ref) {
493
+ return (
494
+ <section ref={ref} className="pm-ui-doc-peek" aria-label={label} aria-busy={busy || undefined} tabIndex={-1}>
495
+ <header className="pm-ui-doc-peek__header">
496
+ <div className="pm-ui-doc-peek__heading">
497
+ {path.length > 0 && <ol className="pm-ui-doc-peek__path">
498
+ {path.map(item => <li key={item.id}>{onPath ? <button type="button" className="pm-ui-doc-peek__crumb" title={item.title} onClick={() => onPath(item.id)}>{item.title}</button> : <span title={item.title}>{item.title}</span>}</li>)}
499
+ </ol>}
500
+ <h2 className="pm-ui-doc-peek__title"><PmIcon name="document" /><span>{title}</span></h2>
501
+ </div>
502
+ <div className="pm-ui-doc-peek__actions">
503
+ {actions}
504
+ <PmIconButton small icon="close" label={closeLabel} onClick={onClose} />
505
+ </div>
506
+ </header>
507
+ {notice}
508
+ <div ref={bodyRef} className="pm-ui-doc-peek__body">{children}</div>
509
+ </section>
510
+ )
511
+ })
512
+
486
513
  /** One place that cites the document: the citing document's title and the sentence around the citation. */
487
514
  export interface BacklinkPlace { id: string, excerpt: string, meta?: string, synced?: boolean }
488
515
 
package/src/knowledge.css CHANGED
@@ -318,3 +318,37 @@
318
318
  text-overflow: ellipsis;
319
319
  white-space: nowrap;
320
320
  }
321
+
322
+ /* The right pane with a document on the side is wider: the page beside it keeps the rest. */
323
+ .pmw-document[data-aside="peek"] .pmw-document__aside {
324
+ flex-basis: min(var(--pm-peek-width), 50%);
325
+ }
326
+
327
+ .pmw-document:not([data-roomy])[data-aside="peek"] .pmw-document__aside {
328
+ width: min(100%, var(--pm-peek-width));
329
+ }
330
+
331
+ .pmw-peek__page {
332
+ margin: var(--pm-space-6) 0 var(--pm-space-2);
333
+ font-size: var(--pm-text-lg);
334
+ }
335
+
336
+ .pmw-peek__page:first-child {
337
+ margin-top: 0;
338
+ }
339
+
340
+ .pmw-peek__block {
341
+ min-width: 0;
342
+ }
343
+
344
+ .pmw-peek__block > :first-child { margin-top: 0; }
345
+ .pmw-peek__block > :last-child { margin-bottom: 0; }
346
+ .pmw-peek__block + .pmw-peek__block { margin-top: var(--pm-space-3); }
347
+
348
+ .pmw-peek__synced {
349
+ display: flex;
350
+ flex-wrap: wrap;
351
+ align-items: center;
352
+ gap: var(--pm-space-1);
353
+ color: var(--pm-color-muted);
354
+ }
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}: `