@lincyaw/workbench 0.2.0-rc.120 → 0.2.0-rc.122
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 +4 -4
- package/src/components.tsx +24 -4
- package/src/context.tsx +17 -0
- package/src/document-editor/BlockNoteSurface.tsx +4 -1
- package/src/document-editor/DocumentBlockFallback.tsx +0 -1
- package/src/document-editor/DocumentEditor.tsx +7 -1
- package/src/document-editor/authoring.tsx +15 -0
- package/src/document-editor/inline.ts +5 -0
- package/src/document-editor/insertion-place.ts +2 -2
- package/src/document-editor/messages.ts +2 -2
- package/src/document-editor/projection.ts +6 -4
- package/src/document-editor/references.tsx +332 -0
- package/src/document-editor/schema.tsx +39 -2
- package/src/document-editor/style.css +10 -0
- package/src/document-production.ts +8 -0
- package/src/document-tree.ts +239 -0
- package/src/import-messages.ts +1 -1
- package/src/index.ts +6 -1
- package/src/knowledge-components.tsx +547 -0
- package/src/knowledge.css +320 -0
- package/src/messages.ts +2 -0
- package/src/panels/DocumentView.tsx +37 -23
- package/src/panels/DocumentVoiceField.tsx +3 -2
- package/src/panels/HomePanel.tsx +12 -3
- package/src/panels/ProductionCaptionSize.tsx +8 -3
- package/src/panels/ReferencesPanel.tsx +115 -0
- package/src/panels/SourceDocumentPanel.tsx +21 -3
- package/src/panels/WorkspaceHome.tsx +93 -0
- package/src/panels/WorkspaceSidebar.tsx +331 -0
- package/src/styles.css +1 -0
- package/src/tree-messages.ts +299 -0
- package/src/workbench-state.ts +13 -0
- package/src/workbench.ts +28 -2
- package/src/workspace-client.ts +25 -1
|
@@ -0,0 +1,332 @@
|
|
|
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, 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>}>
|
|
60
|
+
<PmDocMention title={title} missing={missing} missingLabel={fallback || t.missingDocument} onActivate={open} />
|
|
61
|
+
</PmDocPreviewCard>
|
|
62
|
+
)
|
|
63
|
+
})
|
|
64
|
+
|
|
65
|
+
function inlineView(nodes: readonly InlineNode[], key = ''): ReactNode[] {
|
|
66
|
+
return nodes.map((node, index) => {
|
|
67
|
+
const id = `${key}${index}`
|
|
68
|
+
if (node.type === 'text') {
|
|
69
|
+
let content: ReactNode = node.text
|
|
70
|
+
for (const mark of node.marks ?? []) {
|
|
71
|
+
if (mark.type === 'bold') content = <strong>{content}</strong>
|
|
72
|
+
else if (mark.type === 'italic') content = <em>{content}</em>
|
|
73
|
+
else if (mark.type === 'code') content = <code>{content}</code>
|
|
74
|
+
else if (mark.type === 'underline') content = <u>{content}</u>
|
|
75
|
+
else if (mark.type === 'strike') content = <s>{content}</s>
|
|
76
|
+
}
|
|
77
|
+
return <span key={id}>{content}</span>
|
|
78
|
+
}
|
|
79
|
+
if (node.type === 'break') return <br key={id} />
|
|
80
|
+
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>
|
|
83
|
+
return <span key={id}>{node.fallback}</span>
|
|
84
|
+
})
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function richView(nodes: readonly RichTextNode[]): ReactNode[] {
|
|
88
|
+
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>
|
|
93
|
+
if (node.type === 'code') return <pre key={node.id}><code>{node.value}</code></pre>
|
|
94
|
+
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>
|
|
97
|
+
})
|
|
98
|
+
}
|
|
99
|
+
|
|
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]
|
|
103
|
+
if (!block) return null
|
|
104
|
+
if (block.type === 'text') return <>{richView(block.content)}</>
|
|
105
|
+
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>
|
|
108
|
+
}
|
|
109
|
+
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} />)}</>
|
|
111
|
+
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} />)}
|
|
114
|
+
</>
|
|
115
|
+
return null
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** A synced block in the editor: its source's current content, Edit Original and Convert to Copy, or why it is missing. */
|
|
119
|
+
export const SyncedBlock = memo(function SyncedBlock({ id, document, block }: { id: string, document: string, block: string }) {
|
|
120
|
+
const source = useMemo(() => ({ document, block }), [document, block])
|
|
121
|
+
const t = useTreeMessages()
|
|
122
|
+
const workbench = useWorkbench()
|
|
123
|
+
const ownId = useWorkbenchState(state => state.authoring?.content?.id)
|
|
124
|
+
const readOnly = useWorkbenchState(state => workbench.client.capabilities?.readOnly === true || state.mode !== 'editing')
|
|
125
|
+
const busy = useWorkbenchState(state => Boolean(state.isDocumentTreeBusy))
|
|
126
|
+
const generation = useWorkbenchState(state => state.documentLinksGeneration)
|
|
127
|
+
const [answer, setAnswer] = useState<EmbedSource | 'loading' | 'failed'>('loading')
|
|
128
|
+
useEffect(() => {
|
|
129
|
+
const read = workbench.tree.embedSource(source)
|
|
130
|
+
if (!read) { setAnswer('failed'); return }
|
|
131
|
+
let active = true
|
|
132
|
+
read.then(value => { if (active) setAnswer(value) }, () => { if (active) setAnswer('failed') })
|
|
133
|
+
return () => { active = false }
|
|
134
|
+
}, [workbench, source.document, source.block, generation])
|
|
135
|
+
const ready = typeof answer === 'object' ? answer : undefined
|
|
136
|
+
const missing = Boolean(ready?.missing || ready && !ready.blocks?.[source.block])
|
|
137
|
+
const state = missing ? 'missing' : ready?.trashed ? 'trashed' : 'default'
|
|
138
|
+
const documentTitle = ready?.title ?? workbench.tree.title(source.document) ?? ''
|
|
139
|
+
const blockLabel = useMemo(() => {
|
|
140
|
+
const block = ready?.blocks?.[source.block]
|
|
141
|
+
if (block?.type === 'text') {
|
|
142
|
+
const first = block.content[0]
|
|
143
|
+
const text = first && 'children' in first && Array.isArray(first.children) ? (first.children as InlineNode[]).map(node => node.type === 'text' ? node.text : '').join('') : ''
|
|
144
|
+
return text.slice(0, 24)
|
|
145
|
+
}
|
|
146
|
+
if (block?.type === 'component') return typeof block.parameters.title === 'string' ? block.parameters.title : ''
|
|
147
|
+
return ''
|
|
148
|
+
}, [ready, source.block])
|
|
149
|
+
const edit = () => void workbench.tree.openPlace({ document: source.document, block: source.block, ...sectionOfBlock(workbench, source) }, { focus: 'body' })
|
|
150
|
+
const convert = async () => {
|
|
151
|
+
if (!ownId) return
|
|
152
|
+
await workbench.flushPendingEdits().catch(() => {})
|
|
153
|
+
if (await workbench.tree.embedToCopy(ownId, id)) workbench.tree.toast(t.converted)
|
|
154
|
+
}
|
|
155
|
+
const actions = <>
|
|
156
|
+
{state !== 'missing' && <PmButton small variant="text" onClick={edit}>{t.editOriginal}</PmButton>}
|
|
157
|
+
{!readOnly && state !== 'missing' && workbench.client.operateTree && <PmButton small variant="text" disabled={busy} onClick={() => void convert()}>{t.convertToCopy}</PmButton>}
|
|
158
|
+
</>
|
|
159
|
+
return (
|
|
160
|
+
<PmSyncedBlockFrame label={t.syncedLabel} state={state} stateLabel={state === 'missing' ? t.sourceMissing : t.sourceTrashed} actions={actions}
|
|
161
|
+
source={<><span>{t.syncedFrom}</span><button type="button" className="pm-ui-synced-block__link" onClick={edit}>{[documentTitle, blockLabel].filter(Boolean).join(' › ')}</button></>}>
|
|
162
|
+
{answer === 'loading' ? <PmSkeleton shape="list" label={t.syncedLoading} />
|
|
163
|
+
: answer === 'failed' ? <p className="pmw-muted">{t.syncedFailed}</p>
|
|
164
|
+
: 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>}
|
|
166
|
+
</PmSyncedBlockFrame>
|
|
167
|
+
)
|
|
168
|
+
})
|
|
169
|
+
|
|
170
|
+
function sectionOfBlock(workbench: Workbench, source: { document: string, block: string }): { section?: string } {
|
|
171
|
+
const own = workbench.getState().authoring?.content
|
|
172
|
+
if (own?.id !== source.document) return {}
|
|
173
|
+
const section = Object.values(own.sections).find(item => item.children.includes(source.block))
|
|
174
|
+
return section ? { section: section.id } : {}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
type MentionItem = { kind: 'document', hit: MentionOption } | { kind: 'create', title: string }
|
|
178
|
+
|
|
179
|
+
function MentionMenu(props: SuggestionMenuProps<MentionItem> & { query: () => string }) {
|
|
180
|
+
const t = useTreeMessages()
|
|
181
|
+
const options = props.items.flatMap(item => item.kind === 'document' ? [item.hit] : [])
|
|
182
|
+
const create = props.items.find(item => item.kind === 'create')
|
|
183
|
+
const query = props.query()
|
|
184
|
+
return <PmMentionPicker heading={t.linkHeading(query)} options={options} active={props.selectedIndex ?? 0} hint={t.pickerHint} emptyLabel={t.searchEmpty}
|
|
185
|
+
loading={props.loadingState !== 'loaded'} loadingLabel={t.searching} listId="bn-suggestion-menu" optionId={index => `bn-suggestion-menu-item-${index}`}
|
|
186
|
+
createLabel={create ? t.createChildAndLink(create.title) : undefined}
|
|
187
|
+
onSelect={option => props.onItemClick?.(props.items.find(item => item.kind === 'document' && item.hit.id === option.id)!)}
|
|
188
|
+
onCreate={create ? () => props.onItemClick?.(create) : undefined} />
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function insertReference(editor: NativeDocumentEditor, document: string, title: string): void {
|
|
192
|
+
editor.insertInlineContent([{ type: 'presmiumReference', props: { document, section: '', block: '', label: '', fallback: title } }, ' '])
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Typing @ or [[ in the text opens the document picker: search as you type, the path to tell equal titles apart, and
|
|
197
|
+
* last "New Child Document … and Link", which creates the document under this one and links it without leaving the text.
|
|
198
|
+
*/
|
|
199
|
+
export function DocumentMentionMenus({ editor }: { editor: NativeDocumentEditor }) {
|
|
200
|
+
const workbench = useWorkbench()
|
|
201
|
+
const query = useRef('')
|
|
202
|
+
// Typing debounces the search and cancels the one in flight; a cancelled call answers the previous results.
|
|
203
|
+
const search = useRef<{ controller?: AbortController, items: MentionItem[] }>({ items: [] })
|
|
204
|
+
// Stable, so that the menu reads again only when the query changes, not when the editor around it renders.
|
|
205
|
+
const getItems = useCallback(async (text: string): Promise<MentionItem[]> => {
|
|
206
|
+
query.current = text
|
|
207
|
+
const own = workbench.getState().authoring?.content?.id
|
|
208
|
+
let hits: DocumentSearchHit[] = []
|
|
209
|
+
const trimmed = text.trim()
|
|
210
|
+
search.current.controller?.abort()
|
|
211
|
+
const controller = search.current.controller = new AbortController()
|
|
212
|
+
if (workbench.client.searchDocuments && trimmed) {
|
|
213
|
+
await new Promise(resolve => setTimeout(resolve, MENTION_DEBOUNCE))
|
|
214
|
+
if (controller.signal.aborted) return search.current.items
|
|
215
|
+
try { hits = await workbench.client.searchDocuments(trimmed, 8, controller.signal) } catch { return search.current.items }
|
|
216
|
+
} else {
|
|
217
|
+
const recent = workbench.getState().recentDocuments ?? []
|
|
218
|
+
hits = recent.filter(entry => entry.id !== own && workbench.tree.title(entry.id) !== undefined).slice(0, 6)
|
|
219
|
+
.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 }))
|
|
220
|
+
}
|
|
221
|
+
const seen = new Set<string>()
|
|
222
|
+
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 } }))
|
|
223
|
+
if (trimmed && own && workbench.client.operateTree && workbench.client.capabilities?.readOnly !== true) items.push({ kind: 'create', title: trimmed })
|
|
224
|
+
search.current.items = items
|
|
225
|
+
return items
|
|
226
|
+
}, [workbench])
|
|
227
|
+
const choose = useCallback(async (item: MentionItem) => {
|
|
228
|
+
if (item.kind === 'document') { insertReference(editor, item.hit.id, item.hit.title); return }
|
|
229
|
+
const own = workbench.getState().authoring?.content?.id
|
|
230
|
+
if (!own) return
|
|
231
|
+
const siblings = workbench.getState().documentTree?.nodes[own]?.children
|
|
232
|
+
const result = await workbench.tree.operate({ type: 'create', title: item.title, parent: own, after: siblings?.at(-1) ?? null })
|
|
233
|
+
if (result?.created) insertReference(editor, result.created, item.title)
|
|
234
|
+
}, [workbench, editor])
|
|
235
|
+
const click = useCallback((item: MentionItem) => void choose(item), [choose])
|
|
236
|
+
// Page titles are plain text: the picker opens only in the body, as the slash menu does.
|
|
237
|
+
const inText = useCallback(() => editor.getTextCursorPosition().block.type !== 'presmiumPage', [editor])
|
|
238
|
+
const menu = useMemo(() => (props: SuggestionMenuProps<MentionItem>) => <MentionMenu {...props} query={() => query.current} />, [])
|
|
239
|
+
return <>
|
|
240
|
+
<SuggestionMenuController<(query: string) => Promise<MentionItem[]>> triggerCharacter="@" shouldOpen={inText} getItems={getItems} suggestionMenuComponent={menu} onItemClick={click} />
|
|
241
|
+
<SuggestionMenuController<(query: string) => Promise<MentionItem[]>> triggerCharacter="[[" shouldOpen={inText} getItems={getItems} suggestionMenuComponent={menu} onItemClick={click} />
|
|
242
|
+
</>
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/** The slash menu's items: Link to Document, Synced Block and Child Document. */
|
|
246
|
+
export function referenceSlashItems(editor: NativeDocumentEditor, t: DocumentTreeMessages, group: string, workbench: Workbench, pickSynced: () => void): DefaultReactSuggestionItem[] {
|
|
247
|
+
if (!workbench.client.readTree) return []
|
|
248
|
+
const aliases = (value: string) => value.split('|')
|
|
249
|
+
const items: DefaultReactSuggestionItem[] = [
|
|
250
|
+
{ title: t.linkToDocument, subtext: t.linkToDocumentHint, group, aliases: aliases(t.linkAliases), icon: <PmIcon name="reference" />,
|
|
251
|
+
onItemClick: () => editor.getExtension(SuggestionMenuExtension)?.openSuggestionMenu('@') },
|
|
252
|
+
]
|
|
253
|
+
if (workbench.client.readEmbedSource) items.push({ title: t.syncedBlock, subtext: t.syncedBlockHint, group, aliases: aliases(t.syncedAliases), icon: <PmIcon name="synced" />, onItemClick: pickSynced })
|
|
254
|
+
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" />,
|
|
255
|
+
onItemClick: () => {
|
|
256
|
+
const own = workbench.getState().authoring?.content?.id
|
|
257
|
+
if (!own) return
|
|
258
|
+
const siblings = workbench.getState().documentTree?.nodes[own]?.children
|
|
259
|
+
void workbench.tree.operate({ type: 'create', title: t.untitled, parent: own, after: siblings?.at(-1) ?? null }).then(result => {
|
|
260
|
+
if (result?.created) insertReference(editor, result.created, t.untitled)
|
|
261
|
+
})
|
|
262
|
+
} })
|
|
263
|
+
return items
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Inserts a synced block after the block with the caret (in place of it when it is an empty paragraph). */
|
|
267
|
+
export function insertSyncedBlock(editor: NativeDocumentEditor, source: { document: string, block: string }): void {
|
|
268
|
+
const current = editor.getTextCursorPosition().block
|
|
269
|
+
const block = { type: 'presmiumEmbed' as const, props: source }
|
|
270
|
+
if (current.type === 'paragraph' && Array.isArray(current.content) && current.content.length === 0) editor.replaceBlocks([current], [block])
|
|
271
|
+
else editor.insertBlocks([block], current, 'after')
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function blockLabel(document: PresmiumDocument, id: string): string {
|
|
275
|
+
const block = document.blocks[id]
|
|
276
|
+
if (!block) return id
|
|
277
|
+
if (block.type === 'text') {
|
|
278
|
+
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()
|
|
279
|
+
return text.slice(0, 60) || id
|
|
280
|
+
}
|
|
281
|
+
if (block.type === 'component') return typeof block.parameters.title === 'string' ? block.parameters.title : document.definitions[block.definitionId]?.kind ?? id
|
|
282
|
+
if (block.type === 'image') return block.alt || id
|
|
283
|
+
if (block.type === 'code') return block.title ?? block.language
|
|
284
|
+
if (block.type === 'container') return block.properties.title ?? id
|
|
285
|
+
return id
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/** Insert Synced Block: choose a document, then one of its content blocks. */
|
|
289
|
+
export function SyncedBlockDialog({ onClose, onInsert }: { onClose(): void, onInsert(source: { document: string, block: string }): void }) {
|
|
290
|
+
const t = useTreeMessages()
|
|
291
|
+
const workbench = useWorkbench()
|
|
292
|
+
const tree = useWorkbenchState(state => state.documentTree)
|
|
293
|
+
const [query, setQuery] = useState('')
|
|
294
|
+
const [documentId, setDocumentId] = useState('')
|
|
295
|
+
const [content, setContent] = useState<PresmiumDocument | 'loading' | 'failed'>()
|
|
296
|
+
const [block, setBlock] = useState('')
|
|
297
|
+
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])
|
|
298
|
+
useEffect(() => {
|
|
299
|
+
if (!documentId) return
|
|
300
|
+
const dir = workbench.tree.dirOf(documentId)
|
|
301
|
+
if (dir === undefined) { setContent('failed'); return }
|
|
302
|
+
let active = true
|
|
303
|
+
setContent('loading'); setBlock('')
|
|
304
|
+
workbench.client.readDocument(dir).then(answer => { if (active) setContent(answer.content) }, () => { if (active) setContent('failed') })
|
|
305
|
+
return () => { active = false }
|
|
306
|
+
}, [workbench, documentId])
|
|
307
|
+
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 }))) : []
|
|
308
|
+
return (
|
|
309
|
+
<PmDialog open label={t.insertSynced} closeLabel={t.close} onClose={onClose}
|
|
310
|
+
footer={<><PmButton onClick={onClose}>{t.cancel}</PmButton><PmButton variant="primary" disabled={!documentId || !block} onClick={() => onInsert({ document: documentId, block })}>{t.insert}</PmButton></>}>
|
|
311
|
+
<div className="pm-document-editor__synced-picker">
|
|
312
|
+
<PmSearchList label={t.chooseDocument} searchLabel={t.searchField} searchPlaceholder={t.searchPlaceholder} items={documents} value={documentId} query={query} onQueryChange={setQuery}
|
|
313
|
+
onValueChange={setDocumentId} resultsLabel={t.searchResults} emptyLabel={t.searchEmpty} loadingLabel={t.treeLoading} loading={!tree} autoFocus />
|
|
314
|
+
{documentId && (content === 'loading' ? <PmSkeleton shape="list" label={t.syncedLoading} />
|
|
315
|
+
: content === 'failed' ? <PmNotice tone="danger">{t.syncedFailed}</PmNotice>
|
|
316
|
+
: blocks.length === 0 ? <p className="pmw-muted">{t.noBlocks}</p>
|
|
317
|
+
: <PmSearchList label={t.chooseBlock} searchLabel={t.chooseBlock} items={blocks} value={block} onValueChange={setBlock} onActivate={value => onInsert({ document: documentId, block: value })}
|
|
318
|
+
resultsLabel={t.searchResults} emptyLabel={t.noBlocks} loadingLabel={t.syncedLoading} />)}
|
|
319
|
+
</div>
|
|
320
|
+
</PmDialog>
|
|
321
|
+
)
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** The editor's reference tools: the @ and [[ pickers and Insert Synced Block, opened from the slash menu through `picker`. */
|
|
325
|
+
export function ReferenceEditorTools({ editor, picker }: { editor: NativeDocumentEditor, picker: { open?: (editor: NativeDocumentEditor) => void } }) {
|
|
326
|
+
const [picking, setPicking] = useState<NativeDocumentEditor>()
|
|
327
|
+
useEffect(() => { picker.open = setPicking; return () => { picker.open = undefined } }, [picker])
|
|
328
|
+
return <>
|
|
329
|
+
<DocumentMentionMenus editor={editor} />
|
|
330
|
+
{picking && <SyncedBlockDialog onClose={() => setPicking(undefined)} onInsert={source => { insertSyncedBlock(picking, source); setPicking(undefined) }} />}
|
|
331
|
+
</>
|
|
332
|
+
}
|
|
@@ -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
|