@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.
- 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,547 @@
|
|
|
1
|
+
import * as Popover from '@radix-ui/react-popover'
|
|
2
|
+
import { cloneElement, forwardRef, memo, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react'
|
|
3
|
+
import type { DragEvent, KeyboardEvent, ReactElement, ReactNode } from 'react'
|
|
4
|
+
import { PmButton, PmIcon, PmIconButton } from './base-controls.tsx'
|
|
5
|
+
import type { MenuItem } from './components.tsx'
|
|
6
|
+
import { PmMenu } from './components.tsx'
|
|
7
|
+
|
|
8
|
+
const cls = (...names: (string | false | undefined | null)[]) => names.filter(Boolean).join(' ')
|
|
9
|
+
|
|
10
|
+
// The hover timing of the shared tooltip (docs/design-system.md 4.3): a preview opens after a rest, and stays while the
|
|
11
|
+
// pointer crosses the gap to it.
|
|
12
|
+
const PREVIEW_OPEN_DELAY = 500
|
|
13
|
+
const PREVIEW_CLOSE_DELAY = 300
|
|
14
|
+
const TOAST_DURATION = 4000
|
|
15
|
+
// Above this many visible rows the tree draws only those in view, with this many more on each side.
|
|
16
|
+
const VIRTUAL_ROWS = 200
|
|
17
|
+
const VIRTUAL_MARGIN = 12
|
|
18
|
+
|
|
19
|
+
export interface DocTreeNode { id: string, title: string, children: readonly string[], warning?: string }
|
|
20
|
+
export type DocTreeDrop = 'before' | 'inside' | 'after'
|
|
21
|
+
export interface DocTreeLabels {
|
|
22
|
+
expand(title: string): string
|
|
23
|
+
collapse(title: string): string
|
|
24
|
+
newChild(title: string): string
|
|
25
|
+
more(title: string): string
|
|
26
|
+
renameField: string
|
|
27
|
+
untitled: string
|
|
28
|
+
}
|
|
29
|
+
export interface DocTreeProps {
|
|
30
|
+
label: string
|
|
31
|
+
roots: readonly string[]
|
|
32
|
+
nodes: Readonly<Record<string, DocTreeNode>>
|
|
33
|
+
/** The open document: its row is selected. */
|
|
34
|
+
selected?: string
|
|
35
|
+
expanded: ReadonlySet<string>
|
|
36
|
+
onExpandedChange(id: string, open: boolean): void
|
|
37
|
+
onOpen(id: string): void
|
|
38
|
+
labels: DocTreeLabels
|
|
39
|
+
/** The row whose title is an input now (after F2, a double click, or creating it). */
|
|
40
|
+
renaming?: string
|
|
41
|
+
onRenamingChange(id: string | undefined): void
|
|
42
|
+
onRename?(id: string, title: string): void
|
|
43
|
+
onCreateChild?(id: string): void
|
|
44
|
+
onTrash?(id: string): void
|
|
45
|
+
/** `after`: the sibling the moved document follows; null to be the first of `parent`'s children. */
|
|
46
|
+
onMove?(id: string, parent: string | null, after: string | null): void
|
|
47
|
+
menu?(id: string): MenuItem[]
|
|
48
|
+
onMenu?(id: string, action: string): void
|
|
49
|
+
disabled?: boolean
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
interface Row { id: string, depth: number, parent: string | null, index: number, siblings: readonly string[] }
|
|
53
|
+
|
|
54
|
+
function visibleRows(roots: readonly string[], nodes: DocTreeProps['nodes'], expanded: ReadonlySet<string>): Row[] {
|
|
55
|
+
const rows: Row[] = []
|
|
56
|
+
const visit = (ids: readonly string[], depth: number, parent: string | null) => ids.forEach((id, index) => {
|
|
57
|
+
const node = nodes[id]
|
|
58
|
+
if (!node) return
|
|
59
|
+
rows.push({ id, depth, parent, index, siblings: ids })
|
|
60
|
+
if (node.children.length && expanded.has(id)) visit(node.children, depth + 1, id)
|
|
61
|
+
})
|
|
62
|
+
visit(roots, 0, null)
|
|
63
|
+
return rows
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isWithin(nodes: DocTreeProps['nodes'], ancestor: string, id: string): boolean {
|
|
67
|
+
if (ancestor === id) return true
|
|
68
|
+
return (nodes[ancestor]?.children ?? []).some(child => isWithin(nodes, child, id))
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The workspace's documents as a tree (WAI-ARIA tree view): one tab stop that the arrow keys move, Home and End,
|
|
73
|
+
* typing a title's first letters, * to expand the row's siblings, Enter to open, F2 to rename and Delete to move to the
|
|
74
|
+
* trash. A row can be dragged before, into or after another; the target row shows where it will land. Above 200 visible
|
|
75
|
+
* rows only those in view are drawn.
|
|
76
|
+
*/
|
|
77
|
+
export function PmDocTree(props: DocTreeProps) {
|
|
78
|
+
const { label, roots, nodes, selected, expanded, onExpandedChange, renaming, onRenamingChange, onMove, disabled } = props
|
|
79
|
+
// Rows keep their identity while their place is unchanged, so that expanding one node renders only the new rows.
|
|
80
|
+
const rowCache = useRef(new Map<string, Row>())
|
|
81
|
+
const rows = useMemo(() => visibleRows(roots, nodes, expanded).map(row => {
|
|
82
|
+
const old = rowCache.current.get(row.id)
|
|
83
|
+
if (old && old.depth === row.depth && old.parent === row.parent && old.index === row.index && old.siblings === row.siblings) return old
|
|
84
|
+
rowCache.current.set(row.id, row)
|
|
85
|
+
return row
|
|
86
|
+
}), [roots, nodes, expanded])
|
|
87
|
+
const [focused, setFocused] = useState<string>()
|
|
88
|
+
const [dragging, setDragging] = useState<string>()
|
|
89
|
+
const [drop, setDrop] = useState<{ id: string, at: DocTreeDrop }>()
|
|
90
|
+
const container = useRef<HTMLDivElement>(null)
|
|
91
|
+
const items = useRef(new Map<string, HTMLDivElement>())
|
|
92
|
+
const typed = useRef({ text: '', at: 0 })
|
|
93
|
+
const pendingFocus = useRef<string>()
|
|
94
|
+
const current = focused && rows.some(row => row.id === focused) ? focused : selected && rows.some(row => row.id === selected) ? selected : rows[0]?.id
|
|
95
|
+
|
|
96
|
+
// Windowing: above VIRTUAL_ROWS visible rows only the rows in view (and a margin) are in the DOM.
|
|
97
|
+
const virtual = rows.length > VIRTUAL_ROWS
|
|
98
|
+
const [rowHeight, setRowHeight] = useState(0)
|
|
99
|
+
const [view, setView] = useState({ top: 0, height: 0 })
|
|
100
|
+
useLayoutEffect(() => {
|
|
101
|
+
const element = container.current
|
|
102
|
+
if (!element || !virtual) return
|
|
103
|
+
const first = element.querySelector<HTMLElement>('[role="treeitem"]')
|
|
104
|
+
if (first) setRowHeight(first.getBoundingClientRect().height + parseFloat(getComputedStyle(element).rowGap || '0'))
|
|
105
|
+
const measure = () => setView(before => before.top === element.scrollTop && before.height === element.clientHeight ? before : { top: element.scrollTop, height: element.clientHeight })
|
|
106
|
+
measure()
|
|
107
|
+
let frame: number | undefined
|
|
108
|
+
const scrolled = () => { frame ??= requestAnimationFrame(() => { frame = undefined; measure() }) }
|
|
109
|
+
element.addEventListener('scroll', scrolled, { passive: true })
|
|
110
|
+
const observer = new ResizeObserver(measure)
|
|
111
|
+
observer.observe(element)
|
|
112
|
+
return () => { element.removeEventListener('scroll', scrolled); observer.disconnect(); if (frame !== undefined) cancelAnimationFrame(frame) }
|
|
113
|
+
}, [virtual])
|
|
114
|
+
const step = rowHeight || 1
|
|
115
|
+
const from = virtual && rowHeight ? Math.max(0, Math.floor(view.top / step) - VIRTUAL_MARGIN) : 0
|
|
116
|
+
const to = virtual && rowHeight ? Math.min(rows.length, Math.ceil((view.top + view.height) / step) + VIRTUAL_MARGIN) : virtual ? Math.min(rows.length, VIRTUAL_ROWS) : rows.length
|
|
117
|
+
|
|
118
|
+
// Opening the selected document reveals it: its ancestors expand.
|
|
119
|
+
useEffect(() => {
|
|
120
|
+
if (!selected) return
|
|
121
|
+
const parents: string[] = []
|
|
122
|
+
const find = (ids: readonly string[], trail: string[]): boolean => ids.some(id => id === selected ? (parents.push(...trail), true) : find(nodes[id]?.children ?? [], [...trail, id]))
|
|
123
|
+
find(roots, [])
|
|
124
|
+
for (const id of parents) if (!expanded.has(id)) onExpandedChange(id, true)
|
|
125
|
+
}, [selected, nodes, roots])
|
|
126
|
+
|
|
127
|
+
useEffect(() => {
|
|
128
|
+
const id = pendingFocus.current
|
|
129
|
+
if (!id) return
|
|
130
|
+
const element = items.current.get(id)
|
|
131
|
+
if (element) { pendingFocus.current = undefined; element.focus() }
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
const latest = useRef({ props, rows, drop, dragging })
|
|
135
|
+
latest.current = { props, rows, drop, dragging }
|
|
136
|
+
const focus = useCallback((id: string | undefined) => {
|
|
137
|
+
if (!id) return
|
|
138
|
+
setFocused(id)
|
|
139
|
+
const element = items.current.get(id)
|
|
140
|
+
if (element) { element.focus(); return }
|
|
141
|
+
// A row outside the window: scroll it in, then focus it once it is drawn.
|
|
142
|
+
const index = latest.current.rows.findIndex(row => row.id === id)
|
|
143
|
+
if (container.current && index >= 0) container.current.scrollTop = Math.max(0, index * step - container.current.clientHeight / 2)
|
|
144
|
+
pendingFocus.current = id
|
|
145
|
+
}, [step])
|
|
146
|
+
|
|
147
|
+
const handlers = useMemo<RowHandlers>(() => ({
|
|
148
|
+
register: (id, element) => { if (element) items.current.set(id, element); else items.current.delete(id) },
|
|
149
|
+
focused: id => setFocused(id),
|
|
150
|
+
open: id => latest.current.props.onOpen(id),
|
|
151
|
+
toggle: (id, open) => latest.current.props.onExpandedChange(id, open),
|
|
152
|
+
rename: id => { const p = latest.current.props; if (p.onRename && !p.disabled) p.onRenamingChange(id) },
|
|
153
|
+
finishRename: (id, value) => {
|
|
154
|
+
const p = latest.current.props
|
|
155
|
+
p.onRenamingChange(undefined)
|
|
156
|
+
const title = p.nodes[id]?.title
|
|
157
|
+
if (value !== undefined && value.trim() && value.trim() !== title) p.onRename?.(id, value.trim())
|
|
158
|
+
items.current.get(id)?.focus()
|
|
159
|
+
},
|
|
160
|
+
createChild: id => latest.current.props.onCreateChild?.(id),
|
|
161
|
+
menu: id => latest.current.props.menu?.(id) ?? [],
|
|
162
|
+
menuSelect: (id, action) => latest.current.props.onMenu?.(id, action),
|
|
163
|
+
keyDown: (event, row) => {
|
|
164
|
+
if (event.target !== event.currentTarget || event.altKey || event.ctrlKey || event.metaKey) return
|
|
165
|
+
const { props: p, rows: all } = latest.current
|
|
166
|
+
const node = p.nodes[row.id]!
|
|
167
|
+
const at = all.findIndex(item => item.id === row.id)
|
|
168
|
+
const open = node.children.length > 0 && p.expanded.has(row.id)
|
|
169
|
+
let handled = true
|
|
170
|
+
switch (event.key) {
|
|
171
|
+
case 'ArrowDown': focus(all[at + 1]?.id); break
|
|
172
|
+
case 'ArrowUp': focus(all[at - 1]?.id); break
|
|
173
|
+
case 'Home': focus(all[0]?.id); break
|
|
174
|
+
case 'End': focus(all.at(-1)?.id); break
|
|
175
|
+
case 'ArrowRight':
|
|
176
|
+
if (node.children.length && !open) p.onExpandedChange(row.id, true)
|
|
177
|
+
else if (open) focus(node.children[0])
|
|
178
|
+
break
|
|
179
|
+
case 'ArrowLeft':
|
|
180
|
+
if (open) p.onExpandedChange(row.id, false)
|
|
181
|
+
else focus(row.parent ?? undefined)
|
|
182
|
+
break
|
|
183
|
+
case '*': for (const id of row.siblings) if (p.nodes[id]?.children.length && !p.expanded.has(id)) p.onExpandedChange(id, true); break
|
|
184
|
+
case 'Enter': p.onOpen(row.id); break
|
|
185
|
+
case 'F2': if (p.onRename && !p.disabled) p.onRenamingChange(row.id); break
|
|
186
|
+
case 'Delete': if (p.onTrash && !p.disabled) p.onTrash(row.id); break
|
|
187
|
+
default:
|
|
188
|
+
handled = false
|
|
189
|
+
if (event.key.length === 1 && event.key.trim()) {
|
|
190
|
+
const now = Date.now()
|
|
191
|
+
typed.current = { text: (now - typed.current.at < 700 ? typed.current.text : '') + event.key.toLowerCase(), at: now }
|
|
192
|
+
const ordered = [...all.slice(at + 1), ...all.slice(0, at + 1)]
|
|
193
|
+
const match = ordered.find(item => p.nodes[item.id]!.title.toLowerCase().startsWith(typed.current.text))
|
|
194
|
+
?? (typed.current.text.length === 1 ? undefined : ordered.find(item => p.nodes[item.id]!.title.toLowerCase().startsWith(event.key.toLowerCase())))
|
|
195
|
+
if (match) { focus(match.id); handled = true }
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (handled) event.preventDefault()
|
|
199
|
+
},
|
|
200
|
+
dragStart: (event, id, title) => { event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.setData('text/plain', title); setDragging(id) },
|
|
201
|
+
dragEnd: () => { setDragging(undefined); setDrop(undefined) },
|
|
202
|
+
dragOver: (event, row) => {
|
|
203
|
+
const at = dropAt(event, row)
|
|
204
|
+
if (!at) return
|
|
205
|
+
event.preventDefault()
|
|
206
|
+
event.dataTransfer.dropEffect = 'move'
|
|
207
|
+
const before = latest.current.drop
|
|
208
|
+
if (before?.id !== row.id || before.at !== at) setDrop({ id: row.id, at })
|
|
209
|
+
},
|
|
210
|
+
dragLeave: (event, id) => { if (!event.currentTarget.contains(event.relatedTarget as Node)) setDrop(value => value?.id === id ? undefined : value) },
|
|
211
|
+
drop: (event, row) => {
|
|
212
|
+
const at = dropAt(event, row)
|
|
213
|
+
event.preventDefault()
|
|
214
|
+
const moving = latest.current.dragging
|
|
215
|
+
setDrop(undefined); setDragging(undefined)
|
|
216
|
+
if (!at || !moving) return
|
|
217
|
+
const p = latest.current.props
|
|
218
|
+
if (at === 'inside') {
|
|
219
|
+
const children = (p.nodes[row.id]?.children ?? []).filter(id => id !== moving)
|
|
220
|
+
p.onMove?.(moving, row.id, children.at(-1) ?? null)
|
|
221
|
+
if (!p.expanded.has(row.id)) p.onExpandedChange(row.id, true)
|
|
222
|
+
} else {
|
|
223
|
+
const siblings = row.siblings.filter(id => id !== moving)
|
|
224
|
+
const index = siblings.indexOf(row.id)
|
|
225
|
+
p.onMove?.(moving, row.parent, at === 'after' ? row.id : siblings[index - 1] ?? null)
|
|
226
|
+
}
|
|
227
|
+
},
|
|
228
|
+
}), [focus])
|
|
229
|
+
function dropAt(event: DragEvent<HTMLDivElement>, row: Row): DocTreeDrop | undefined {
|
|
230
|
+
const moving = latest.current.dragging
|
|
231
|
+
if (!moving || isWithin(latest.current.props.nodes, moving, row.id)) return undefined
|
|
232
|
+
const box = event.currentTarget.getBoundingClientRect()
|
|
233
|
+
const y = (event.clientY - box.top) / box.height
|
|
234
|
+
return y < 0.25 ? 'before' : y > 0.75 ? 'after' : 'inside'
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
return (
|
|
238
|
+
<div ref={container} className="pm-ui-doc-tree" role="tree" aria-label={label} data-dragging={dragging ? '' : undefined} data-virtual={virtual || undefined}>
|
|
239
|
+
{from > 0 && <div aria-hidden="true" style={{ height: from * step }} />}
|
|
240
|
+
{rows.slice(from, to).map(row => {
|
|
241
|
+
const node = nodes[row.id]!
|
|
242
|
+
return <TreeRow key={row.id} row={row} node={node} open={node.children.length > 0 && expanded.has(row.id)} selected={row.id === selected}
|
|
243
|
+
tabStop={row.id === current} drop={drop?.id === row.id ? drop.at : undefined} dragged={dragging === row.id}
|
|
244
|
+
draggable={Boolean(onMove) && !disabled && renaming !== row.id} renaming={renaming === row.id && Boolean(props.onRename)}
|
|
245
|
+
actions={!disabled && renaming !== row.id} canCreate={Boolean(props.onCreateChild)} hasMenu={Boolean(props.menu && props.onMenu)}
|
|
246
|
+
labels={props.labels} handlers={handlers} />
|
|
247
|
+
})}
|
|
248
|
+
{to < rows.length && <div aria-hidden="true" style={{ height: (rows.length - to) * step }} />}
|
|
249
|
+
</div>
|
|
250
|
+
)
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
interface RowHandlers {
|
|
254
|
+
register(id: string, element: HTMLDivElement | null): void
|
|
255
|
+
focused(id: string): void
|
|
256
|
+
open(id: string): void
|
|
257
|
+
toggle(id: string, open: boolean): void
|
|
258
|
+
rename(id: string): void
|
|
259
|
+
finishRename(id: string, value: string | undefined): void
|
|
260
|
+
createChild(id: string): void
|
|
261
|
+
menu(id: string): MenuItem[]
|
|
262
|
+
menuSelect(id: string, action: string): void
|
|
263
|
+
keyDown(event: KeyboardEvent<HTMLDivElement>, row: Row): void
|
|
264
|
+
dragStart(event: DragEvent<HTMLDivElement>, id: string, title: string): void
|
|
265
|
+
dragEnd(): void
|
|
266
|
+
dragOver(event: DragEvent<HTMLDivElement>, row: Row): void
|
|
267
|
+
dragLeave(event: DragEvent<HTMLDivElement>, id: string): void
|
|
268
|
+
drop(event: DragEvent<HTMLDivElement>, row: Row): void
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** One row; it renders again only when its own node, state or drop target changes. */
|
|
272
|
+
const TreeRow = memo(function TreeRow({ row, node, open, selected, tabStop, drop, dragged, draggable, renaming, actions, canCreate, hasMenu, labels, handlers }: {
|
|
273
|
+
row: Row, node: DocTreeNode, open: boolean, selected: boolean, tabStop: boolean, drop?: DocTreeDrop, dragged: boolean, draggable: boolean,
|
|
274
|
+
renaming: boolean, actions: boolean, canCreate: boolean, hasMenu: boolean, labels: DocTreeLabels, handlers: RowHandlers,
|
|
275
|
+
}) {
|
|
276
|
+
const title = node.title || labels.untitled
|
|
277
|
+
const [menuOpen, setMenuOpen] = useState(false)
|
|
278
|
+
return (
|
|
279
|
+
<div
|
|
280
|
+
ref={element => handlers.register(row.id, element)}
|
|
281
|
+
className="pm-ui-doc-tree__item"
|
|
282
|
+
role="treeitem"
|
|
283
|
+
aria-level={row.depth + 1}
|
|
284
|
+
aria-setsize={row.siblings.length}
|
|
285
|
+
aria-posinset={row.index + 1}
|
|
286
|
+
aria-expanded={node.children.length ? open : undefined}
|
|
287
|
+
aria-selected={selected}
|
|
288
|
+
aria-current={selected ? 'page' : undefined}
|
|
289
|
+
tabIndex={tabStop ? 0 : -1}
|
|
290
|
+
data-depth={Math.min(row.depth, 8)}
|
|
291
|
+
data-drop={drop}
|
|
292
|
+
data-dragged={dragged || undefined}
|
|
293
|
+
draggable={draggable}
|
|
294
|
+
title={node.warning}
|
|
295
|
+
onFocus={event => { if (event.target === event.currentTarget) handlers.focused(row.id) }}
|
|
296
|
+
onKeyDown={event => handlers.keyDown(event, row)}
|
|
297
|
+
onClick={event => { if ((event.target as HTMLElement).closest('button, input, [role="menu"]')) return; handlers.focused(row.id); handlers.open(row.id) }}
|
|
298
|
+
onDoubleClick={event => { if (!(event.target as HTMLElement).closest('button')) handlers.rename(row.id) }}
|
|
299
|
+
onDragStart={event => handlers.dragStart(event, row.id, title)}
|
|
300
|
+
onDragEnd={handlers.dragEnd}
|
|
301
|
+
onDragOver={event => handlers.dragOver(event, row)}
|
|
302
|
+
onDragLeave={event => handlers.dragLeave(event, row.id)}
|
|
303
|
+
onDrop={event => handlers.drop(event, row)}
|
|
304
|
+
>
|
|
305
|
+
<span className="pm-ui-doc-tree__twisty">
|
|
306
|
+
{node.children.length > 0 && <button type="button" tabIndex={-1} className="pm-ui-doc-tree__toggle" aria-label={open ? labels.collapse(title) : labels.expand(title)} onClick={() => handlers.toggle(row.id, !open)}>
|
|
307
|
+
<PmIcon name={open ? 'chevron-down' : 'chevron-right'} />
|
|
308
|
+
</button>}
|
|
309
|
+
</span>
|
|
310
|
+
<span className="pm-ui-doc-tree__icon"><PmIcon name={node.warning ? 'warning' : 'document'} /></span>
|
|
311
|
+
{renaming
|
|
312
|
+
? <TreeRename title={node.title} label={labels.renameField} onDone={value => handlers.finishRename(row.id, value)} />
|
|
313
|
+
: <span className="pm-ui-doc-tree__title" title={title}>{title}</span>}
|
|
314
|
+
{actions && <span className="pm-ui-doc-tree__actions" data-open={menuOpen || undefined}>
|
|
315
|
+
{canCreate && <PmIconButton icon="plus" small tabIndex={-1} label={labels.newChild(title)} onClick={() => handlers.createChild(row.id)} />}
|
|
316
|
+
{/* The menu's items are built when it opens, not for every row on every render. */}
|
|
317
|
+
{hasMenu && <PmMenu label={labels.more(title)} items={menuOpen ? handlers.menu(row.id) : []} onOpenChange={setMenuOpen} onSelect={action => handlers.menuSelect(row.id, action)} />}
|
|
318
|
+
</span>}
|
|
319
|
+
</div>
|
|
320
|
+
)
|
|
321
|
+
})
|
|
322
|
+
|
|
323
|
+
function TreeRename({ title, label, onDone }: { title: string, label: string, onDone(value: string | undefined): void }) {
|
|
324
|
+
const [value, setValue] = useState(title)
|
|
325
|
+
const done = useRef(false)
|
|
326
|
+
const finish = (next: string | undefined) => { if (done.current) return; done.current = true; onDone(next) }
|
|
327
|
+
return <input
|
|
328
|
+
className="pm-ui-doc-tree__rename pm-ui-input"
|
|
329
|
+
aria-label={label}
|
|
330
|
+
value={value}
|
|
331
|
+
autoFocus
|
|
332
|
+
onFocus={event => event.currentTarget.select()}
|
|
333
|
+
onChange={event => setValue(event.target.value)}
|
|
334
|
+
onBlur={() => finish(value)}
|
|
335
|
+
onKeyDown={event => {
|
|
336
|
+
event.stopPropagation()
|
|
337
|
+
if (event.nativeEvent.isComposing) return
|
|
338
|
+
if (event.key === 'Enter') { event.preventDefault(); finish(value) }
|
|
339
|
+
else if (event.key === 'Escape') { event.preventDefault(); finish(undefined) }
|
|
340
|
+
}}
|
|
341
|
+
/>
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** An inline reference to a document, a page or a block: its icon and current title; `missing` when the target is gone. */
|
|
345
|
+
export const PmDocMention = forwardRef<HTMLSpanElement, { title: string, missing?: boolean, missingLabel?: string, onActivate?(): void, describedBy?: string }>(function PmDocMention({ title, missing, missingLabel, onActivate, describedBy, ...rest }, ref) {
|
|
346
|
+
return <span
|
|
347
|
+
ref={ref}
|
|
348
|
+
{...rest}
|
|
349
|
+
className="pm-ui-doc-mention"
|
|
350
|
+
role="link"
|
|
351
|
+
tabIndex={0}
|
|
352
|
+
aria-disabled={missing || undefined}
|
|
353
|
+
aria-describedby={describedBy}
|
|
354
|
+
data-missing={missing || undefined}
|
|
355
|
+
onClick={event => { event.preventDefault(); if (!missing) onActivate?.() }}
|
|
356
|
+
onKeyDown={event => { if (event.key === 'Enter' && !missing) { event.preventDefault(); onActivate?.() } }}
|
|
357
|
+
><PmIcon name="document" /><span className="pm-ui-doc-mention__title">{missing ? missingLabel ?? title : title}</span></span>
|
|
358
|
+
})
|
|
359
|
+
|
|
360
|
+
export interface DocPreview { path: string[], title: string, excerpt: string, meta: string, missing?: boolean }
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* A preview of a reference's target on hover: it opens after the pointer rests 500 ms (or the trigger is focused for as
|
|
364
|
+
* long), stays while the pointer crosses to it within 300 ms, and its buttons take the keyboard with Tab. `load` runs
|
|
365
|
+
* when it opens; `children` is the trigger.
|
|
366
|
+
*/
|
|
367
|
+
export function PmDocPreviewCard({ label, load, loadingLabel, failedLabel, actions, children }: { label: string, load(): Promise<DocPreview>, loadingLabel: string, failedLabel: string, actions?: ReactNode, children: ReactElement }) {
|
|
368
|
+
const [open, setOpen] = useState(false)
|
|
369
|
+
const [preview, setPreview] = useState<DocPreview | 'loading' | 'failed'>('loading')
|
|
370
|
+
const timer = useRef<ReturnType<typeof setTimeout>>()
|
|
371
|
+
const id = useId()
|
|
372
|
+
const loader = useRef(load)
|
|
373
|
+
loader.current = load
|
|
374
|
+
// The preview is read when the pointer arrives, so that it is usually there when the card opens 500 ms later.
|
|
375
|
+
const reading = useRef<{ promise: Promise<DocPreview>, value?: DocPreview }>()
|
|
376
|
+
const schedule = (next: boolean) => {
|
|
377
|
+
clearTimeout(timer.current)
|
|
378
|
+
if (next && !open && !reading.current) {
|
|
379
|
+
const entry: { promise: Promise<DocPreview>, value?: DocPreview } = { promise: loader.current() }
|
|
380
|
+
entry.promise.then(value => { entry.value = value }, () => {})
|
|
381
|
+
reading.current = entry
|
|
382
|
+
}
|
|
383
|
+
timer.current = setTimeout(() => setOpen(next), next ? PREVIEW_OPEN_DELAY : PREVIEW_CLOSE_DELAY)
|
|
384
|
+
}
|
|
385
|
+
useEffect(() => () => clearTimeout(timer.current), [])
|
|
386
|
+
useEffect(() => {
|
|
387
|
+
if (!open) return
|
|
388
|
+
let active = true
|
|
389
|
+
const entry = reading.current
|
|
390
|
+
reading.current = undefined
|
|
391
|
+
// Already read during the hover delay: shown at once, without a loading line first.
|
|
392
|
+
if (entry?.value) { setPreview(entry.value); return }
|
|
393
|
+
setPreview('loading')
|
|
394
|
+
const read = entry?.promise ?? loader.current()
|
|
395
|
+
read.then(value => { if (active) setPreview(value) }, () => { if (active) setPreview('failed') })
|
|
396
|
+
return () => { active = false }
|
|
397
|
+
}, [open])
|
|
398
|
+
const trigger = cloneElement(children as ReactElement<Record<string, unknown>>, {
|
|
399
|
+
describedBy: open ? id : undefined,
|
|
400
|
+
onPointerEnter: () => schedule(true),
|
|
401
|
+
onPointerLeave: () => schedule(false),
|
|
402
|
+
onFocus: () => schedule(true),
|
|
403
|
+
onBlur: (event: FocusEvent) => { if (!(event.relatedTarget instanceof Node && document.getElementById(id)?.contains(event.relatedTarget))) schedule(false) },
|
|
404
|
+
onKeyDownCapture: (event: globalThis.KeyboardEvent) => { if (event.key === 'Escape' && open) { event.stopPropagation(); clearTimeout(timer.current); setOpen(false) } },
|
|
405
|
+
})
|
|
406
|
+
return (
|
|
407
|
+
<Popover.Root open={open} onOpenChange={setOpen}>
|
|
408
|
+
<Popover.Anchor asChild>{trigger}</Popover.Anchor>
|
|
409
|
+
<Popover.Portal>
|
|
410
|
+
<Popover.Content id={id} className="pm-ui-doc-preview pm-ui-floating pm-ui" aria-label={label} side="bottom" align="start" sideOffset={6} collisionPadding={16}
|
|
411
|
+
onOpenAutoFocus={event => event.preventDefault()} onCloseAutoFocus={event => event.preventDefault()}
|
|
412
|
+
onPointerEnter={() => clearTimeout(timer.current)} onPointerLeave={() => schedule(false)}
|
|
413
|
+
onBlur={event => { if (!event.currentTarget.contains(event.relatedTarget as Node)) schedule(false) }}
|
|
414
|
+
onEscapeKeyDown={event => event.stopPropagation()}>
|
|
415
|
+
{preview === 'loading' ? <p className="pm-ui-doc-preview__excerpt" role="status">{loadingLabel}</p>
|
|
416
|
+
: preview === 'failed' ? <p className="pm-ui-doc-preview__excerpt" role="status">{failedLabel}</p>
|
|
417
|
+
: <>
|
|
418
|
+
{preview.path.length > 0 && <p className="pm-ui-doc-preview__path">{preview.path.join(' › ')}</p>}
|
|
419
|
+
<p className="pm-ui-doc-preview__title">{preview.title}</p>
|
|
420
|
+
{preview.excerpt && <p className="pm-ui-doc-preview__excerpt">{preview.excerpt}</p>}
|
|
421
|
+
<p className="pm-ui-doc-preview__meta">{preview.meta}</p>
|
|
422
|
+
{!preview.missing && actions && <div className="pm-ui-doc-preview__actions">{actions}</div>}
|
|
423
|
+
</>}
|
|
424
|
+
</Popover.Content>
|
|
425
|
+
</Popover.Portal>
|
|
426
|
+
</Popover.Root>
|
|
427
|
+
)
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
export interface MentionOption { id: string, title: string, path: string[] }
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* The list typing @ or [[ opens in the text: matching documents with the path that tells equal titles apart, and last
|
|
434
|
+
* "new child document … and link". The editor owns the keyboard (↑↓, Enter, Esc) and passes the active index.
|
|
435
|
+
*/
|
|
436
|
+
export function PmMentionPicker({ heading, options, active, createLabel, hint, emptyLabel, loading, loadingLabel, failed, listId, optionId, onSelect, onCreate, onActiveChange }: {
|
|
437
|
+
heading: string, options: readonly MentionOption[], active: number, createLabel?: string, hint: string, emptyLabel: string,
|
|
438
|
+
loading?: boolean, loadingLabel: string, failed?: string,
|
|
439
|
+
/** The ids the editor's aria-controls and aria-activedescendant name, when it owns them. */
|
|
440
|
+
listId?: string, optionId?(index: number): string,
|
|
441
|
+
onSelect(option: MentionOption): void, onCreate?(): void, onActiveChange?(index: number): void,
|
|
442
|
+
}) {
|
|
443
|
+
const id = useId()
|
|
444
|
+
const option = (index: number) => optionId?.(index) ?? `${id}-${index}`
|
|
445
|
+
const list = useRef<HTMLDivElement>(null)
|
|
446
|
+
useEffect(() => { list.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' }) }, [active])
|
|
447
|
+
return (
|
|
448
|
+
<div className="pm-ui-mention-picker pm-ui-floating pm-ui" data-density="compact">
|
|
449
|
+
<p className="pm-ui-mention-picker__heading" id={`${id}-heading`}>{heading}</p>
|
|
450
|
+
<div ref={list} className="pm-ui-mention-picker__list" role="listbox" id={listId ?? `${id}-list`} aria-labelledby={`${id}-heading`} aria-activedescendant={option(active)} aria-busy={loading || undefined}>
|
|
451
|
+
{options.map((item, index) => (
|
|
452
|
+
<div key={item.id} id={option(index)} role="option" aria-selected={index === active} className="pm-ui-mention-picker__option"
|
|
453
|
+
onPointerMove={() => { if (index !== active) onActiveChange?.(index) }} onMouseDown={event => { event.preventDefault(); onSelect(item) }}>
|
|
454
|
+
<PmIcon name="document" />
|
|
455
|
+
<span className="pm-ui-mention-picker__text"><span className="pm-ui-mention-picker__title">{item.title}</span>{item.path.length > 0 && <span className="pm-ui-mention-picker__path">{item.path.join(' › ')}</span>}</span>
|
|
456
|
+
</div>
|
|
457
|
+
))}
|
|
458
|
+
{!options.length && <p className="pm-ui-mention-picker__status" role="status">{failed ?? (loading ? loadingLabel : emptyLabel)}</p>}
|
|
459
|
+
{createLabel && onCreate && <div id={option(options.length)} role="option" aria-selected={active === options.length} className="pm-ui-mention-picker__option" data-create=""
|
|
460
|
+
onPointerMove={() => { if (active !== options.length) onActiveChange?.(options.length) }} onMouseDown={event => { event.preventDefault(); onCreate() }}>
|
|
461
|
+
<PmIcon name="plus" /><span className="pm-ui-mention-picker__title">{createLabel}</span>
|
|
462
|
+
</div>}
|
|
463
|
+
</div>
|
|
464
|
+
<p className="pm-ui-mention-picker__hint">{hint}</p>
|
|
465
|
+
</div>
|
|
466
|
+
)
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* A block shown from another document: the source in its header, the actions (Edit Original, Convert to Copy) while
|
|
471
|
+
* hovered or focused, and a dashed warning frame when the source was moved to the trash or no longer exists.
|
|
472
|
+
*/
|
|
473
|
+
export function PmSyncedBlockFrame({ source, state = 'default', stateLabel, actions, children, label }: { source: ReactNode, state?: 'default' | 'missing' | 'trashed', stateLabel?: string, actions?: ReactNode, children?: ReactNode, label: string }) {
|
|
474
|
+
return (
|
|
475
|
+
<figure className="pm-ui-synced-block" data-state={state === 'default' ? undefined : state} aria-label={label}>
|
|
476
|
+
<figcaption className="pm-ui-synced-block__header">
|
|
477
|
+
<PmIcon name={state === 'default' ? 'synced' : 'warning'} />
|
|
478
|
+
<span className="pm-ui-synced-block__source">{state === 'default' ? source : stateLabel}</span>
|
|
479
|
+
{actions && <span className="pm-ui-synced-block__actions">{actions}</span>}
|
|
480
|
+
</figcaption>
|
|
481
|
+
<div className="pm-ui-synced-block__body">{children}</div>
|
|
482
|
+
</figure>
|
|
483
|
+
)
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/** One place that cites the document: the citing document's title and the sentence around the citation. */
|
|
487
|
+
export interface BacklinkPlace { id: string, excerpt: string, meta?: string, synced?: boolean }
|
|
488
|
+
|
|
489
|
+
/**
|
|
490
|
+
* A document that cites this one: its title, then each place with the sentence around it (two lines at most) and what
|
|
491
|
+
* tells equal sentences apart (`meta`). One place makes the whole card the button; several are a list under the title.
|
|
492
|
+
*/
|
|
493
|
+
export function PmBacklinkItem({ title, count, places, syncedLabel, onActivate }: { title: string, count?: string, places: readonly BacklinkPlace[], syncedLabel?: string, onActivate(id: string): void }) {
|
|
494
|
+
const icon = (place: BacklinkPlace) => <PmIcon name={place.synced ? 'synced' : 'document'} />
|
|
495
|
+
const label = (place: BacklinkPlace) => place.synced && syncedLabel ? <span className="pm-ui-sr-only">{syncedLabel}</span> : null
|
|
496
|
+
if (places.length === 1) {
|
|
497
|
+
const place = places[0]!
|
|
498
|
+
return (
|
|
499
|
+
<button type="button" className="pm-ui-backlink" title={title} onClick={() => onActivate(place.id)}>
|
|
500
|
+
<span className="pm-ui-backlink__title">{icon(place)}<span className="pm-ui-backlink__name">{title}</span>{label(place)}</span>
|
|
501
|
+
{place.excerpt && <span className="pm-ui-backlink__excerpt">{place.excerpt}</span>}
|
|
502
|
+
{place.meta && <span className="pm-ui-backlink__meta">{place.meta}</span>}
|
|
503
|
+
</button>
|
|
504
|
+
)
|
|
505
|
+
}
|
|
506
|
+
return (
|
|
507
|
+
<div className="pm-ui-backlink" data-group="">
|
|
508
|
+
<span className="pm-ui-backlink__title" title={title}><PmIcon name="document" /><span className="pm-ui-backlink__name">{title}</span>{count && <span className="pm-ui-backlink__count">{count}</span>}</span>
|
|
509
|
+
<ul className="pm-ui-backlink__places">{places.map(place => (
|
|
510
|
+
<li key={place.id}><button type="button" className="pm-ui-backlink__place" onClick={() => onActivate(place.id)}>
|
|
511
|
+
{place.excerpt && <span className="pm-ui-backlink__excerpt">{place.excerpt}</span>}
|
|
512
|
+
<span className="pm-ui-backlink__meta">{icon(place)}{place.meta}{label(place)}</span>
|
|
513
|
+
</button></li>
|
|
514
|
+
))}</ul>
|
|
515
|
+
</div>
|
|
516
|
+
)
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
export interface ToastMessage { id: string, text: string, tone?: 'neutral' | 'danger', action?: { label: string, run(): void } }
|
|
520
|
+
|
|
521
|
+
/**
|
|
522
|
+
* One message at a time at the bottom center, in the inverse colors: it closes by itself after 4 seconds (not while the
|
|
523
|
+
* pointer or the keyboard is on it); errors stay until closed. Polite for results, assertive for errors.
|
|
524
|
+
*/
|
|
525
|
+
export function PmToast({ toast, closeLabel, onClose }: { toast?: ToastMessage, closeLabel: string, onClose(id: string): void }) {
|
|
526
|
+
const [paused, setPaused] = useState(false)
|
|
527
|
+
useEffect(() => {
|
|
528
|
+
if (!toast || toast.tone === 'danger' || paused) return
|
|
529
|
+
const timer = setTimeout(() => onClose(toast.id), TOAST_DURATION)
|
|
530
|
+
return () => clearTimeout(timer)
|
|
531
|
+
}, [toast, paused, onClose])
|
|
532
|
+
useEffect(() => setPaused(false), [toast?.id])
|
|
533
|
+
return (
|
|
534
|
+
<div className="pm-ui-toast-region pm-ui">
|
|
535
|
+
<div role="status" aria-live="polite" className="pm-ui-sr-only">{toast && toast.tone !== 'danger' ? toast.text : ''}</div>
|
|
536
|
+
<div role="alert" aria-live="assertive" className="pm-ui-sr-only">{toast?.tone === 'danger' ? toast.text : ''}</div>
|
|
537
|
+
{toast && <div className="pm-ui-toast" data-tone={toast.tone === 'danger' ? 'danger' : undefined}
|
|
538
|
+
onPointerEnter={() => setPaused(true)} onPointerLeave={() => setPaused(false)}
|
|
539
|
+
onFocus={() => setPaused(true)} onBlur={event => { if (!event.currentTarget.contains(event.relatedTarget as Node)) setPaused(false) }}>
|
|
540
|
+
<PmIcon name={toast.tone === 'danger' ? 'warning' : 'check'} />
|
|
541
|
+
<span className="pm-ui-toast__text" aria-hidden="true">{toast.text}</span>
|
|
542
|
+
{toast.action && <PmButton small variant="text" className="pm-ui-toast__action" onClick={() => { toast.action!.run(); onClose(toast.id) }}>{toast.action.label}</PmButton>}
|
|
543
|
+
<PmIconButton icon="close" small className="pm-ui-toast__close" label={closeLabel} onClick={() => onClose(toast.id)} />
|
|
544
|
+
</div>}
|
|
545
|
+
</div>
|
|
546
|
+
)
|
|
547
|
+
}
|