@lincyaw/workbench 0.2.0-rc.121 → 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.
Files changed (39) hide show
  1. package/package.json +4 -4
  2. package/src/StepProductionEditor.tsx +13 -8
  3. package/src/components.tsx +24 -4
  4. package/src/context.tsx +30 -0
  5. package/src/document-editor/BlockNoteSurface.tsx +4 -1
  6. package/src/document-editor/DocumentBlockFallback.tsx +0 -1
  7. package/src/document-editor/DocumentEditor.tsx +7 -1
  8. package/src/document-editor/DocumentStepNarration.tsx +4 -2
  9. package/src/document-editor/authoring.tsx +15 -0
  10. package/src/document-editor/inline.ts +5 -0
  11. package/src/document-editor/insertion-place.ts +2 -2
  12. package/src/document-editor/messages.ts +2 -2
  13. package/src/document-editor/projection.ts +6 -4
  14. package/src/document-editor/references.tsx +352 -0
  15. package/src/document-editor/schema.tsx +39 -2
  16. package/src/document-editor/style.css +10 -0
  17. package/src/document-production.ts +8 -0
  18. package/src/document-session.ts +5 -3
  19. package/src/document-tree.ts +271 -0
  20. package/src/import-messages.ts +1 -1
  21. package/src/index.ts +6 -1
  22. package/src/knowledge-components.tsx +574 -0
  23. package/src/knowledge.css +354 -0
  24. package/src/messages.ts +12 -0
  25. package/src/panels/DocumentPeekPanel.tsx +190 -0
  26. package/src/panels/DocumentView.tsx +46 -23
  27. package/src/panels/DocumentVoiceField.tsx +3 -2
  28. package/src/panels/HomePanel.tsx +12 -3
  29. package/src/panels/MaterialsDialog.tsx +67 -0
  30. package/src/panels/ProductionCaptionSize.tsx +8 -3
  31. package/src/panels/ReferencesPanel.tsx +115 -0
  32. package/src/panels/SourceDocumentPanel.tsx +21 -3
  33. package/src/panels/WorkspaceHome.tsx +109 -0
  34. package/src/panels/WorkspaceSidebar.tsx +331 -0
  35. package/src/styles.css +20 -0
  36. package/src/tree-messages.ts +345 -0
  37. package/src/workbench-state.ts +21 -0
  38. package/src/workbench.ts +76 -3
  39. package/src/workspace-client.ts +35 -1
@@ -0,0 +1,352 @@
1
+ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
2
+ import type { ReactNode } from 'react'
3
+ import { SuggestionMenu as SuggestionMenuExtension } from '@blocknote/core/extensions'
4
+ import { SuggestionMenuController } from '@blocknote/react'
5
+ import type { DefaultReactSuggestionItem, SuggestionMenuProps } from '@blocknote/react'
6
+ import type { DocumentBlock, EmbedBlock, InlineNode, PresmiumDocument, ReferenceTarget, RichTextNode } from '@lincyaw/kernel'
7
+ import type { DocumentSearchHit, EmbedSource } from '@lincyaw/kernel/contracts'
8
+ import { PmButton, PmDialog, PmDocMention, PmDocPreviewCard, PmIcon, PmMentionPicker, PmNotice, PmSearchList, PmSkeleton, PmSyncedBlockFrame } from '../components.tsx'
9
+ import type { DocPreview, MentionOption } from '../components.tsx'
10
+ import { useTreeMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
11
+ import type { DocumentTreeMessages } from '../tree-messages.ts'
12
+ import type { Workbench } from '../workbench.ts'
13
+ import type { NativeDocumentEditor } from './schema.tsx'
14
+
15
+ /** The text a synced block link is copied as; pasted into a document, it inserts the synced block. */
16
+ const MENTION_DEBOUNCE = 100
17
+
18
+ const SYNCED_LINK = /^presmium-synced:([^\s/#]+)#([^\s/#]+)$/
19
+ export const syncedLinkOf = (document: string, block: string) => `presmium-synced:${encodeURIComponent(document)}#${encodeURIComponent(block)}`
20
+ export function parseSyncedLink(text: string): { document: string, block: string } | undefined {
21
+ const match = SYNCED_LINK.exec(text.trim())
22
+ return match ? { document: decodeURIComponent(match[1]!), block: decodeURIComponent(match[2]!) } : undefined
23
+ }
24
+
25
+ function currentTitle(workbench: Workbench, target: ReferenceTarget): string | undefined {
26
+ const own = workbench.getState().authoring?.content
27
+ if (own?.id === target.document) {
28
+ if (target.section) return own.sections[target.section]?.title
29
+ return own.metadata.title
30
+ }
31
+ return target.section || target.block ? undefined : workbench.tree.title(target.document)
32
+ }
33
+
34
+ function previewOf(t: DocumentTreeMessages, workbench: Workbench, target: ReferenceTarget, fallback: string): Promise<DocPreview> {
35
+ const read = workbench.tree.preview(target)
36
+ if (read) return read.then(preview => ({
37
+ path: preview.ancestors, title: preview.title,
38
+ excerpt: preview.missing ? t.previewMissing : preview.trashed ? `${t.previewTrashed} ${preview.excerpt}` : preview.excerpt,
39
+ meta: t.previewMeta(preview.pages, preview.steps, preview.citedBy), missing: preview.missing,
40
+ }))
41
+ const title = workbench.tree.title(target.document)
42
+ return Promise.resolve({ path: workbench.tree.ancestors(target.document).map(item => item.title), title: title ?? fallback, excerpt: title ? '' : t.previewMissing, meta: '', missing: !title })
43
+ }
44
+
45
+ /** An inline reference in the editor: the target's current title as a mention, its preview on hover, Enter or a click to go there. */
46
+ // Memoised on primitive props: the editor's node views render again on each edit, a chip only when its target changes.
47
+ export const DocumentReference = memo(function DocumentReference({ document, section, block, label, fallback }: { document: string, section?: string, block?: string, label?: string, fallback: string }) {
48
+ const target = useMemo<ReferenceTarget>(() => ({ document, ...section ? { section } : {}, ...block ? { block } : {} }), [document, section, block])
49
+ const t = useTreeMessages()
50
+ const workbench = useWorkbench()
51
+ const tree = useWorkbenchState(state => state.documentTree)
52
+ useWorkbenchState(state => state.authoring?.content?.metadata.title)
53
+ const own = workbench.getState().authoring?.content?.id === target.document
54
+ const missing = Boolean(tree && !own && !tree.nodes[target.document] && !tree.trash.some(entry => entry.id === target.document))
55
+ const title = label ?? currentTitle(workbench, target) ?? fallback
56
+ const open = () => void workbench.tree.openPlace(target, { focus: 'body' })
57
+ return (
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><PmButton small icon="rail" onClick={() => workbench.tree.peek(target)}>{t.openOnSide}</PmButton></>}>
60
+ <PmDocMention title={title} missing={missing} missingLabel={fallback || t.missingDocument} onActivate={open} />
61
+ </PmDocPreviewCard>
62
+ )
63
+ })
64
+
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[] {
79
+ return nodes.map((node, index) => {
80
+ const id = `${key}${index}`
81
+ if (node.type === 'text') {
82
+ let content: ReactNode = node.text
83
+ for (const mark of node.marks ?? []) {
84
+ if (mark.type === 'bold') content = <strong>{content}</strong>
85
+ else if (mark.type === 'italic') content = <em>{content}</em>
86
+ else if (mark.type === 'code') content = <code>{content}</code>
87
+ else if (mark.type === 'underline') content = <u>{content}</u>
88
+ else if (mark.type === 'strike') content = <s>{content}</s>
89
+ }
90
+ return <span key={id}>{content}</span>
91
+ }
92
+ if (node.type === 'break') return <br key={id} />
93
+ if (node.type === 'math') return <code key={id}>{node.value}</code>
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
+ }
101
+ return <span key={id}>{node.fallback}</span>
102
+ })
103
+ }
104
+
105
+ function richView(nodes: readonly RichTextNode[], view: ReadOnlyBlocks): ReactNode[] {
106
+ return nodes.map(node => {
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>
111
+ if (node.type === 'code') return <pre key={node.id}><code>{node.value}</code></pre>
112
+ if (node.type === 'math') return <pre key={node.id}><code>{node.value}</code></pre>
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>
115
+ })
116
+ }
117
+
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]
121
+ if (!block) return null
122
+ if (block.type === 'text') return <>{richView(block.content, view)}</>
123
+ if (block.type === 'image') {
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>
126
+ }
127
+ if (block.type === 'code') return <pre><code>{block.value ?? block.title ?? ''}</code></pre>
128
+ if (block.type === 'container') return <>{block.children.map(child => <ReadOnlyBlock key={child} view={view} id={child} />)}</>
129
+ if (block.type === 'component') return <>
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} />)}
132
+ </>
133
+ if (block.type === 'embed') return view.embed?.(block) ?? null
134
+ return null
135
+ }
136
+
137
+ /** A synced block in the editor: its source's current content, Edit Original and Convert to Copy, or why it is missing. */
138
+ export const SyncedBlock = memo(function SyncedBlock({ id, document, block }: { id: string, document: string, block: string }) {
139
+ const source = useMemo(() => ({ document, block }), [document, block])
140
+ const t = useTreeMessages()
141
+ const workbench = useWorkbench()
142
+ const ownId = useWorkbenchState(state => state.authoring?.content?.id)
143
+ const readOnly = useWorkbenchState(state => workbench.client.capabilities?.readOnly === true || state.mode !== 'editing')
144
+ const busy = useWorkbenchState(state => Boolean(state.isDocumentTreeBusy))
145
+ const generation = useWorkbenchState(state => state.documentLinksGeneration)
146
+ const [answer, setAnswer] = useState<EmbedSource | 'loading' | 'failed'>('loading')
147
+ useEffect(() => {
148
+ const read = workbench.tree.embedSource(source)
149
+ if (!read) { setAnswer('failed'); return }
150
+ let active = true
151
+ read.then(value => { if (active) setAnswer(value) }, () => { if (active) setAnswer('failed') })
152
+ return () => { active = false }
153
+ }, [workbench, source.document, source.block, generation])
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])
156
+ const missing = Boolean(ready?.missing || ready && !ready.blocks?.[source.block])
157
+ const state = missing ? 'missing' : ready?.trashed ? 'trashed' : 'default'
158
+ const documentTitle = ready?.title ?? workbench.tree.title(source.document) ?? ''
159
+ const blockLabel = useMemo(() => {
160
+ const block = ready?.blocks?.[source.block]
161
+ if (block?.type === 'text') {
162
+ const first = block.content[0]
163
+ const text = first && 'children' in first && Array.isArray(first.children) ? (first.children as InlineNode[]).map(node => node.type === 'text' ? node.text : '').join('') : ''
164
+ return text.slice(0, 24)
165
+ }
166
+ if (block?.type === 'component') return typeof block.parameters.title === 'string' ? block.parameters.title : ''
167
+ return ''
168
+ }, [ready, source.block])
169
+ const edit = () => void workbench.tree.openPlace({ document: source.document, block: source.block, ...sectionOfBlock(workbench, source) }, { focus: 'body' })
170
+ const convert = async () => {
171
+ if (!ownId) return
172
+ await workbench.flushPendingEdits().catch(() => {})
173
+ if (await workbench.tree.embedToCopy(ownId, id)) workbench.tree.toast(t.converted)
174
+ }
175
+ const actions = <>
176
+ {state !== 'missing' && <PmButton small variant="text" onClick={edit}>{t.editOriginal}</PmButton>}
177
+ {!readOnly && state !== 'missing' && workbench.client.operateTree && <PmButton small variant="text" disabled={busy} onClick={() => void convert()}>{t.convertToCopy}</PmButton>}
178
+ </>
179
+ return (
180
+ <PmSyncedBlockFrame label={t.syncedLabel} state={state} stateLabel={state === 'missing' ? t.sourceMissing : t.sourceTrashed} actions={actions}
181
+ source={<><span>{t.syncedFrom}</span><button type="button" className="pm-ui-synced-block__link" onClick={edit}>{[documentTitle, blockLabel].filter(Boolean).join(' › ')}</button></>}>
182
+ {answer === 'loading' ? <PmSkeleton shape="list" label={t.syncedLoading} />
183
+ : answer === 'failed' ? <p className="pmw-muted">{t.syncedFailed}</p>
184
+ : missing ? <p className="pmw-muted">{t.sourceMissing}</p>
185
+ : <div className="pm-document-editor__synced-content">{view && <ReadOnlyBlock view={view} id={source.block} />}</div>}
186
+ </PmSyncedBlockFrame>
187
+ )
188
+ })
189
+
190
+ function sectionOfBlock(workbench: Workbench, source: { document: string, block: string }): { section?: string } {
191
+ const own = workbench.getState().authoring?.content
192
+ if (own?.id !== source.document) return {}
193
+ const section = Object.values(own.sections).find(item => item.children.includes(source.block))
194
+ return section ? { section: section.id } : {}
195
+ }
196
+
197
+ type MentionItem = { kind: 'document', hit: MentionOption } | { kind: 'create', title: string }
198
+
199
+ function MentionMenu(props: SuggestionMenuProps<MentionItem> & { query: () => string }) {
200
+ const t = useTreeMessages()
201
+ const options = props.items.flatMap(item => item.kind === 'document' ? [item.hit] : [])
202
+ const create = props.items.find(item => item.kind === 'create')
203
+ const query = props.query()
204
+ return <PmMentionPicker heading={t.linkHeading(query)} options={options} active={props.selectedIndex ?? 0} hint={t.pickerHint} emptyLabel={t.searchEmpty}
205
+ loading={props.loadingState !== 'loaded'} loadingLabel={t.searching} listId="bn-suggestion-menu" optionId={index => `bn-suggestion-menu-item-${index}`}
206
+ createLabel={create ? t.createChildAndLink(create.title) : undefined}
207
+ onSelect={option => props.onItemClick?.(props.items.find(item => item.kind === 'document' && item.hit.id === option.id)!)}
208
+ onCreate={create ? () => props.onItemClick?.(create) : undefined} />
209
+ }
210
+
211
+ function insertReference(editor: NativeDocumentEditor, document: string, title: string): void {
212
+ editor.insertInlineContent([{ type: 'presmiumReference', props: { document, section: '', block: '', label: '', fallback: title } }, ' '])
213
+ }
214
+
215
+ /**
216
+ * Typing @ or [[ in the text opens the document picker: search as you type, the path to tell equal titles apart, and
217
+ * last "New Child Document … and Link", which creates the document under this one and links it without leaving the text.
218
+ */
219
+ export function DocumentMentionMenus({ editor }: { editor: NativeDocumentEditor }) {
220
+ const workbench = useWorkbench()
221
+ const query = useRef('')
222
+ // Typing debounces the search and cancels the one in flight; a cancelled call answers the previous results.
223
+ const search = useRef<{ controller?: AbortController, items: MentionItem[] }>({ items: [] })
224
+ // Stable, so that the menu reads again only when the query changes, not when the editor around it renders.
225
+ const getItems = useCallback(async (text: string): Promise<MentionItem[]> => {
226
+ query.current = text
227
+ const own = workbench.getState().authoring?.content?.id
228
+ let hits: DocumentSearchHit[] = []
229
+ const trimmed = text.trim()
230
+ search.current.controller?.abort()
231
+ const controller = search.current.controller = new AbortController()
232
+ if (workbench.client.searchDocuments && trimmed) {
233
+ await new Promise(resolve => setTimeout(resolve, MENTION_DEBOUNCE))
234
+ if (controller.signal.aborted) return search.current.items
235
+ try { hits = await workbench.client.searchDocuments(trimmed, 8, controller.signal) } catch { return search.current.items }
236
+ } else {
237
+ const recent = workbench.getState().recentDocuments ?? []
238
+ hits = recent.filter(entry => entry.id !== own && workbench.tree.title(entry.id) !== undefined).slice(0, 6)
239
+ .map(entry => ({ id: entry.id, title: workbench.tree.title(entry.id)!, ancestors: workbench.tree.ancestors(entry.id).map(item => item.title), match: 'title' as const }))
240
+ }
241
+ const seen = new Set<string>()
242
+ const items: MentionItem[] = hits.filter(hit => !seen.has(hit.id) && seen.add(hit.id)).map(hit => ({ kind: 'document', hit: { id: hit.id, title: hit.title, path: hit.ancestors } }))
243
+ if (trimmed && own && workbench.client.operateTree && workbench.client.capabilities?.readOnly !== true) items.push({ kind: 'create', title: trimmed })
244
+ search.current.items = items
245
+ return items
246
+ }, [workbench])
247
+ const choose = useCallback(async (item: MentionItem) => {
248
+ if (item.kind === 'document') { insertReference(editor, item.hit.id, item.hit.title); return }
249
+ const own = workbench.getState().authoring?.content?.id
250
+ if (!own) return
251
+ const siblings = workbench.getState().documentTree?.nodes[own]?.children
252
+ const result = await workbench.tree.operate({ type: 'create', title: item.title, parent: own, after: siblings?.at(-1) ?? null })
253
+ if (result?.created) insertReference(editor, result.created, item.title)
254
+ }, [workbench, editor])
255
+ const click = useCallback((item: MentionItem) => void choose(item), [choose])
256
+ // Page titles are plain text: the picker opens only in the body, as the slash menu does.
257
+ const inText = useCallback(() => editor.getTextCursorPosition().block.type !== 'presmiumPage', [editor])
258
+ const menu = useMemo(() => (props: SuggestionMenuProps<MentionItem>) => <MentionMenu {...props} query={() => query.current} />, [])
259
+ return <>
260
+ <SuggestionMenuController<(query: string) => Promise<MentionItem[]>> triggerCharacter="@" shouldOpen={inText} getItems={getItems} suggestionMenuComponent={menu} onItemClick={click} />
261
+ <SuggestionMenuController<(query: string) => Promise<MentionItem[]>> triggerCharacter="[[" shouldOpen={inText} getItems={getItems} suggestionMenuComponent={menu} onItemClick={click} />
262
+ </>
263
+ }
264
+
265
+ /** The slash menu's items: Link to Document, Synced Block and Child Document. */
266
+ export function referenceSlashItems(editor: NativeDocumentEditor, t: DocumentTreeMessages, group: string, workbench: Workbench, pickSynced: () => void): DefaultReactSuggestionItem[] {
267
+ if (!workbench.client.readTree) return []
268
+ const aliases = (value: string) => value.split('|')
269
+ const items: DefaultReactSuggestionItem[] = [
270
+ { title: t.linkToDocument, subtext: t.linkToDocumentHint, group, aliases: aliases(t.linkAliases), icon: <PmIcon name="reference" />,
271
+ onItemClick: () => editor.getExtension(SuggestionMenuExtension)?.openSuggestionMenu('@') },
272
+ ]
273
+ if (workbench.client.readEmbedSource) items.push({ title: t.syncedBlock, subtext: t.syncedBlockHint, group, aliases: aliases(t.syncedAliases), icon: <PmIcon name="synced" />, onItemClick: pickSynced })
274
+ if (workbench.client.operateTree && workbench.client.capabilities?.readOnly !== true) items.push({ title: t.childDocument, subtext: t.childDocumentHint, group, aliases: aliases(t.childAliases), icon: <PmIcon name="document-add" />,
275
+ onItemClick: () => {
276
+ const own = workbench.getState().authoring?.content?.id
277
+ if (!own) return
278
+ const siblings = workbench.getState().documentTree?.nodes[own]?.children
279
+ void workbench.tree.operate({ type: 'create', title: t.untitled, parent: own, after: siblings?.at(-1) ?? null }).then(result => {
280
+ if (result?.created) insertReference(editor, result.created, t.untitled)
281
+ })
282
+ } })
283
+ return items
284
+ }
285
+
286
+ /** Inserts a synced block after the block with the caret (in place of it when it is an empty paragraph). */
287
+ export function insertSyncedBlock(editor: NativeDocumentEditor, source: { document: string, block: string }): void {
288
+ const current = editor.getTextCursorPosition().block
289
+ const block = { type: 'presmiumEmbed' as const, props: source }
290
+ if (current.type === 'paragraph' && Array.isArray(current.content) && current.content.length === 0) editor.replaceBlocks([current], [block])
291
+ else editor.insertBlocks([block], current, 'after')
292
+ }
293
+
294
+ function blockLabel(document: PresmiumDocument, id: string): string {
295
+ const block = document.blocks[id]
296
+ if (!block) return id
297
+ if (block.type === 'text') {
298
+ const text = block.content.map(node => 'children' in node && Array.isArray(node.children) ? (node.children as InlineNode[]).map(child => child.type === 'text' ? child.text : '').join('') : node.type === 'code' ? node.value : '').join(' ').trim()
299
+ return text.slice(0, 60) || id
300
+ }
301
+ if (block.type === 'component') return typeof block.parameters.title === 'string' ? block.parameters.title : document.definitions[block.definitionId]?.kind ?? id
302
+ if (block.type === 'image') return block.alt || id
303
+ if (block.type === 'code') return block.title ?? block.language
304
+ if (block.type === 'container') return block.properties.title ?? id
305
+ return id
306
+ }
307
+
308
+ /** Insert Synced Block: choose a document, then one of its content blocks. */
309
+ export function SyncedBlockDialog({ onClose, onInsert }: { onClose(): void, onInsert(source: { document: string, block: string }): void }) {
310
+ const t = useTreeMessages()
311
+ const workbench = useWorkbench()
312
+ const tree = useWorkbenchState(state => state.documentTree)
313
+ const [query, setQuery] = useState('')
314
+ const [documentId, setDocumentId] = useState('')
315
+ const [content, setContent] = useState<PresmiumDocument | 'loading' | 'failed'>()
316
+ const [block, setBlock] = useState('')
317
+ const documents = useMemo(() => Object.values(tree?.nodes ?? {}).map(node => ({ value: node.id, label: node.title || t.untitled, icon: 'document' as const, description: workbench.tree.ancestors(node.id).map(item => item.title).join(' › ') })), [tree, workbench, t])
318
+ useEffect(() => {
319
+ if (!documentId) return
320
+ const dir = workbench.tree.dirOf(documentId)
321
+ if (dir === undefined) { setContent('failed'); return }
322
+ let active = true
323
+ setContent('loading'); setBlock('')
324
+ workbench.client.readDocument(dir).then(answer => { if (active) setContent(answer.content) }, () => { if (active) setContent('failed') })
325
+ return () => { active = false }
326
+ }, [workbench, documentId])
327
+ const blocks = typeof content === 'object' ? content.sectionOrder.flatMap(section => content.sections[section]!.children.map(id => ({ value: id, label: blockLabel(content, id), description: content.sections[section]!.title }))) : []
328
+ return (
329
+ <PmDialog open label={t.insertSynced} closeLabel={t.close} onClose={onClose}
330
+ footer={<><PmButton onClick={onClose}>{t.cancel}</PmButton><PmButton variant="primary" disabled={!documentId || !block} onClick={() => onInsert({ document: documentId, block })}>{t.insert}</PmButton></>}>
331
+ <div className="pm-document-editor__synced-picker">
332
+ <PmSearchList label={t.chooseDocument} searchLabel={t.searchField} searchPlaceholder={t.searchPlaceholder} items={documents} value={documentId} query={query} onQueryChange={setQuery}
333
+ onValueChange={setDocumentId} resultsLabel={t.searchResults} emptyLabel={t.searchEmpty} loadingLabel={t.treeLoading} loading={!tree} autoFocus />
334
+ {documentId && (content === 'loading' ? <PmSkeleton shape="list" label={t.syncedLoading} />
335
+ : content === 'failed' ? <PmNotice tone="danger">{t.syncedFailed}</PmNotice>
336
+ : blocks.length === 0 ? <p className="pmw-muted">{t.noBlocks}</p>
337
+ : <PmSearchList label={t.chooseBlock} searchLabel={t.chooseBlock} items={blocks} value={block} onValueChange={setBlock} onActivate={value => onInsert({ document: documentId, block: value })}
338
+ resultsLabel={t.searchResults} emptyLabel={t.noBlocks} loadingLabel={t.syncedLoading} />)}
339
+ </div>
340
+ </PmDialog>
341
+ )
342
+ }
343
+
344
+ /** The editor's reference tools: the @ and [[ pickers and Insert Synced Block, opened from the slash menu through `picker`. */
345
+ export function ReferenceEditorTools({ editor, picker }: { editor: NativeDocumentEditor, picker: { open?: (editor: NativeDocumentEditor) => void } }) {
346
+ const [picking, setPicking] = useState<NativeDocumentEditor>()
347
+ useEffect(() => { picker.open = setPicking; return () => { picker.open = undefined } }, [picker])
348
+ return <>
349
+ <DocumentMentionMenus editor={editor} />
350
+ {picking && <SyncedBlockDialog onClose={() => setPicking(undefined)} onInsert={source => { insertSyncedBlock(picking, source); setPicking(undefined) }} />}
351
+ </>
352
+ }
@@ -3,7 +3,9 @@ import type { ReactNode } from 'react'
3
3
  import { BlockNoteSchema, defaultBlockSpecs, defaultInlineContentSpecs, defaultStyleSpecs } from '@blocknote/core'
4
4
  import type { Block, BlockNoteEditor, PartialBlock, StyleConfig, StyleSpec } from '@blocknote/core'
5
5
  import { createReactBlockSpec, createReactInlineContentSpec } from '@blocknote/react'
6
+ import type { DefaultReactSuggestionItem } from '@blocknote/react'
6
7
  import { DOCUMENT_IMAGE_MEDIA_TYPES } from '@lincyaw/kernel'
8
+ import type { ReferenceTarget } from '@lincyaw/kernel'
7
9
  import { tableIdentityExtension } from './table-identities.ts'
8
10
  import { documentColorStyles } from './colors.ts'
9
11
  import { mathBlock, mathInline } from './math.tsx'
@@ -11,6 +13,17 @@ import { mathBlock, mathInline } from './math.tsx'
11
13
  export interface DocumentNodeViews {
12
14
  renderBlock?(id: string, kind: string): ReactNode
13
15
  renderInline?(id: string, kind: string, label: string): ReactNode
16
+ /** An inline reference to a document, a page or a block: the current title, its preview and the way to it. */
17
+ renderReference?(target: ReferenceTarget, label: string | undefined, fallback: string): ReactNode
18
+ /** A synced block: the source's current content, read-only. */
19
+ renderEmbed?(id: string, source: { document: string, block: string }): ReactNode
20
+ /** The link that inserts the native block's document block as a synced block elsewhere; none when it has none yet. */
21
+ syncedLink?(nativeBlockId: string): string | undefined
22
+ copySyncedLink?(link: string): void
23
+ /** More slash menu items, controls rendered with the editor (suggestion menus, dialogs), and plain text pasted. */
24
+ slashItems?(editor: NativeDocumentEditor): DefaultReactSuggestionItem[]
25
+ editorChildren?(editor: NativeDocumentEditor): ReactNode
26
+ pasteText?(text: string, editor: NativeDocumentEditor): boolean
14
27
  }
15
28
  export const DOCUMENT_NODE_VIEWS = createContext<DocumentNodeViews>({})
16
29
 
@@ -57,6 +70,30 @@ const inline = createReactInlineContentSpec({
57
70
  },
58
71
  })
59
72
 
73
+ const reference = createReactInlineContentSpec({
74
+ type: 'presmiumReference',
75
+ propSchema: { document: { default: '' }, section: { default: '' }, block: { default: '' }, label: { default: '' }, fallback: { default: '' } },
76
+ content: 'none',
77
+ }, {
78
+ render: ({ inlineContent }) => {
79
+ const views = useContext(DOCUMENT_NODE_VIEWS)
80
+ const { document, section, block, label, fallback } = inlineContent.props
81
+ const target: ReferenceTarget = { document, ...section ? { section } : {}, ...block ? { block } : {} }
82
+ return <span className="pm-document-editor__reference" contentEditable={false}>{views.renderReference?.(target, label || undefined, fallback) ?? (label || fallback)}</span>
83
+ },
84
+ })
85
+
86
+ const embed = createReactBlockSpec({
87
+ type: 'presmiumEmbed',
88
+ propSchema: { document: { default: '' }, block: { default: '' } },
89
+ content: 'none',
90
+ }, {
91
+ render: ({ block }) => {
92
+ const views = useContext(DOCUMENT_NODE_VIEWS)
93
+ return <div className="pm-document-editor__embed" contentEditable={false}>{views.renderEmbed?.(block.id, { document: block.props.document, block: block.props.block })}</div>
94
+ },
95
+ })()
96
+
60
97
  const table = { ...defaultBlockSpecs.table, extensions: [...defaultBlockSpecs.table.extensions ?? [], tableIdentityExtension] }
61
98
  const image: typeof defaultBlockSpecs.image = { ...defaultBlockSpecs.image, implementation: { ...defaultBlockSpecs.image.implementation,
62
99
  meta: { ...defaultBlockSpecs.image.implementation.meta, fileBlockAccept: [...DOCUMENT_IMAGE_MEDIA_TYPES] },
@@ -98,9 +135,9 @@ export const documentEditorSchema = BlockNoteSchema.create({
98
135
  bulletListItem: defaultBlockSpecs.bulletListItem, numberedListItem: defaultBlockSpecs.numberedListItem,
99
136
  checkListItem: defaultBlockSpecs.checkListItem, quote: defaultBlockSpecs.quote,
100
137
  codeBlock: defaultBlockSpecs.codeBlock, table, image,
101
- presmiumPage: page, presmiumAtom: atom, presmiumContainer: container, presmiumMath: mathBlock,
138
+ presmiumPage: page, presmiumAtom: atom, presmiumContainer: container, presmiumMath: mathBlock, presmiumEmbed: embed,
102
139
  },
103
- inlineContentSpecs: { ...defaultInlineContentSpecs, presmiumInline: inline, presmiumMathInline: mathInline },
140
+ inlineContentSpecs: { ...defaultInlineContentSpecs, presmiumInline: inline, presmiumMathInline: mathInline, presmiumReference: reference },
104
141
  styleSpecs: clipboardStyles,
105
142
  })
106
143
  export const commentEditorSchema = BlockNoteSchema.create({
@@ -12,3 +12,13 @@
12
12
  .pm-document-editor__comment-tools { position: sticky; top: var(--pm-space-2); z-index: var(--pm-z-site-header); width: fit-content; margin-inline-start: var(--pm-space-5); }
13
13
 
14
14
  .pm-document-place-comment__trigger { display: inline-flex; align-items: center; gap: var(--pm-space-1); }
15
+
16
+ /* References and synced blocks: the shared PmDocMention and PmSyncedBlockFrame inside the editor's node views. */
17
+ .pm-document-editor__embed { flex: 1; width: 100%; min-width: 0; margin-block: var(--pm-space-2); }
18
+ .pm-document-editor .bn-block-content[data-content-type='presmiumEmbed'] > * { flex: 1; width: 100%; min-width: 0; }
19
+ .pm-document-editor__synced-content { min-width: 0; }
20
+ .pm-document-editor__synced-content > :first-child { margin-top: 0; }
21
+ .pm-document-editor__synced-content > :last-child { margin-bottom: 0; }
22
+ .pm-document-editor__synced-image { display: block; max-width: 100%; height: auto; }
23
+ .pm-document-editor__synced-link { color: var(--pm-color-accent); }
24
+ .pm-document-editor__synced-picker { display: grid; gap: var(--pm-space-4); }
@@ -408,6 +408,14 @@ export class DocumentProduction {
408
408
  this.#options.session.record(next)
409
409
  }
410
410
  /** The whole document's caption size (`production.captions.scale`), recorded like a step's timing. */
411
+ /** Removes the document's own caption size, so that it takes the one it inherits (its ancestors', or the workspace's). */
412
+ inheritCaptionScale(identity?: string): void {
413
+ const document = this.#options.document(identity)
414
+ if (!document?.production.captions || isAgentChanging(this.#options.store.state)) return
415
+ const { captions: _captions, ...production } = document.production
416
+ this.#options.session.record({ ...document, production })
417
+ }
418
+
411
419
  setCaptionScale(scale: number, identity?: string): void {
412
420
  const document = this.#options.document(identity)
413
421
  if (!document || isAgentChanging(this.#options.store.state)) return
@@ -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 }