feat(editor-header): 编辑器头部支持外部插件注册动作(registerTabAction,feature 'tabActions')
宿主的 sidebar.right.tab.document.actions 插槽属于宿主自己的文档预览面; 本插件接管 dsh-resource://file/** 之后文件不再进宿主预览,该插槽无人渲染, 「上传到云端」「存到云盘」「在 App 中打开」这类按钮整体消失。 新增 registerTabAction/getTabActions:按钮渲染在刷新与文件树开关右侧, 回调拿到 tabId/tabType/sessionId/path/isDir/title 与 fail 出口,失败落错误条, 同一 (id, tabId) 飞行中重复点击忽略,when 抛错只隐藏自身。
This commit is contained in:
1 parent
bff5beb689
commit
01146717c0
6 files changed
+473
-1
No files matched your search
@@ -4,6 +4,9 @@
|
||||
|
||||
### v0.30.1
|
||||
|
||||
- 🧩 **编辑器头部也能挂外部按钮了(`registerTabAction`,新能力 `'tabActions'`)**:文件 tab 进的是本插件的 `editor` / `code` 视图,宿主的 `sidebar.right.tab.document.actions` 插槽属于**宿主自己的**文档预览面,于是「上传到云端」「存到云盘」「在 App 中打开」这类由宿主插槽承载的按钮会整体消失(用户实测:禁用本插件后按钮才出现)。现在 `ctx.betterSidebar.registerTabAction({ id, label, title, icon, order, when, run })` 在刷新与文件树开关右侧加按钮:回调拿到 `tabId / tabType / sessionId / path / isDir / title` 与一个 `fail` 出口,失败落进编辑器上方的错误条,同一 (id, tabId) 在飞行中的重复点击被忽略,`when` 抛错只隐藏该注册。说明与「这一面为什么需要自己的扩展点」写进[指南 §7.4](docs/external-plugin-guide.md)。
|
||||
- 🧪 测试:新增 `tests/tab-actions.spec.tsx`(9 例:能力声明与初始为空、注册序 = order 升序 + 注册序、重复 id 抛错、旧 disposer 不能拆掉新注册、dispose 清表、头部渲染与 run 上下文、挂载后注册的按钮会补上、`when` 过滤与抛错隔离、失败进错误条)。
|
||||
|
||||
- 🧩 **插件可以往文件树的行菜单里加自己的动作(`registerFileAction`,新能力 `'fileActions'`)**:此前文件树的右键菜单完全由插件自己组装(打开方式 / 下载 / 上传到此目录 / 复制 / 重命名 / 删除),外部插件没有任何位置能加一项——「把这个文件传到我的云端」这类入口只能另开界面。现在 `ctx.betterSidebar.registerFileAction({ id, label, icon, row, dirs, order, when, run })` 注册的项排在内置打开/下载行之后、复制/重命名之前;`row: true` 再在行右侧「引用」按钮旁加一个悬停按钮(要求同时给 `icon`)。回调拿到的是行的**绝对路径**加上这棵树的根与会话,失败按既有策略落进文件树的错误条(`run` 抛错即 `error.message`),**树只提供入口,不替注册方上传、复制或移动任何东西**;同一 (id, path) 在飞行中的重复点击会被忽略。`when` 抛错只隐藏该注册,不打断文件树。接入面与两条约定写进[指南 §7.3](docs/external-plugin-guide.md)。
|
||||
- 🧪 测试:新增 `tests/file-actions.spec.tsx`(12 例:注册序 = order 升序 + 注册序、重复 id 抛错、旧 disposer 不能拆掉新注册、菜单位置、绝对路径/根/会话、目录默认不认领、`when` 判定与抛错隔离、悬停按钮与 `title`/`aria-label`、无图标只进菜单、reject 落错误条且成功静默)。
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
|
||||
### v0.30.1
|
||||
|
||||
- 🧩 **External buttons can now live in the editor header (`registerTabAction`, new `'tabActions'` capability)**: file tabs open in this plugin's `editor` / `code` views, while the host's `sidebar.right.tab.document.actions` slot belongs to the host's own document preview — so host-slot buttons such as "upload to cloud", "save to my drive" or "open in app" vanished entirely whenever this plugin rendered the file (observed in the field: disabling the plugin made the button appear). `ctx.betterSidebar.registerTabAction({ id, label, title, icon, order, when, run })` now adds buttons right of the refresh and tree controls: the callback receives `tabId / tabType / sessionId / path / isDir / title` plus a `fail` exit, a failure lands in the editor's error strip, a second press on the same (id, tabId) while in flight is ignored, and a throwing `when` hides just its own registration. The surface and why this face needs its own extension point are documented in [guide §7.4](docs/external-plugin-guide.md).
|
||||
- 🧪 `tests/tab-actions.spec.tsx` (9 cases): capability declared and initially empty, render order = `order` ascending then registration order, duplicate ids throw, a stale disposer cannot tear down a newer registration, disposal empties the registry, header render plus run context, a registration made after mount still appears, `when` filtering with throw isolation, and a failure landing in the error strip.
|
||||
|
||||
- 🧩 **Plugins can contribute actions to the file tree's row menu (`registerFileAction`, new `'fileActions'` capability)**: the row menu used to be assembled entirely by this plugin (open with / download / upload here / copy / rename / delete), leaving external plugins no place to add an entry — "send this file to my cloud" had to live in some other surface. Entries registered with `ctx.betterSidebar.registerFileAction({ id, label, icon, row, dirs, order, when, run })` now render after the built-in open/download rows and before the copy/mutation block; `row: true` also adds a hover button next to the row's reference button (an `icon` is required for that). The callback receives the row's **absolute path** plus the tree's root and session, and a failure lands in the tree's error strip under the existing policy (`run` throwing reports `error.message`) — **the tree contributes the entry point only; the registrant does the uploading, copying or moving**. A second press on the same (id, path) while the first is in flight is ignored. A `when` that throws hides just its own registration instead of breaking the tree. The surface and its two rules are documented in [guide §7.3](docs/external-plugin-guide.md).
|
||||
- 🧪 `tests/file-actions.spec.tsx` (12 cases): render order = `order` ascending then registration order, duplicate ids throw, a stale disposer cannot tear down a newer registration, menu position, absolute path/root/session, directories excluded by default, `when` filtering plus throw isolation, hover button with `title`/`aria-label`, glyph-less registrations stay menu-only, a rejection lands in the strip while success stays silent.
|
||||
|
||||
|
||||
@@ -746,6 +746,9 @@ interface BetterSidebarService {
|
||||
registerFileIcon(descriptor: FileIconDescriptor): () => void
|
||||
/** 往文件树行菜单加一项(v0.31.0+,features 含 'fileActions');返回 disposer */
|
||||
registerFileAction(descriptor: FileActionDescriptor): () => void
|
||||
/** 编辑器头部的外部按钮(§7.4) */
|
||||
registerTabAction(descriptor: TabActionDescriptor): () => void
|
||||
getTabActions(): readonly TabActionDescriptor[]
|
||||
/** 当前已注册的 tab 描述符快照(同步,供 useSyncExternalStore 用;含被设置页禁用的类型) */
|
||||
getTabs(): readonly TabDescriptor[]
|
||||
/** 当前已注册的 file viewer 描述符快照(含被设置页禁用的 viewer) */
|
||||
@@ -1161,6 +1164,78 @@ if (ctx.betterSidebar.features.includes('fileActions')) {
|
||||
|
||||
---
|
||||
|
||||
### 7.4 编辑器头部动作(tabActions,v0.32.0+)
|
||||
|
||||
文件 tab 的头部原本只有插件自己的按钮(预览 / 编辑 / 保存 / 刷新 / 文件树)。`registerTabAction` 让外部插件在刷新与文件树按钮右侧再加自己的按钮——**同样只管入口,不管动作**:头部不替你上传或解析任何东西,它只把 tab 的事实交给你、把你的失败原样显示出来。
|
||||
|
||||
为什么需要它:宿主的 `sidebar.right.tab.document.actions` 插槽属于**宿主自己的**文档预览面。本插件用 `editor` / `code` 类型接管了 `dsh-resource://file/**`,文件不再进宿主的预览,那个插槽也就没有人渲染了——「上传到云端」「存到云盘」「在 App 中打开」这类按钮会整体消失。要让它们在这一面继续存在,就得有这一面的扩展点。
|
||||
|
||||
```ts
|
||||
interface TabActionDescriptor {
|
||||
/** 唯一 id('my-plugin:upload');重复注册同一个 id 会抛错 */
|
||||
id: string
|
||||
/** 按钮文案(接受 thunk)。空串 = 只画图标 */
|
||||
label: string | (() => string)
|
||||
/** tooltip / 无障碍名;缺省用 label */
|
||||
title?: string | (() => string)
|
||||
/** 按钮图标;`(size) => ReactNode` 形式会收到尺寸 */
|
||||
icon?: ReactNode | ((size: number) => ReactNode)
|
||||
/** 外部动作之间的排序(升序,默认 0);内置按钮不受影响 */
|
||||
order?: number
|
||||
/** 只对部分 tab 出现;每次头部渲染调一次,必须廉价且无副作用。
|
||||
* 抛错 = 该注册自己隐藏,不会打断头部 */
|
||||
when?: (context: Omit<TabActionContext, 'fail'>) => boolean
|
||||
/** 真正干活。抛错或 reject 会以 error.message 落进编辑器上方的错误条;
|
||||
* resolve 则静默(成功提示由注册方自己给)。同一 (id, tabId) 在飞行中
|
||||
* 的重复点击会被忽略 */
|
||||
run: (context: TabActionContext) => void | Promise<void>
|
||||
}
|
||||
|
||||
/** `when` / `run` 看到的 tab 事实 */
|
||||
interface TabActionContext {
|
||||
tabId: string
|
||||
tabType: string // 'editor' / 'terminal' / …
|
||||
sessionId: string
|
||||
path: string // 文件 tab 的路径;无路径的 Files 窗口是 ''
|
||||
isDir: boolean
|
||||
title: string
|
||||
fail(message: string): void // 仅 `run` 有
|
||||
}
|
||||
```
|
||||
|
||||
**用法**(把同一份上传动作同时挂到文件树行菜单和编辑器头部):
|
||||
|
||||
```ts
|
||||
if (ctx.betterSidebar.features.includes('tabActions')) {
|
||||
ctx.effect(() =>
|
||||
ctx.betterSidebar.registerTabAction({
|
||||
id: 'my-plugin:upload',
|
||||
label: () => t('uploadToCloud'),
|
||||
icon: size => <IconCloudArrowUp size={size} />,
|
||||
order: 10,
|
||||
when: tab => tab.path !== '' && !tab.isDir,
|
||||
run: async ({ path, fail }) => {
|
||||
const answer = await fetch('/my-plugin/api/upload', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ path }),
|
||||
})
|
||||
if (!answer.ok) fail(await answer.text())
|
||||
},
|
||||
})
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
**渲染位置**:编辑器头部最右侧——保存状态、刷新、文件树开关之后,`order` 升序(同序按注册序)。有 `label` 的按钮用与「预览 / 编辑」一致的文本按钮样式,空 `label` 用图标按钮样式。头部只在文件 tab 上渲染,所以无路径的 Files 窗口不会被塞进一排按钮(`when` 仍会看到 `path: ''`)。
|
||||
|
||||
**两条约定**:
|
||||
|
||||
- **头部不替你做确认**。危险动作的二次确认在 `run` 里自己做。
|
||||
- **`path` 的安全边界由你负责**。头部给的是 tab 的路径原文,是否在工作区内、大小限制如何,不在这层——见 §10 的平台约束。
|
||||
|
||||
---
|
||||
|
||||
## 8. 声明式设置(v0.4.1+)
|
||||
|
||||
每个注册的 tab / viewer **自动**出现在 DSH 设置页「侧边卡片」分区(`SideCardSection` 按注册表驱动渲染,无硬编码),**`hidden: true` 的 tab 类型除外**:
|
||||
|
||||
+101
-1
@@ -45,10 +45,33 @@ import { consumeLineTarget, peekLineTarget } from './line-target.ts'
|
||||
import { relativeTo } from './paths.ts'
|
||||
import { resolveSidebarPath } from './paths.ts'
|
||||
import { clearRetargetedPath, closePathTabs, consumeRetargetedPath, pathTabKey, retargetPathTabs } from './tree-mutations.ts'
|
||||
import type { EditorToolbarControls, EditorToolbarState, FileViewerDescriptor } from './service.ts'
|
||||
import type { EditorToolbarControls, EditorToolbarState, FileViewerDescriptor, TabActionDescriptor } from './service.ts'
|
||||
import { firstLeaf, insertLeafAt, leafWithTab, mintTabId, type SidebarStore, type SidebarTab } from './state.ts'
|
||||
import css from './sidebar.module.css'
|
||||
|
||||
/**
|
||||
* Resolve a descriptor's `string | (() => string)` text, first non-empty wins.
|
||||
* A throwing thunk is logged and skipped: one broken label must not take the
|
||||
* whole header down.
|
||||
*/
|
||||
function textOf(...values: Array<string | (() => string) | undefined>): string {
|
||||
for (const value of values) {
|
||||
if (value === undefined) continue
|
||||
if (typeof value === 'string') {
|
||||
if (value !== '') return value
|
||||
continue
|
||||
}
|
||||
try {
|
||||
const text = value()
|
||||
if (typeof text === 'string' && text !== '') return text
|
||||
}
|
||||
catch (error) {
|
||||
console.error('[dsh-better-sidebar] tab action label error:', error)
|
||||
}
|
||||
}
|
||||
return ''
|
||||
}
|
||||
|
||||
/** One landing navigation the editor host has read from the side channel. */
|
||||
interface LineNav { key: string; nonce: number | null; end?: number }
|
||||
|
||||
@@ -153,6 +176,28 @@ export function EditorHost(props: {
|
||||
// with the same path/scope — the only reload entry besides open/close.
|
||||
const [reloadSeq, setReloadSeq] = useState(0)
|
||||
|
||||
/**
|
||||
* External header buttons (feature `tabActions`). The registry lives on the
|
||||
* client service, so the header subscribes to it instead of receiving the
|
||||
* list as a prop: an editor tab renders inside the host's tree, and the
|
||||
* plugins that contribute buttons activate AFTER this component mounted.
|
||||
*/
|
||||
const tabActionService = ctx.get('betterSidebar')
|
||||
const [tabActions, setTabActions] = useState<readonly TabActionDescriptor[]>(
|
||||
() => tabActionService?.getTabActions() ?? [],
|
||||
)
|
||||
useEffect(() => {
|
||||
if (tabActionService === undefined) return
|
||||
const sync = (): void => { setTabActions(tabActionService.getTabActions()) }
|
||||
sync()
|
||||
return tabActionService.subscribe(sync)
|
||||
}, [tabActionService])
|
||||
|
||||
/** A failure reported by an external action; cleared on the next reload. */
|
||||
const [actionError, setActionError] = useState<string | null>(null)
|
||||
/** Runs in flight, keyed `actionId:tabId`, so a double press is ignored. */
|
||||
const runningActions = useRef(new Set<string>())
|
||||
|
||||
// The reference's landing line, SPENT once per open (#826).
|
||||
//
|
||||
// `tab.line` is one navigation, but the record keeps it for as long as the
|
||||
@@ -649,6 +694,43 @@ export function EditorHost(props: {
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The buttons this tab shows: `when` runs once per render and a throwing
|
||||
* predicate drops its own button rather than the whole header.
|
||||
*/
|
||||
const visibleTabActions = tabActions.filter((action) => {
|
||||
if (action.when === undefined) return true
|
||||
try {
|
||||
return action.when({ tabId: tab.id, tabType: tab.type, sessionId: scope.sessionId, path, isDir, title })
|
||||
}
|
||||
catch (error) {
|
||||
console.error('[dsh-better-sidebar] tab action predicate error:', error)
|
||||
return false
|
||||
}
|
||||
})
|
||||
|
||||
/** Run one external action; the header owns the in-flight guard. */
|
||||
const runTabAction = (action: TabActionDescriptor): void => {
|
||||
if (!visible) return
|
||||
const key = `${action.id}:${tab.id}`
|
||||
if (runningActions.current.has(key)) return
|
||||
runningActions.current.add(key)
|
||||
setActionError(null)
|
||||
const fail = (message: string): void => { setActionError(`${textOf(action.title, action.label, action.id)}: ${message}`) }
|
||||
try {
|
||||
const outcome = action.run({ tabId: tab.id, tabType: tab.type, sessionId: scope.sessionId, path, isDir, title, fail })
|
||||
if (outcome !== undefined) {
|
||||
void outcome.catch((error: unknown) => { fail(error instanceof Error ? error.message : String(error)) })
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
fail(error instanceof Error ? error.message : String(error))
|
||||
}
|
||||
finally {
|
||||
runningActions.current.delete(key)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={css.editor}>
|
||||
<div className={css.editorHeader}>
|
||||
@@ -716,9 +798,27 @@ export function EditorHost(props: {
|
||||
>
|
||||
<IconFolderOpenRegular size={14} />
|
||||
</button>
|
||||
{visibleTabActions.map((action) => {
|
||||
const label = textOf(action.label)
|
||||
const glyph = typeof action.icon === 'function' ? action.icon(14) : action.icon
|
||||
return (
|
||||
<button
|
||||
key={action.id}
|
||||
type="button"
|
||||
className={label === '' ? css.iconButton : css.editorModeButton}
|
||||
aria-label={textOf(action.title, label, action.id)}
|
||||
title={textOf(action.title, label, action.id)}
|
||||
onClick={() => { runTabAction(action) }}
|
||||
>
|
||||
{glyph}
|
||||
{label !== '' && <span>{label}</span>}
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<div className={css.editorBody}>
|
||||
<div className={css.editorMain}>
|
||||
{actionError !== null && <div className={css.editorError}>{actionError}</div>}
|
||||
{showEmpty && <div className={css.editorPlaceholder}>{t('editorEmptyHint')}</div>}
|
||||
{!showEmpty && load.status === 'loading' && <div className={css.editorPlaceholder}>{t('loading')}</div>}
|
||||
{!showEmpty && load.status === 'error' && <div className={css.editorError}>{load.message}</div>}
|
||||
|
||||
@@ -478,6 +478,61 @@ export interface FileActionRow {
|
||||
isDir: boolean
|
||||
}
|
||||
|
||||
/** What a tab action is handed when it runs. */
|
||||
export interface TabActionContext {
|
||||
/** The tab whose header drew the button. */
|
||||
tabId: string
|
||||
/** The tab's type (`editor`, `terminal`, …). */
|
||||
tabType: string
|
||||
/** The session the tab belongs to. */
|
||||
sessionId: string
|
||||
/** The tab's file path; `''` for a path-less tab (the Files home). */
|
||||
path: string
|
||||
/** Whether the tab shows a directory instead of a file. */
|
||||
isDir: boolean
|
||||
/** The tab's current title. */
|
||||
title: string
|
||||
/**
|
||||
* Show a message in the sidebar's own error strip. Use it for anything the
|
||||
* user must read; an exception thrown by `run` reaches the same strip as
|
||||
* `error.message`.
|
||||
*/
|
||||
fail: (message: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Describes one external tab action (feature `tabActions`): a button in the
|
||||
* editor's header, right of the built-in save / reload / tree controls.
|
||||
*
|
||||
* The callback runs CLIENT-SIDE only — the plugin that registers it owns the
|
||||
* work (its own routes, its own toasts). The header contributes the entry
|
||||
* point and the error strip; it never uploads, copies or moves anything.
|
||||
*/
|
||||
export interface TabActionDescriptor {
|
||||
/** Unique id (`'my-plugin:upload'`). Re-registering the same id throws. */
|
||||
id: string
|
||||
/** Button label (i18n-friendly: string or a thunk). Empty = glyph only. */
|
||||
label: string | (() => string)
|
||||
/** Tooltip / accessible name; defaults to the label. */
|
||||
title?: string | (() => string)
|
||||
/** Leading glyph for the button. */
|
||||
icon?: ReactNode | ((size: number) => ReactNode)
|
||||
/** Order among external actions; ascending, default 0. */
|
||||
order?: number
|
||||
/**
|
||||
* Whether the action applies to one tab. Called once per header render, so
|
||||
* it must be cheap and side-effect free. Omitted = every editor tab.
|
||||
*/
|
||||
when?: (context: Omit<TabActionContext, 'fail'>) => boolean
|
||||
/**
|
||||
* Do the work. A rejected promise is reported as `error.message` in the
|
||||
* sidebar's error strip; a resolved one says nothing (the owner reports its
|
||||
* own outcome). Runs are guarded per (id, tabId): a second press while the
|
||||
* first is in flight is ignored.
|
||||
*/
|
||||
run: (context: TabActionContext) => void | Promise<void>
|
||||
}
|
||||
|
||||
/** What a file action is handed when it runs. */
|
||||
export interface FileActionContext extends FileActionRow {
|
||||
/**
|
||||
@@ -707,11 +762,19 @@ export interface BetterSidebarService {
|
||||
* reference button. The registration is disposed with the plugin fiber.
|
||||
*/
|
||||
registerFileAction(descriptor: FileActionDescriptor): () => void
|
||||
/**
|
||||
* Contribute a button to the editor's header (feature `tabActions`).
|
||||
* Buttons appear right of the built-in controls, in `order` (then
|
||||
* registration) order. The registration is disposed with the plugin fiber.
|
||||
*/
|
||||
registerTabAction(descriptor: TabActionDescriptor): () => void
|
||||
getTabs(): readonly TabDescriptor[]
|
||||
getFileViewers(): readonly FileViewerDescriptor[]
|
||||
getFileIcons(): readonly FileIconDescriptor[]
|
||||
/** Every registered file action, in the order the tree renders them. */
|
||||
getFileActions(): readonly FileActionDescriptor[]
|
||||
/** Every registered tab action, in the order the header renders them. */
|
||||
getTabActions(): readonly TabActionDescriptor[]
|
||||
/**
|
||||
* Find a SPECIFIC registered file icon for a path (priority desc, then
|
||||
* registration order): a `names` match first, then an `exts` match.
|
||||
@@ -962,6 +1025,10 @@ export const SIDEBAR_SERVICE_VERSION = '0.30.1'
|
||||
* contributions to the file tree's row menu (and, with `row: true`, a
|
||||
* hover button on the row). The callback is client-side only: the tree
|
||||
* supplies the entry point and the error strip, the owner does the work.
|
||||
* - 'tabActions' (v0.32.0): registerTabAction/getTabActions — external buttons
|
||||
* in the editor header (right of save/reload/tree). Same contract as
|
||||
* `fileActions`: the header supplies the entry point, the owner does the
|
||||
* work.
|
||||
*
|
||||
* v0.19.0 REMOVED 'floatWindows': the free-window feature is gone (DSH 0.1.5
|
||||
* owns the right column, so the plugin keeps only its bottom workbench).
|
||||
@@ -983,6 +1050,7 @@ export const SIDEBAR_FEATURES = [
|
||||
'settingPatterns',
|
||||
'hostRouteUrl',
|
||||
'fileActions',
|
||||
'tabActions',
|
||||
] as const
|
||||
|
||||
/** Run one plugin callback; a throw is logged and never breaks the caller. */
|
||||
@@ -1004,6 +1072,7 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
const viewers = new Map<string, FileViewerDescriptor>()
|
||||
const fileIcons = new Map<string, FileIconDescriptor>()
|
||||
const fileActions = new Map<string, FileActionDescriptor>()
|
||||
const tabActions = new Map<string, TabActionDescriptor>()
|
||||
const listeners = new Set<() => void>()
|
||||
/** The native right-Sidebar write face, installed by the client half. */
|
||||
let surface: SidebarSurface | undefined
|
||||
@@ -1100,6 +1169,24 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
const getFileActions = (): readonly FileActionDescriptor[] =>
|
||||
Array.from(fileActions.values()).sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
|
||||
|
||||
const registerTabAction = (descriptor: TabActionDescriptor): (() => void) => {
|
||||
if (tabActions.has(descriptor.id)) {
|
||||
throw new Error(`[dsh-better-sidebar] tab action "${descriptor.id}" already registered`)
|
||||
}
|
||||
tabActions.set(descriptor.id, descriptor)
|
||||
notify()
|
||||
return () => {
|
||||
if (tabActions.get(descriptor.id) === descriptor) {
|
||||
tabActions.delete(descriptor.id)
|
||||
notify()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** External tab actions in render order — same ranking as the file rows. */
|
||||
const getTabActions = (): readonly TabActionDescriptor[] =>
|
||||
Array.from(tabActions.values()).sort((a, b) => (a.order ?? 0) - (b.order ?? 0))
|
||||
|
||||
// Registrations in ranking order: priority desc, stable for equal
|
||||
// priorities (insertion order) — the same ranking `matchFileViewer` uses.
|
||||
const rankedFileIcons = (): FileIconDescriptor[] =>
|
||||
@@ -1594,10 +1681,12 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe
|
||||
registerFileViewer,
|
||||
registerFileIcon,
|
||||
registerFileAction,
|
||||
registerTabAction,
|
||||
getTabs,
|
||||
getFileViewers,
|
||||
getFileIcons,
|
||||
getFileActions,
|
||||
getTabActions,
|
||||
matchFileIcon,
|
||||
matchFolderIcon,
|
||||
fileIcon,
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* External tab actions (feature `tabActions`): the registry half, and the
|
||||
* editor header that draws the buttons — placement, `when` filtering, the
|
||||
* run context, and a failure landing in the error strip instead of the
|
||||
* console.
|
||||
*/
|
||||
// @vitest-environment jsdom
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createElement } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { act } from 'react-dom/test-utils'
|
||||
import type { Context } from '../src/context-types.ts'
|
||||
import { EditorHost } from '../src/client/EditorHost.tsx'
|
||||
import { createBetterSidebarService, type TabActionDescriptor } from '../src/client/service.ts'
|
||||
import { createSidebarStore, type SidebarTab } from '../src/client/state.ts'
|
||||
|
||||
// The tree dock subscribes to the git-status poll and the editor reads files
|
||||
// through these seams; a path-less tab fetches neither, but the module-level
|
||||
// imports still resolve, so the answer shape stays honest.
|
||||
vi.mock('../src/client/api.ts', () => ({
|
||||
api: {
|
||||
fsTrees: async () => ({ levels: [] }),
|
||||
gitStatus: async () => ({ isRepo: false, entries: [] }),
|
||||
fsRead: async () => ({ content: 'const a = 1\n', size: 12 }),
|
||||
openExternal: async () => ({ started: true }),
|
||||
},
|
||||
archiveDownloadUrl: () => '/sidebar/archive?id=ar-1',
|
||||
downloadUrl: () => '/sidebar/file',
|
||||
mediaUrl: () => '/sidebar/file',
|
||||
archiveUrl: () => '/sidebar/archive',
|
||||
isOutsideWorkspaceMessage: () => false,
|
||||
}))
|
||||
|
||||
import { setupReactAct } from './test-utils.ts'
|
||||
setupReactAct()
|
||||
|
||||
let sessionSeq = 0
|
||||
let sessionId: string
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
sessionId = `tab-actions-session-${++sessionSeq}`
|
||||
})
|
||||
|
||||
/** One external tab action with test-friendly defaults. */
|
||||
function action(id: string, overrides: Partial<TabActionDescriptor> = {}): TabActionDescriptor {
|
||||
return { id, label: id.toUpperCase(), run: () => {}, ...overrides }
|
||||
}
|
||||
|
||||
describe('tabActions registry', () => {
|
||||
it('declares the feature and starts empty', () => {
|
||||
const service = createBetterSidebarService(createSidebarStore())
|
||||
expect(service.features).toContain('tabActions')
|
||||
expect(service.getTabActions()).toEqual([])
|
||||
})
|
||||
|
||||
it('answers in render order: order ascending, then registration order', () => {
|
||||
const service = createBetterSidebarService(createSidebarStore())
|
||||
service.registerTabAction(action('late', { order: 5 }))
|
||||
service.registerTabAction(action('early', { order: -5 }))
|
||||
service.registerTabAction(action('default'))
|
||||
service.registerTabAction(action('default-second'))
|
||||
expect(service.getTabActions().map(entry => entry.id)).toEqual(
|
||||
['early', 'default', 'default-second', 'late'],
|
||||
)
|
||||
})
|
||||
|
||||
it('refuses a duplicate id', () => {
|
||||
const service = createBetterSidebarService(createSidebarStore())
|
||||
service.registerTabAction(action('same'))
|
||||
expect(() => service.registerTabAction(action('same'))).toThrow(/already registered/u)
|
||||
})
|
||||
|
||||
it('a stale disposer cannot remove a newer registration', () => {
|
||||
const service = createBetterSidebarService(createSidebarStore())
|
||||
const disposeFirst = service.registerTabAction(action('same'))
|
||||
disposeFirst()
|
||||
const replacement = action('same')
|
||||
service.registerTabAction(replacement)
|
||||
disposeFirst()
|
||||
expect(service.getTabActions()).toEqual([replacement])
|
||||
})
|
||||
|
||||
it('disposal empties the registry for the header', () => {
|
||||
const service = createBetterSidebarService(createSidebarStore())
|
||||
const dispose = service.registerTabAction(action('gone'))
|
||||
expect(service.getTabActions()).toHaveLength(1)
|
||||
dispose()
|
||||
expect(service.getTabActions()).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
/** A service + ctx over a path-less files window (no tree, no file read). */
|
||||
function harness(): {
|
||||
service: ReturnType<typeof createBetterSidebarService>
|
||||
ctx: Context
|
||||
store: ReturnType<typeof createSidebarStore>
|
||||
tab: () => SidebarTab
|
||||
} {
|
||||
const store = createSidebarStore()
|
||||
const service = createBetterSidebarService(store)
|
||||
service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: tab => tab.path, component: () => null })
|
||||
store.setSession(sessionId)
|
||||
service.openTab({ type: 'editor', title: 'Files', meta: { treeOpen: false } })
|
||||
// A FILE tab (not the path-less window): split mode turns a path-less
|
||||
// window into the standalone explorer, which draws no editor header.
|
||||
const tab = (): SidebarTab => ({ id: 'tab-file', type: 'editor', title: 'a.ts', path: '/tmp/a.ts' })
|
||||
const ctx = {
|
||||
betterSidebar: service,
|
||||
get: (name: string) => name === 'betterSidebar' ? service : undefined,
|
||||
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => ({ byId: { [sessionId]: { cwd: '/tmp' } }, current: sessionId }) } },
|
||||
} as unknown as Context
|
||||
return { service, ctx, store, tab }
|
||||
}
|
||||
|
||||
/** Mount the editor header for the harness' tab; returns the container. */
|
||||
function mount(ctx: Context, store: ReturnType<typeof createSidebarStore>, tab: () => SidebarTab): { container: HTMLDivElement; unmount: () => void } {
|
||||
const container = document.createElement('div')
|
||||
document.body.append(container)
|
||||
const root = createRoot(container)
|
||||
act(() => {
|
||||
root.render(createElement(EditorHost, {
|
||||
ctx,
|
||||
store,
|
||||
scope: { sessionId },
|
||||
tab: tab(),
|
||||
expanded: [],
|
||||
revealed: [],
|
||||
onToggleDir: () => {},
|
||||
onReferenceFile: () => {},
|
||||
}))
|
||||
})
|
||||
return { container, unmount: () => { act(() => { root.unmount() }); container.remove() } }
|
||||
}
|
||||
|
||||
describe('tabActions in the editor header', () => {
|
||||
it('draws a registered action and hands it the tab context', () => {
|
||||
const { service, ctx, store, tab } = harness()
|
||||
const run = vi.fn()
|
||||
service.registerTabAction(action('upload', { label: '上传到云端', run }))
|
||||
const page = mount(ctx, store, tab)
|
||||
try {
|
||||
const button = [...page.container.querySelectorAll('button')]
|
||||
.find(el => el.textContent === '上传到云端')
|
||||
expect(button).toBeDefined()
|
||||
act(() => { button!.click() })
|
||||
expect(run).toHaveBeenCalledTimes(1)
|
||||
expect(run.mock.calls[0]![0]).toMatchObject({ sessionId, path: '/tmp/a.ts', isDir: false, tabType: 'editor' })
|
||||
}
|
||||
finally {
|
||||
page.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('an action registered AFTER the mount still appears', () => {
|
||||
const { service, ctx, store, tab } = harness()
|
||||
const page = mount(ctx, store, tab)
|
||||
try {
|
||||
act(() => { service.registerTabAction(action('late', { label: '后到' })) })
|
||||
expect([...page.container.querySelectorAll('button')].some(el => el.textContent === '后到')).toBe(true)
|
||||
}
|
||||
finally {
|
||||
page.unmount()
|
||||
}
|
||||
})
|
||||
|
||||
it('`when: false` hides the button and a throwing predicate drops only itself', () => {
|
||||
const { service, ctx, store, tab } = harness()
|
||||
service.registerTabAction(action('never', { label: 'NEVER', when: () => false }))
|
||||
service.registerTabAction(action('boom', { label: 'BOOM', when: () => { throw new Error('predicate') } }))
|
||||
service.registerTabAction(action('always', { label: 'ALWAYS' }))
|
||||
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
const page = mount(ctx, store, tab)
|
||||
try {
|
||||
const labels = [...page.container.querySelectorAll('button')].map(el => el.textContent)
|
||||
expect(labels).not.toContain('NEVER')
|
||||
expect(labels).not.toContain('BOOM')
|
||||
expect(labels).toContain('ALWAYS')
|
||||
expect(consoleError).toHaveBeenCalled()
|
||||
}
|
||||
finally {
|
||||
page.unmount()
|
||||
consoleError.mockRestore()
|
||||
}
|
||||
})
|
||||
|
||||
it('a failed run reports in the error strip, not the console', async () => {
|
||||
const { service, ctx, store, tab } = harness()
|
||||
service.registerTabAction(action('fail', {
|
||||
label: 'FAIL',
|
||||
run: () => { throw new Error('上传失败:磁盘满了') },
|
||||
}))
|
||||
const page = mount(ctx, store, tab)
|
||||
try {
|
||||
const button = [...page.container.querySelectorAll('button')].find(el => el.textContent === 'FAIL')
|
||||
act(() => { button!.click() })
|
||||
expect(page.container.textContent).toContain('上传失败:磁盘满了')
|
||||
}
|
||||
finally {
|
||||
page.unmount()
|
||||
}
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user