@lincyaw/workbench 0.2.0-rc.120 → 0.2.0-rc.122

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,239 @@
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
+ #treeText?: string
30
+ readonly #previews = new Map<string, Promise<DocumentPreview>>()
31
+ readonly #embeds = new Map<string, Promise<EmbedSource>>()
32
+ #unsubscribe?: () => void
33
+ #toastSequence = 0
34
+
35
+ constructor(options: { client: WorkspaceClient, store: WorkbenchStore, open(dir: string, focus?: 'body'): Promise<void>, reveal(section: string, block?: string): void }) {
36
+ this.#client = options.client
37
+ this.#store = options.store
38
+ this.#open = options.open
39
+ this.#reveal = options.reveal
40
+ this.#store.set({ recentDocuments: readRecent() })
41
+ }
42
+
43
+ get available(): boolean { return Boolean(this.#client.readTree && this.#client.operateTree) }
44
+
45
+ get #t() { return DOCUMENT_TREE_MESSAGES[this.#store.state.locale] }
46
+
47
+ async load(): Promise<void> {
48
+ if (!this.#client.readTree) return
49
+ // Other clients' changes (and the AI's) arrive as tree events; the first read starts listening.
50
+ this.#unsubscribe ??= this.#client.subscribeTree?.(() => void this.load(), () => {})
51
+ this.#reading?.abort()
52
+ const reading = this.#reading = new AbortController()
53
+ if (!this.#store.state.documentTree) this.#store.set({ isDocumentTreeLoading: true })
54
+ try {
55
+ const tree = await this.#client.readTree(reading.signal)
56
+ if (reading.signal.aborted) return
57
+ this.#adopt(tree)
58
+ if (this.#store.state.documentTreeFailure || this.#store.state.isDocumentTreeLoading) this.#store.set({ documentTreeFailure: undefined, isDocumentTreeLoading: false })
59
+ } catch (error) {
60
+ if (reading.signal.aborted) return
61
+ this.#store.set({ documentTreeFailure: error instanceof WorkspaceServerError && error.status === 404 ? 'tree-unavailable' : errorMessage(error), isDocumentTreeLoading: false })
62
+ }
63
+ }
64
+
65
+ /** The folder of the document, as the workbench opens it. */
66
+ dirOf(id: string): string | undefined {
67
+ const state = this.#store.state
68
+ return state.documents?.documents.find(doc => doc.id === id)?.dir ?? state.documentTree?.nodes[id]?.path
69
+ }
70
+
71
+ /** The ID of the document in a folder. */
72
+ idOf(dir: string | undefined): string | undefined {
73
+ if (dir === undefined) return undefined
74
+ const state = this.#store.state
75
+ return state.documents?.documents.find(doc => doc.dir === dir)?.id ?? Object.values(state.documentTree?.nodes ?? {}).find(node => node.path === dir)?.id
76
+ }
77
+
78
+ /** The titles of the document's ancestors, the top level first. */
79
+ ancestors(id: string): { id: string, title: string }[] {
80
+ const nodes = this.#store.state.documentTree?.nodes ?? {}
81
+ const trail: { id: string, title: string }[] = []
82
+ for (let node = nodes[nodes[id]?.parent ?? '']; node && trail.length < 64; node = nodes[node.parent ?? '']) trail.unshift({ id: node.id, title: node.title })
83
+ return trail
84
+ }
85
+
86
+ title(id: string): string | undefined {
87
+ return this.#store.state.documentTree?.nodes[id]?.title ?? this.#store.state.documents?.documents.find(doc => doc.id === id)?.title
88
+ }
89
+
90
+ /** Opens a document by its ID, then shows the page or block of `place`. */
91
+ async openPlace(place: DocumentPlace, options: { focus?: 'body' } = {}): Promise<boolean> {
92
+ const dir = this.dirOf(place.document)
93
+ if (dir === undefined) { this.toast(this.#t.openFailed, 'danger'); return false }
94
+ await this.#open(dir, options.focus)
95
+ if (place.section) this.#reveal(place.section, place.block)
96
+ return true
97
+ }
98
+
99
+ /** Remembers that the author opened the document. */
100
+ visited(id: string | undefined): void {
101
+ if (!id) return
102
+ const recent = [{ id, at: new Date().toISOString() }, ...(this.#store.state.recentDocuments ?? []).filter(entry => entry.id !== id)].slice(0, RECENT_LIMIT)
103
+ this.#store.set({ recentDocuments: recent })
104
+ try { localStorage.setItem(RECENT_KEY, JSON.stringify(recent)) } catch {}
105
+ }
106
+
107
+ async operate(operation: TreeOperation): Promise<TreeOperationResult | undefined> {
108
+ if (!this.#client.operateTree) return undefined
109
+ this.#store.set({ isDocumentTreeBusy: true })
110
+ try {
111
+ const result = await this.#client.operateTree(operation)
112
+ this.#adopt(result.tree, true)
113
+ return result
114
+ } catch (error) {
115
+ const code = error instanceof WorkspaceServerError ? (error.answer as { code?: string }).code ?? error.answer.error : undefined
116
+ this.toast(this.#t.operationFailed(this.#t.failures[code ?? ''] ?? this.#t.failureGeneric), 'danger')
117
+ return undefined
118
+ } finally {
119
+ this.#store.set({ isDocumentTreeBusy: false })
120
+ }
121
+ }
122
+
123
+ /** Creates a document under `parent` (the top level when null), opens it and selects its title in the tree. */
124
+ async create(parent: string | null, title = this.#t.untitled): Promise<string | undefined> {
125
+ const siblings = parent ? this.#store.state.documentTree?.nodes[parent]?.children : this.#store.state.documentTree?.roots
126
+ const result = await this.operate({ type: 'create', title, parent, after: siblings?.at(-1) ?? null })
127
+ if (!result?.created) return undefined
128
+ this.#store.set({ renamingDocument: result.created })
129
+ void this.loadDocumentsThenOpen(result.created)
130
+ return result.created
131
+ }
132
+
133
+ async loadDocumentsThenOpen(id: string): Promise<void> {
134
+ if (this.dirOf(id) === undefined) this.#store.set({ documents: await this.#client.readDocuments().catch(() => this.#store.state.documents) })
135
+ await this.openPlace({ document: id })
136
+ }
137
+
138
+ /** A tree read again keeps its identity when nothing changed, so that what depends on it does not render or read again. */
139
+ #adopt(tree: DocumentTree, changed = false): void {
140
+ const text = JSON.stringify(tree)
141
+ if (!changed && text === this.#treeText) return
142
+ this.#treeText = text
143
+ this.invalidateLinks()
144
+ this.#store.set({ documentTree: tree })
145
+ }
146
+
147
+ /** Forgets the cached previews and synced block sources (after a tree change, or a document saved). */
148
+ invalidateLinks(): void {
149
+ this.#previews.clear(); this.#embeds.clear()
150
+ this.#store.set({ documentLinksGeneration: (this.#store.state.documentLinksGeneration ?? 0) + 1 })
151
+ }
152
+
153
+ /** One read per target until the next tree change: hovering again, or many chips of the same target, reuse it. */
154
+ preview(target: ReferenceTarget): Promise<DocumentPreview> | undefined {
155
+ if (!this.#client.readDocumentPreview) return undefined
156
+ const key = JSON.stringify([target.document, target.section ?? '', target.block ?? ''])
157
+ let read = this.#previews.get(key)
158
+ if (!read) { read = this.#client.readDocumentPreview(target); this.#previews.set(key, read); read.catch(() => this.#previews.delete(key)) }
159
+ return read
160
+ }
161
+
162
+ embedSource(source: { document: string, block: string }): Promise<EmbedSource> | undefined {
163
+ if (!this.#client.readEmbedSource) return undefined
164
+ const key = `${source.document}\0${source.block}`
165
+ let read = this.#embeds.get(key)
166
+ if (!read) { read = this.#client.readEmbedSource(source); this.#embeds.set(key, read); read.catch(() => this.#embeds.delete(key)) }
167
+ return read
168
+ }
169
+
170
+ startRenaming(id: string | undefined): void {
171
+ if (this.#store.state.renamingDocument !== id) this.#store.set({ renamingDocument: id })
172
+ }
173
+
174
+ async rename(id: string, title: string): Promise<void> {
175
+ await this.operate({ type: 'rename', id, title })
176
+ }
177
+
178
+ async duplicate(id: string): Promise<void> {
179
+ const result = await this.operate({ type: 'duplicate', id })
180
+ if (result?.created) this.toast(this.#t.duplicated(this.title(result.created) ?? ''))
181
+ }
182
+
183
+ async move(id: string, parent: string | null, after: string | null): Promise<void> {
184
+ const tree = this.#store.state.documentTree
185
+ const node = tree?.nodes[id]
186
+ if (!tree || !node) return
187
+ const siblings = node.parent ? tree.nodes[node.parent]?.children ?? [] : tree.roots
188
+ const before = { parent: node.parent, after: siblings[siblings.indexOf(id) - 1] ?? null }
189
+ if (before.parent === parent && before.after === after) return
190
+ const result = await this.operate({ type: 'move', id, parent, after })
191
+ if (!result) return
192
+ const where = parent ? this.title(parent) ?? '' : undefined
193
+ 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 }) })
194
+ }
195
+
196
+ async trash(id: string): Promise<void> {
197
+ const title = this.title(id) ?? ''
198
+ const result = await this.operate({ type: 'trash', id })
199
+ if (!result) return
200
+ this.toast(this.#t.trashed(title), 'neutral', { label: this.#t.undo, run: () => void this.restore(id) })
201
+ }
202
+
203
+ async restore(id: string): Promise<void> {
204
+ const result = await this.operate({ type: 'restore', id })
205
+ if (result) this.#store.set({ documents: await this.#client.readDocuments().catch(() => this.#store.state.documents) })
206
+ }
207
+
208
+ async purge(id: string): Promise<boolean> {
209
+ const result = await this.operate({ type: 'purge', id })
210
+ if (result?.converted?.length) this.toast(this.#t.purgedConverted(result.converted.length))
211
+ return Boolean(result)
212
+ }
213
+
214
+ async embedToCopy(document: string, block: string): Promise<boolean> {
215
+ return Boolean(await this.operate({ type: 'embed-to-copy', document, block }))
216
+ }
217
+
218
+ toast(text: string, tone: 'neutral' | 'danger' = 'neutral', action?: ToastMessage['action']): void {
219
+ this.#store.set({ toast: { id: String(++this.#toastSequence), text, tone, ...action ? { action } : {} } })
220
+ }
221
+
222
+ closeToast = (id: string): void => {
223
+ if (this.#store.state.toast?.id === id) this.#store.set({ toast: undefined })
224
+ }
225
+
226
+ dispose(): void { this.#reading?.abort(); this.#unsubscribe?.() }
227
+ }
228
+
229
+ function readRecent(): RecentDocument[] {
230
+ try {
231
+ const value = JSON.parse(localStorage.getItem(RECENT_KEY) ?? '[]') as unknown
232
+ return Array.isArray(value) ? value.filter((entry): entry is RecentDocument => typeof entry?.id === 'string' && typeof entry.at === 'string').slice(0, RECENT_LIMIT) : []
233
+ } catch { return [] }
234
+ }
235
+
236
+ /** The document's tree that is ready for the tree view: a missing tree is an empty one. */
237
+ export function treeOrEmpty(tree: DocumentTree | undefined): DocumentTree {
238
+ return tree ?? { roots: [], nodes: {}, trash: [] }
239
+ }
@@ -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'