From bff5beb68922ef57e1bc347c305bfb6020da6349 Mon Sep 17 00:00:00 2001 From: "lu.wang7" Date: Fri, 6 Nov 2026 01:15:10 +0800 Subject: [PATCH] =?UTF-8?q?feat(file-tree):=20=E8=A1=8C=E8=8F=9C=E5=8D=95?= =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=A4=96=E9=83=A8=E6=8F=92=E4=BB=B6=E6=B3=A8?= =?UTF-8?q?=E5=86=8C=E5=8A=A8=E4=BD=9C=EF=BC=88registerFileAction=EF=BC=8C?= =?UTF-8?q?feature=20'fileActions'=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 文件树的行菜单此前完全由插件自己组装(打开方式 / 下载 / 上传到此目录 / 复制 / 重命名 / 删除),外部插件没有任何位置能加一项——「把这个文件传到 我的云端」这类入口只能另开界面,而它需要的恰恰是这个文件。 新增第四个注册表 `registerFileAction(descriptor)`(能力 'fileActions'): - 菜单项排在内置打开/下载行之后、复制/重命名之前,多条外部动作之间不加 分隔线,第一个之前有一条;排序 order 升序、同 order 按注册序; - `row: true` 在行右侧「引用」按钮旁再加一个悬停按钮(要求同时给 icon, 无图标的注册只进菜单); - 回调拿到行的绝对路径 + 这棵树的 root 与会话;目录默认不认领(`dirs`); - `when` 每行渲染与每次开菜单各调一次,抛错只隐藏该注册,不打断文件树; - `run` 抛错/reject 以 error.message 落进既有错误条,resolve 静默(成功 提示由注册方自己给),同一 (id, path) 在飞行中的重复点击被忽略; - 树只提供入口:不替注册方上传、复制或移动任何东西。 文档:指南新增 §7.3(类型、用例、渲染位置、两条约定),§1/§7 能力清单与 README 扩展点计数同步;CHANGELOG 中英各一条。 测试:新增 tests/file-actions.spec.tsx(12 例,注册表 5 + 文件树 7); tests/file-tree-row-memo / file-tree-menu-perf 的最小 service stub 补 getFileActions(它们的计数器仍是重渲染探针)。 --- CHANGELOG.md | 3 + CHANGELOG_EN.md | 3 + README.md | 2 +- README_ZH.md | 2 +- docs/external-plugin-guide.md | 84 +++++++- src/client/FileTree.tsx | 164 ++++++++++++++- src/client/service.ts | 105 ++++++++++ src/client/sidebar.module.css | 34 ++++ tests/file-actions.spec.tsx | 311 +++++++++++++++++++++++++++++ tests/file-tree-menu-perf.spec.tsx | 2 + tests/file-tree-row-memo.spec.tsx | 2 + 11 files changed, 706 insertions(+), 6 deletions(-) create mode 100644 tests/file-actions.spec.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index ce4e9d04..3be0cd77 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ ### v0.30.1 +- 🧩 **插件可以往文件树的行菜单里加自己的动作(`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 落错误条且成功静默)。 + - 🎯 **设置页「侧边卡片」的导航图标不再叠成两个**:插件此前按"宿主设置导航还没有图标通道"的老假设,用 CSS 把兜底齿轮藏起来、再画自己的图标;宿主早已提供按 section id 寻址的 `settings.section.icon` 插槽,而且图标的 DOM 外面多了一层 span,老选择器失效后兜底 SVG 露了出来,与插件图标并排显示。现在改为**走宿主插槽**提供图标,删掉标记 + CSS 遮罩那一套(顺带去掉了一个监听整个 document 的 MutationObserver)。 - 🧪 测试:`tests/settings-nav-icon.spec.tsx` 钉住图标按宿主给的 `size` 缩放、只用 `currentColor`;真实宿主上用无头浏览器确认导航行只剩一个 `svg`、无残留标记。 diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md index 3c2917d3..ea31f779 100644 --- a/CHANGELOG_EN.md +++ b/CHANGELOG_EN.md @@ -6,6 +6,9 @@ ### v0.30.1 +- 🧩 **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. + - 🎯 **The "Side card" settings row no longer shows two icons**: the plugin still assumed the settings navigation had no icon channel, so it hid the fallback gear with CSS and painted its own glyph. The shell has long since exposed a `settings.section.icon` slot addressed by section id, and it now wraps the nav icon in a span — the stale `> svg:first-child` rule stopped hiding the fallback, so both glyphs rendered side by side. The row now contributes its icon **through the slot**, and the marker + CSS-mask apparatus is gone (along with a document-wide MutationObserver). - 🧪 `tests/settings-nav-icon.spec.tsx` pins the glyph to the slot-provided `size` and `currentColor`; a headless pass against a real host confirms one `svg` in the row and no leftover marker. diff --git a/README.md b/README.md index dd49c154..802a660f 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ If something fails, check the FAQ table in https://github.com/omdsh-dev/DSH-bett ## 🔌 Plugin Ecosystem -`ctx.betterSidebar` offers two extension points to every plugin — `registerTab` / `registerFileViewer`; the built-in 6 tabs + 4 viewers use the very same API. The GitHub topic [`dsh-better-sidebar`](https://github.com/topics/dsh-better-sidebar) already lists **30+ ecosystem plugins**; the full integration guide is at **[docs/external-plugin-guide.md](./docs/external-plugin-guide.md)**. +`ctx.betterSidebar` offers four extension points to every plugin — `registerTab` / `registerFileViewer` / `registerFileIcon` / `registerFileAction`; the built-in 6 tabs + 4 viewers use the very same API. The GitHub topic [`dsh-better-sidebar`](https://github.com/topics/dsh-better-sidebar) already lists **30+ ecosystem plugins**; the full integration guide is at **[docs/external-plugin-guide.md](./docs/external-plugin-guide.md)**. ```ts import type {} from 'dsh-better-sidebar' // triggers the ctx.betterSidebar type merge diff --git a/README_ZH.md b/README_ZH.md index df79ddad..8c56c81b 100644 --- a/README_ZH.md +++ b/README_ZH.md @@ -120,7 +120,7 @@ dsh plugin --profile web add dsh-better-sidebar@latest ## 🔌 插件生态 -`ctx.betterSidebar` 向所有插件开放 `registerTab` / `registerFileViewer` 两个扩展点,内置 6 tab + 4 viewer 与第三方插件走同一套 API。GitHub topic [`dsh-better-sidebar`](https://github.com/topics/dsh-better-sidebar) 下已有 **30+ 生态插件**;完整接入文档见 **[docs/external-plugin-guide.md](./docs/external-plugin-guide.md)**。 +`ctx.betterSidebar` 向所有插件开放 `registerTab` / `registerFileViewer` / `registerFileIcon` / `registerFileAction` 四个扩展点,内置 6 tab + 4 viewer 与第三方插件走同一套 API。GitHub topic [`dsh-better-sidebar`](https://github.com/topics/dsh-better-sidebar) 下已有 **30+ 生态插件**;完整接入文档见 **[docs/external-plugin-guide.md](./docs/external-plugin-guide.md)**。 ```ts import type {} from 'dsh-better-sidebar' // 触发 ctx.betterSidebar 类型合并 diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md index 6b2d70c7..f588e1f2 100644 --- a/docs/external-plugin-guide.md +++ b/docs/external-plugin-guide.md @@ -55,6 +55,7 @@ better-sidebar 从 v0.4.0 起把自己改造成一个**注册表服务**: - **新页面(tab)**:注册一种新的侧边栏 tab 类型,出现在侧边栏 `+` 菜单里,用户点击后在自己的分栏里打开你的 React 页面; +- **文件树行内动作(file action,v0.31.0+)**:往文件树的右键菜单里加一项(可选再加一个行内悬停按钮),拿到的是行的**绝对路径**——适合「上传到云端」「在 X 里打开」这类由你的插件自己完成动作的入口; - **文件预览器(file viewer)**:注册一种文件类型预览器,让用户在侧边栏打开文件时走你的渲染组件(覆盖或补充内置的 markdown/html/code)。**宿主自己也有文档预览**——DSH 0.1.7 的 `ui-sidebar-documentpreview` 拿走了表格 / PDF / 图片 / Office 等只读格式,本插件因此**拒绝**认领那些扩展名,你的 viewer 也接不到它们(清单与原因见 §5.4)。 内置的 6 个 tab(editor / git——「Git」统一 tab(Source Control 视角 + 本轮文件视角,Git 视角内含只读提交图)/ subagent / sidechat / terminal-bottom / diff)和 4 个 viewer(markdown / html / jsonl / code)**自己也是通过同一套 API 注册的**(吃自己的狗粮),所以外部插件的能力与内置功能完全对等。**不再内置 terminal / browser 两个 tab 类型**:DSH 0.1.6 自带右列终端(`ui-sidebar-terminal`、kind `terminal`),浏览器是 0.1.6 的 `ui-sidebar-browser`(kind `browser`,**0.1.7 起只在 desktop profile 挂载**,Web profile 没有这个 kind);插件的同名类型会让读者看到两份实现。同理,0.1.7 的 `ui-sidebar-documentpreview` 让插件的 image / pdf / Office / 表格预览失去意义,那三个 viewer 描述符(image / pdf / binary-download)已删除。 @@ -743,12 +744,17 @@ interface BetterSidebarService { registerFileViewer(descriptor: FileViewerDescriptor): () => void /** 注册自定义文件树/文件 tab 图标(v0.19.0+,features 含 'fileIcons');返回 disposer */ registerFileIcon(descriptor: FileIconDescriptor): () => void + /** 往文件树行菜单加一项(v0.31.0+,features 含 'fileActions');返回 disposer */ + registerFileAction(descriptor: FileActionDescriptor): () => void /** 当前已注册的 tab 描述符快照(同步,供 useSyncExternalStore 用;含被设置页禁用的类型) */ getTabs(): readonly TabDescriptor[] /** 当前已注册的 file viewer 描述符快照(含被设置页禁用的 viewer) */ getFileViewers(): readonly FileViewerDescriptor[] /** 当前已注册的文件图标描述符快照(v0.19.0+) */ getFileIcons(): readonly FileIconDescriptor[] + /** 当前已注册的文件动作快照(v0.31.0+),按渲染顺序: + * order 升序,同 order 按注册序 */ + getFileActions(): readonly FileActionDescriptor[] /** 按 path 匹配**具体**注册(priority 降序、注册序):先 names 文件名,再 * 具体扩展名;不查 catch-all 与 folder 保留值。消费方一般直接用 * fileIcon/folderIcon 全链解析器。 */ @@ -813,7 +819,7 @@ interface BetterSidebarService { * 'badge' | 'tabLifecycle' | 'updateTab' | 'openFile' | 'targetedOpen' | * 'stateSubscription' | 'tabMeta' | 'pluginSettings' | 'urlTarget' | * 'settingSelect' | 'fileIcons' | 'rightActions' | 'settingPatterns' | - * 'hostRouteUrl' + * 'hostRouteUrl' | 'fileActions' * ——用 `features.includes('xxx')` 按能力 gate。 */ readonly features: readonly string[] /** 当前快照:激活 sessionId + 其状态(面板几何/打开的 tabs/展开集)+ prefs。 @@ -1079,6 +1085,82 @@ registerSidechatSurfaceAdapter(adapter: SidechatSurfaceAdapter): () => void --- +### 7.3 文件树行内动作(fileActions,v0.31.0+) + +文件树的行菜单原本只由插件自己组装(打开方式 / 下载 / 上传到此目录 / 复制 / 重命名 / 删除)。`registerFileAction` 让外部插件在里面加自己的项,并且**只管入口,不管动作**:树不替你上传、复制或移动任何东西,它只把行的事实交给你、把你的失败原样显示出来。 + +```ts +interface FileActionDescriptor { + /** 唯一 id('my-plugin:upload');重复注册同一个 id 会抛错 */ + id: string + /** 菜单与行按钮的文案(接受 thunk,随界面语言实时解析) */ + label: string | (() => string) + /** 菜单行与行按钮的图标;`(size) => ReactNode` 形式会收到尺寸 */ + icon?: ReactNode | ((size: number) => ReactNode) + /** 外部动作之间的排序(升序,默认 0);内置菜单项不受影响 */ + order?: number + /** 除了菜单项,还要在行上渲染一个悬停按钮(默认 false)。 + * 行按钮要求同时提供 icon:没有图标的注册只进菜单 */ + row?: boolean + /** 是否也认领目录行(默认 false)。`run` 里仍可从 isDir 自行再判断 */ + dirs?: boolean + /** 只对部分行出现;每行渲染与每次开菜单各调一次,必须廉价且无副作用。 + * 抛错 = 该注册自己隐藏,不会打断文件树 */ + when?: (row: FileActionRow) => boolean + /** 真正干活。抛错或 reject 会以 error.message 落进文件树的错误条; + * resolve 则静默(成功提示由注册方自己给)。同一 (id, path) 在飞行中 + * 的重复点击会被忽略 */ + run: (context: FileActionContext) => void | Promise +} + +/** `when` 看到的行事实 */ +interface FileActionRow { + path: string // 行的**绝对路径** + root: string | undefined // 这棵树的 workspace 根 + sessionId?: string // 拥有这棵树的主会话 + isDir: boolean +} + +/** `run` 收到的上下文 = 行事实 + 一个报错出口 */ +interface FileActionContext extends FileActionRow { + fail(message: string): void // 同一条错误条(不带「失败:」前缀) +} +``` + +**用法**(一个「上传到云端」动作,宿主侧另有自己的上传路由): + +```ts +if (ctx.betterSidebar.features.includes('fileActions')) { + ctx.effect(() => + ctx.betterSidebar.registerFileAction({ + id: 'my-plugin:upload', + label: () => t('uploadToCloud'), + icon: size => , + row: true, // 行上也放一个按钮 + order: 10, // 排在内置菜单项之后、按注册序 + when: row => !row.path.endsWith('.log'), // 例:日志不给传 + 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()) // 用户能读到的原文 + }, + }) + ) +} +``` + +**渲染位置**:菜单里排在内置「打开方式 / 新标签打开 / 侧栏打开 / 下载 / 上传到此目录 / 新建」之后、「打包下载 / 复制路径 / 重命名 / 删除」之前,多条外部动作之间**不加**分隔线,第一个外部动作前有一条;`row: true` 的按钮出现在行右侧「引用」按钮之后,随行悬停 / 键盘聚焦显隐。 + +**两条约定**: + +- **树不替你做确认**。危险动作(覆盖、删除、超限上传)的二次确认在 `run` 里自己做。 +- **宿主路由的路径由你负责校验**。`path` 是树给的绝对路径,安全边界(是否在工作区内、大小限制)不在这层——见 §10 的平台约束。 + +--- + ## 8. 声明式设置(v0.4.1+) 每个注册的 tab / viewer **自动**出现在 DSH 设置页「侧边卡片」分区(`SideCardSection` 按注册表驱动渲染,无硬编码),**`hidden: true` 的 tab 类型除外**: diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index 704a092f..ee5859bd 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -65,7 +65,7 @@ import type { OpenInApp, OpenInAppEntry } from './open-in-app.ts' import type { OpenWithTarget } from './open-with.ts' import { relativeTo } from './paths.ts' import { t } from './locales.ts' -import type { BetterSidebarService } from './service.ts' +import type { BetterSidebarService, FileActionDescriptor, FileActionRow } from './service.ts' import { Chip, ConfirmDialog, IconButton, Notice, StatusBadge, useGitStatus, type GitTone, type StatusTone, @@ -217,10 +217,61 @@ interface RowActions { activate(event: ActivateModifiers, path: string, isDir: boolean, chain?: readonly FsEntry[]): void contextMenu(event: MouseEvent, path: string, isDir: boolean): void reference(path: string, isDir: boolean): void + /** Run one externally registered file action (feature `fileActions`). */ + fileAction(id: string, path: string, isDir: boolean): void dragOver(event: DragEvent, dir: string): void drop(event: DragEvent, path: string, isDir: boolean): void } +/** One external action's label, resolved (a thunk re-reads the live locale). */ +function actionLabelOf(action: FileActionDescriptor): string { + if (typeof action.label === 'string') return action.label + try { + return action.label() + } catch (error) { + console.error(`[dsh-better-sidebar] file action "${action.id}" label() threw:`, error) + return action.id + } +} + +/** One external action's glyph at `size` (a factory gets the size). */ +function actionIconOf(action: FileActionDescriptor, size: number): ReactNode { + if (typeof action.icon === 'function') return action.icon(size) + return action.icon +} + +/** + * The external actions claiming one row, in registry order. `when` is + * crash-isolated: a throwing predicate hides its own row instead of breaking + * the tree (the registries' `fileIcon` follows the same policy). + * + * Directories are excluded unless the descriptor opts in with `dirs: true`; + * `hoverOnly` keeps just the descriptors that asked for a row button. + */ +function applicableFileActions( + actions: readonly FileActionDescriptor[], + row: FileActionRow, + options: { hoverOnly: boolean }, +): FileActionDescriptor[] { + const applicable: FileActionDescriptor[] = [] + for (const action of actions) { + if (options.hoverOnly && action.row !== true) continue + if (row.isDir && action.dirs !== true) continue + if (action.when !== undefined) { + let claims: boolean + try { + claims = action.when(row) === true + } catch (error) { + console.error(`[dsh-better-sidebar] file action "${action.id}" when() threw:`, error) + claims = false + } + if (!claims) continue + } + applicable.push(action) + } + return applicable +} + /** One open-in-app entry's leading glyph: the host's icon route / data URL, * or a generic mark when the host has no icon for it. */ function AppGlyph(props: { entry: OpenInAppEntry }): ReactNode { @@ -251,14 +302,27 @@ interface FileRowProps { */ gitTone: GitTone | undefined gitLetter: string | undefined + /** External actions (registry order) — the row's `when` sees its own facts. */ + fileActions: readonly FileActionDescriptor[] + /** The tree's workspace root (absolute), for `when`. */ + root: string | undefined + /** The host session owning this tree, for `when`. */ + sessionId: string actions: RowActions } const FileRow = memo(function FileRow(props: FileRowProps): ReactNode { - const { entry, depth, iconsVersion, service, selected, revealed, dropTarget, copied, gitTone, gitLetter, actions } = props + const { entry, depth, iconsVersion, service, selected, revealed, dropTarget, copied, gitTone, gitLetter, fileActions, root, sessionId, actions } = props // Referenced so a registry change re-renders the row with its new icon. void iconsVersion const icon = service !== undefined ? service.fileIcon(entry.path, 14) : builtinFileIcon(entry.path, 14) + // Row buttons only exist for actions that asked for one AND brought a glyph: + // a text button per registration would crowd the name out of the row. + const rowButtons = applicableFileActions( + fileActions, + { path: entry.path, root, sessionId, isDir: false }, + { hoverOnly: true }, + ).filter(action => action.icon !== undefined) return (
)} + {rowButtons.map(action => ( + + ))}
) }) @@ -602,6 +681,16 @@ export function FileTree(props: { () => service?.subscribe(() => { setIconsVersion(version => version + 1) }), [service], ) + /** + * The external file actions in render order. Re-read on every registry + * change (`iconsVersion` IS that revision — one listener set for tabs, + * viewers, icons and actions) and memoized because the memoized rows take it + * as a prop: a fresh array per render would defeat `memo()`. + */ + const fileActions = useMemo(() => { + void iconsVersion + return service?.getFileActions() ?? [] + }, [service, iconsVersion]) /** One directory's leading glyph for the surfaces WITHOUT a memoized row * (the inline rename and new-folder editors). */ const dirRowIcon = (path: string, open: boolean): ReactNode => @@ -638,6 +727,8 @@ export function FileTree(props: { const [deletingSelected, setDeletingSelected] = useState(false) /** The last mutation failure (dismissable strip above the tree). */ const [actionError, setActionError] = useState(null) + /** External action runs in flight (`id\u0000path`): a double press fires once. */ + const runningFileActionsRef = useRef(new Set()) /** A failed re-list that kept the previous rows on screen (hint line). */ const [loadError, setLoadError] = useState(null) /** The multi-selection (absolute paths) and its Shift anchor. */ @@ -1295,13 +1386,44 @@ export function FileTree(props: { propsRef.current.onReferenceFile(path, isDir) }, []) + /** + * Run one external file action. The registry is read LIVE rather than off + * the rendered list: a plugin can register between the menu opening and the + * click, and a disposed one must not run its stale closure. + * + * The failure policy is the strip's: a throw or a rejection lands as + * `error.message`, a resolution reports nothing (the owner shows its own + * outcome). Runs are guarded per (id, path), so a double press while the + * first is still in flight cannot fire the work twice. + */ + const handleFileAction = useCallback((id: string, path: string, isDir: boolean): void => { + const current = propsRef.current + const action = current.service?.getFileActions().find(candidate => candidate.id === id) + if (action === undefined) return + const key = `${id}\u0000${path}` + if (runningFileActionsRef.current.has(key)) return + runningFileActionsRef.current.add(key) + setActionError(null) + const fail = (message: string): void => { setActionError(message) } + try { + const pending = action.run({ path, root: current.cwd, sessionId: current.sessionId, isDir, fail }) + void Promise.resolve(pending) + .catch((error: unknown) => { fail(error instanceof Error ? error.message : String(error)) }) + .finally(() => { runningFileActionsRef.current.delete(key) }) + } catch (error) { + runningFileActionsRef.current.delete(key) + fail(error instanceof Error ? error.message : String(error)) + } + }, []) + const actions = useMemo(() => ({ activate: handleActivate, contextMenu: handleContextMenu, reference: handleReference, + fileAction: handleFileAction, dragOver: handleRowDragOver, drop: handleDrop, - }), [handleActivate, handleContextMenu, handleReference, handleRowDragOver, handleDrop]) + }), [handleActivate, handleContextMenu, handleReference, handleFileAction, handleRowDragOver, handleDrop]) // ── New folder ───────────────────────────────────────────────────────── const newFolderRef = useRef(newFolder) @@ -1710,6 +1832,33 @@ export function FileTree(props: { * LONE directory archives its own subtree. A lone FILE is skipped — it would * only duplicate the plain download row. */ + /** + * External file actions as menu entries (feature `fileActions`), preceded by + * a separator when any apply. The tree renders them after its open/download + * rows and before the copy/mutation block it owns. + */ + const fileActionEntries = (target: { path: string; isDir: boolean }): MenuEntry[] => { + const applicable = applicableFileActions( + propsRef.current.service?.getFileActions() ?? [], + { + path: target.path, + root: propsRef.current.cwd, + sessionId: propsRef.current.sessionId, + isDir: target.isDir, + }, + { hoverOnly: false }, + ) + if (applicable.length === 0) return [] + return [ + { id: 'file-action-sep', type: 'separator' } as MenuEntry, + ...applicable.map((action): MenuItem => ({ + id: `file-action:${action.id}`, + label: actionLabelOf(action), + ...(action.icon === undefined ? {} : { icon: actionIconOf(action, 14) }), + })), + ] + } + const zipEntries = (target: { path: string; isDir: boolean }): MenuEntry[] => { const count = selected.size if (count >= 2) { @@ -2174,6 +2323,9 @@ export function FileTree(props: { gitTone={git?.tone} gitLetter={git?.letter} copied={copiedPath === entry.path} + fileActions={fileActions} + root={cwd} + sessionId={sessionId} actions={actions} /> ) @@ -2355,6 +2507,8 @@ export function FileTree(props: { ...(rowMenu?.isDir === true ? [{ id: 'new-file', label: t('newFile'), icon: }] : []), + // 4b: externally registered file actions (feature `fileActions`). + ...(rowMenu === null ? [] : fileActionEntries(rowMenu)), // 5: ZIP of the current selection (≥2 rows, or one lone directory). ...(rowMenu === null ? [] : zipEntries(rowMenu)), // 6: copy, then the mutations (never on the workspace root row). @@ -2390,6 +2544,10 @@ export function FileTree(props: { } // The plugin's own targets share one id space (pinned rows and // submenu children alike), so the caller gets the target id + path. + if (id.startsWith('file-action:')) { + handleFileAction(id.slice('file-action:'.length), target.path, target.isDir) + return + } if (id.startsWith('open-with:')) { // The caller owns the launch and answers whether it was accepted; // a refusal (or a rejection) means nothing opened, so the failure diff --git a/src/client/service.ts b/src/client/service.ts index 5fe45d70..23d36db8 100644 --- a/src/client/service.ts +++ b/src/client/service.ts @@ -466,6 +466,71 @@ export interface FileIconDescriptor { icon: (path: string, size: number, open?: boolean) => ReactNode } +/** The row a file action is asked about — everything `when` sees. */ +export interface FileActionRow { + /** ABSOLUTE path of the row the action was invoked on. */ + path: string + /** The tree's workspace root (absolute), when the tree knows one. */ + root: string | undefined + /** The host session whose conversation owns this tree. */ + sessionId?: string + /** Whether the target is a directory row. */ + isDir: boolean +} + +/** What a file action is handed when it runs. */ +export interface FileActionContext extends FileActionRow { + /** + * Show a message in the file tree's own error strip (the same strip a failed + * rename or open-in-app lands in). 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 file action (feature `fileActions`): a row-menu item, + * and optionally a hover button on the row itself. + * + * The callback runs CLIENT-SIDE only — the plugin that registers it owns the + * work (its own routes, its own toasts). The tree contributes the entry point + * and the failure strip; it never uploads, copies or moves anything itself. + */ +export interface FileActionDescriptor { + /** Unique id (`'my-plugin:upload'`). Re-registering the same id throws. */ + id: string + /** Menu and hover label (i18n-friendly: string or a thunk). */ + label: string | (() => string) + /** Leading glyph for the menu row and the hover button. */ + icon?: ReactNode | ((size: number) => ReactNode) + /** Order among external actions; ascending, default 0 (built-ins are unaffected). */ + order?: number + /** + * Render a hover button on the row as well as the menu item (default + * false: menu only). The button shows the same label through `title` / + * `aria-label`, so a glyph-only affordance stays readable. + */ + row?: boolean + /** + * Claim DIRECTORY rows too (default false). The action gets `isDir` in its + * context either way, so it can refine the decision itself. + */ + dirs?: boolean + /** + * Whether the action applies to one row. Called per row render (for `row`) + * and once per menu open, so it must be cheap and side-effect free. Omitted + * = every row this descriptor's `dirs` setting allows. + */ + when?: (row: FileActionRow) => boolean + /** + * Do the work. A rejected promise is reported as `error.message` in the + * tree's error strip; a resolved one says nothing (the owner reports its + * own outcome). Runs are guarded per (id, path): a second press while the + * first is in flight is ignored. + */ + run: (context: FileActionContext) => void | Promise +} + /** * Reserved `exts` values that claim DIRECTORY rows instead of file * extensions: `'folder'` matches a closed directory, `'folder-open'` an @@ -634,9 +699,19 @@ export interface BetterSidebarService { registerTab(descriptor: TabDescriptor): () => void registerFileViewer(descriptor: FileViewerDescriptor): () => void registerFileIcon(descriptor: FileIconDescriptor): () => void + /** + * Contribute an action to the file tree's row menu (feature `fileActions`). + * Menu items appear in `order` (then registration) order, after the + * built-in open/download rows and before the copy/mutation rows the tree + * owns; `row: true` also puts a hover button on the row next to the + * reference button. The registration is disposed with the plugin fiber. + */ + registerFileAction(descriptor: FileActionDescriptor): () => void getTabs(): readonly TabDescriptor[] getFileViewers(): readonly FileViewerDescriptor[] getFileIcons(): readonly FileIconDescriptor[] + /** Every registered file action, in the order the tree renders them. */ + getFileActions(): readonly FileActionDescriptor[] /** * Find a SPECIFIC registered file icon for a path (priority desc, then * registration order): a `names` match first, then an `exts` match. @@ -883,6 +958,10 @@ export const SIDEBAR_SERVICE_VERSION = '0.30.1' * right-aligned action area rendered at the tab strip's right end. * - 'settingPatterns': SidebarSettingToggle type 'patterns' (editable * string-list row, committed as one string[] value). + * - 'fileActions' (v0.31.0): registerFileAction/getFileActions — external + * 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. * * 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). @@ -903,6 +982,7 @@ export const SIDEBAR_FEATURES = [ 'rightActions', 'settingPatterns', 'hostRouteUrl', + 'fileActions', ] as const /** Run one plugin callback; a throw is logged and never breaks the caller. */ @@ -923,6 +1003,7 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe const tabs = new Map() const viewers = new Map() const fileIcons = new Map() + const fileActions = new Map() const listeners = new Set<() => void>() /** The native right-Sidebar write face, installed by the client half. */ let surface: SidebarSurface | undefined @@ -997,6 +1078,28 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe } } + const registerFileAction = (descriptor: FileActionDescriptor): (() => void) => { + if (fileActions.has(descriptor.id)) { + throw new Error(`[dsh-better-sidebar] file action "${descriptor.id}" already registered`) + } + fileActions.set(descriptor.id, descriptor) + notify() + return () => { + if (fileActions.get(descriptor.id) === descriptor) { + fileActions.delete(descriptor.id) + notify() + } + } + } + + /** + * External actions in render order: `order` ascending, then registration + * order (Map insertion is stable, and `Array#sort` is stable, so equal + * orders keep the order they registered in). + */ + const getFileActions = (): readonly FileActionDescriptor[] => + Array.from(fileActions.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[] => @@ -1490,9 +1593,11 @@ export function createBetterSidebarService(store: SidebarStore): BetterSidebarSe registerTab, registerFileViewer, registerFileIcon, + registerFileAction, getTabs, getFileViewers, getFileIcons, + getFileActions, matchFileIcon, matchFolderIcon, fileIcon, diff --git a/src/client/sidebar.module.css b/src/client/sidebar.module.css index b6898eca..43c41556 100644 --- a/src/client/sidebar.module.css +++ b/src/client/sidebar.module.css @@ -1048,6 +1048,40 @@ body[data-dsh-sidebar-dragging] .bottomPanel { color: var(--dsw-alias-label-tertiary); } +/* Externally registered row actions (feature `fileActions`, `row: true`): + glyph buttons beside the reference button, revealed with it on hover or + focus. The trailing affordances ride the reference button's auto margin, + so a second and third button simply follow it. */ +.explorerAction { + flex: none; + display: none; + align-items: center; + justify-content: center; + width: 20px; + height: 20px; + padding: 0; + border: none; + border-radius: 4px; + background: transparent; + color: var(--dsw-alias-label-tertiary); + cursor: pointer; +} + +.explorerAction:hover { + background: var(--dsw-alias-interactive-bg-hover); + color: var(--dsw-alias-label-primary); +} + +.explorerAction:focus-visible { + outline: 2px solid var(--dsw-alias-brand-primary); + outline-offset: 1px; +} + +.explorerRow:hover .explorerAction, +.explorerRow:focus-within .explorerAction { + display: inline-flex; +} + .explorerError { font: var(--dsw-font-xxs-12); color: var(--dsw-alias-state-error-primary); diff --git a/tests/file-actions.spec.tsx b/tests/file-actions.spec.tsx new file mode 100644 index 00000000..630935e3 --- /dev/null +++ b/tests/file-actions.spec.tsx @@ -0,0 +1,311 @@ +/** + * External file actions (feature `fileActions`): the registry half and the + * tree half. + * + * REGISTRY — `registerFileAction` follows the other registries exactly: a + * duplicate id throws, the disposer removes only its own descriptor (a later + * re-registration must not be torn down by an older disposer), and + * `getFileActions()` answers in RENDER order — `order` ascending, registration + * order for equal orders (the tree renders the array as it arrives, so the + * getter is the only place this can be decided). + * + * TREE — an applicable action is a row-menu entry: it runs with the row's + * ABSOLUTE path plus the tree's root and session (never a display path, that + * is what a caller would upload/move with), and it sits between the tree's + * open/download rows and its own copy/mutation block. `row: true` adds a hover + * button, but only when the descriptor brought a glyph. Directories are out + * unless the descriptor says `dirs: true`. A `when()` that says no hides the + * row, and one that THROWS hides it too instead of breaking the tree. A + * rejecting `run` lands its own message in the tree's error strip — the same + * strip a failed rename uses — and a resolved one says nothing (the owner + * reports its own outcome). + */ +// @vitest-environment jsdom +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { act } from 'react-dom/test-utils' +import { FileTree } from '../src/client/FileTree.tsx' +import { createBetterSidebarService } from '../src/client/service.ts' +import { createSidebarStore } from '../src/client/state.ts' +import css from '../src/client/sidebar.module.css' + +import { setupReactAct } from './test-utils.ts' +setupReactAct() + +// vitest follows the OS locale; pin en-US so menu copy is English. +beforeAll(() => { + Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true }) +}) + +const ROOT = '/tmp/ws' + +vi.mock('../src/client/api.ts', () => ({ + api: { + fsTrees: async (_scope: unknown, paths: readonly string[]) => ({ + levels: paths.map(path => ({ path, entries: levelOf(path).entries, truncated: false })), + }), + gitStatus: async () => ({ isRepo: false, entries: [] }), + }, + downloadUrl: () => '/sidebar/file', + isOutsideWorkspaceMessage: () => false, +})) + +/** Directories first, then case-insensitive by name — what a host lists. */ +function levelOf(path: string): { entries: { name: string; path: string; isDir: boolean; hidden: boolean; isSymlink: boolean; broken: boolean }[] } { + const entries = path === ROOT + ? [ + { name: 'sub', path: `${ROOT}/sub`, isDir: true }, + { name: 'notes.md', path: `${ROOT}/notes.md`, isDir: false }, + ] + : [] + return { + entries: entries.map(entry => ({ ...entry, hidden: false, isSymlink: false, broken: false })), + } +} + +/** The smallest WebSocket the directory watcher talks to. */ +class FakeSocket { + static readonly OPEN = 1 + static readonly CONNECTING = 0 + readyState = FakeSocket.CONNECTING + onopen: (() => void) | null = null + onmessage: ((event: { data: string }) => void) | null = null + onclose: (() => void) | null = null + constructor(readonly url: string) {} + send(): void {} + close(): void { this.readyState = 3 } +} + +interface Harness { + container: HTMLDivElement + service: ReturnType + unmount: () => void +} + +function mountTree(): Harness { + const container = document.createElement('div') + document.body.append(container) + const root: Root = createRoot(container) + const service = createBetterSidebarService(createSidebarStore()) + act(() => { + root.render(createElement(FileTree, { + sessionId: 's1', + cwd: ROOT, + expanded: [], + revealed: [], + onToggle: () => {}, + onOpenFile: () => {}, + onReferenceFile: () => {}, + refreshTick: 0, + onUploadRequest: () => {}, + busy: false, + service, + })) + }) + return { container, service, unmount: () => { act(() => { root.unmount() }); container.remove() } } +} + +/** Flush the batch promise chain (the level cache fill + fold preload). */ +async function flush(): Promise { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + }) +} + +/** The row rendering `label` (labels are unique in this fixture). */ +function rowByLabel(container: HTMLElement, label: string): HTMLElement { + const row = [...container.querySelectorAll(`.${css.explorerRow}`)] + .find(candidate => candidate.querySelector(`.${css.explorerName}`)?.textContent === label) + if (row === undefined) throw new Error(`no row "${label}"`) + return row +} + +function rightClick(el: Element): void { + act(() => { + el.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 })) + }) +} + +/** Every open menu row's label, in DOM order. */ +function menuLabels(): string[] { + return [...document.querySelectorAll('[role="menuitem"]')].map(item => item.textContent ?? '') +} + +function clickMenuitem(label: string): void { + const item = [...document.querySelectorAll('[role="menuitem"]')] + .find(el => el.textContent === label) + if (item === undefined) throw new Error(`no menu row "${label}" in ${JSON.stringify(menuLabels())}`) + act(() => { item.click() }) +} + +/** One external action with test-friendly defaults. */ +function action(id: string, overrides: Partial['registerFileAction']>[0]> = {}) { + return { + id, + label: id.toUpperCase(), + icon: createElement('span', { 'data-testid': `glyph-${id}` }), + run: () => {}, + ...overrides, + } +} + +describe('fileActions registry', () => { + it('declares the feature and starts empty', () => { + const service = createBetterSidebarService(createSidebarStore()) + expect(service.features).toContain('fileActions') + expect(service.getFileActions()).toEqual([]) + }) + + it('answers in render order: order ascending, then registration order', () => { + const service = createBetterSidebarService(createSidebarStore()) + service.registerFileAction(action('late', { order: 5 })) + service.registerFileAction(action('early', { order: -5 })) + service.registerFileAction(action('default')) + service.registerFileAction(action('default-second')) + expect(service.getFileActions().map(entry => entry.id)).toEqual( + ['early', 'default', 'default-second', 'late'], + ) + }) + + it('refuses a duplicate id', () => { + const service = createBetterSidebarService(createSidebarStore()) + service.registerFileAction(action('same')) + expect(() => service.registerFileAction(action('same'))).toThrow(/already registered/u) + }) + + it('a stale disposer cannot remove a newer registration', () => { + const service = createBetterSidebarService(createSidebarStore()) + const disposeFirst = service.registerFileAction(action('same')) + disposeFirst() + const replacement = action('same') + service.registerFileAction(replacement) + disposeFirst() + expect(service.getFileActions()).toEqual([replacement]) + }) + + it('disposal empties the registry for the tree', () => { + const service = createBetterSidebarService(createSidebarStore()) + const dispose = service.registerFileAction(action('gone')) + expect(service.getFileActions()).toHaveLength(1) + dispose() + expect(service.getFileActions()).toEqual([]) + }) +}) + +describe('fileActions in the tree', () => { + let harness: Harness + + beforeEach(() => { + vi.stubGlobal('WebSocket', FakeSocket) + }) + + afterEach(() => { + harness.unmount() + document.body.innerHTML = '' + vi.unstubAllGlobals() + }) + + it('is a menu row for files, between the open rows and the copy block', async () => { + harness = mountTree() + act(() => { harness.service.registerFileAction(action('upload')) }) + await flush() + + rightClick(rowByLabel(harness.container, 'notes.md')) + const labels = menuLabels() + expect(labels).toContain('UPLOAD') + // After the built-in download row, before the copy rows the tree owns. + expect(labels.indexOf('UPLOAD')).toBeGreaterThan(labels.indexOf('Download')) + expect(labels.indexOf('UPLOAD')).toBeLessThan(labels.indexOf('Copy relative path')) + }) + + it('runs with the ABSOLUTE path, the tree root and the session', async () => { + harness = mountTree() + const run = vi.fn() + act(() => { harness.service.registerFileAction(action('upload', { run })) }) + await flush() + + rightClick(rowByLabel(harness.container, 'notes.md')) + clickMenuitem('UPLOAD') + + expect(run).toHaveBeenCalledTimes(1) + expect(run).toHaveBeenCalledWith({ + path: `${ROOT}/notes.md`, + root: ROOT, + sessionId: 's1', + isDir: false, + fail: expect.any(Function), + }) + }) + + it('hides itself from directory rows unless the descriptor claims them', async () => { + harness = mountTree() + act(() => { harness.service.registerFileAction(action('upload')) }) + act(() => { harness.service.registerFileAction(action('dir-only', { dirs: true })) }) + await flush() + + rightClick(rowByLabel(harness.container, 'sub')) + const labels = menuLabels() + expect(labels).not.toContain('UPLOAD') + expect(labels).toContain('DIR-ONLY') + }) + + it('honours when(), and a throwing when() only hides its own row', async () => { + harness = mountTree() + act(() => { harness.service.registerFileAction(action('sql-only', { when: row => row.path.endsWith('.sql') })) }) + act(() => { harness.service.registerFileAction(action('boom', { when: () => { throw new Error('nope') } })) }) + await flush() + + rightClick(rowByLabel(harness.container, 'notes.md')) + const labels = menuLabels() + expect(labels).not.toContain('SQL-ONLY') + expect(labels).not.toContain('BOOM') + }) + + it('puts a hover button on the row when asked for one', async () => { + harness = mountTree() + const run = vi.fn() + act(() => { harness.service.registerFileAction(action('pin', { row: true, label: 'Send to cloud', run })) }) + await flush() + + const button = rowByLabel(harness.container, 'notes.md') + .querySelector(`.${css.explorerAction}`) + expect(button).not.toBeNull() + expect(button?.getAttribute('title')).toBe('Send to cloud') + expect(button?.getAttribute('aria-label')).toBe('Send to cloud') + act(() => { button?.click() }) + expect(run).toHaveBeenCalledWith(expect.objectContaining({ path: `${ROOT}/notes.md`, isDir: false })) + }) + + it('keeps a glyph-less registration menu-only', async () => { + harness = mountTree() + act(() => { harness.service.registerFileAction({ id: 'textual', label: 'Textual', row: true, run: () => {} }) }) + await flush() + + expect(rowByLabel(harness.container, 'notes.md').querySelector(`.${css.explorerAction}`)).toBeNull() + rightClick(rowByLabel(harness.container, 'notes.md')) + expect(menuLabels()).toContain('Textual') + }) + + it('reports a rejection in the error strip and stays quiet on success', async () => { + harness = mountTree() + const run = vi.fn() + .mockRejectedValueOnce(new Error('upload refused')) + .mockResolvedValueOnce(undefined) + act(() => { harness.service.registerFileAction(action('upload', { run })) }) + await flush() + + rightClick(rowByLabel(harness.container, 'notes.md')) + clickMenuitem('UPLOAD') + await flush() + expect(harness.container.querySelector('[role="alert"]')?.textContent).toContain('upload refused') + + rightClick(rowByLabel(harness.container, 'notes.md')) + clickMenuitem('UPLOAD') + await flush() + expect(harness.container.querySelector('[role="alert"]')).toBeNull() + }) +}) \ No newline at end of file diff --git a/tests/file-tree-menu-perf.spec.tsx b/tests/file-tree-menu-perf.spec.tsx index 6d3510cb..19ae8d7f 100644 --- a/tests/file-tree-menu-perf.spec.tsx +++ b/tests/file-tree-menu-perf.spec.tsx @@ -55,6 +55,8 @@ const service = { subscribe: () => () => {}, fileIcon: (path: string) => { fileIcons.push(path); return null }, folderIcon: (path: string) => { folderIcons.push(path); return null }, + // No external file actions in these fixtures — the counters stay the probe. + getFileActions: () => [], } as unknown as BetterSidebarService const HOST_APPS = [ diff --git a/tests/file-tree-row-memo.spec.tsx b/tests/file-tree-row-memo.spec.tsx index f14d00ab..f12d4b1a 100644 --- a/tests/file-tree-row-memo.spec.tsx +++ b/tests/file-tree-row-memo.spec.tsx @@ -48,6 +48,8 @@ const service = { subscribe: () => () => {}, fileIcon: (path: string) => { fileIcons.push(path); return null }, folderIcon: (path: string) => { folderIcons.push(path); return null }, + // No external file actions in these fixtures — the counters stay the probe. + getFileActions: () => [], } as unknown as BetterSidebarService interface Harness {