@lincyaw/workbench 0.2.0-rc.121 → 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.
@@ -0,0 +1,115 @@
1
+ import { useEffect, useState } from 'react'
2
+ import type { DocumentCitation, DocumentLinks, OutgoingLink } from '@lincyaw/kernel/contracts'
3
+ import { PmBacklinkItem, PmButton, PmIcon, PmNotice, PmSkeleton } from '../components.tsx'
4
+ import { useTreeMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
5
+
6
+ type Links = { state: 'loading' } | { state: 'failed' } | { state: 'unavailable' } | { state: 'ready', links: DocumentLinks }
7
+
8
+ /** The open document's links (`document/links`), read again when it is saved or the tree changes. */
9
+ export function useDocumentLinks(): { links: Links, retry(): void } {
10
+ const workbench = useWorkbench()
11
+ const id = useWorkbenchState(state => state.authoring?.content?.id)
12
+ const version = useWorkbenchState(state => state.authoring?.version)
13
+ const tree = useWorkbenchState(state => state.documentTree)
14
+ const [links, setLinks] = useState<Links>({ state: 'loading' })
15
+ const [attempt, setAttempt] = useState(0)
16
+ useEffect(() => {
17
+ if (!id) return
18
+ if (!workbench.client.readDocumentLinks) { setLinks({ state: 'unavailable' }); return }
19
+ const controller = new AbortController()
20
+ setLinks(current => current.state === 'ready' && current.links.document === id ? current : { state: 'loading' })
21
+ workbench.client.readDocumentLinks(id, controller.signal).then(answer => setLinks({ state: 'ready', links: answer }), () => { if (!controller.signal.aborted) setLinks({ state: 'failed' }) })
22
+ return () => controller.abort()
23
+ }, [workbench, id, version, tree, attempt])
24
+ return { links, retry: () => setAttempt(n => n + 1) }
25
+ }
26
+
27
+ /** The places one document cites this one, together, in the order the service gives them. */
28
+ function groupCitations(citations: readonly DocumentCitation[]): { document: string, title: string, citations: DocumentCitation[] }[] {
29
+ const groups = new Map<string, { document: string, title: string, citations: DocumentCitation[] }>()
30
+ for (const citation of citations) {
31
+ let group = groups.get(citation.document)
32
+ if (!group) groups.set(citation.document, group = { document: citation.document, title: citation.title, citations: [] })
33
+ group.citations.push(citation)
34
+ }
35
+ return [...groups.values()]
36
+ }
37
+
38
+ /** Several references to one target are one row with their count. */
39
+ function sameTargets(links: readonly OutgoingLink[]): { link: OutgoingLink, count: number }[] {
40
+ const rows = new Map<string, { link: OutgoingLink, count: number }>()
41
+ for (const link of links) {
42
+ const key = JSON.stringify([link.target.document, link.target.section ?? '', link.target.block ?? ''])
43
+ const row = rows.get(key)
44
+ if (row) row.count++
45
+ else rows.set(key, { link, count: 1 })
46
+ }
47
+ return [...rows.values()]
48
+ }
49
+
50
+ function OutgoingItem({ link, count }: { link: OutgoingLink, count: number }) {
51
+ const t = useTreeMessages()
52
+ const workbench = useWorkbench()
53
+ const gone = link.missing || link.trashed
54
+ return <li>
55
+ <button type="button" className="pm-ui-nav-item pmw-references__link" title={link.title} disabled={link.missing} aria-disabled={gone || undefined} onClick={() => void workbench.tree.openPlace(link.target)}>
56
+ <PmIcon name={link.kind === 'embed' ? 'synced' : 'document'} />
57
+ <span className="pmw-references__title">{link.title}</span>
58
+ {gone ? <span className="pm-ui-nav-item__count">{link.missing ? t.missingTarget : t.trashedTarget}</span> : count > 1 && <span className="pm-ui-nav-item__count">{t.placeCount(count)}</span>}
59
+ </button>
60
+ </li>
61
+ }
62
+
63
+ /** Who cites this document (with the sentence around it), what it references, and the synced blocks it shows. */
64
+ export function ReferencesPanel() {
65
+ return <ReferencesView read={useDocumentLinks()} />
66
+ }
67
+
68
+ function ReferencesView({ read }: { read: ReturnType<typeof useDocumentLinks> }) {
69
+ const t = useTreeMessages()
70
+ const workbench = useWorkbench()
71
+ const { links, retry } = read
72
+ if (links.state === 'loading') return <div className="pmw-references"><PmSkeleton shape="list" label={t.referencesLoading} /></div>
73
+ if (links.state === 'unavailable') return <div className="pmw-references"><p className="pmw-muted">{t.referencesUnavailable}</p></div>
74
+ if (links.state === 'failed') return <div className="pmw-references"><PmNotice tone="danger" action={<PmButton small onClick={retry}>{t.retry}</PmButton>}>{t.referencesFailed}</PmNotice></div>
75
+ const { incoming, outgoing } = links.links
76
+ const references = sameTargets(outgoing.filter(link => link.kind === 'reference'))
77
+ const synced = sameTargets(outgoing.filter(link => link.kind === 'embed'))
78
+ return (
79
+ <div className="pmw-references">
80
+ <section className="pmw-references__group" aria-labelledby="pmw-references-incoming">
81
+ <h3 className="pmw-references__heading" id="pmw-references-incoming">{t.citedBy} · {incoming.length}</h3>
82
+ {incoming.length ? <ul className="pmw-references__list">{groupCitations(incoming).map(group => (
83
+ <li key={group.document}>
84
+ <PmBacklinkItem title={group.title} count={group.citations.length > 1 ? t.placeCount(group.citations.length) : undefined} syncedLabel={t.syncedLabel}
85
+ places={group.citations.map((citation, index) => ({ id: String(index), excerpt: citation.excerpt, synced: citation.kind === 'embed',
86
+ meta: group.citations.length > 1 ? `${citation.kind === 'embed' ? t.syncedLabel : t.referenceLabel} · ${t.placeIndex(index + 1)}` : undefined }))}
87
+ onActivate={id => { const citation = group.citations[Number(id)]!; void workbench.tree.openPlace({ document: citation.document, ...citation.section ? { section: citation.section } : {}, block: citation.block }) }} />
88
+ </li>
89
+ ))}</ul> : <p className="pmw-muted">{t.noCitations}</p>}
90
+ </section>
91
+ <section className="pmw-references__group" aria-labelledby="pmw-references-outgoing">
92
+ <h3 className="pmw-references__heading" id="pmw-references-outgoing">{t.outgoing} · {references.length}</h3>
93
+ {references.length ? <ul className="pmw-references__links">{references.map(({ link, count }, index) => <OutgoingItem key={index} link={link} count={count} />)}</ul> : <p className="pmw-muted">{t.noOutgoing}</p>}
94
+ </section>
95
+ <section className="pmw-references__group" aria-labelledby="pmw-references-synced">
96
+ <h3 className="pmw-references__heading" id="pmw-references-synced">{t.syncedBlocks} · {synced.length}</h3>
97
+ {synced.length ? <ul className="pmw-references__links">{synced.map(({ link, count }, index) => <OutgoingItem key={index} link={link} count={count} />)}</ul> : <p className="pmw-muted">{t.noSynced}</p>}
98
+ </section>
99
+ </div>
100
+ )
101
+ }
102
+
103
+ /** On a narrow screen the references are one collapsed row at the end of the document. */
104
+ export function ReferencesSummary() {
105
+ const t = useTreeMessages()
106
+ const read = useDocumentLinks()
107
+ const links = read.links
108
+ if (links.state !== 'ready') return null
109
+ return (
110
+ <details className="pmw-references-summary">
111
+ <summary className="pmw-references-summary__row">{t.referencesSummary(links.links.incoming.length, links.links.outgoing.filter(link => link.kind === 'reference').length)}<PmIcon name="chevron-right" /></summary>
112
+ <ReferencesView read={read} />
113
+ </details>
114
+ )
115
+ }
@@ -1,7 +1,9 @@
1
1
  import { useEffect, useMemo, useRef } from 'react'
2
+ import type { ReactNode } from 'react'
2
3
  import { hasRole } from '@lincyaw/kernel'
3
4
  import { PmButton, PmNotice, PmSkeleton } from '../components.tsx'
4
- import { useMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
5
+ import { useMessages, useTreeMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
6
+ import { DocumentReference, insertSyncedBlock, parseSyncedLink, ReferenceEditorTools, referenceSlashItems, SyncedBlock } from '../document-editor/references.tsx'
5
7
  import { DocumentEditor } from '../document-editor/DocumentEditor.tsx'
6
8
  import { DOCUMENT_EDITOR_MESSAGES } from '../document-editor/messages.ts'
7
9
  import { DocumentBlockFallback } from '../document-editor/DocumentBlockFallback.tsx'
@@ -13,7 +15,7 @@ import { isAgentChanging } from '../workbench-state.ts'
13
15
  import { effectiveOf } from '../effective-settings.ts'
14
16
 
15
17
  /** Source editing is available before the first successful runtime compilation. */
16
- export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore, onOpenComments }: { commentsPortal?: HTMLElement | null, onCommentDraftRestore?(): void, onOpenComments?(): void }) {
18
+ export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore, onOpenComments, after }: { commentsPortal?: HTMLElement | null, onCommentDraftRestore?(): void, onOpenComments?(): void, /** Shown below the page (the references on a narrow screen). */ after?: ReactNode }) {
17
19
  const workbench = useWorkbench(), t = useMessages()
18
20
  const source = useWorkbenchState(state => state.authoring)
19
21
  const activities = useWorkbenchState(state => state.agentActivities)
@@ -25,6 +27,8 @@ export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore, onO
25
27
  }
26
28
  const positionFailure = useWorkbenchState(state => state.documentPositionFailure)
27
29
  const locale = useWorkbenchState(state => state.locale), messages = DOCUMENT_EDITOR_MESSAGES[locale]
30
+ const tt = useTreeMessages()
31
+ const syncedPicker = useMemo<{ open?: (editor: NativeDocumentEditor) => void }>(() => ({}), [])
28
32
  const navigation = useWorkbenchState(state => state.documentNavigation)
29
33
  const readOnly = useWorkbenchState(state => state.mode !== 'editing' || workbench.client.capabilities?.readOnly === true || Boolean(state.authoring?.member && !hasRole(state.authoring.member, 'editor')) || Boolean(state.authoring?.loading) || isAgentChanging(state))
30
34
  const container = useRef<HTMLElement>(null)
@@ -180,7 +184,20 @@ export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore, onO
180
184
  const effective = effectiveOf(source.content, source.inherited)
181
185
  const fallback = <DocumentBlockFallback block={block} document={effective} locale={locale} />
182
186
  return hasBlockPreview(block, effective.metadata.plugins) ? <DocumentBlockPreview blockId={id} fallback={fallback} /> : fallback
183
- } }}
187
+ },
188
+ renderReference: (target, label, fallback) => <DocumentReference document={target.document} section={target.section} block={target.block} label={label} fallback={fallback} />,
189
+ renderEmbed: (id, embed) => <SyncedBlock id={id} document={embed.document} block={embed.block} />,
190
+ ...workbench.tree.available ? {
191
+ slashItems: editor => readOnly ? [] : referenceSlashItems(editor, tt, tt.documents, workbench, () => syncedPicker.open?.(editor)),
192
+ editorChildren: editor => readOnly ? null : <ReferenceEditorTools editor={editor} picker={syncedPicker} />,
193
+ pasteText: (text, editor) => {
194
+ const source = parseSyncedLink(text)
195
+ if (!source || readOnly) return false
196
+ insertSyncedBlock(editor, source)
197
+ return true
198
+ },
199
+ copySyncedLink: link => { void navigator.clipboard.writeText(link).then(() => workbench.tree.toast(tt.linkCopied), () => workbench.tree.toast(tt.copyFailed, 'danger')) },
200
+ } : {} }}
184
201
  commentsPortal={commentsPortal} onChange={document => workbench.recordDocument(document)} onReady={(editor, commands) => {
185
202
  bodyEditor.current = editor
186
203
  editingPosition.current = undefined
@@ -195,5 +212,6 @@ export function SourceDocumentPanel({ commentsPortal, onCommentDraftRestore, onO
195
212
  }}
196
213
  onComposition={composing => workbench.documentComposition(composing, 'body', source.identity)} onError={() => workbench.documentError(new Error(messages.adapterError))} />
197
214
  </div>}
215
+ {source?.content && after}
198
216
  </section>
199
217
  }
@@ -0,0 +1,93 @@
1
+ import { useState } from 'react'
2
+ import type { ReactNode } from 'react'
3
+ import { PmButton, PmCard, PmIcon, PmNotice } from '../components.tsx'
4
+ import { useMessages, useTreeMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
5
+ import { IMPORT_MESSAGES } from '../import-messages.ts'
6
+ import { timeAgo } from '../messages.ts'
7
+ import { DocumentImportDialog } from './DocumentImportDialog.tsx'
8
+ import { SearchDialog } from './WorkspaceSidebar.tsx'
9
+
10
+ /**
11
+ * The workspace's home when it has a document tree: start a document (blank or imported), what needs attention, and
12
+ * the documents opened recently. The tree in the sidebar is the way to every other document.
13
+ */
14
+ export function WorkspaceHome({ actions }: { actions?: ReactNode }) {
15
+ const t = useMessages()
16
+ const tt = useTreeMessages()
17
+ const workbench = useWorkbench()
18
+ const answer = useWorkbenchState(state => state.documents)
19
+ const tree = useWorkbenchState(state => state.documentTree)!
20
+ const recent = useWorkbenchState(state => state.recentDocuments ?? [])
21
+ const locale = useWorkbenchState(state => state.locale)
22
+ const busy = useWorkbenchState(state => Boolean(state.isDocumentTreeBusy))
23
+ const failure = useWorkbenchState(state => state.documentsFailure)
24
+ const importMessages = IMPORT_MESSAGES[locale]
25
+ const [importing, setImporting] = useState(false)
26
+ const [searching, setSearching] = useState(false)
27
+ const [upgrading, setUpgrading] = useState(false)
28
+ const readOnly = workbench.client.capabilities?.readOnly === true
29
+ const canImport = Boolean(answer?.git && !answer.single && workbench.client.importDocuments && !readOnly)
30
+ const count = Object.keys(tree.nodes).length
31
+ const issues = Object.values(tree.nodes).filter(node => node.issues?.length)
32
+ const pending = answer?.migration?.documents.length ?? 0
33
+ const shown = recent.filter(entry => tree.nodes[entry.id]).slice(0, 8)
34
+ const create = () => void workbench.tree.create(null)
35
+ const upgrade = async () => {
36
+ setUpgrading(true)
37
+ try { workbench.tree.toast(tt.upgraded((await workbench.migrateWorkspace()).documents.length)) } catch { workbench.tree.toast(tt.operationFailed(tt.failureGeneric), 'danger') } finally { setUpgrading(false) }
38
+ }
39
+ return (
40
+ <section className="pmw-home pmw-workspace-home" aria-labelledby="pmw-home-title">
41
+ <header className="pmw-home__bar">
42
+ <h1 id="pmw-home-title" className="pmw-home__title">{answer?.title ?? t.documents}</h1>
43
+ {actions}
44
+ {canImport && <PmButton icon="upload" onClick={() => setImporting(true)}>{importMessages.title}</PmButton>}
45
+ {!readOnly && <PmButton variant="primary" icon="plus" loading={busy} onClick={create}>{tt.newDocument}</PmButton>}
46
+ </header>
47
+ <p className="pmw-muted pmw-workspace-home__meta">{tt.documentCount(count)}</p>
48
+ {failure && <PmNotice tone="danger">{failure}</PmNotice>}
49
+ {!readOnly && <ul className="pmw-workspace-home__start">
50
+ <li><PmCard variant="interactive">
51
+ <span className="pm-ui-card__icon"><PmIcon name="document" /></span>
52
+ <button type="button" className="pm-ui-card__cover" disabled={busy} onClick={create}>{tt.blankDocument}</button>
53
+ <p className="pm-ui-card__hint">{tt.blankDocumentHint}</p>
54
+ </PmCard></li>
55
+ {canImport && <li><PmCard variant="interactive">
56
+ <span className="pm-ui-card__icon"><PmIcon name="upload" /></span>
57
+ <button type="button" className="pm-ui-card__cover" onClick={() => setImporting(true)}>{importMessages.title}</button>
58
+ <p className="pm-ui-card__hint">{tt.importHint}</p>
59
+ </PmCard></li>}
60
+ </ul>}
61
+ {(pending > 0 || issues.length > 0) && <>
62
+ <h2 className="pmw-home__heading">{tt.needsAttention}</h2>
63
+ <div className="pmw-workspace-home__attention">
64
+ {pending > 0 && workbench.client.migrateWorkspace && <PmNotice tone="warn" action={<PmButton small loading={upgrading} onClick={() => void upgrade()}>{tt.upgrade}</PmButton>}>{tt.upgradePending(pending)}</PmNotice>}
65
+ {issues.length > 0 && <PmNotice tone="warn" action={<PmButton small onClick={() => void workbench.tree.openPlace({ document: issues[0]!.id })}>{tt.show}</PmButton>}>{tt.treeIssues(issues.length)}</PmNotice>}
66
+ </div>
67
+ </>}
68
+ <div className="pmw-home__heading-row">
69
+ <h2 className="pmw-home__heading">{tt.recent}</h2>
70
+ {count > 0 && <PmButton small variant="text" onClick={() => setSearching(true)}>{tt.searchTitle}</PmButton>}
71
+ </div>
72
+ {shown.length === 0
73
+ ? <p className="pmw-muted">{count === 0 && !pending ? tt.treeEmpty : tt.recentEmpty}</p>
74
+ : <ul className="pmw-home__cards" aria-label={tt.recent}>
75
+ {shown.map(entry => {
76
+ const node = tree.nodes[entry.id]!
77
+ return <li key={entry.id} className="pmw-home__card">
78
+ <button type="button" className="pmw-home__open" onClick={() => void workbench.tree.openPlace({ document: entry.id })}>
79
+ <span className="pmw-home__doc-icon" aria-hidden="true"><PmIcon name="document" /></span>
80
+ <span className="pmw-home__doc-title">{node.title || tt.untitled}</span>
81
+ <span className="pmw-workspace-home__path">{workbench.tree.ancestors(entry.id).map(item => item.title).join(' › ')}</span>
82
+ <span className="pmw-workspace-home__time">{timeAgo(entry.at, locale)}</span>
83
+ </button>
84
+ </li>
85
+ })}
86
+ </ul>}
87
+ {importing && <DocumentImportDialog onClose={() => setImporting(false)} onImported={result => {
88
+ setImporting(false); workbench.tree.toast(importMessages.done(result.documents.length, result.unresolved, result.warnings)); void workbench.tree.load()
89
+ }} />}
90
+ {searching && <SearchDialog onClose={() => setSearching(false)} onOpen={(id, section, block) => { setSearching(false); void workbench.tree.openPlace({ document: id, ...section ? { section } : {}, ...block ? { block } : {} }) }} />}
91
+ </section>
92
+ )
93
+ }
@@ -0,0 +1,331 @@
1
+ import { useEffect, useMemo, useRef, useState } from 'react'
2
+ import type { DocumentSearchHit, DocumentTree, TrashEntry } from '@lincyaw/kernel/contracts'
3
+ import { PmButton, PmDialog, PmDocTree, PmEmpty, PmIcon, PmIconButton, PmNotice, PmPopover, PmSearchList, PmSelect, PmSkeleton, PmToast } from '../components.tsx'
4
+ import type { DocTreeNode, MenuItem } from '../components.tsx'
5
+ import { useTreeMessages, useWorkbench, useWorkbenchState } from '../context.tsx'
6
+ import { timeAgo } from '../messages.ts'
7
+
8
+ /** Typing waits this long before it searches; the previous results stay while the next arrive. */
9
+ const SEARCH_DEBOUNCE = 100
10
+
11
+ export interface DocumentTreeView {
12
+ roots: string[]
13
+ nodes: Record<string, DocTreeNode>
14
+ /** The tree comes from the workspace's tree route and can be changed; otherwise it is read from the document list. */
15
+ editable: boolean
16
+ trash: TrashEntry[]
17
+ loading: boolean
18
+ failed: boolean
19
+ }
20
+
21
+ /** The tree to draw: the workspace's, or (on a host without one) the document list's parents. */
22
+ export function useDocumentTreeView(): DocumentTreeView {
23
+ const tree = useWorkbenchState(state => state.documentTree)
24
+ const failure = useWorkbenchState(state => state.documentTreeFailure)
25
+ const loading = useWorkbenchState(state => Boolean(state.isDocumentTreeLoading))
26
+ const documents = useWorkbenchState(state => state.documents)
27
+ const t = useTreeMessages()
28
+ return useMemo(() => {
29
+ if (tree) return { ...fromTree(tree, t.treeIssue), editable: true, trash: tree.trash, loading: false, failed: false }
30
+ const list = documents?.documents ?? []
31
+ const nodes: Record<string, DocTreeNode> = {}
32
+ const roots: string[] = []
33
+ for (const doc of list) nodes[doc.id ?? doc.dir] = { id: doc.id ?? doc.dir, title: doc.title, children: [] }
34
+ for (const doc of list) {
35
+ const id = doc.id ?? doc.dir
36
+ const parent = doc.parent ? nodes[doc.parent] : undefined
37
+ if (parent) (parent.children as string[]).push(id); else roots.push(id)
38
+ }
39
+ return { roots, nodes, editable: false, trash: [], loading: loading || (!documents && !failure), failed: Boolean(failure && failure !== 'tree-unavailable' && !documents) }
40
+ }, [tree, documents, failure, loading, t])
41
+ }
42
+
43
+ function fromTree(tree: DocumentTree, issue: string): { roots: string[], nodes: Record<string, DocTreeNode> } {
44
+ const nodes: Record<string, DocTreeNode> = {}
45
+ for (const node of Object.values(tree.nodes)) nodes[node.id] = { id: node.id, title: node.title, children: node.children, ...node.issues?.length ? { warning: issue } : {} }
46
+ return { roots: tree.roots, nodes }
47
+ }
48
+
49
+ /**
50
+ * The workspace's sidebar: its name, search (Ctrl+K), Home, Recent, the document tree with New Document, and the
51
+ * trash. `onNavigate` closes a drawer that holds it.
52
+ */
53
+ export function WorkspaceSidebar({ onHome, onNavigate, closeLabel, onClose }: { onHome(): void, onNavigate?(): void, closeLabel?: string, onClose?(): void }) {
54
+ const t = useTreeMessages()
55
+ const workbench = useWorkbench()
56
+ const view = useDocumentTreeView()
57
+ const title = useWorkbenchState(state => state.documents?.title)
58
+ const open = useWorkbenchState(state => state.document)
59
+ const renaming = useWorkbenchState(state => state.renamingDocument)
60
+ const busy = useWorkbenchState(state => Boolean(state.isDocumentTreeBusy))
61
+ const readOnly = workbench.client.capabilities?.readOnly === true
62
+ const atHome = open === undefined
63
+ const selected = workbench.tree.idOf(open)
64
+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set())
65
+ const [searching, setSearching] = useState(false)
66
+ const [trashOpen, setTrashOpen] = useState(false)
67
+ const [moving, setMoving] = useState<string>()
68
+ const [recentOpen, setRecentOpen] = useState(false)
69
+ const editable = view.editable && !readOnly
70
+ const labels = useMemo(() => ({ expand: t.expand, collapse: t.collapse, newChild: t.newChildIn, more: t.more, renameField: t.renameField, untitled: t.untitled }), [t])
71
+ const count = Object.keys(view.nodes).length
72
+
73
+ useEffect(() => {
74
+ const key = (event: KeyboardEvent) => {
75
+ if (event.defaultPrevented || event.isComposing || !(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey || event.key.toLowerCase() !== 'k') return
76
+ event.preventDefault()
77
+ setSearching(true)
78
+ }
79
+ window.addEventListener('keydown', key)
80
+ return () => window.removeEventListener('keydown', key)
81
+ }, [])
82
+
83
+ const openDocument = (id: string) => { void workbench.tree.openPlace({ document: id }); onNavigate?.() }
84
+ const menu = (id: string): MenuItem[] => [
85
+ { id: 'rename', label: t.rename, icon: 'edit', disabled: busy },
86
+ { id: 'child', label: t.newChild, icon: 'document-add', disabled: busy },
87
+ { id: 'duplicate', label: t.duplicate, icon: 'copy', disabled: busy },
88
+ { id: 'move', label: t.moveTo, icon: 'move', disabled: busy || count < 2 },
89
+ { id: 'trash', label: t.moveToTrash, icon: 'trash', danger: true, separator: true, disabled: busy },
90
+ ]
91
+ const onMenu = (id: string, action: string) => {
92
+ if (action === 'rename') workbench.tree.startRenaming(id)
93
+ else if (action === 'child') void createChild(id)
94
+ else if (action === 'duplicate') void workbench.tree.duplicate(id)
95
+ else if (action === 'move') setMoving(id)
96
+ else if (action === 'trash') void workbench.tree.trash(id)
97
+ }
98
+ const createChild = async (parent: string | null) => {
99
+ if (parent) setExpanded(current => new Set(current).add(parent))
100
+ await workbench.tree.create(parent)
101
+ onNavigate?.()
102
+ }
103
+
104
+ return (
105
+ <nav className="pmw-sidebar" aria-label={t.sidebar}>
106
+ <header className="pmw-sidebar__header">
107
+ <span className="pmw-sidebar__mark" aria-hidden="true">{(title ?? '').trim().slice(0, 1) || <PmIcon name="folder" />}</span>
108
+ <span className="pmw-sidebar__workspace">
109
+ <span className="pmw-sidebar__name" title={title}>{title ?? ''}</span>
110
+ <span className="pmw-sidebar__meta">{t.documentCount(count)}</span>
111
+ </span>
112
+ {onClose && closeLabel && <PmIconButton icon="close" small label={closeLabel} onClick={onClose} />}
113
+ </header>
114
+ <button type="button" className="pm-ui-search-trigger pmw-sidebar__search" onClick={() => setSearching(true)}>
115
+ <PmIcon name="search" /><span className="pm-ui-search-trigger__label">{t.search}</span><kbd className="pm-ui-shortcut">{t.searchShortcut}</kbd>
116
+ </button>
117
+ <ul className="pmw-sidebar__places">
118
+ <li><button type="button" className="pm-ui-nav-item" aria-current={atHome ? 'page' : undefined} onClick={() => { onHome(); onNavigate?.() }}><PmIcon name="home" />{t.home}</button></li>
119
+ <li>
120
+ <PmPopover open={recentOpen} label={t.recent} placement="below-start" onOpenChange={setRecentOpen}
121
+ trigger={<button type="button" className="pm-ui-nav-item" aria-expanded={recentOpen}><PmIcon name="recent" />{t.recent}</button>}>
122
+ <RecentList onOpen={id => { setRecentOpen(false); openDocument(id) }} />
123
+ </PmPopover>
124
+ </li>
125
+ </ul>
126
+ <div className="pmw-sidebar__section">
127
+ <h2 className="pmw-sidebar__heading" id="pmw-sidebar-tree">{t.documents}</h2>
128
+ {editable && <PmIconButton icon="plus" small label={t.newDocument} loading={busy} onClick={() => void createChild(null)} />}
129
+ </div>
130
+ <div className="pmw-sidebar__tree">
131
+ {view.loading ? <PmSkeleton shape="list" label={t.treeLoading} />
132
+ : view.failed ? <PmNotice tone="danger" action={<PmButton small onClick={() => void workbench.loadDocuments()}>{t.retry}</PmButton>}>{t.treeFailed}</PmNotice>
133
+ : view.roots.length === 0 ? <MigrationOrEmpty />
134
+ : <PmDocTree
135
+ label={t.tree}
136
+ roots={view.roots}
137
+ nodes={view.nodes}
138
+ selected={selected}
139
+ expanded={expanded}
140
+ onExpandedChange={(id, next) => setExpanded(current => { const value = new Set(current); if (next) value.add(id); else value.delete(id); return value })}
141
+ onOpen={openDocument}
142
+ labels={labels}
143
+ renaming={renaming}
144
+ onRenamingChange={id => workbench.tree.startRenaming(id)}
145
+ disabled={!editable}
146
+ {...editable ? {
147
+ onRename: (id: string, value: string) => void workbench.tree.rename(id, value),
148
+ onCreateChild: (id: string) => void createChild(id),
149
+ onTrash: (id: string) => void workbench.tree.trash(id),
150
+ onMove: (id: string, parent: string | null, after: string | null) => void workbench.tree.move(id, parent, after),
151
+ menu, onMenu,
152
+ } : {}}
153
+ />}
154
+ </div>
155
+ {view.editable && <button type="button" className="pm-ui-nav-item pmw-sidebar__trash" onClick={() => setTrashOpen(true)}>
156
+ <PmIcon name="trash" />{t.trash}{view.trash.length > 0 && <span className="pm-ui-nav-item__count">{view.trash.length}</span>}
157
+ </button>}
158
+ {searching && <SearchDialog onClose={() => setSearching(false)} onOpen={(id, section, block) => { setSearching(false); void workbench.tree.openPlace({ document: id, ...section ? { section } : {}, ...block ? { block } : {} }); onNavigate?.() }} />}
159
+ {trashOpen && <TrashDialog entries={view.trash} onClose={() => setTrashOpen(false)} />}
160
+ {moving && <MoveDialog id={moving} view={view} onClose={() => setMoving(undefined)} />}
161
+ </nav>
162
+ )
163
+ }
164
+
165
+ /** While documents wait for the upgrade the list is not empty: it says how many and offers Upgrade. */
166
+ function MigrationOrEmpty() {
167
+ const t = useTreeMessages()
168
+ const workbench = useWorkbench()
169
+ const migration = useWorkbenchState(state => state.documents?.migration)
170
+ const [working, setWorking] = useState(false)
171
+ if (migration?.documents.length && workbench.client.migrateWorkspace) return <PmNotice tone="warn" action={<PmButton small loading={working} onClick={async () => {
172
+ setWorking(true)
173
+ try { const answer = await workbench.migrateWorkspace(); workbench.tree.toast(t.upgraded(answer.documents.length)) } catch { workbench.tree.toast(t.operationFailed(t.failureGeneric), 'danger') } finally { setWorking(false) }
174
+ }}>{t.upgrade}</PmButton>}>{t.upgradePending(migration.documents.length)}</PmNotice>
175
+ return <p className="pmw-muted pmw-sidebar__empty">{t.treeEmpty}</p>
176
+ }
177
+
178
+ export function RecentList({ onOpen }: { onOpen(id: string): void }) {
179
+ const t = useTreeMessages()
180
+ const workbench = useWorkbench()
181
+ const recent = useWorkbenchState(state => state.recentDocuments ?? [])
182
+ const locale = useWorkbenchState(state => state.locale)
183
+ useWorkbenchState(state => state.documentTree)
184
+ const known = recent.filter(entry => workbench.tree.title(entry.id) !== undefined)
185
+ if (!known.length) return <p className="pmw-muted pmw-recent__empty">{t.recentEmpty}</p>
186
+ return <ul className="pmw-recent">{known.map(entry => (
187
+ <li key={entry.id}><button type="button" className="pm-ui-nav-item pmw-recent__item" onClick={() => onOpen(entry.id)}>
188
+ <PmIcon name="document" /><span className="pmw-recent__title" title={workbench.tree.title(entry.id)}>{workbench.tree.title(entry.id)}</span>
189
+ <span className="pmw-recent__path">{workbench.tree.ancestors(entry.id).map(item => item.title).join(' › ')}</span>
190
+ <span className="pmw-recent__time">{timeAgo(entry.at, locale)}</span>
191
+ </button></li>
192
+ ))}</ul>
193
+ }
194
+
195
+ /** Search across the workspace's titles and text (`documents/search`); Enter opens the result at its place. */
196
+ export function SearchDialog({ onClose, onOpen }: { onClose(): void, onOpen(id: string, section?: string, block?: string): void }) {
197
+ const t = useTreeMessages()
198
+ const workbench = useWorkbench()
199
+ const [query, setQuery] = useState('')
200
+ const [hits, setHits] = useState<DocumentSearchHit[]>([])
201
+ const [loading, setLoading] = useState(false)
202
+ const [failed, setFailed] = useState(false)
203
+ const [value, setValue] = useState('')
204
+ useEffect(() => {
205
+ const text = query.trim()
206
+ if (!text || !workbench.client.searchDocuments) { setHits([]); setLoading(false); return }
207
+ const controller = new AbortController()
208
+ setLoading(true); setFailed(false)
209
+ const timer = setTimeout(() => {
210
+ workbench.client.searchDocuments!(text, 20, controller.signal).then(answer => { setHits(answer); setValue(answer[0] ? key(answer[0]) : '') }, () => { if (!controller.signal.aborted) setFailed(true) })
211
+ .finally(() => { if (!controller.signal.aborted) setLoading(false) })
212
+ }, SEARCH_DEBOUNCE)
213
+ return () => { clearTimeout(timer); controller.abort() }
214
+ }, [query, workbench])
215
+ const key = (hit: DocumentSearchHit) => `${hit.id}\0${hit.section ?? ''}\0${hit.block ?? ''}`
216
+ const items = hits.map(hit => ({ value: key(hit), label: hit.title, icon: 'document' as const,
217
+ description: [hit.ancestors.join(' › '), hit.match === 'content' && hit.excerpt ? t.contentMatch(hit.excerpt) : ''].filter(Boolean).join(' · ') }))
218
+ const activate = (selected: string) => {
219
+ const hit = hits.find(item => key(item) === selected)
220
+ if (hit) onOpen(hit.id, hit.section, hit.block)
221
+ }
222
+ return (
223
+ <PmDialog open label={t.searchTitle} closeLabel={t.close} name="pmw-search" onClose={onClose}>
224
+ <PmSearchList label={t.documents} searchLabel={t.searchField} searchPlaceholder={t.searchPlaceholder} items={items} value={value} filter={false}
225
+ query={query} onQueryChange={setQuery} onValueChange={setValue} onActivate={activate} autoFocus
226
+ resultsLabel={t.searchResults} emptyLabel={query.trim() ? t.searchEmpty : ''} loadingLabel={t.searching} loading={loading} error={failed ? t.searchFailed : undefined} />
227
+ </PmDialog>
228
+ )
229
+ }
230
+
231
+ /** The trash: restore a document (with its children) or delete it permanently after a warning. */
232
+ function TrashDialog({ entries, onClose }: { entries: TrashEntry[], onClose(): void }) {
233
+ const t = useTreeMessages()
234
+ const workbench = useWorkbench()
235
+ const locale = useWorkbenchState(state => state.locale)
236
+ const busy = useWorkbenchState(state => Boolean(state.isDocumentTreeBusy))
237
+ const [purging, setPurging] = useState<TrashEntry>()
238
+ const readOnly = workbench.client.capabilities?.readOnly === true
239
+ return (
240
+ <PmDialog open label={t.trashTitle} closeLabel={t.close} name="pmw-trash" description={t.trashHint} busy={busy} onClose={onClose}>
241
+ {entries.length === 0 ? <PmEmpty icon="trash" title={t.trashEmpty} />
242
+ : <ul className="pmw-trash">{entries.map(entry => (
243
+ <li key={entry.id} className="pmw-trash__item">
244
+ <PmIcon name="document" />
245
+ <span className="pmw-trash__text">
246
+ <span className="pmw-trash__title">{entry.title}</span>
247
+ <span className="pmw-trash__meta">{[t.deletedAt(timeAgo(entry.deletedAt, locale)), entry.children.length ? t.childCount(entry.children.length) : ''].filter(Boolean).join(' · ')}</span>
248
+ </span>
249
+ <PmButton small icon="restore" disabled={busy || readOnly} onClick={async () => { await workbench.tree.restore(entry.id); workbench.tree.toast(t.restored(entry.title)) }}>{t.restore}</PmButton>
250
+ <PmButton small variant="text" disabled={busy || readOnly} onClick={() => setPurging(entry)}>{t.deletePermanently}</PmButton>
251
+ </li>
252
+ ))}</ul>}
253
+ {purging && <PmDialog open label={t.deletePermanentlyTitle} closeLabel={t.close} busy={busy} onClose={() => setPurging(undefined)}
254
+ footer={<>
255
+ <PmButton disabled={busy} onClick={() => setPurging(undefined)}>{t.cancel}</PmButton>
256
+ <PmButton variant="danger" loading={busy} onClick={async () => { if (await workbench.tree.purge(purging.id)) setPurging(undefined) }}>{t.deleteAction}</PmButton>
257
+ </>}>
258
+ <p>{t.deleteConfirm(purging.title)}</p>
259
+ <PmNotice tone="warn">{t.deleteSynced}</PmNotice>
260
+ </PmDialog>}
261
+ </PmDialog>
262
+ )
263
+ }
264
+
265
+ /** Move To…: choose the new parent; the document goes last among its children. */
266
+ function MoveDialog({ id, view, onClose }: { id: string, view: DocumentTreeView, onClose(): void }) {
267
+ const t = useTreeMessages()
268
+ const workbench = useWorkbench()
269
+ const busy = useWorkbenchState(state => Boolean(state.isDocumentTreeBusy))
270
+ const node = view.nodes[id]
271
+ const parentOf = (child: string) => Object.values(view.nodes).find(item => item.children.includes(child))?.id ?? ''
272
+ const [target, setTarget] = useState(parentOf(id))
273
+ const choices = useMemo(() => {
274
+ const list: { id: string, label: string }[] = []
275
+ const visit = (ids: readonly string[], depth: number) => ids.forEach(child => {
276
+ if (child === id) return
277
+ const item = view.nodes[child]
278
+ if (!item) return
279
+ list.push({ id: child, label: `${' '.repeat(depth)}${item.title || t.untitled}` })
280
+ visit(item.children, depth + 1)
281
+ })
282
+ visit(view.roots, 0)
283
+ return list
284
+ }, [view, id, t])
285
+ const select = useRef<HTMLSelectElement>(null)
286
+ if (!node) return null
287
+ return (
288
+ <PmDialog open label={t.moveTitle(node.title)} closeLabel={t.close} busy={busy} onClose={onClose}
289
+ footer={<>
290
+ <PmButton disabled={busy} onClick={onClose}>{t.cancel}</PmButton>
291
+ <PmButton variant="primary" loading={busy} onClick={async () => {
292
+ const parent = target || null
293
+ const siblings = (parent ? view.nodes[parent]?.children ?? [] : view.roots).filter(child => child !== id)
294
+ await workbench.tree.move(id, parent, siblings.at(-1) ?? null)
295
+ onClose()
296
+ }}>{t.move}</PmButton>
297
+ </>}>
298
+ <PmSelect ref={select} label={t.moveTarget} density="regular" value={target} onChange={event => setTarget(event.target.value)}>
299
+ <option value="">{t.topLevel}</option>
300
+ {choices.map(choice => <option key={choice.id} value={choice.id}>{choice.label}</option>)}
301
+ </PmSelect>
302
+ </PmDialog>
303
+ )
304
+ }
305
+
306
+ /** The open document's ancestors in the app bar, each one a way to open it (items of the bar's place list). */
307
+ export function DocumentBreadcrumb({ compact }: { compact?: boolean }) {
308
+ const t = useTreeMessages()
309
+ const workbench = useWorkbench()
310
+ const open = useWorkbenchState(state => state.document)
311
+ useWorkbenchState(state => state.documentTree)
312
+ useWorkbenchState(state => state.documents)
313
+ const id = workbench.tree.idOf(open)
314
+ const trail = id ? workbench.tree.ancestors(id) : []
315
+ const shown = compact ? trail.slice(-1) : trail
316
+ return <>{shown.map(item => (
317
+ <li key={item.id} className="pmw-appbar__ancestor">
318
+ <button type="button" className="pmw-appbar__place" title={item.title} aria-label={`${t.location}: ${item.title}`} onClick={() => void workbench.tree.openPlace({ document: item.id })}>
319
+ <span className="pmw-appbar__label">{item.title}</span>
320
+ </button>
321
+ </li>
322
+ ))}</>
323
+ }
324
+
325
+ /** The workbench's one toast (what a tree operation did, with Undo). */
326
+ export function WorkbenchToast() {
327
+ const t = useTreeMessages()
328
+ const workbench = useWorkbench()
329
+ const toast = useWorkbenchState(state => state.toast)
330
+ return <PmToast toast={toast} closeLabel={t.close} onClose={workbench.tree.closeToast} />
331
+ }
package/src/styles.css CHANGED
@@ -4,6 +4,7 @@
4
4
  @import './step-production.css';
5
5
  @import './component-properties.css';
6
6
  @import './caption-timing.css';
7
+ @import './knowledge.css';
7
8
 
8
9
  .pmw-preview__frames[data-pending-snapshot]:not([data-presentation-gated]) { visibility: hidden; }
9
10