@lincyaw/workbench 0.2.0-rc.121 → 0.2.0-rc.123

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/package.json +4 -4
  2. package/src/StepProductionEditor.tsx +13 -8
  3. package/src/components.tsx +24 -4
  4. package/src/context.tsx +30 -0
  5. package/src/document-editor/BlockNoteSurface.tsx +4 -1
  6. package/src/document-editor/DocumentBlockFallback.tsx +0 -1
  7. package/src/document-editor/DocumentEditor.tsx +7 -1
  8. package/src/document-editor/DocumentStepNarration.tsx +4 -2
  9. package/src/document-editor/authoring.tsx +15 -0
  10. package/src/document-editor/inline.ts +5 -0
  11. package/src/document-editor/insertion-place.ts +2 -2
  12. package/src/document-editor/messages.ts +2 -2
  13. package/src/document-editor/projection.ts +6 -4
  14. package/src/document-editor/references.tsx +352 -0
  15. package/src/document-editor/schema.tsx +39 -2
  16. package/src/document-editor/style.css +10 -0
  17. package/src/document-production.ts +8 -0
  18. package/src/document-session.ts +5 -3
  19. package/src/document-tree.ts +271 -0
  20. package/src/import-messages.ts +1 -1
  21. package/src/index.ts +6 -1
  22. package/src/knowledge-components.tsx +574 -0
  23. package/src/knowledge.css +354 -0
  24. package/src/messages.ts +12 -0
  25. package/src/panels/DocumentPeekPanel.tsx +190 -0
  26. package/src/panels/DocumentView.tsx +46 -23
  27. package/src/panels/DocumentVoiceField.tsx +3 -2
  28. package/src/panels/HomePanel.tsx +12 -3
  29. package/src/panels/MaterialsDialog.tsx +67 -0
  30. package/src/panels/ProductionCaptionSize.tsx +8 -3
  31. package/src/panels/ReferencesPanel.tsx +115 -0
  32. package/src/panels/SourceDocumentPanel.tsx +21 -3
  33. package/src/panels/WorkspaceHome.tsx +109 -0
  34. package/src/panels/WorkspaceSidebar.tsx +331 -0
  35. package/src/styles.css +20 -0
  36. package/src/tree-messages.ts +345 -0
  37. package/src/workbench-state.ts +21 -0
  38. package/src/workbench.ts +76 -3
  39. package/src/workspace-client.ts +35 -1
@@ -0,0 +1,271 @@
1
+ import { errorMessage } from '@lincyaw/kernel'
2
+ import type { ReferenceTarget } from '@lincyaw/kernel'
3
+ import type { DocumentPreview, DocumentTree, EmbedSource, TreeOperation, TreeOperationResult } from '@lincyaw/kernel/contracts'
4
+ import type { ToastMessage } from './knowledge-components.tsx'
5
+ import { WorkspaceServerError } from './workspace-client.ts'
6
+ import type { WorkspaceClient } from './workspace-client.ts'
7
+ import type { WorkbenchStore } from './workbench-state.ts'
8
+ import { DOCUMENT_TREE_MESSAGES } from './tree-messages.ts'
9
+
10
+ const RECENT_KEY = 'presmium.recent-documents'
11
+ const RECENT_LIMIT = 12
12
+
13
+ export interface RecentDocument { id: string, at: string }
14
+
15
+ /** Where a reference or a search result leads: a document, then a page or a block of it. */
16
+ export type DocumentPlace = ReferenceTarget
17
+
18
+ /**
19
+ * The workspace's document tree as the workbench uses it: read on start and on each tree event, changed through
20
+ * `tree/operation`, with the documents opened recently (kept in this browser) and the one message (toast) that says
21
+ * what an operation did and offers its Undo.
22
+ */
23
+ export class DocumentTreeActions {
24
+ readonly #client: WorkspaceClient
25
+ readonly #store: WorkbenchStore
26
+ readonly #open: (dir: string, focus?: 'body') => Promise<void>
27
+ readonly #reveal: (section: string, block?: string) => void
28
+ #reading?: AbortController
29
+ #attention?: AbortController
30
+ #treeText?: string
31
+ readonly #previews = new Map<string, Promise<DocumentPreview>>()
32
+ readonly #embeds = new Map<string, Promise<EmbedSource>>()
33
+ #unsubscribe?: () => void
34
+ #toastSequence = 0
35
+
36
+ constructor(options: { client: WorkspaceClient, store: WorkbenchStore, open(dir: string, focus?: 'body'): Promise<void>, reveal(section: string, block?: string): void }) {
37
+ this.#client = options.client
38
+ this.#store = options.store
39
+ this.#open = options.open
40
+ this.#reveal = options.reveal
41
+ this.#store.set({ recentDocuments: readRecent() })
42
+ }
43
+
44
+ get available(): boolean { return Boolean(this.#client.readTree && this.#client.operateTree) }
45
+
46
+ get #t() { return DOCUMENT_TREE_MESSAGES[this.#store.state.locale] }
47
+
48
+ async load(): Promise<void> {
49
+ if (!this.#client.readTree) return
50
+ // Other clients' changes (and the AI's) arrive as tree events; the first read starts listening.
51
+ if (!this.#unsubscribe) {
52
+ this.#unsubscribe = this.#client.subscribeTree?.(kind => void (kind === 'attention' ? this.loadAttention() : this.load()), () => {})
53
+ void this.loadAttention()
54
+ }
55
+ this.#reading?.abort()
56
+ const reading = this.#reading = new AbortController()
57
+ if (!this.#store.state.documentTree) this.#store.set({ isDocumentTreeLoading: true })
58
+ try {
59
+ const tree = await this.#client.readTree(reading.signal)
60
+ if (reading.signal.aborted) return
61
+ this.#adopt(tree)
62
+ if (this.#store.state.documentTreeFailure || this.#store.state.isDocumentTreeLoading) this.#store.set({ documentTreeFailure: undefined, isDocumentTreeLoading: false })
63
+ } catch (error) {
64
+ if (reading.signal.aborted) return
65
+ this.#store.set({ documentTreeFailure: error instanceof WorkspaceServerError && error.status === 404 ? 'tree-unavailable' : errorMessage(error), isDocumentTreeLoading: false })
66
+ }
67
+ }
68
+
69
+ /** Reads what needs attention across the workspace again (on start and when the workspace says it changed). */
70
+ async loadAttention(): Promise<void> {
71
+ if (!this.#client.readAttention) return
72
+ this.#attention?.abort()
73
+ const reading = this.#attention = new AbortController()
74
+ try {
75
+ const attention = await this.#client.readAttention(reading.signal)
76
+ if (!reading.signal.aborted && JSON.stringify(attention) !== JSON.stringify(this.#store.state.workspaceAttention)) this.#store.set({ workspaceAttention: attention })
77
+ } catch { /* The notices stay as they were; the next change reads them again. */ }
78
+ }
79
+
80
+ /** The folder of the document, as the workbench opens it. */
81
+ dirOf(id: string): string | undefined {
82
+ const state = this.#store.state
83
+ return state.documents?.documents.find(doc => doc.id === id)?.dir ?? state.documentTree?.nodes[id]?.path
84
+ }
85
+
86
+ /** The ID of the document in a folder. */
87
+ idOf(dir: string | undefined): string | undefined {
88
+ if (dir === undefined) return undefined
89
+ const state = this.#store.state
90
+ return state.documents?.documents.find(doc => doc.dir === dir)?.id ?? Object.values(state.documentTree?.nodes ?? {}).find(node => node.path === dir)?.id
91
+ }
92
+
93
+ /** The titles of the document's ancestors, the top level first. */
94
+ ancestors(id: string): { id: string, title: string }[] {
95
+ const nodes = this.#store.state.documentTree?.nodes ?? {}
96
+ const trail: { id: string, title: string }[] = []
97
+ for (let node = nodes[nodes[id]?.parent ?? '']; node && trail.length < 64; node = nodes[node.parent ?? '']) trail.unshift({ id: node.id, title: node.title })
98
+ return trail
99
+ }
100
+
101
+ title(id: string): string | undefined {
102
+ return this.#store.state.documentTree?.nodes[id]?.title ?? this.#store.state.documents?.documents.find(doc => doc.id === id)?.title
103
+ }
104
+
105
+ /** Opens a document by its ID, then shows the page or block of `place`. */
106
+ async openPlace(place: DocumentPlace, options: { focus?: 'body' } = {}): Promise<boolean> {
107
+ const dir = this.dirOf(place.document)
108
+ if (dir === undefined) { this.toast(this.#t.openFailed, 'danger'); return false }
109
+ await this.#open(dir, options.focus)
110
+ if (place.section) this.#reveal(place.section, place.block)
111
+ return true
112
+ }
113
+
114
+ /** Shows the document of `place` read-only in the right pane, beside the open one, at its page or block. */
115
+ peek(place: DocumentPlace): void {
116
+ const { document, section, block } = place
117
+ const current = this.#store.state.documentPeek
118
+ if (current && current.document === document && current.section === section && current.block === block) return
119
+ this.#store.set({ documentPeek: { document, ...section ? { section } : {}, ...block ? { block } : {} } })
120
+ }
121
+
122
+ closePeek(): void {
123
+ if (this.#store.state.documentPeek) this.#store.set({ documentPeek: undefined })
124
+ }
125
+
126
+ /** Remembers that the author opened the document. */
127
+ visited(id: string | undefined): void {
128
+ if (!id) return
129
+ const recent = [{ id, at: new Date().toISOString() }, ...(this.#store.state.recentDocuments ?? []).filter(entry => entry.id !== id)].slice(0, RECENT_LIMIT)
130
+ this.#store.set({ recentDocuments: recent })
131
+ try { localStorage.setItem(RECENT_KEY, JSON.stringify(recent)) } catch {}
132
+ }
133
+
134
+ async operate(operation: TreeOperation): Promise<TreeOperationResult | undefined> {
135
+ if (!this.#client.operateTree) return undefined
136
+ this.#store.set({ isDocumentTreeBusy: true })
137
+ try {
138
+ const result = await this.#client.operateTree(operation)
139
+ this.#adopt(result.tree, true)
140
+ return result
141
+ } catch (error) {
142
+ const code = error instanceof WorkspaceServerError ? (error.answer as { code?: string }).code ?? error.answer.error : undefined
143
+ this.toast(this.#t.operationFailed(this.#t.failures[code ?? ''] ?? this.#t.failureGeneric), 'danger')
144
+ return undefined
145
+ } finally {
146
+ this.#store.set({ isDocumentTreeBusy: false })
147
+ }
148
+ }
149
+
150
+ /** Creates a document under `parent` (the top level when null), opens it and selects its title in the tree. */
151
+ async create(parent: string | null, title = this.#t.untitled): Promise<string | undefined> {
152
+ const siblings = parent ? this.#store.state.documentTree?.nodes[parent]?.children : this.#store.state.documentTree?.roots
153
+ const result = await this.operate({ type: 'create', title, parent, after: siblings?.at(-1) ?? null })
154
+ if (!result?.created) return undefined
155
+ this.#store.set({ renamingDocument: result.created })
156
+ void this.loadDocumentsThenOpen(result.created)
157
+ return result.created
158
+ }
159
+
160
+ async loadDocumentsThenOpen(id: string): Promise<void> {
161
+ if (this.dirOf(id) === undefined) this.#store.set({ documents: await this.#client.readDocuments().catch(() => this.#store.state.documents) })
162
+ await this.openPlace({ document: id })
163
+ }
164
+
165
+ /** A tree read again keeps its identity when nothing changed, so that what depends on it does not render or read again. */
166
+ #adopt(tree: DocumentTree, changed = false): void {
167
+ const text = JSON.stringify(tree)
168
+ if (!changed && text === this.#treeText) return
169
+ this.#treeText = text
170
+ this.invalidateLinks()
171
+ this.#store.set({ documentTree: tree })
172
+ }
173
+
174
+ /** Forgets the cached previews and synced block sources (after a tree change, or a document saved). */
175
+ invalidateLinks(): void {
176
+ this.#previews.clear(); this.#embeds.clear()
177
+ this.#store.set({ documentLinksGeneration: (this.#store.state.documentLinksGeneration ?? 0) + 1 })
178
+ }
179
+
180
+ /** One read per target until the next tree change: hovering again, or many chips of the same target, reuse it. */
181
+ preview(target: ReferenceTarget): Promise<DocumentPreview> | undefined {
182
+ if (!this.#client.readDocumentPreview) return undefined
183
+ const key = JSON.stringify([target.document, target.section ?? '', target.block ?? ''])
184
+ let read = this.#previews.get(key)
185
+ if (!read) { read = this.#client.readDocumentPreview(target); this.#previews.set(key, read); read.catch(() => this.#previews.delete(key)) }
186
+ return read
187
+ }
188
+
189
+ embedSource(source: { document: string, block: string }): Promise<EmbedSource> | undefined {
190
+ if (!this.#client.readEmbedSource) return undefined
191
+ const key = `${source.document}\0${source.block}`
192
+ let read = this.#embeds.get(key)
193
+ if (!read) { read = this.#client.readEmbedSource(source); this.#embeds.set(key, read); read.catch(() => this.#embeds.delete(key)) }
194
+ return read
195
+ }
196
+
197
+ startRenaming(id: string | undefined): void {
198
+ if (this.#store.state.renamingDocument !== id) this.#store.set({ renamingDocument: id })
199
+ }
200
+
201
+ async rename(id: string, title: string): Promise<void> {
202
+ await this.operate({ type: 'rename', id, title })
203
+ }
204
+
205
+ async duplicate(id: string): Promise<void> {
206
+ const result = await this.operate({ type: 'duplicate', id })
207
+ if (result?.created) this.toast(this.#t.duplicated(this.title(result.created) ?? ''))
208
+ }
209
+
210
+ async move(id: string, parent: string | null, after: string | null): Promise<void> {
211
+ const tree = this.#store.state.documentTree
212
+ const node = tree?.nodes[id]
213
+ if (!tree || !node) return
214
+ const siblings = node.parent ? tree.nodes[node.parent]?.children ?? [] : tree.roots
215
+ const before = { parent: node.parent, after: siblings[siblings.indexOf(id) - 1] ?? null }
216
+ if (before.parent === parent && before.after === after) return
217
+ const result = await this.operate({ type: 'move', id, parent, after })
218
+ if (!result) return
219
+ const where = parent ? this.title(parent) ?? '' : undefined
220
+ this.toast(where === undefined ? this.#t.movedToTop(node.title) : this.#t.movedUnder(node.title, where), 'neutral', { label: this.#t.undo, run: () => void this.operate({ type: 'move', id, parent: before.parent, after: before.after }) })
221
+ }
222
+
223
+ async trash(id: string): Promise<void> {
224
+ const title = this.title(id) ?? ''
225
+ const result = await this.operate({ type: 'trash', id })
226
+ if (!result) return
227
+ this.toast(this.#t.trashed(title), 'neutral', { label: this.#t.undo, run: () => void this.restore(id) })
228
+ }
229
+
230
+ /** Restores a document (with the children trashed along with it) and says where it went. */
231
+ async restore(id: string): Promise<void> {
232
+ const title = this.#store.state.documentTree?.trash.find(entry => entry.id === id)?.title ?? ''
233
+ const result = await this.operate({ type: 'restore', id })
234
+ if (!result) return
235
+ const top = result.toTopLevel?.find(item => item.document === id)
236
+ this.toast(top ? this.#t.restoredToTop(title, top.parent) : this.#t.restored(title))
237
+ this.#store.set({ documents: await this.#client.readDocuments().catch(() => this.#store.state.documents) })
238
+ }
239
+
240
+ async purge(id: string): Promise<boolean> {
241
+ const result = await this.operate({ type: 'purge', id })
242
+ if (result?.converted?.length) this.toast(this.#t.purgedConverted(result.converted.length))
243
+ return Boolean(result)
244
+ }
245
+
246
+ async embedToCopy(document: string, block: string): Promise<boolean> {
247
+ return Boolean(await this.operate({ type: 'embed-to-copy', document, block }))
248
+ }
249
+
250
+ toast(text: string, tone: 'neutral' | 'danger' = 'neutral', action?: ToastMessage['action']): void {
251
+ this.#store.set({ toast: { id: String(++this.#toastSequence), text, tone, ...action ? { action } : {} } })
252
+ }
253
+
254
+ closeToast = (id: string): void => {
255
+ if (this.#store.state.toast?.id === id) this.#store.set({ toast: undefined })
256
+ }
257
+
258
+ dispose(): void { this.#reading?.abort(); this.#attention?.abort(); this.#unsubscribe?.() }
259
+ }
260
+
261
+ function readRecent(): RecentDocument[] {
262
+ try {
263
+ const value = JSON.parse(localStorage.getItem(RECENT_KEY) ?? '[]') as unknown
264
+ return Array.isArray(value) ? value.filter((entry): entry is RecentDocument => typeof entry?.id === 'string' && typeof entry.at === 'string').slice(0, RECENT_LIMIT) : []
265
+ } catch { return [] }
266
+ }
267
+
268
+ /** The document's tree that is ready for the tree view: a missing tree is an empty one. */
269
+ export function treeOrEmpty(tree: DocumentTree | undefined): DocumentTree {
270
+ return tree ?? { roots: [], nodes: {}, trash: [] }
271
+ }
@@ -1,6 +1,6 @@
1
1
  export const IMPORT_MESSAGES = {
2
2
  'zh-CN': {
3
- title: '导入文档', files: '选择文件', folder: '选择文件夹', submit: '导入',
3
+ title: '导入文稿', files: '选择文件', folder: '选择文件夹', submit: '导入',
4
4
  description: '支持 Markdown(.md、.markdown)和 Word(.docx)。每个文件生成一份文稿,保留目录层级;一级、二级标题分成页面。',
5
5
  images: '含本地图片或文件间链接的 Markdown,请导入所在文件夹。Word 保留标题、段落、列表、表格、强调、链接和内嵌图片。',
6
6
  limits: '最多 1000 个文件,合计 32 MiB。导入后可在工作区中继续编辑。',
package/src/index.ts CHANGED
@@ -8,7 +8,12 @@ export type { StepProductionEditorProps } from './StepProductionEditor.tsx'
8
8
  export { MediaClipEditor } from './MediaClipEditor.tsx'
9
9
  export type { MediaClipAssetChoice, MediaClipDraft, MediaClipEditorProps } from './MediaClipEditor.tsx'
10
10
  export type { StepDurationDraft, StepDurationKey, StepTimingKey, StepTimingPatch } from './step-production.ts'
11
- export { useMessages, useWorkbench, useWorkbenchState, WorkbenchProvider } from './context.tsx'
11
+ export { useMessages, useTreeMessages, useWorkbench, useWorkbenchState, WorkbenchProvider } from './context.tsx'
12
+ export { DOCUMENT_TREE_MESSAGES } from './tree-messages.ts'
13
+ export type { DocumentTreeMessages } from './tree-messages.ts'
14
+ export { DocumentBreadcrumb, SearchDialog, WorkbenchToast, WorkspaceSidebar } from './panels/WorkspaceSidebar.tsx'
15
+ export { DocumentTreeActions } from './document-tree.ts'
16
+ export type { RecentDocument } from './document-tree.ts'
12
17
  export type { DocumentComment } from '@lincyaw/kernel'
13
18
  export { localeOf, MESSAGES, timeAgo } from './messages.ts'
14
19
  export type { Locale, WorkbenchMessages } from './messages.ts'