@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/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.124",
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.123",
59
+ "@lincyaw/kernel": "1.0.0-rc.123"
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.123"
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[] {
@@ -1,6 +1,6 @@
1
1
  import * as Popover from '@radix-ui/react-popover'
2
2
  import { cloneElement, forwardRef, memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react'
3
- import type { DragEvent, KeyboardEvent, ReactElement, ReactNode } from 'react'
3
+ import type { DragEvent, KeyboardEvent, MouseEvent as ReactMouseEvent, PointerEvent as ReactPointerEvent, ReactElement, ReactNode } from 'react'
4
4
  import { PmButton, PmIcon, PmIconButton } from './base-controls.tsx'
5
5
  import type { MenuItem } from './components.tsx'
6
6
  import { PmMenu } from './components.tsx'
@@ -361,8 +361,9 @@ export interface DocPreview { path: string[], title: string, excerpt: string, me
361
361
 
362
362
  /**
363
363
  * A preview of a reference's target on hover: it opens after the pointer rests 500 ms (or the trigger is focused for as
364
- * long), stays while the pointer crosses to it within 300 ms, and its buttons take the keyboard with Tab. `load` runs
365
- * when it opens; `children` is the trigger.
364
+ * long), stays while the pointer crosses to it within 300 ms, and its buttons take the keyboard with Tab. A touch has
365
+ * no hover: a tap on the trigger opens the card at once instead of activating the trigger, a second tap or one outside
366
+ * closes it. `load` runs when it opens; `children` is the trigger.
366
367
  */
367
368
  export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actions, children }: { label: string, load(): Promise<DocPreview>, loadingLabel: string, failedLabel: string, actions?: ReactNode, children: ReactElement }) {
368
369
  const [open, setOpen] = useState(false)
@@ -373,13 +374,17 @@ export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actio
373
374
  loader.current = load
374
375
  // The preview is read when the pointer arrives, so that it is usually there when the card opens 500 ms later.
375
376
  const reading = useRef<{ promise: Promise<DocPreview>, value?: DocPreview }>()
377
+ // The pointer that pressed the trigger last: a touch taps it open, a mouse or pen keeps hovering and clicking.
378
+ const pressed = useRef<{ touch: boolean, trigger?: Element }>({ touch: false })
379
+ const read = () => {
380
+ if (open || reading.current) return
381
+ const entry: { promise: Promise<DocPreview>, value?: DocPreview } = { promise: loader.current() }
382
+ entry.promise.then(value => { entry.value = value }, () => {})
383
+ reading.current = entry
384
+ }
376
385
  const schedule = (next: boolean) => {
377
386
  clearTimeout(timer.current)
378
- if (next && !open && !reading.current) {
379
- const entry: { promise: Promise<DocPreview>, value?: DocPreview } = { promise: loader.current() }
380
- entry.promise.then(value => { entry.value = value }, () => {})
381
- reading.current = entry
382
- }
387
+ if (next) read()
383
388
  timer.current = setTimeout(() => setOpen(next), next ? PREVIEW_OPEN_DELAY : PREVIEW_CLOSE_DELAY)
384
389
  }
385
390
  useEffect(() => () => clearTimeout(timer.current), [])
@@ -397,9 +402,20 @@ export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actio
397
402
  }, [open])
398
403
  const trigger = cloneElement(children as ReactElement<Record<string, unknown>>, {
399
404
  describedBy: open ? id : undefined,
400
- onPointerEnter: () => schedule(true),
401
- onPointerLeave: () => schedule(false),
402
- onFocus: () => schedule(true),
405
+ onPointerEnter: (event: ReactPointerEvent) => { if (event.pointerType !== 'touch') schedule(true) },
406
+ onPointerLeave: (event: ReactPointerEvent) => { if (event.pointerType !== 'touch') schedule(false) },
407
+ onPointerDown: (event: ReactPointerEvent) => { pressed.current = { touch: event.pointerType === 'touch', trigger: event.currentTarget as Element } },
408
+ // Capturing, so that the trigger's own click (going to the target) does not run.
409
+ onClickCapture: (event: ReactMouseEvent) => {
410
+ if (!pressed.current.touch) return
411
+ pressed.current.touch = false
412
+ event.preventDefault()
413
+ event.stopPropagation()
414
+ clearTimeout(timer.current)
415
+ if (!open) read()
416
+ setOpen(!open)
417
+ },
418
+ onFocus: () => { if (!pressed.current.touch) schedule(true) },
403
419
  onBlur: (event: FocusEvent) => { if (!(event.relatedTarget instanceof Node && document.getElementById(id)?.contains(event.relatedTarget))) schedule(false) },
404
420
  onKeyDownCapture: (event: globalThis.KeyboardEvent) => { if (event.key === 'Escape' && open) { event.stopPropagation(); clearTimeout(timer.current); setOpen(false) } },
405
421
  })
@@ -409,6 +425,7 @@ export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actio
409
425
  <Popover.Portal>
410
426
  <Popover.Content id={id} className="pm-ui-doc-preview pm-ui-floating pm-ui" aria-label={label} side="bottom" align="start" sideOffset={6} collisionPadding={16}
411
427
  onOpenAutoFocus={event => event.preventDefault()} onCloseAutoFocus={event => event.preventDefault()}
428
+ onInteractOutside={event => { if (event.target instanceof Node && pressed.current.trigger?.contains(event.target)) event.preventDefault() }}
412
429
  onPointerEnter={() => clearTimeout(timer.current)} onPointerLeave={() => schedule(false)}
413
430
  onBlur={event => { if (!event.currentTarget.contains(event.relatedTarget as Node)) schedule(false) }}
414
431
  onEscapeKeyDown={event => event.stopPropagation()}>
@@ -419,7 +436,8 @@ export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actio
419
436
  <p className="pm-ui-doc-preview__title">{preview.title}</p>
420
437
  {preview.excerpt && <p className="pm-ui-doc-preview__excerpt">{preview.excerpt}</p>}
421
438
  <p className="pm-ui-doc-preview__meta">{preview.meta}</p>
422
- {!preview.missing && actions && <div className="pm-ui-doc-preview__actions">{actions}</div>}
439
+ {/* An action leads elsewhere (the document, or the right pane): the card closes behind it. */}
440
+ {!preview.missing && actions && <div className="pm-ui-doc-preview__actions" onClick={() => { clearTimeout(timer.current); setOpen(false) }}>{actions}</div>}
423
441
  </>}
424
442
  </Popover.Content>
425
443
  </Popover.Portal>
@@ -483,34 +501,64 @@ export function PmSyncedBlockFrame({ source, state = 'default', stateLabel, acti
483
501
  )
484
502
  }
485
503
 
504
+ /**
505
+ * Another document shown read-only beside the open one (the right pane's "Open on the Side"): its ancestors as a
506
+ * breadcrumb (each opens there in turn), its title, the actions (Open) and Close, a notice when it is in the trash or
507
+ * gone, and its content, which scrolls on its own. The frame takes focus when it opens.
508
+ */
509
+ 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) {
510
+ return (
511
+ <section ref={ref} className="pm-ui-doc-peek" aria-label={label} aria-busy={busy || undefined} tabIndex={-1}>
512
+ <header className="pm-ui-doc-peek__header">
513
+ <div className="pm-ui-doc-peek__heading">
514
+ {path.length > 0 && <ol className="pm-ui-doc-peek__path">
515
+ {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>)}
516
+ </ol>}
517
+ <h2 className="pm-ui-doc-peek__title"><PmIcon name="document" /><span>{title}</span></h2>
518
+ </div>
519
+ <div className="pm-ui-doc-peek__actions">
520
+ {actions}
521
+ <PmIconButton small icon="close" label={closeLabel} onClick={onClose} />
522
+ </div>
523
+ </header>
524
+ {notice}
525
+ <div ref={bodyRef} className="pm-ui-doc-peek__body">{children}</div>
526
+ </section>
527
+ )
528
+ })
529
+
486
530
  /** One place that cites the document: the citing document's title and the sentence around the citation. */
487
531
  export interface BacklinkPlace { id: string, excerpt: string, meta?: string, synced?: boolean }
488
532
 
489
533
  /**
490
534
  * A document that cites this one: its title, then each place with the sentence around it (two lines at most) and what
491
535
  * tells equal sentences apart (`meta`). One place makes the whole card the button; several are a list under the title.
536
+ * With `onPeek`, each place has a second, smaller action at its end (Open on the Side), always shown.
492
537
  */
493
- export function PmBacklinkItem({ title, count, places, syncedLabel, onActivate }: { title: string, count?: string, places: readonly BacklinkPlace[], syncedLabel?: string, onActivate(id: string): void }) {
538
+ export function PmBacklinkItem({ title, count, places, syncedLabel, peekLabel, onActivate, onPeek }: { title: string, count?: string, places: readonly BacklinkPlace[], syncedLabel?: string, peekLabel?: string, onActivate(id: string): void, onPeek?(id: string): void }) {
494
539
  const icon = (place: BacklinkPlace) => <PmIcon name={place.synced ? 'synced' : 'document'} />
495
540
  const label = (place: BacklinkPlace) => place.synced && syncedLabel ? <span className="pm-ui-sr-only">{syncedLabel}</span> : null
541
+ const peek = (place: BacklinkPlace) => onPeek && peekLabel ? <PmIconButton small icon="rail" className="pm-ui-backlink__peek" label={peekLabel} onClick={() => onPeek(place.id)} /> : null
496
542
  if (places.length === 1) {
497
543
  const place = places[0]!
498
- return (
544
+ const card = (
499
545
  <button type="button" className="pm-ui-backlink" title={title} onClick={() => onActivate(place.id)}>
500
546
  <span className="pm-ui-backlink__title">{icon(place)}<span className="pm-ui-backlink__name">{title}</span>{label(place)}</span>
501
547
  {place.excerpt && <span className="pm-ui-backlink__excerpt">{place.excerpt}</span>}
502
548
  {place.meta && <span className="pm-ui-backlink__meta">{place.meta}</span>}
503
549
  </button>
504
550
  )
551
+ const action = peek(place)
552
+ return action ? <div className="pm-ui-backlink__row">{card}{action}</div> : card
505
553
  }
506
554
  return (
507
555
  <div className="pm-ui-backlink" data-group="">
508
556
  <span className="pm-ui-backlink__title" title={title}><PmIcon name="document" /><span className="pm-ui-backlink__name">{title}</span>{count && <span className="pm-ui-backlink__count">{count}</span>}</span>
509
557
  <ul className="pm-ui-backlink__places">{places.map(place => (
510
- <li key={place.id}><button type="button" className="pm-ui-backlink__place" onClick={() => onActivate(place.id)}>
558
+ <li key={place.id} className="pm-ui-backlink__row"><button type="button" className="pm-ui-backlink__place" onClick={() => onActivate(place.id)}>
511
559
  {place.excerpt && <span className="pm-ui-backlink__excerpt">{place.excerpt}</span>}
512
560
  <span className="pm-ui-backlink__meta">{icon(place)}{place.meta}{label(place)}</span>
513
- </button></li>
561
+ </button>{peek(place)}</li>
514
562
  ))}</ul>
515
563
  </div>
516
564
  )