@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,299 @@
1
+ /** The document tree, references, synced blocks and the trash (docs/glossary.md, docs/studio.md). */
2
+ export const DOCUMENT_TREE_MESSAGES = {
3
+ 'zh-CN': {
4
+ sidebar: '工作区',
5
+ search: '搜索文稿与正文',
6
+ searchShortcut: 'Ctrl+K',
7
+ home: '主页',
8
+ recent: '最近打开',
9
+ documents: '文稿',
10
+ tree: '文稿树',
11
+ newDocument: '新建文稿',
12
+ newChild: '新建子文稿',
13
+ newChildIn: (title: string) => `在“${title}”下新建子文稿`,
14
+ more: (title: string) => `“${title}”的更多操作`,
15
+ expand: (title: string) => `展开“${title}”`,
16
+ collapse: (title: string) => `折叠“${title}”`,
17
+ untitled: '未命名文稿',
18
+ renameField: '文稿标题',
19
+ rename: '重命名…',
20
+ duplicate: '创建副本',
21
+ moveTo: '移动到…',
22
+ trash: '回收站',
23
+ moveToTrash: '移到回收站',
24
+ documentCount: (count: number) => `${count} 份文稿`,
25
+ treeLoading: '正在加载文稿…',
26
+ treeEmpty: '还没有文稿。',
27
+ treeFailed: '无法加载文稿树,请重试。',
28
+ retry: '重试',
29
+ treeIssue: '这份文稿的上级无效,暂时显示在顶层。',
30
+ upgradePending: (count: number) => `${count} 份文稿等待升级。升级后才能打开与编辑它们;每份文稿的升级都记入版本历史。`,
31
+ upgrade: '升级',
32
+ upgraded: (count: number) => `已升级 ${count} 份文稿。`,
33
+ openSidebar: '打开文稿树',
34
+ closeSidebar: '关闭文稿树',
35
+ location: '位置',
36
+ undo: '撤消',
37
+ close: '关闭',
38
+ movedUnder: (title: string, parent: string) => `“${title}”已移到“${parent}”下`,
39
+ movedToTop: (title: string) => `“${title}”已移到顶层`,
40
+ trashed: (title: string) => `“${title}”已移到回收站`,
41
+ duplicated: (title: string) => `已创建“${title}”`,
42
+ purgedConverted: (count: number) => `引用它的 ${count} 个同步块已转为副本。`,
43
+ openFailed: '无法打开文稿。它可能已被删除或移到回收站。',
44
+ operationFailed: (reason: string) => `无法完成操作。${reason}`,
45
+ failureGeneric: '请稍后重试。',
46
+ failures: {
47
+ 'tree.not-found': '文稿已不存在,请刷新后重试。',
48
+ 'tree.cycle': '不能把文稿移到它自己的子文稿下。',
49
+ 'tree.trash-not-found': '回收站中已没有这份文稿。',
50
+ 'tree.title-empty': '请输入标题。',
51
+ } as Record<string, string>,
52
+ searchTitle: '搜索',
53
+ searchField: '标题或正文',
54
+ searchPlaceholder: '输入标题或正文中的文字',
55
+ searching: '正在搜索…',
56
+ searchEmpty: '没有找到匹配的文稿。',
57
+ searchFailed: '无法搜索,请重试。',
58
+ searchResults: (count: number) => `${count} 个结果`,
59
+ contentMatch: (excerpt: string) => `正文:${excerpt}`,
60
+ recentEmpty: '还没有打开过文稿。',
61
+ trashTitle: '回收站',
62
+ trashEmpty: '回收站是空的。',
63
+ trashHint: '移到回收站的文稿连同其子文稿保存在这里,可以还原。',
64
+ restore: '还原',
65
+ restored: (title: string) => `已还原“${title}”`,
66
+ deletePermanently: '永久删除…',
67
+ deletePermanentlyTitle: '永久删除',
68
+ deleteConfirm: (title: string) => `永久删除“${title}”及其子文稿?此操作无法撤消。`,
69
+ deleteSynced: '其他文稿中来自它的同步块会先转为副本,保留当前内容;指向它的引用将显示为已删除。',
70
+ deleteAction: '删除',
71
+ cancel: '取消',
72
+ deletedAt: (time: string) => `删除于 ${time}`,
73
+ childCount: (count: number) => `含 ${count} 份子文稿`,
74
+ moveTitle: (title: string) => `移动“${title}”`,
75
+ moveTarget: '移到',
76
+ topLevel: '顶层',
77
+ move: '移动',
78
+ outline: '目录',
79
+ references: '引用',
80
+ rail: '右栏',
81
+ citedBy: '引用了本文',
82
+ outgoing: '本文引用',
83
+ syncedBlocks: '同步块',
84
+ citedByCount: (count: number) => `被 ${count} 篇文稿引用`,
85
+ noCitations: '还没有文稿引用本文。',
86
+ noOutgoing: '本文还没有引用其他文稿。',
87
+ noSynced: '本文没有同步块。',
88
+ referencesLoading: '正在加载引用…',
89
+ referencesFailed: '无法加载引用,请重试。',
90
+ referencesUnavailable: '这个工作区不提供引用信息。',
91
+ referencesSummary: (incoming: number, outgoing: number) => `引用了本文 ${incoming} 篇 · 本文引用 ${outgoing} 篇`,
92
+ missingTarget: '已删除',
93
+ trashedTarget: '在回收站中',
94
+ syncedLabel: '同步块',
95
+ referenceLabel: '引用',
96
+ placeCount: (count: number) => `${count} 处`,
97
+ placeIndex: (index: number) => `第 ${index} 处`,
98
+ previewLabel: '文稿预览',
99
+ previewLoading: '正在加载预览…',
100
+ previewFailed: '无法加载预览。',
101
+ previewMeta: (pages: number, steps: number, citedBy: number) => `${pages} 页 · ${steps} 步 · 被 ${citedBy} 篇文稿引用`,
102
+ previewMissing: '这份文稿已删除。',
103
+ previewTrashed: '这份文稿在回收站中。',
104
+ open: '打开',
105
+ missingDocument: '文稿已删除',
106
+ linkHeading: (query: string) => query ? `链接到文稿 · 输入“${query}”` : '链接到文稿',
107
+ createChildAndLink: (query: string) => `新建子文稿“${query}”并链接`,
108
+ pickerHint: '↑↓ 选择 · Enter 插入 · Esc 关闭',
109
+ linkToDocument: '链接到文稿',
110
+ linkToDocumentHint: '插入指向另一份文稿、页面或内容块的引用',
111
+ linkAliases: '链接|引用|文稿',
112
+ syncedBlock: '同步块',
113
+ syncedBlockHint: '显示另一份文稿中的内容块,只在原处修改',
114
+ syncedAliases: '同步|嵌入',
115
+ childDocument: '子文稿',
116
+ childDocumentHint: '在本文稿下新建子文稿,并在这里链接它',
117
+ childAliases: '子文稿|新建',
118
+ syncedFrom: '同步自',
119
+ editOriginal: '编辑原文',
120
+ convertToCopy: '转为副本',
121
+ converted: '已转为副本。',
122
+ sourceTrashed: '原文稿在回收站中 · 显示的是它当前的内容',
123
+ sourceMissing: '原内容已不存在',
124
+ syncedLoading: '正在加载同步块…',
125
+ syncedFailed: '无法加载同步块的内容。',
126
+ syncedEmpty: '原内容块没有文字。',
127
+ syncedComponent: (title: string) => `组件:${title}`,
128
+ insertSynced: '插入同步块',
129
+ chooseDocument: '文稿',
130
+ chooseBlock: '内容块',
131
+ noBlocks: '这份文稿没有可同步的内容块。',
132
+ insert: '插入',
133
+ copySyncedLink: '复制同步块链接',
134
+ linkCopied: '已复制同步块链接。粘贴到另一份文稿即可插入同步块。',
135
+ copyFailed: '无法复制链接,请重试。',
136
+ blankDocument: '空白文稿',
137
+ blankDocumentHint: '从标题开始写,随时添加页面和动画',
138
+ importHint: '用已有的文件生成文稿',
139
+ needsAttention: '需要处理',
140
+ treeIssues: (count: number) => `${count} 份文稿的上级无效,暂时显示在顶层。请把它们移到正确的位置。`,
141
+ show: '查看',
142
+ trashCount: (count: number) => `回收站中有 ${count} 份文稿`,
143
+ allDocuments: '全部文稿',
144
+ pages: (count: number) => `${count} 页`,
145
+ inheritedFrom: (name: string) => `继承自“${name}”`,
146
+ inheritedWorkspace: '继承自工作区默认设置',
147
+ override: '改写',
148
+ useInherited: '使用继承值',
149
+ },
150
+ en: {
151
+ sidebar: 'Workspace',
152
+ search: 'Search Documents',
153
+ searchShortcut: 'Ctrl+K',
154
+ home: 'Home',
155
+ recent: 'Recent',
156
+ documents: 'Documents',
157
+ tree: 'Document Tree',
158
+ newDocument: 'New Document',
159
+ newChild: 'New Child Document',
160
+ newChildIn: (title: string) => `New Child Document in “${title}”`,
161
+ more: (title: string) => `More Actions for “${title}”`,
162
+ expand: (title: string) => `Expand “${title}”`,
163
+ collapse: (title: string) => `Collapse “${title}”`,
164
+ untitled: 'Untitled document',
165
+ renameField: 'Document title',
166
+ rename: 'Rename…',
167
+ duplicate: 'Make a Copy',
168
+ moveTo: 'Move To…',
169
+ trash: 'Trash',
170
+ moveToTrash: 'Move to Trash',
171
+ documentCount: (count: number) => `${count} ${count === 1 ? 'document' : 'documents'}`,
172
+ treeLoading: 'Loading documents…',
173
+ treeEmpty: 'No documents yet.',
174
+ treeFailed: 'Couldn’t load the document tree. Try again.',
175
+ retry: 'Retry',
176
+ treeIssue: 'This document’s parent isn’t valid, so it’s shown at the top level for now.',
177
+ upgradePending: (count: number) => `${count} ${count === 1 ? 'document is' : 'documents are'} waiting for the upgrade. Upgrade to open and edit them; each document’s upgrade is recorded in its history.`,
178
+ upgrade: 'Upgrade',
179
+ upgraded: (count: number) => `Upgraded ${count} ${count === 1 ? 'document' : 'documents'}.`,
180
+ openSidebar: 'Open Document Tree',
181
+ closeSidebar: 'Close Document Tree',
182
+ location: 'Location',
183
+ undo: 'Undo',
184
+ close: 'Close',
185
+ movedUnder: (title: string, parent: string) => `Moved “${title}” under “${parent}”.`,
186
+ movedToTop: (title: string) => `Moved “${title}” to the top level.`,
187
+ trashed: (title: string) => `Moved “${title}” to the trash.`,
188
+ duplicated: (title: string) => `Created “${title}”.`,
189
+ purgedConverted: (count: number) => `Converted ${count} synced ${count === 1 ? 'block' : 'blocks'} from it to copies.`,
190
+ openFailed: 'Couldn’t open the document. It may have been deleted or moved to the trash.',
191
+ operationFailed: (reason: string) => `Couldn’t complete the operation. ${reason}`,
192
+ failureGeneric: 'Try again later.',
193
+ failures: {
194
+ 'tree.not-found': 'The document no longer exists. Refresh and try again.',
195
+ 'tree.cycle': 'A document can’t move under its own child document.',
196
+ 'tree.trash-not-found': 'The document is no longer in the trash.',
197
+ 'tree.title-empty': 'Enter a title.',
198
+ } as Record<string, string>,
199
+ searchTitle: 'Search',
200
+ searchField: 'Title or text',
201
+ searchPlaceholder: 'Type a title or text from a document',
202
+ searching: 'Searching…',
203
+ searchEmpty: 'No matching documents.',
204
+ searchFailed: 'Couldn’t search. Try again.',
205
+ searchResults: (count: number) => `${count} ${count === 1 ? 'result' : 'results'}`,
206
+ contentMatch: (excerpt: string) => `Text: ${excerpt}`,
207
+ recentEmpty: 'You haven’t opened any documents yet.',
208
+ trashTitle: 'Trash',
209
+ trashEmpty: 'The trash is empty.',
210
+ trashHint: 'Documents moved to the trash stay here with their child documents until you restore or delete them.',
211
+ restore: 'Restore',
212
+ restored: (title: string) => `Restored “${title}”.`,
213
+ deletePermanently: 'Delete Permanently…',
214
+ deletePermanentlyTitle: 'Delete Permanently',
215
+ deleteConfirm: (title: string) => `Delete “${title}” and its child documents permanently? You can’t undo this.`,
216
+ deleteSynced: 'Synced blocks from it in other documents become copies first and keep their current content; references to it show as deleted.',
217
+ deleteAction: 'Delete',
218
+ cancel: 'Cancel',
219
+ deletedAt: (time: string) => `Deleted ${time}`,
220
+ childCount: (count: number) => `With ${count} child ${count === 1 ? 'document' : 'documents'}`,
221
+ moveTitle: (title: string) => `Move “${title}”`,
222
+ moveTarget: 'Move to',
223
+ topLevel: 'Top level',
224
+ move: 'Move',
225
+ outline: 'Outline',
226
+ references: 'References',
227
+ rail: 'Right Pane',
228
+ citedBy: 'Cited By',
229
+ outgoing: 'References',
230
+ syncedBlocks: 'Synced Blocks',
231
+ citedByCount: (count: number) => `Cited by ${count} ${count === 1 ? 'document' : 'documents'}`,
232
+ noCitations: 'No documents cite this one yet.',
233
+ noOutgoing: 'This document doesn’t reference other documents yet.',
234
+ noSynced: 'This document has no synced blocks.',
235
+ referencesLoading: 'Loading references…',
236
+ referencesFailed: 'Couldn’t load the references. Try again.',
237
+ referencesUnavailable: 'This workspace doesn’t provide references.',
238
+ referencesSummary: (incoming: number, outgoing: number) => `Cited by ${incoming} · References ${outgoing}`,
239
+ missingTarget: 'Deleted',
240
+ trashedTarget: 'In the trash',
241
+ syncedLabel: 'Synced block',
242
+ referenceLabel: 'Reference',
243
+ placeCount: (count: number) => `${count} places`,
244
+ placeIndex: (index: number) => `place ${index}`,
245
+ previewLabel: 'Document preview',
246
+ previewLoading: 'Loading preview…',
247
+ previewFailed: 'Couldn’t load the preview.',
248
+ previewMeta: (pages: number, steps: number, citedBy: number) => `${pages} ${pages === 1 ? 'page' : 'pages'} · ${steps} ${steps === 1 ? 'step' : 'steps'} · cited by ${citedBy} ${citedBy === 1 ? 'document' : 'documents'}`,
249
+ previewMissing: 'This document was deleted.',
250
+ previewTrashed: 'This document is in the trash.',
251
+ open: 'Open',
252
+ missingDocument: 'Deleted document',
253
+ linkHeading: (query: string) => query ? `Link to Document · “${query}”` : 'Link to Document',
254
+ createChildAndLink: (query: string) => `New Child Document “${query}” and Link`,
255
+ pickerHint: '↑↓ to choose · Enter to insert · Esc to close',
256
+ linkToDocument: 'Link to Document',
257
+ linkToDocumentHint: 'A reference to another document, a page, or a content block',
258
+ linkAliases: 'link|reference|document',
259
+ syncedBlock: 'Synced Block',
260
+ syncedBlockHint: 'A content block from another document, edited only there',
261
+ syncedAliases: 'synced|embed|transclude',
262
+ childDocument: 'Child Document',
263
+ childDocumentHint: 'A new document under this one, linked here',
264
+ childAliases: 'child|new document',
265
+ syncedFrom: 'Synced from',
266
+ editOriginal: 'Edit Original',
267
+ convertToCopy: 'Convert to Copy',
268
+ converted: 'Converted to a copy.',
269
+ sourceTrashed: 'The original document is in the trash · showing its current content',
270
+ sourceMissing: 'The original no longer exists',
271
+ syncedLoading: 'Loading synced block…',
272
+ syncedFailed: 'Couldn’t load the synced block’s content.',
273
+ syncedEmpty: 'The original content block has no text.',
274
+ syncedComponent: (title: string) => `Component: ${title}`,
275
+ insertSynced: 'Insert Synced Block',
276
+ chooseDocument: 'Document',
277
+ chooseBlock: 'Content block',
278
+ noBlocks: 'This document has no content blocks to sync.',
279
+ insert: 'Insert',
280
+ copySyncedLink: 'Copy Synced Block Link',
281
+ linkCopied: 'Copied the synced block link. Paste it into another document to insert a synced block.',
282
+ copyFailed: 'Couldn’t copy the link. Try again.',
283
+ blankDocument: 'Blank Document',
284
+ blankDocumentHint: 'Start from a title and add pages and animations as you go',
285
+ importHint: 'Make documents from files you already have',
286
+ needsAttention: 'Needs Attention',
287
+ treeIssues: (count: number) => `${count} ${count === 1 ? 'document has an invalid parent and is' : 'documents have an invalid parent and are'} shown at the top level for now. Move them where they belong.`,
288
+ show: 'Show',
289
+ trashCount: (count: number) => `${count} ${count === 1 ? 'document' : 'documents'} in the trash`,
290
+ allDocuments: 'All Documents',
291
+ pages: (count: number) => `${count} ${count === 1 ? 'page' : 'pages'}`,
292
+ inheritedFrom: (name: string) => `Inherited from “${name}”`,
293
+ inheritedWorkspace: 'Inherited from the workspace defaults',
294
+ override: 'Override',
295
+ useInherited: 'Use Inherited Value',
296
+ },
297
+ }
298
+
299
+ export type DocumentTreeMessages = typeof DOCUMENT_TREE_MESSAGES['en']
@@ -66,6 +66,19 @@ export interface WorkbenchState {
66
66
  isDark: boolean
67
67
  documents?: DocumentsAnswer
68
68
  documentsFailure?: string
69
+ /** The workspace's document tree and trash; `documentTreeFailure` is `tree-unavailable` when the host has none. */
70
+ documentTree?: import('@lincyaw/kernel/contracts').DocumentTree
71
+ documentTreeFailure?: string
72
+ isDocumentTreeLoading?: boolean
73
+ isDocumentTreeBusy?: boolean
74
+ /** The document whose title is being edited in the tree (a new one starts so). */
75
+ renamingDocument?: string
76
+ /** Documents opened recently in this browser, the latest first. */
77
+ recentDocuments?: import('./document-tree.ts').RecentDocument[]
78
+ /** Changes when cached reference previews and synced block sources are forgotten. */
79
+ documentLinksGeneration?: number
80
+ /** The one message at the bottom that says what an operation did. */
81
+ toast?: import('./knowledge-components.tsx').ToastMessage
69
82
  /** The workspace's routes answer 404: `@lincyaw/dsh` is turned off on the plugins page. */
70
83
  isBundleDisabled?: boolean
71
84
  document?: string
package/src/workbench.ts CHANGED
@@ -43,6 +43,7 @@ import { ProductionPlayback } from './production-playback.ts'
43
43
  import type { ProductionBinding, ProductionPlan, ProductionPlaybackCommand, ProductionPlaybackState } from '@lincyaw/kernel'
44
44
  import { workspaceClient, WorkspaceServerError } from './workspace-client.ts'
45
45
  import type { WorkspaceClient } from './workspace-client.ts'
46
+ import { DocumentTreeActions } from './document-tree.ts'
46
47
  import type { AuthoringClientAction, AuthoringClientActionType, AuthoringClientActionResult, AuthoringClientSnapshot } from '@lincyaw/kernel'
47
48
  import { PRODUCTION_PLAYBACK_RATES } from '@lincyaw/kernel'
48
49
 
@@ -116,6 +117,8 @@ export class Workbench {
116
117
  readonly production: DocumentProduction
117
118
  #removedDocumentPosition?: { identity: string, documentId: string, sectionId: string, stepId?: string, version: string, fingerprint: string, scope: number, generation: number, token: string }
118
119
  readonly editing: DocumentEditing
120
+ readonly tree: DocumentTreeActions
121
+ #pendingPlace?: { document: string | undefined, section: string, block?: string }
119
122
  #state: WorkbenchState
120
123
  readonly #listeners = new Set<Listener>()
121
124
  readonly #clientControls = new Set<AuthoringClientControls>()
@@ -226,6 +229,7 @@ export class Workbench {
226
229
  ...selected ? { stepId: selected } : {}, version: previous.version, fingerprint: previous.fingerprint, scope, generation, token: this.#state.documentPositionToken }
227
230
  }
228
231
  this.editing.finishOpening()
232
+ this.#applyPendingPlace()
229
233
  // Native insertion can select a page before the source actor receives that new entity.
230
234
  if (position && previous && previous.identity === authoring.identity && !previous.content?.sections[position.section]
231
235
  && authoring.content?.sections[position.section]) this.editing.saveReturnPoint()
@@ -243,6 +247,7 @@ export class Workbench {
243
247
  flush: signal => this.flushPendingEdits(signal), goToSection: section => this.goToSection(section),
244
248
  rememberStep: (directory, section, step) => { this.#selectedSteps.set(`${directory}\0${section}`, step) },
245
249
  canAskAnimation: () => this.#drafters.size > 0, askAnimation: place => this.draftAnimation(place) })
250
+ this.tree = new DocumentTreeActions({ client: this.client, store, open: (dir, focus) => this.openDocument(dir, focus ? { focus } : {}), reveal: (section, block) => this.#revealInDocument(section, block) })
246
251
  this.#diagnostics = new DocumentDiagnostics(this.client, store)
247
252
  this.#jobs = new DocumentJobs(this.client, store)
248
253
  this.#voiceover = new VoiceoverJobs(this.client, store, (job, signal) => this.#refreshVoiceover(job, signal))
@@ -436,6 +441,8 @@ export class Workbench {
436
441
  }
437
442
 
438
443
  async loadDocuments(): Promise<void> {
444
+ // With tree events the tree is read once and then on each change; without them, with the document list.
445
+ if (!this.client.subscribeTree || !this.#state.documentTree) void this.tree.load()
439
446
  try {
440
447
  this.#set({ documents: await this.client.readDocuments(), documentsFailure: undefined, isBundleDisabled: false })
441
448
  } catch (error) {
@@ -509,6 +516,7 @@ export class Workbench {
509
516
  this.#set({ ...DOCUMENT_RESET, document: dir, previewRenderer: 'web', webView: 'document' })
510
517
  this.editing.beginOpening(dir, options.focus, options.fallbackReturnPoint)
511
518
  this.#record('document.open')
519
+ this.tree.visited(this.tree.idOf(dir))
512
520
  this.#diagnostics.subscribe(dir)
513
521
  // Authoring is ready from source JSON; compilation and preview are independent.
514
522
  const [opened] = await Promise.all([this.#documentSession.open(dir, options.expectedIdentity, options.signal), this.#readFocus(dir, options.signal), this.#history.read(dir, options.signal)])
@@ -1380,6 +1388,21 @@ export class Workbench {
1380
1388
  documentNavigation: { section: sectionId, block: blockId, request: randomUUID() } })
1381
1389
  }
1382
1390
 
1391
+ /** Shows a page, or a block on it, of the open document once its content is there (a reference followed from elsewhere). */
1392
+ #revealInDocument(section: string, block?: string): void {
1393
+ this.#pendingPlace = { document: this.#state.document, section, ...block ? { block } : {} }
1394
+ this.#applyPendingPlace()
1395
+ }
1396
+
1397
+ #applyPendingPlace(): void {
1398
+ const place = this.#pendingPlace, content = this.#state.authoring?.content
1399
+ if (!place || place.document !== this.#state.document || !content) return
1400
+ this.#pendingPlace = undefined
1401
+ if (!content.sections[place.section]) return
1402
+ this.#set({ position: { section: place.section, step: 0, trail: [], view: 'document' }, documentPositionFailure: undefined,
1403
+ documentNavigation: { section: place.section, ...place.block && content.blocks[place.block] ? { block: place.block } : {}, request: randomUUID() } })
1404
+ }
1405
+
1383
1406
  observeDocumentSection(section: string): void {
1384
1407
  if (this.#state.webView !== 'document' || !this.#state.authoring?.content?.sections[section]) return
1385
1408
  if (this.#state.documentPositionFailure) this.#set({ documentPositionFailure: undefined })
@@ -1641,8 +1664,10 @@ export class Workbench {
1641
1664
  this.#record('shortcut', { 'presmium.command': report.command })
1642
1665
  if (report.command === 'dismiss') {
1643
1666
  if (this.#state.pointer) this.point(undefined)
1644
- } else if (report.command === 'undo') void this.undo()
1645
- else if (report.command === 'redo') void this.redo()
1667
+ // A preview's keys come from inside the page (a block preview in the editor): they reach the editor's history only,
1668
+ // never a saved version, which the toolbar's Undo and Redo take back.
1669
+ } else if (report.command === 'undo') this.editing.nativeHistory('undo')
1670
+ else if (report.command === 'redo') this.editing.nativeHistory('redo')
1646
1671
  else if (report.command === 'save') void this.flushPendingEdits().catch(() => {})
1647
1672
  else for (const listener of this.#playbackKeys) listener(report.command)
1648
1673
  break
@@ -1685,6 +1710,7 @@ export class Workbench {
1685
1710
  this.#stopSubscriptions()
1686
1711
  this.#diagnostics.dispose()
1687
1712
  this.#documentSession.dispose()
1713
+ this.tree.dispose()
1688
1714
  this.#commentDrafts.close()
1689
1715
  this.#componentPropertyDrafts.close()
1690
1716
  this.production.dispose()
@@ -15,6 +15,9 @@ import type { DocumentImageImport, DocumentImageImportAnswer } from '@lincyaw/ke
15
15
  import type { ProductionAssetAnswer, ProductionAssetQuery, ProductionMediaQuery, ProductionPlan, ProductionPlanQuery } from '@lincyaw/kernel'
16
16
  import type { DocumentTranscriptionRequest, TranscriptionCapabilities, TranscriptionTask, TranscriptionListAnswer, TranscriptionRevision, TranscriptionCancellation, TranscriptionAdoptionDraft, TranscriptionAdoptionPlan, TranscriptionAdoptionApply, TranscriptionAdoptionAnswer } from '@lincyaw/kernel'
17
17
  import { randomUUID } from '@lincyaw/kernel'
18
+ import type { ReferenceTarget } from '@lincyaw/kernel'
19
+ // The contract's DocumentTree is the workspace's answer; the kernel's root also names its own tree builder DocumentTree.
20
+ import type { DocumentLinks, DocumentPreview, DocumentSearchHit, DocumentTree, EmbedSource, TreeOperation, TreeOperationResult } from '@lincyaw/kernel/contracts'
18
21
 
19
22
  /** A change of the host's pending approvals that this author may answer. */
20
23
  export type ApprovalEvent =
@@ -82,6 +85,15 @@ export interface WorkspaceClient {
82
85
  importDocuments?(files: readonly File[], signal?: AbortSignal): Promise<import('@lincyaw/kernel').DocumentImportAnswer>
83
86
  /** Converts the workspace's documents to the current format, one revision per document. */
84
87
  migrateWorkspace?(): Promise<import('@lincyaw/kernel').WorkspaceMigrationAnswer>
88
+ /** The workspace's document tree and trash (absent for a host without one). */
89
+ readTree?(signal?: AbortSignal): Promise<DocumentTree>
90
+ operateTree?(operation: TreeOperation, signal?: AbortSignal): Promise<TreeOperationResult>
91
+ readDocumentLinks?(id: string, signal?: AbortSignal): Promise<DocumentLinks>
92
+ searchDocuments?(query: string, limit?: number, signal?: AbortSignal): Promise<DocumentSearchHit[]>
93
+ readDocumentPreview?(target: ReferenceTarget, signal?: AbortSignal): Promise<DocumentPreview>
94
+ readEmbedSource?(source: { document: string, block: string }, signal?: AbortSignal): Promise<EmbedSource>
95
+ /** Each change of the workspace's document tree (created, moved, renamed, trashed, restored). */
96
+ subscribeTree?(changed: () => void, failed?: () => void): () => void
85
97
  planProjectChange(request: ProjectPlanRequest): Promise<ProjectPlan>
86
98
  operateDocument(operation: ProjectOperation, planned?: ProjectPlan): Promise<OperationAnswer>
87
99
  readSource(document: string, path: string): Promise<SourceAnswer>
@@ -205,7 +217,7 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
205
217
  const path = target.pathname.slice(prefix.length)
206
218
  const method = (init?.method ?? 'GET').toUpperCase()
207
219
  if (client.capabilities?.readOnly && !['GET', 'HEAD', 'OPTIONS'].includes(method)
208
- && /^(?:documents?(?:\/|$)|source(?:\/|$)|project\/|pages\/|history\/|revisions\/|review(?:\/|$))/.test(path)) throw new WorkspaceServerError(403, { error: 'permission-denied' })
220
+ && /^(?:documents?(?:\/|$)|tree\/|source(?:\/|$)|project\/|pages\/|history\/|revisions\/|review(?:\/|$))/.test(path)) throw new WorkspaceServerError(403, { error: 'permission-denied' })
209
221
  if (path === 'telemetry' || (path === 'diagnostics' || path === 'diagnostics/authoring') && method === 'POST') return fetch(address, { credentials: 'same-origin', ...init })
210
222
  const document = target.searchParams.get('document') ?? undefined
211
223
  const requestId = ++requestSequence
@@ -380,6 +392,18 @@ export function workspaceClient(base = 'api/presmium/', subscription?: Workspace
380
392
  return call(url('documents/import'), { method: 'POST', body, signal })
381
393
  },
382
394
  migrateWorkspace: () => call(url('workspace/migrate'), { method: 'POST' }),
395
+ readTree: signal => call(url('tree'), { signal }),
396
+ operateTree: (operation, signal) => post(url('tree/operation'), operation, signal),
397
+ readDocumentLinks: (id, signal) => call(url('document/links', undefined, { id }), { signal }),
398
+ searchDocuments: (q, limit = 20, signal) => call(url('documents/search', undefined, { q, limit: String(limit) }), { signal }),
399
+ readDocumentPreview: (target, signal) => call(url('document/preview', undefined, { id: target.document, ...target.section ? { section: target.section } : {}, ...target.block ? { block: target.block } : {} }), { signal }),
400
+ readEmbedSource: async (source, signal) => {
401
+ const answer = await call<EmbedSource>(url('embed/source', undefined, { document: source.document, block: source.block }), { signal })
402
+ // Asset URLs are relative to the workspace routes; the editor loads them from any page.
403
+ const routes = new URL(base, globalThis.document.baseURI)
404
+ return answer.assets ? { ...answer, assets: Object.fromEntries(Object.entries(answer.assets).map(([id, address]) => [id, new URL(address, routes).href])) } : answer
405
+ },
406
+ subscribeTree: (changed, failed) => subscribe(url('tree/events', ''), 'tree', () => changed(), failed),
383
407
  readSource: (document, path) => call(url('source', document, { path })),
384
408
  saveSource: (document, path, content, base, message) => post(url('source', document), { path, content, base, ...message ? { message } : {} }),
385
409
  saveSourceTransaction: (document, changes, message) => post(url('source/transaction', document), { changes, ...message ? { message } : {} }),