feat(tab-bar): Tab 右键菜单补「关闭全部页签」与「在资源管理器中定位」

This commit is contained in:
Menghuan1918 committed 2026-10-05 21:53:08 +08:00
1 parent 38ceecb051
commit e88b7e02ed
27 files changed
+348 -30

No files matched your search

+2
View File
@@ -4,6 +4,8 @@
### Unreleased
- 📑 **Tab 右键菜单补两项**([#109](https://github.com/omdsh-dev/DSH-better-sidebar/issues/109)):「**关闭全部页签**」与「**在资源管理器中定位**」。前者作用域与相邻三项一致——**右键所在的那个标签组**(分栏各管各的),含右键的那个页签本身(这是它与「关闭其他页签」的区别),逐条走既有单页签关闭路径(descriptor `onClose` 生命周期 + 终端 pty 释放 + 会话作用域),页签在滚动视口外也能关;菜单只从页签上打开,所以该项恒可用。后者对页签关联的文件(`tab.path`,即编辑器/文件夹窗口)调用宿主 **open-in-app** 的 reveal——与资源管理器行右键「在文件管理器中显示」**同一个适配器**(`createOpenInApp` → `ctx.remote.session.openWorkspacePath({ action: 'reveal' })`),不新增任何宿主调用;变更 / 任务 / 侧边对话 / diff 页签没有可定位的文件(diff 的 ref 是仓库相对路径,不是宿主能定位的路径),该项置灰,无 resolver 时同样置灰。词条 `closeAllTabs` / `revealTabInFileManager` 同批进入 `locales.ts` 的 zh/en 与 19 份第三语言词典。
- 🧪 测试:`tests/tab-bar-context-menu.spec.tsx` 把菜单整份钉到 **6 项**(标签序 + 每行 disabled 数组),新增「关闭全部」「定位」「无关联文件置灰」「无 resolver 置灰」用例,并新增一条 Workbench 用例钉住 reveal resolver 穿到**分栏后每个 pane 的** tab 条(回退任一层传递即红)。
- 🔍 **文件搜索优先走本机原生引擎(fd / ripgrep),缺失或失败自动回退 JS 遍历**([#203](https://github.com/omdsh-dev/DSH-better-sidebar/issues/203),PR [#303](https://github.com/omdsh-dev/DSH-better-sidebar/pull/303) 重写落地):`fs.search` 之前是纯 JS 递归遍历,十万级目录秒级、10 万条访问预算一顶就静默截断。现在启动后惰性探测一次(每个候选二进制 `--version` 500ms 内验证通过才用,进程内缓存),探到就用引擎,探不到/运行失败回退原遍历;rg 优先用 DSH 自己捆绑的 `@vscode/ripgrep`(agent 侧搜索工具同一个二进制,从 CLI 入口的依赖树推导候选路径),fd 走 `--fixed-strings` 字面量匹配。噪声目录排除名单单源化到 `SKIP_DIR_NAMES`(18 项,walk 与两条 argv 共用),引擎输出统一归一化成 walk 契约(根相对、`/` 分隔、大小写不敏感),**路由与客户端零改动**。**目录命中按 #801 的契约同时产出 `dirs`**:fd 用 `--type d` 直接列目录,rg 由文件路径倒推匹配的目录段(`deriveRgMatches`)——唯一残留差异是**空目录在 rg 下不可见**(已记录)。运行失败禁用该引擎(坏二进制不该拖慢后续搜索),**超时只降级本次**(树太大不等于二进制坏)。调试插桩 `DSH_SEARCH_DEBUG=1` 写 `$DSH_HOME/search-debug.log`,默认完全静默。Windows 侧由 `ci-windows` lane 承载:`choco install fd ripgrep` + `pnpm check:engines` 对插件自己的 argv 做字节级断言(不得含 `\`/CR、非 ASCII 文件名必须命中)。
- 🧪 测试:`tests/search-engines.spec.ts`(探测缓存 / 失败禁用 / 超时不禁用 / argv 对称性 / `deriveRgMatches` / 捆绑 rg 候选路径推导 / 真引擎在场时的端到端),`tests/fs-search.spec.ts` 的 dispatch 组(引擎优先、`dirs` 透传、预算透传、运行失败回退并禁用)。
+1 -1
View File
@@ -246,7 +246,7 @@ dsh registry enable dsh-external/dsh-better-sidebar
| 选中下一个相同片段 | `Ctrl/Cmd + D` |
| Git 提交 | `Ctrl + Enter` |
| 关闭 Tab | 鼠标中键 |
| Tab 右键菜单 | 关闭 / 关闭其他页签 / 关闭左侧页签 / 关闭右侧页签(当前标签组) |
| Tab 右键菜单 | 关闭 / 关闭其他页签 / 关闭左侧页签 / 关闭右侧页签 / 关闭全部页签(均限当前标签组);在资源管理器中定位(该页签对应一个文件时可用) |
| 拆分/合并分栏 | 拖 Tab 到分栏边缘 / 中间 |
| 引用文件到输入框 | 悬浮行尾 `@文件` 按钮 |
| 复制文件路径 | 右键行 → 复制相对/绝对地址 |
+1 -1
View File
@@ -255,7 +255,7 @@ WeChat / QQ group QR codes will live here. After uploading the QR images (drag t
| Select next occurrence | `Ctrl/Cmd + D` |
| Git commit | `Ctrl + Enter` |
| Close tab | Middle mouse button |
| Tab context menu (right-click) | Close / Close Other Tabs / Close Tabs to the Left / Close Tabs to the Right (current pane) |
| Tab context menu (right-click) | Close / Close Other Tabs / Close Tabs to the Left / Close Tabs to the Right / Close All Tabs (all scoped to the current pane); Reveal in File Manager (for a tab that has a file) |
| Split / merge panes | Drag tab to pane edge / middle |
| Reference file to input | Hover the `@file` button at end of line |
| Copy file path | Right-click row → copy relative/absolute path |
+22
View File
@@ -47,6 +47,7 @@ import { getShellPreset } from './shell-presets.ts'
import { computeTitleBarStrip } from './titlebar-strip.ts'
import { TabContent, buildNewTabOptions } from './sidebar/TabContent.tsx'
import { confirmDiscardDraft, dirtyCount, editorDirtyRevision, subscribeEditorDirty } from './editor-dirty.ts'
import { createOpenInApp } from './open-in-app.ts'
import { useCenterColumn } from './sidebar/use-center-column.ts'
import { useHostFeeds } from './sidebar/use-host-feeds.ts'
import { mountedSessions } from './native/surface.ts'
@@ -569,6 +570,26 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
referenceInChatShared(ctx, sessionId, path, isDir)
}, [ctx, sessionId])
/**
* The tab context menu's "reveal in the file manager" row. The host's
* open-in-app capability is the ONLY path this plugin reveals through
* (`ctx.remote.session.openWorkspacePath({action:'reveal'})`, shared with
* the explorer's own reveal row via `createOpenInApp`); a deployment
* without a desktop (plain web) answers false, which is logged and
* otherwise a no-op — the bottom panel has no error strip to write to, and
* a failed reveal must never take the strip down. Defined above the
* no-session early return — a hook must never sit behind a conditional
* return (React counts hooks per render).
*/
const openInApp = useMemo(() => createOpenInApp(ctx), [ctx])
const revealTabFile = useCallback((path: string): void => {
void openInApp.reveal(path).then((ok) => {
if (!ok) console.error(`[dsh-better-sidebar] reveal in file manager failed: ${path}`)
}).catch((error: unknown) => {
console.error('[dsh-better-sidebar] reveal in file manager error:', error)
})
}, [openInApp])
if (state === undefined || sessionId === undefined) {
// No conversation yet: the host stays mounted (the drag shield keeps
// covering the region) but nothing is rendered — the toggle button lives
@@ -769,6 +790,7 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
getTabIcon={tabIconOf}
getTabBadge={tabBadgeOf}
getTabRightActions={tabRightActionsOf}
onRevealInFileManager={revealTabFile}
/>
</div>
</div>
+33 -5
View File
@@ -5,7 +5,8 @@
* are draggable; dropping onto another tab inserts before it, dropping on the
* strip background appends to this pane. Right-clicking a tab opens the tab
* context menu (close / close others / close to the left / close to the
* right, the close ones scoped to this pane).
* right / close all — every close scoped to this pane — plus reveal the
* right-clicked tab's file in the OS file manager).
*/
import { useEffect, useRef, useState, type ReactNode } from 'react'
import clsx from 'clsx'
@@ -79,9 +80,18 @@ export function TabBar(props: {
* render their own).
*/
getTabRightActions?: (tab: SidebarTab, paneId: string) => ReactNode
/**
* Reveal one tab's associated file in the OS file manager — the tab
* context menu's reveal row, fed by the shell with the host's open-in-app
* capability. The row is disabled for a tab with no associated file (no
* `path`, e.g. the changes / tasks / side-chat / diff pages) and when the
* shell passes no resolver at all.
*/
onRevealInFileManager?: (path: string) => void
}) {
const {
paneId, tabs, active, onActivate, onClose, onNewTab, newTabOptions, onDropTab, getTabIcon, getTabBadge, getTabRightActions,
onRevealInFileManager,
} = props
const [menuOpen, setMenuOpen] = useState(false)
// The tab right-click context menu: the target tab plus the cursor
@@ -92,6 +102,12 @@ export function TabBar(props: {
// The context target's index in the render-time tab snapshot; -1 when the
// tab disappeared since the menu opened (the menu hides then).
const tabMenuIndex = tabMenu === null ? -1 : tabs.findIndex(tab => tab.id === tabMenu.tabId)
// The context target's associated file: `path` carries it for file tabs
// (editor windows, folder windows included). The changes / tasks /
// side-chat / diff pages have none — a diff's repo-relative ref is not a
// path the host could reveal — so the reveal row greys out for them.
const tabMenuPath = tabs[tabMenuIndex]?.path
const canReveal = onRevealInFileManager !== undefined && tabMenuPath !== undefined && tabMenuPath !== ''
// The active tab's right-actions node, resolved up front so the render
// below can skip the wrapper entirely when there is nothing to show (an
@@ -284,10 +300,12 @@ export function TabBar(props: {
{/*
The tab context menu, positioned at the right-click cursor (portal
so the panel's overflow clip cannot crop it). Close operations are
scoped to THIS pane: "close others/left/right" walk the render-time
tab snapshot and reuse the per-tab onClose path (which routes
through the service), so the target tab is never closed and the
pane never empties mid-loop.
scoped to THIS pane: "close others/left/right/all" walk the
render-time tab snapshot and reuse the per-tab onClose path (which
routes through the service), so every closed tab runs its own
lifecycle and the target tab is only closed by the operations that
mean it (close / close all). "Close all" is always available: the
menu only opens from a tab, so the pane always holds at least one.
*/}
<Menu
open={tabMenu !== null && tabMenuIndex >= 0}
@@ -297,6 +315,8 @@ export function TabBar(props: {
{ id: 'closeOthers', label: t('closeOtherTabs'), ...(tabs.length <= 1 ? { disabled: true } : {}) },
{ id: 'closeLeft', label: t('closeLeftTabs'), ...(tabMenuIndex <= 0 ? { disabled: true } : {}) },
{ id: 'closeRight', label: t('closeRightTabs'), ...(tabMenuIndex >= tabs.length - 1 ? { disabled: true } : {}) },
{ id: 'closeAll', label: t('closeAllTabs') },
{ id: 'revealInFileManager', label: t('revealTabInFileManager'), ...(canReveal ? {} : { disabled: true }) },
]}
onSelect={(id) => {
const target = tabMenu
@@ -314,6 +334,14 @@ export function TabBar(props: {
for (const tab of tabs.slice(0, index)) onClose(tab.id)
} else if (id === 'closeRight') {
for (const tab of tabs.slice(index + 1)) onClose(tab.id)
} else if (id === 'closeAll') {
// EVERY tab in this pane, the right-clicked one included (that
// is what separates it from "close others") and the ones
// scrolled out of the strip's viewport included.
for (const tab of tabs) onClose(tab.id)
} else if (id === 'revealInFileManager') {
const path = tabs[index]?.path
if (path !== undefined && path !== '') onRevealInFileManager?.(path)
}
}}
portal
+2
View File
@@ -119,6 +119,8 @@ export const ar: Record<string, string> = {
closeOtherTabs: 'إغلاق التبويبات الأخرى',
closeLeftTabs: 'إغلاق التبويبات على اليسار',
closeRightTabs: 'إغلاق التبويبات على اليمين',
closeAllTabs: 'إغلاق كل التبويبات',
revealTabInFileManager: 'إظهار الملف في مدير الملفات',
pinTerminal: 'تثبيت الطرفية',
pinAgentTerminal: 'تثبيت طرفية Agent',
pinToWorkspace: 'تثبيت إلى مساحة العمل',
+2
View File
@@ -104,6 +104,8 @@ export const de: Record<string, string> = {
closeOtherTabs: 'Andere Tabs schließen',
closeLeftTabs: 'Tabs links schließen',
closeRightTabs: 'Tabs rechts schließen',
closeAllTabs: 'Alle Tabs schließen',
revealTabInFileManager: 'Datei im Dateimanager anzeigen',
pinTerminal: 'Terminal anheften',
pinAgentTerminal: 'Agent-Terminal anheften',
pinToWorkspace: 'An Arbeitsbereich anheften',
+2
View File
@@ -111,6 +111,8 @@ export const fr: Record<string, string> = {
closeOtherTabs: 'Fermer les autres onglets',
closeLeftTabs: 'Fermer les onglets à gauche',
closeRightTabs: 'Fermer les onglets à droite',
closeAllTabs: 'Fermer tous les onglets',
revealTabInFileManager: 'Afficher le fichier dans le gestionnaire de fichiers',
pinTerminal: 'Épingler le terminal',
pinAgentTerminal: 'Épingler le terminal Agent',
pinToWorkspace: 'Épingler à l\'espace de travail',
+2
View File
@@ -118,6 +118,8 @@ export const hi: Record<string, string> = {
closeOtherTabs: 'अन्य टैब बंद करें',
closeLeftTabs: 'बाएँ टैब बंद करें',
closeRightTabs: 'दाएँ टैब बंद करें',
closeAllTabs: 'सभी टैब बंद करें',
revealTabInFileManager: 'फ़ाइल को फ़ाइल मैनेजर में दिखाएँ',
pinTerminal: 'टर्मिनल पिन करें',
pinAgentTerminal: 'Agent टर्मिनल पिन करें',
pinToWorkspace: 'वर्कस्पेस पर पिन करें',
+2
View File
@@ -116,6 +116,8 @@ export const id: Record<string, string> = {
closeOtherTabs: 'Tutup Tab Lain',
closeLeftTabs: 'Tutup Tab di Kiri',
closeRightTabs: 'Tutup Tab di Kanan',
closeAllTabs: 'Tutup Semua Tab',
revealTabInFileManager: 'Tampilkan Berkas di Pengelola Berkas',
pinTerminal: 'Sematkan Terminal',
pinAgentTerminal: 'Sematkan Terminal Agent',
pinToWorkspace: 'Sematkan ke Workspace',
+2
View File
@@ -109,6 +109,8 @@ export const it: Record<string, string> = {
closeOtherTabs: 'Chiudi le altre schede',
closeLeftTabs: 'Chiudi le schede a sinistra',
closeRightTabs: 'Chiudi le schede a destra',
closeAllTabs: 'Chiudi tutte le schede',
revealTabInFileManager: 'Mostra il file nel gestore file',
pinTerminal: 'Blocca Terminale',
pinAgentTerminal: 'Blocca Terminale Agent',
pinToWorkspace: 'Blocca in Workspace',
+2
View File
@@ -118,6 +118,8 @@ export const ja: Record<string, string> = {
closeOtherTabs: '他のタブを閉じる',
closeLeftTabs: '左のタブを閉じる',
closeRightTabs: '右のタブを閉じる',
closeAllTabs: 'すべてのタブを閉じる',
revealTabInFileManager: 'ファイルの場所を開く',
pinTerminal: 'ターミナルを固定',
pinAgentTerminal: 'Agent ターミナルを固定',
pinToWorkspace: 'ワークスペースに固定',
+2
View File
@@ -110,6 +110,8 @@ export const ko: Record<string, string> = {
closeOtherTabs: '다른 탭 닫기',
closeLeftTabs: '왼쪽 탭 닫기',
closeRightTabs: '오른쪽 탭 닫기',
closeAllTabs: '모든 탭 닫기',
revealTabInFileManager: '파일 위치 열기',
pinTerminal: '터미널 고정',
pinAgentTerminal: 'Agent 터미널 고정',
pinToWorkspace: '워크스페이스에 고정',
+2
View File
@@ -116,6 +116,8 @@ export const nl: Record<string, string> = {
closeOtherTabs: 'Andere tabbladen sluiten',
closeLeftTabs: 'Tabbladen links sluiten',
closeRightTabs: 'Tabbladen rechts sluiten',
closeAllTabs: 'Alle tabbladen sluiten',
revealTabInFileManager: 'Bestand tonen in bestandsbeheerder',
pinTerminal: 'Terminal vastmaken',
pinAgentTerminal: 'Agent-terminal vastmaken',
pinToWorkspace: 'Vastmaken aan werkruimte',
+2
View File
@@ -120,6 +120,8 @@ export const pl: Record<string, string> = {
closeOtherTabs: 'Zamknij inne karty',
closeLeftTabs: 'Zamknij karty po lewej',
closeRightTabs: 'Zamknij karty po prawej',
closeAllTabs: 'Zamknij wszystkie karty',
revealTabInFileManager: 'Pokaż plik w menedżerze plików',
pinTerminal: 'Przypnij Terminal',
pinAgentTerminal: 'Przypnij Terminal Agent',
pinToWorkspace: 'Przypnij do obszaru roboczego',
+2
View File
@@ -101,6 +101,8 @@ export const pt: Record<string, string> = {
closeOtherTabs: 'Fechar outras abas',
closeLeftTabs: 'Fechar abas à esquerda',
closeRightTabs: 'Fechar abas à direita',
closeAllTabs: 'Fechar todas as abas',
revealTabInFileManager: 'Mostrar arquivo no gerenciador de arquivos',
pinTerminal: 'Fixar Terminal',
pinAgentTerminal: 'Fixar Terminal do Agent',
pinToWorkspace: 'Fixar no Workspace',
+2
View File
@@ -114,6 +114,8 @@ export const ru: Record<string, string> = {
closeOtherTabs: 'Закрыть остальные вкладки',
closeLeftTabs: 'Закрыть вкладки слева',
closeRightTabs: 'Закрыть вкладки справа',
closeAllTabs: 'Закрыть все вкладки',
revealTabInFileManager: 'Показать файл в файловом менеджере',
pinTerminal: 'Закрепить терминал',
pinAgentTerminal: 'Закрепить терминал Agent',
pinToWorkspace: 'Закрепить в рабочей области',
+2
View File
@@ -101,6 +101,8 @@ export const sv: Record<string, string> = {
closeOtherTabs: 'Stäng andra flikar',
closeLeftTabs: 'Stäng flikar till vänster',
closeRightTabs: 'Stäng flikar till höger',
closeAllTabs: 'Stäng alla flikar',
revealTabInFileManager: 'Visa filen i filhanteraren',
pinTerminal: 'Fäst Terminal',
pinAgentTerminal: 'Fäst Agent-terminal',
pinToWorkspace: 'Fäst på arbetsyta',
+2
View File
@@ -118,6 +118,8 @@ export const th: Record<string, string> = {
closeOtherTabs: 'ปิด Tab อื่น',
closeLeftTabs: 'ปิด Tab ด้านซ้าย',
closeRightTabs: 'ปิด Tab ด้านขวา',
closeAllTabs: 'ปิด Tab ทั้งหมด',
revealTabInFileManager: 'แสดงไฟล์ในตัวจัดการไฟล์',
pinTerminal: 'ปักหมุดเทอร์มินัล',
pinAgentTerminal: 'ปักหมุดเทอร์มินัล Agent',
pinToWorkspace: 'ปักหมุดไปยังพื้นที่ทำงาน',
+2
View File
@@ -118,6 +118,8 @@ export const tr: Record<string, string> = {
closeOtherTabs: 'Diğer sekmeleri kapat',
closeLeftTabs: 'Soldaki sekmeleri kapat',
closeRightTabs: 'Sağdaki sekmeleri kapat',
closeAllTabs: 'Tüm sekmeleri kapat',
revealTabInFileManager: 'Dosyayı dosya yöneticisinde göster',
pinTerminal: 'Terminali Sabitle',
pinAgentTerminal: 'Agent Terminalini Sabitle',
pinToWorkspace: 'Çalışma Alanına Sabitle',
+2
View File
@@ -118,6 +118,8 @@ export const vi: Record<string, string> = {
closeOtherTabs: 'Đóng các tab khác',
closeLeftTabs: 'Đóng tab bên trái',
closeRightTabs: 'Đóng tab bên phải',
closeAllTabs: 'Đóng tất cả tab',
revealTabInFileManager: 'Hiển thị tệp trong trình quản lý tệp',
pinTerminal: 'Ghim Terminal',
pinAgentTerminal: 'Ghim Terminal Agent',
pinToWorkspace: 'Ghim vào Workspace',
+2
View File
@@ -133,6 +133,8 @@ export const zhHK: Record<string, string> = {
closeOtherTabs: '關閉其他標籤',
closeLeftTabs: '關閉左側標籤',
closeRightTabs: '關閉右側標籤',
closeAllTabs: '關閉全部標籤',
revealTabInFileManager: '在檔案總管中定位',
pinTerminal: '固定終端',
pinAgentTerminal: '固定 Agent 終端',
pinToWorkspace: '固定到工作區',
+2
View File
@@ -133,6 +133,8 @@ export const zhMO: Record<string, string> = {
closeOtherTabs: '關閉其他標籤',
closeLeftTabs: '關閉左側標籤',
closeRightTabs: '關閉右側標籤',
closeAllTabs: '關閉全部標籤',
revealTabInFileManager: '在檔案總管中定位',
pinTerminal: '固定終端',
pinAgentTerminal: '固定 Agent 終端',
pinToWorkspace: '固定到工作區',
+2
View File
@@ -133,6 +133,8 @@ export const zhTW: Record<string, string> = {
closeOtherTabs: '關閉其他標籤',
closeLeftTabs: '關閉左側標籤',
closeRightTabs: '關閉右側標籤',
closeAllTabs: '關閉全部標籤',
revealTabInFileManager: '在檔案總管中定位',
pinTerminal: '固定終端',
pinAgentTerminal: '固定 Agent 終端',
pinToWorkspace: '固定到工作區',
+4
View File
@@ -130,6 +130,8 @@ export const zh = {
closeOtherTabs: '关闭其他页签',
closeLeftTabs: '关闭左侧页签',
closeRightTabs: '关闭右侧页签',
closeAllTabs: '关闭全部页签',
revealTabInFileManager: '在资源管理器中定位',
pinTerminal: '固定终端',
pinAgentTerminal: '固定 Agent 终端',
pinToWorkspace: '固定到工作区',
@@ -696,6 +698,8 @@ export const en: Record<keyof typeof zh, string> = {
closeOtherTabs: 'Close Other Tabs',
closeLeftTabs: 'Close Tabs to the Left',
closeRightTabs: 'Close Tabs to the Right',
closeAllTabs: 'Close All Tabs',
revealTabInFileManager: 'Reveal in File Manager',
pinTerminal: 'Pin Terminal',
pinAgentTerminal: 'Pin Agent Terminal',
pinToWorkspace: 'Pin to Workspace',
+16 -3
View File
@@ -148,8 +148,13 @@ function LeafView(props: {
getTabIcon?: (tab: SidebarTab) => ReactNode
getTabBadge?: (tab: SidebarTab) => ReactNode
getTabRightActions?: (tab: SidebarTab, paneId: string) => ReactNode
/**
* Reveal a tab's file in the OS file manager (the tab context menu's
* reveal row; see TabBar). Absent → that row stays disabled.
*/
onRevealInFileManager?: (path: string) => void
}) {
const { leaf, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions } = props
const { leaf, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions, onRevealInFileManager } = props
const [dropZone, setDropZone] = useState<DropZone | null>(null)
const activeTab = leaf.tabs.find(tab => tab.id === leaf.active) ?? leaf.tabs[leaf.tabs.length - 1]
@@ -206,6 +211,7 @@ function LeafView(props: {
getTabIcon={getTabIcon}
getTabBadge={getTabBadge}
getTabRightActions={getTabRightActions}
onRevealInFileManager={onRevealInFileManager}
onDropTab={(payload, before) => {
if (before === null) actions.moveTabToEdge(payload, leaf.id, 'center')
else actions.moveTabBefore(payload, leaf.id, before)
@@ -246,8 +252,9 @@ function NodeView(props: {
getTabIcon?: (tab: SidebarTab) => ReactNode
getTabBadge?: (tab: SidebarTab) => ReactNode
getTabRightActions?: (tab: SidebarTab, paneId: string) => ReactNode
onRevealInFileManager?: (path: string) => void
}) {
const { node, state, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions } = props
const { node, state, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions, onRevealInFileManager } = props
if (node.kind === 'leaf') {
return (
<LeafView
@@ -259,6 +266,7 @@ function NodeView(props: {
getTabIcon={getTabIcon}
getTabBadge={getTabBadge}
getTabRightActions={getTabRightActions}
onRevealInFileManager={onRevealInFileManager}
/>
)
}
@@ -287,6 +295,7 @@ function NodeView(props: {
getTabIcon={getTabIcon}
getTabBadge={getTabBadge}
getTabRightActions={getTabRightActions}
onRevealInFileManager={onRevealInFileManager}
/>
</div>
</Fragment>
@@ -309,8 +318,11 @@ export function Workbench(props: {
getTabIcon?: (tab: SidebarTab) => ReactNode
getTabBadge?: (tab: SidebarTab) => ReactNode
getTabRightActions?: (tab: SidebarTab, paneId: string) => ReactNode
/** Reveal a tab's file in the OS file manager (see TabBar); absent → the
* tab context menu's reveal row is disabled. */
onRevealInFileManager?: (path: string) => void
}) {
const { state, tree, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions } = props
const { state, tree, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions, onRevealInFileManager } = props
return (
<div className={css.workbench}>
<NodeView
@@ -323,6 +335,7 @@ export function Workbench(props: {
getTabIcon={getTabIcon}
getTabBadge={getTabBadge}
getTabRightActions={getTabRightActions}
onRevealInFileManager={onRevealInFileManager}
/>
</div>
)
+231 -20
View File
@@ -1,13 +1,17 @@
/**
* Tab-strip right-click context-menu tests. Right-clicking a tab takes over
* the browser menu (preventDefault) and shows the tab context menu with
* exactly five items: move to free window / close / close others / close to
* the left / close to the right. All bulk operations are scoped to the
* CURRENT pane (the render time tab snapshot) and reuse the per-tab onClose
* path, so the target tab is never closed and the pane never empties
* mid-loop. The menu items gray out when there is nothing to close (single
* tab → close others; leftmost → close left; rightmost → close right).
* Opening the menu must not activate the right-clicked tab.
* exactly six items: close / close others / close to the left / close to the
* right / close all / reveal in the file manager. All close operations are
* scoped to the CURRENT pane (the render-time tab snapshot) and reuse the
* per-tab onClose path, so every closed tab keeps its own lifecycle and the
* pane never empties mid-loop; "close all" is the one that closes the
* right-clicked tab too. The reveal row hands the tab's associated file
* (`path`, i.e. an editor window) to the shell's reveal resolver and is
* disabled for a tab that has none. Menu rows gray out when there is nothing
* to do (single tab → close others; leftmost → close left; rightmost → close
* right; no file → reveal). Opening the menu must not activate the
* right-clicked tab.
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -20,7 +24,10 @@ import { setupReactAct } from './test-utils.ts'
setupReactAct()
import { TabBar } from '../src/client/TabBar.tsx'
import type { SidebarTab } from '../src/client/state.ts'
import { Sidebar } from '../src/client/Sidebar.tsx'
import { Workbench } from '../src/client/split-pane.tsx'
import { createSidebarStore, makeDefaultState, type SidebarState, type SidebarTab } from '../src/client/state.ts'
import { createBetterSidebarService } from '../src/client/service.ts'
/** Point the browser-language fallback at Chinese so the menu labels assert. */
function stubZh(): void {
@@ -30,20 +37,27 @@ function stubZh(): void {
})
}
const MENU_LABELS = ['关闭', '关闭其他页签', '关闭左侧页签', '关闭右侧页签']
const MENU_LABELS = [
'关闭', '关闭其他页签', '关闭左侧页签', '关闭右侧页签', '关闭全部页签', '在资源管理器中定位',
]
function mountBar(tabs: SidebarTab[], opts: { onPinTab?: (tabId: string, scope: 'workspace' | 'global' | null) => void } = {}): {
function mountBar(tabs: SidebarTab[], opts: {
/** Omit the reveal resolver (the shell always passes one; this pins the
* disabled-without-resolver half of the contract). */
noRevealResolver?: boolean
} = {}): {
tabEls: HTMLElement[]
onClose: ReturnType<typeof vi.fn>
onActivate: ReturnType<typeof vi.fn>
onPinTab?: (tabId: string, scope: 'workspace' | 'global' | null) => void
/** The reveal resolver the strip was given (undefined when omitted). */
onRevealInFileManager?: ReturnType<typeof vi.fn>
unmount: () => void
} {
const container = document.createElement('div')
document.body.append(container)
const onClose = vi.fn()
const onActivate = vi.fn()
const onPinTab = opts.onPinTab
const onRevealInFileManager = opts.noRevealResolver === true ? undefined : vi.fn()
const root: Root = createRoot(container)
act(() => {
root.render(createElement(TabBar, {
@@ -54,7 +68,7 @@ function mountBar(tabs: SidebarTab[], opts: { onPinTab?: (tabId: string, scope:
onClose,
onNewTab: () => {},
newTabOptions: [],
...(onPinTab !== undefined ? { onPinTab } : {}),
...(onRevealInFileManager === undefined ? {} : { onRevealInFileManager }),
onDropTab: () => {},
}))
})
@@ -63,7 +77,7 @@ function mountBar(tabs: SidebarTab[], opts: { onPinTab?: (tabId: string, scope:
tabEls,
onClose,
onActivate,
...(onPinTab !== undefined ? { onPinTab } : {}),
...(onRevealInFileManager === undefined ? {} : { onRevealInFileManager }),
unmount: () => {
act(() => { root.unmount() })
container.remove()
@@ -80,6 +94,14 @@ function fourTabs(): SidebarTab[] {
]
}
/** Two tabs where only the first carries a file (an editor window). */
function fileTabs(): SidebarTab[] {
return [
{ id: 'f1', type: 'editor', title: 'a.ts', path: '/repo/src/a.ts' },
{ id: 'f2', type: 'git', title: 'Changes' },
]
}
/** Dispatch a native right-click (contextmenu) and return the event. */
function rightClick(target: EventTarget): MouseEvent {
const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 40 })
@@ -92,13 +114,20 @@ function menuItems(): HTMLElement[] {
return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
}
/** The disabled flags of the portaled rows, in menu order. */
function menuDisabled(): boolean[] {
return menuItems().map(item => (item as HTMLButtonElement).disabled)
}
afterEach(() => {
document.body.innerHTML = ''
vi.restoreAllMocks()
vi.unstubAllGlobals()
localStorage.clear()
})
describe('TabBar right-click context menu', () => {
it('opens the five-item menu at the cursor, prevents the browser menu, and does not activate', () => {
it('opens the six-item menu at the cursor, prevents the browser menu, and does not activate', () => {
stubZh()
const { tabEls, onActivate, unmount } = mountBar(fourTabs())
try {
@@ -180,6 +209,37 @@ describe('TabBar right-click context menu', () => {
}
})
it('close all closes every tab in the pane, the right-clicked one included', () => {
stubZh()
const { tabEls, onClose, unmount } = mountBar(fourTabs())
try {
act(() => { rightClick(tabEls[1]!) })
act(() => { menuItems()[4]!.click() })
expect(onClose.mock.calls.map(call => call[0])).toEqual(['t1', 't2', 't3', 't4'])
expect(menuItems()).toHaveLength(0)
} finally {
unmount()
}
})
it('reveals the right-clicked tab file through the shell resolver', () => {
stubZh()
const { tabEls, onRevealInFileManager, onClose, unmount } = mountBar(fileTabs())
try {
act(() => { rightClick(tabEls[0]!) })
// The file tab's row is live; the pane's other tab has no file.
expect(menuDisabled()).toEqual([false, false, true, false, false, false])
act(() => { menuItems()[5]!.click() })
expect(onRevealInFileManager).toHaveBeenCalledTimes(1)
expect(onRevealInFileManager).toHaveBeenCalledWith('/repo/src/a.ts')
// Revealing is not a close: no tab may go away.
expect(onClose).not.toHaveBeenCalled()
expect(menuItems()).toHaveLength(0)
} finally {
unmount()
}
})
it('grays out close others on a single tab and close left/right at the strip ends', () => {
stubZh()
const single = mountBar([
@@ -187,11 +247,11 @@ describe('TabBar right-click context menu', () => {
])
try {
act(() => { rightClick(single.tabEls[0]!) })
const items = menuItems()
// The Menu renders each row as a disabled <button role="menuitem">.
expect(items.map(item => (item as HTMLButtonElement).disabled)).toEqual([false, true, true, true])
// Close all stays live (it always has at least the right-clicked tab).
expect(menuDisabled()).toEqual([false, true, true, true, false, true])
// Clicking the disabled row must not close anything.
act(() => { items[1]!.click() })
act(() => { menuItems()[1]!.click() })
expect(single.onClose).not.toHaveBeenCalled()
} finally {
single.unmount()
@@ -200,11 +260,162 @@ describe('TabBar right-click context menu', () => {
const four = mountBar(fourTabs())
try {
act(() => { rightClick(four.tabEls[0]!) })
expect(menuItems().map(item => (item as HTMLButtonElement).disabled)).toEqual([false, false, true, false])
expect(menuDisabled()).toEqual([false, false, true, false, false, true])
act(() => { rightClick(four.tabEls[3]!) })
expect(menuItems().map(item => (item as HTMLButtonElement).disabled)).toEqual([false, false, false, true])
expect(menuDisabled()).toEqual([false, false, false, true, false, true])
} finally {
four.unmount()
}
})
it('grays out the reveal row for a tab with no associated file', () => {
stubZh()
const tabs = fileTabs()
const { tabEls, onRevealInFileManager, onClose, unmount } = mountBar(tabs)
try {
act(() => { rightClick(tabEls[1]!) })
// The changes tab carries no file of its own (its diff ref is
// repo-relative, not a path the host could reveal).
expect(menuDisabled()).toEqual([false, false, false, true, false, true])
act(() => { menuItems()[5]!.click() })
expect(onRevealInFileManager).not.toHaveBeenCalled()
expect(onClose).not.toHaveBeenCalled()
} finally {
unmount()
}
})
it('grays out the reveal row when the shell passes no resolver', () => {
stubZh()
const { tabEls, onRevealInFileManager, unmount } = mountBar(fileTabs(), { noRevealResolver: true })
try {
act(() => { rightClick(tabEls[0]!) })
expect(onRevealInFileManager).toBeUndefined()
expect(menuDisabled()[5]).toBe(true)
} finally {
unmount()
}
})
})
describe('Workbench tab context menu', () => {
/** Two panes side by side, each with one file tab (the recursive render
* path a split workbench takes to its strips). */
function splitState(): SidebarState {
return {
...makeDefaultState(),
bottomSplits: {
kind: 'split',
id: 'split:1',
dir: 'row',
sizes: [0.5, 0.5],
children: [
{ kind: 'leaf', id: 'pane:1', tabs: [{ id: 't1', type: 'editor', title: 'a.ts', path: '/repo/a.ts' }], active: 't1' },
{ kind: 'leaf', id: 'pane:2', tabs: [{ id: 't2', type: 'editor', title: 'b.ts', path: '/repo/b.ts' }], active: 't2' },
],
},
}
}
it('hands every pane strip the shell reveal resolver', () => {
stubZh()
const state = splitState()
const onRevealInFileManager = vi.fn()
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
act(() => {
root.render(createElement(Workbench, {
state,
tree: state.bottomSplits,
newTabOptions: [],
actions: {
closeTab: () => {},
activateTab: () => {},
focusPane: () => {},
moveTabToEdge: () => {},
moveTabBefore: () => {},
resizeSplit: () => {},
},
onNewTab: () => {},
// The strip is what this spec is about: the panes' bodies stay empty.
renderTab: () => null,
onRevealInFileManager,
}))
})
try {
const paneTabs = [...container.querySelectorAll<HTMLElement>('[class*="tabList"] > [class*="tab"]')]
expect(paneTabs).toHaveLength(2)
// Each strip's reveal row must reach the resolver with ITS tab's file.
act(() => { rightClick(paneTabs[0]!) })
expect(menuDisabled()[5]).toBe(false)
act(() => { menuItems()[5]!.click() })
expect(onRevealInFileManager).toHaveBeenLastCalledWith('/repo/a.ts')
act(() => { rightClick(paneTabs[1]!) })
act(() => { menuItems()[5]!.click() })
expect(onRevealInFileManager).toHaveBeenLastCalledWith('/repo/b.ts')
expect(onRevealInFileManager).toHaveBeenCalledTimes(2)
} finally {
act(() => { root.unmount() })
container.remove()
}
})
})
describe('Sidebar tab context menu reveal', () => {
/**
* The whole shell on a fake host: the bottom workbench holds one file tab,
* and the reveal row must reach the host's open-in-app remote — the same
* call the explorer's own reveal row makes (`ctx.remote.session.
* openWorkspacePath({ path, action: 'reveal' })`). This is the only
* coverage of the shell's own wiring between the strip resolver and the
* open-in-app adapter; `tests/open-in-app.spec.ts` covers the adapter.
*/
it('reveals the tab file through the host open-in-app remote', async () => {
vi.stubGlobal('WebSocket', class { close(): void {} })
const store = createSidebarStore()
store.setSession('s1')
store.reduce(state => ({ ...state, bottomOpen: true }))
const service = createBetterSidebarService(store)
service.registerTab({ id: 'probe', title: 'Probe', component: () => null })
service.openTab({ type: 'probe', title: 'probe.ts', path: '/repo/src/probe.ts' })
const reveal = vi.fn(async () => ({ ok: true }))
// Both snapshots are stable references (useSyncExternalStore re-reads
// them on every render: a fresh object here is an infinite loop). The
// shell follows the host's MOUNTED seat (`ctx.sidebarRight.mounted`) for
// its per-session state, so the fake column has to report one — without
// it the shell unbinds the store and renders nothing.
const localeSnapshot = { active: 'en' }
const sessionsSnapshot = { byId: { s1: { id: 's1', cwd: '/repo' } } }
const ctx = {
locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot },
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } },
get: (name: string) => ({
betterSidebar: service,
remote: { session: { openWorkspacePath: reveal } },
sidebarRight: { mounted: { subscribe: () => () => {}, getSnapshot: () => 's1' } },
})[name],
}
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
act(() => { root.render(createElement(Sidebar, { ctx: ctx as never, store })) })
try {
const tab = container.querySelector<HTMLElement>('[class*="bottomPanel"] [class*="tabList"] > [class*="tab"]')
expect(tab).not.toBeNull()
act(() => { rightClick(tab!) })
// The copy is pinned by the TabBar block above (against zh); here the
// shape and the row's live state are what matter (the shell runs on the
// default locale).
expect(menuItems()).toHaveLength(MENU_LABELS.length)
expect(menuDisabled()[5]).toBe(false)
await act(async () => { menuItems()[5]!.click() })
expect(reveal).toHaveBeenCalledTimes(1)
expect(reveal).toHaveBeenCalledWith({ path: '/repo/src/probe.ts', action: 'reveal' })
} finally {
act(() => { root.unmount() })
container.remove()
}
})
})