878 lines
32 KiB
Vue
878 lines
32 KiB
Vue
<script setup lang="ts">
|
||
/**
|
||
* 终端工作区(模块「终端」页的全部内容)。
|
||
*
|
||
* # 为什么从 TerminalModule 里拆出来
|
||
*
|
||
* 拆分前 TerminalModule.vue 有 1197 行,同时承担两件性质完全不同的事:
|
||
* (a) 模块级编排 —— 5 个 tab、tab 记忆、快捷键分发;
|
||
* (b) 终端页的全部交互 —— 搜索、右键菜单、分屏、清屏、重命名、
|
||
* 模板拉起、AI 助手、会话日志、独立窗口。
|
||
*
|
||
* 后者是终端模块里体量最大、改动最频繁的部分,与前者混在一个文件里,
|
||
* 每次动终端页都要在 1200 行里找位置。现在 (b) 整体搬到这里,(a) 留在
|
||
* TerminalModule —— 它回到「薄编排」的形态,和 proxy / monitor 的模块根一致。
|
||
*
|
||
* # 布局口径(2026-09-21 把控制栏收进终端卡片)
|
||
*
|
||
* ```
|
||
* ┌───────────────────────────────────────────────┐
|
||
* │ ╭───────────────────────────────────────────╮ │
|
||
* │ │ [会话标签…] │ 历史 片段 搜索 字体 清屏 ⋯ │ │ ← 控制栏(h-9,带下边框)
|
||
* │ ├───────────────────────────────────────────┤ │
|
||
* │ │ 画布(xterm) │ │
|
||
* │ ├───────────────────────────────────────────┤ │
|
||
* │ │ 状态栏:会话 · 目标 · 编码 · cwd · 尺寸 │ │ ← 与控制栏同高(h-9)
|
||
* │ ╰───────────────────────────────────────────╯ │
|
||
* └───────────────────────────────────────────────┘
|
||
* ```
|
||
*
|
||
* 文件管理器**不在**卡片里(2026-09-24):它是模块级的一页(`FileManager`,
|
||
* 双栏 + 两栏各自选连接)与一个独立窗口。控制栏的文件按钮只负责跳过去。
|
||
*
|
||
* 控制栏最左的两个图标(历史 / 片段)各带一个浮层,见 `TerminalToolbar` 的文件头。
|
||
*
|
||
* 上一版把「会话标签 + 操作组」放在卡片**外面**当作页面级工具条。结果是卡片里
|
||
* 只有画布与状态栏,控制栏反而悬在页面顶部 —— 一个终端窗口的控件应该长在窗口上,
|
||
* 而不是浮在它上面。现在三层(控制栏 / 画布 / 状态栏)同属一张卡片,卡片就是
|
||
* 「终端窗口」本身;页面上也不再多出一条既不属于模块 Tabs、也不属于卡片的横条。
|
||
*
|
||
* 上下两条栏同为 h-9 且都用 12px 字号:它们是同一块屏幕的边框,视觉上必须等高,
|
||
* 否则卡片看起来是歪的。
|
||
*
|
||
* # 面板为什么不销毁
|
||
*
|
||
* 切标签时**不销毁**非激活的 `TerminalPane`,只用 `v-show` 隐藏。
|
||
* xterm 实例的构造代价不小(解析字体度量、建 WebGL 上下文、分配回滚缓冲),
|
||
* 保留实例还能保住滚动位置与选区 —— 用户切回来时应该还是刚才那一屏。
|
||
* 代价是不活跃会话也持有 WebGL 上下文,超出上限时 `useXterm` 会自动回退到
|
||
* DOM 渲染器。
|
||
*
|
||
* # stream 为什么由父组件传入
|
||
*
|
||
* `useTerminalStream()` 内部的 `tabOrder` / `panes` / `activeSessionId`
|
||
* 是**每次调用各创建一份**的局部状态。父组件(模块根)需要 `activeSession`
|
||
* 去喂历史/片段面板,本组件需要 `panes` 去排分屏 —— 若两边各调一次,
|
||
* 就会出现两套独立的标签顺序与分屏状态。因此全模块只创建一次,
|
||
* 由父组件通过 prop 传下来。
|
||
*/
|
||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||
import { AlertTriangle, ChevronsRight, Loader2, Plus, Server, TerminalSquare, X } from '@lucide/vue'
|
||
import { toast } from 'vue-sonner'
|
||
import { useTerminalStore } from '@/stores/terminalStore'
|
||
import type { useTerminalStream } from '@/composables/useSessionStream'
|
||
import TerminalPane from './TerminalPane.vue'
|
||
import TerminalTabs from './TerminalTabs.vue'
|
||
import TerminalToolbar from './TerminalToolbar.vue'
|
||
import TerminalStatusBar from './TerminalStatusBar.vue'
|
||
import TerminalContextMenu from './TerminalContextMenu.vue'
|
||
import ForwardPanel from './ForwardPanel.vue'
|
||
import TemplatePanel from './TemplatePanel.vue'
|
||
import AiPanel from './AiPanel.vue'
|
||
import { Button } from '@/components/ui/button'
|
||
import {
|
||
Dialog,
|
||
DialogContent,
|
||
DialogDescription,
|
||
DialogFooter,
|
||
DialogHeader,
|
||
DialogTitle
|
||
} from '@/components/ui/dialog'
|
||
import type { SessionTemplate } from '@/types/terminal'
|
||
|
||
const props = defineProps<{
|
||
/** 窗口级会话编排(只能由模块根创建一次,见文件头) */
|
||
stream: ReturnType<typeof useTerminalStream>
|
||
/** 模块初始化是否完成(完成前显示加载态) */
|
||
ready: boolean
|
||
}>()
|
||
|
||
const emit = defineEmits<{
|
||
/** 请求切换到模块的「主机」tab(空态与标签栏的「管理主机」入口) */
|
||
(e: 'go-hosts'): void
|
||
/** 请求切换到模块的「文件」tab(控制栏的文件按钮,见 `openFiles`) */
|
||
(e: 'open-files'): void
|
||
}>()
|
||
|
||
const store = useTerminalStore()
|
||
|
||
const {
|
||
activeSessionId,
|
||
activeSession,
|
||
orderedSessions,
|
||
effectiveAppearance,
|
||
confirmDialog,
|
||
selectSession,
|
||
closeTab,
|
||
applyOrder,
|
||
newLocalTab,
|
||
newSshTab,
|
||
bumpFont,
|
||
resetFont,
|
||
resolveConfirm,
|
||
isSplit,
|
||
splitLayout,
|
||
panes,
|
||
resetPanesTo,
|
||
addPane,
|
||
splitRight,
|
||
splitDown,
|
||
closePane,
|
||
toggleSplitDirection
|
||
} = props.stream
|
||
|
||
// ===== 面板引用(用于调用 fit / 搜索 / 清屏) =====
|
||
|
||
/** sessionId → TerminalPane 暴露的方法。用普通 Map:面板实例不需要响应式 */
|
||
const paneRefs = new Map<string, InstanceType<typeof TerminalPane>>()
|
||
|
||
function setPaneRef(sessionId: string, el: unknown) {
|
||
if (el) paneRefs.set(sessionId, el as InstanceType<typeof TerminalPane>)
|
||
else paneRefs.delete(sessionId)
|
||
}
|
||
|
||
function activePane() {
|
||
return activeSessionId.value ? paneRefs.get(activeSessionId.value) : undefined
|
||
}
|
||
|
||
/** 会话列表变化时清理面板引用,防止 Map 无限增长 */
|
||
watch(
|
||
() => store.sessions.map(s => s.id).join(','),
|
||
() => {
|
||
const alive = new Set(store.sessions.map(s => s.id))
|
||
for (const id of [...paneRefs.keys()]) {
|
||
if (!alive.has(id)) paneRefs.delete(id)
|
||
}
|
||
}
|
||
)
|
||
|
||
// ===== 文件管理器(已从终端卡片里的面板改为独立 tab / 独立窗口) =====
|
||
//
|
||
// 2026-09-24:原先这里挂着一个绑定当前会话的 SFTP 面板(含拖拽调宽)。
|
||
// 它有两个绕不开的限制:一次只能服务一个会话(本地↔远端是唯一组合),
|
||
// 且每次看文件都得先切到对应会话的标签。现在文件管理器是模块级的一页
|
||
// (双栏 + 两栏各自选连接),本组件只负责把它「叫出来」并预选当前会话。
|
||
|
||
/**
|
||
* 从控制栏的文件按钮跳到「文件」页。
|
||
*
|
||
* 把激活会话写进右栏是**关键的一步**:文件页自己读不到「终端页当前在看哪个会话」
|
||
* (`activeSessionId` 是 `useTerminalStream` 的窗口级局部状态,见文件头),
|
||
* 所以由这里顺手带过去。非 SSH 会话不带(本地会话没有远端目录可浏览)。
|
||
*/
|
||
function openFiles() {
|
||
if (activeSession.value?.kind === 'ssh') {
|
||
store.setFilePaneSource('right', { kind: 'ssh', sessionId: activeSession.value.id })
|
||
}
|
||
emit('open-files')
|
||
}
|
||
|
||
/** 激活会话的显示名(端口转发对话框的标题用;store 的派生方法需要看到 hosts,故在这层取) */
|
||
const activeSessionLabel = computed(() => store.sessionLabel(activeSession.value))
|
||
|
||
// ===== 端口转发 / 会话模板 / AI 助手(低频配置,用 Dialog) =====
|
||
|
||
const forwardsOpen = ref(false)
|
||
const templatesOpen = ref(false)
|
||
const applyingTemplate = ref(false)
|
||
const aiOpen = ref(false)
|
||
|
||
/**
|
||
* 按模板拉起一组会话并排成布局。
|
||
*
|
||
* 逐条开会话:第 1 个作主面板(resetPanesTo 收敛布局),
|
||
* 其余依次 addPane —— 分屏方向沿用 splitDirection(默认左右)。
|
||
* 条目失败不中断整体(主机连不上不该挡住本地 Shell 拉起),
|
||
* 汇总成一条 toast;超分屏上限的孤儿会话按 splitTo 同款收掉。
|
||
*/
|
||
async function applyTemplate(t: SessionTemplate) {
|
||
if (applyingTemplate.value) return
|
||
applyingTemplate.value = true
|
||
const failures: string[] = []
|
||
let opened = 0
|
||
let first = true
|
||
try {
|
||
for (const e of t.entries.slice(0, 4)) {
|
||
try {
|
||
const info = e.kind === 'ssh' ? await newSshTab(e.targetId) : await newLocalTab()
|
||
if (!info) {
|
||
failures.push(`${e.label || '未知目标'}:没有可用的 Shell`)
|
||
continue
|
||
}
|
||
if (first) {
|
||
resetPanesTo(info.id)
|
||
first = false
|
||
} else if (!addPane(info.id)) {
|
||
// 超出分屏上限:把刚建的会话收掉,不留看不见的孤儿
|
||
await store.closeSession(info.id)
|
||
failures.push(`${e.label}:超出分屏上限`)
|
||
continue
|
||
}
|
||
opened++
|
||
} catch (err) {
|
||
failures.push(`${e.label || '未知目标'}:${String(err)}`)
|
||
}
|
||
}
|
||
} finally {
|
||
applyingTemplate.value = false
|
||
}
|
||
if (opened > 0 && failures.length === 0) {
|
||
toast.success(`已按模板「${t.name}」拉起 ${opened} 个会话`)
|
||
} else if (opened > 0) {
|
||
toast.warning(`已拉起 ${opened} 个,部分失败:${failures.join(';')}`)
|
||
} else {
|
||
toast.error(`模板「${t.name}」拉起失败:${failures.join(';') || '没有可用条目'}`)
|
||
}
|
||
}
|
||
|
||
/** 当前可见面板的会话 id(模板「保存当前布局」的捕获源) */
|
||
const currentPaneIds = computed(() => {
|
||
if (panes.value.length > 0) return panes.value.map(p => p.sessionId)
|
||
return activeSessionId.value ? [activeSessionId.value] : []
|
||
})
|
||
|
||
/** 终端上下文:当前会话的选中文本(供 AI 理解「接着上一步做什么」) */
|
||
function getTerminalContext(): string {
|
||
const id = activeSessionId.value
|
||
if (!id) return ''
|
||
return paneRefs.get(id)?.getSelection?.() ?? ''
|
||
}
|
||
|
||
/**
|
||
* 开关当前会话的日志。
|
||
*
|
||
* 成功提示里带日志路径——用户需要知道日志在哪才能在事后找到它;
|
||
* 开关状态本身由后端的 TERMINAL_STATE 事件刷新(SessionInfo.logging)。
|
||
*/
|
||
async function toggleLogging() {
|
||
const id = activeSessionId.value
|
||
const sess = activeSession.value
|
||
if (!id || !sess) return
|
||
try {
|
||
await store.toggleLogging(id, !sess.logging)
|
||
if (!sess.logging) {
|
||
const p = await store.logPath(id)
|
||
toast.success(p ? `已开始记录会话日志:${p}` : '已开始记录会话日志')
|
||
} else {
|
||
toast.success('已停止记录会话日志(文件已保留)')
|
||
}
|
||
} catch (e) {
|
||
toast.error(`切换日志记录失败:${String(e)}`)
|
||
}
|
||
}
|
||
|
||
/** 在文件管理器中显示当前日志文件 */
|
||
async function openLogDir() {
|
||
const id = activeSessionId.value
|
||
if (!id) return
|
||
try {
|
||
const p = await store.logPath(id)
|
||
if (!p) {
|
||
toast.info('当前会话未开启日志')
|
||
return
|
||
}
|
||
await store.revealLocalPath(p)
|
||
} catch (e) {
|
||
toast.error(`打开日志位置失败:${String(e)}`)
|
||
}
|
||
}
|
||
|
||
// ===== 搜索 =====
|
||
|
||
const searching = ref(false)
|
||
const searchHint = ref('')
|
||
|
||
function toggleSearch() {
|
||
searching.value = !searching.value
|
||
if (!searching.value) {
|
||
activePane()?.clearSearch?.()
|
||
searchHint.value = ''
|
||
}
|
||
}
|
||
|
||
function doSearch(keyword: string) {
|
||
const pane = activePane()
|
||
if (!pane) return
|
||
const found = pane.findNext?.(keyword)
|
||
searchHint.value = found === false ? '无匹配' : ''
|
||
}
|
||
|
||
function searchNext(keyword: string) {
|
||
const pane = activePane()
|
||
if (!pane) return
|
||
const found = pane.findNext?.(keyword)
|
||
searchHint.value = found === false ? '无匹配' : ''
|
||
}
|
||
|
||
function searchPrev(keyword: string) {
|
||
const pane = activePane()
|
||
if (!pane) return
|
||
const found = pane.findPrevious?.(keyword)
|
||
searchHint.value = found === false ? '无匹配' : ''
|
||
}
|
||
|
||
// ===== 会话操作 =====
|
||
|
||
const creating = ref(false)
|
||
|
||
/**
|
||
* 新建本地会话。
|
||
*
|
||
* `shellId` 由标签栏的「新建」下拉传入(用户明确选了某个 shell);
|
||
* 从空态、快捷键、分屏进来的调用都不带参数,走「上次使用的 shell」。
|
||
*/
|
||
async function handleNewLocal(shellId?: string) {
|
||
if (creating.value) return
|
||
creating.value = true
|
||
try {
|
||
const info = await newLocalTab({ shellId })
|
||
// 新建标签后把分屏容器收敛到它:否则会看到上一个标签的分屏布局残留
|
||
if (info) resetPanesTo(info.id)
|
||
} catch (e) {
|
||
toast.error(`新建会话失败:${String(e)}`)
|
||
} finally {
|
||
creating.value = false
|
||
}
|
||
}
|
||
|
||
/** 从标签栏的「新建」下拉里选中已保存主机 → 建立 SSH 会话 */
|
||
async function handleConnect(hostId: string) {
|
||
try {
|
||
const info = await newSshTab(hostId)
|
||
if (info) resetPanesTo(info.id)
|
||
} catch (e) {
|
||
// SSH 失败的具体原因(握手/认证/主机密钥)后端已写进 session.error,
|
||
// 这里只给一个总括提示,详细原因会显示在面板中央
|
||
toast.error(`连接失败:${String(e)}`)
|
||
}
|
||
}
|
||
|
||
// ===== 分屏 =====
|
||
|
||
async function handleSplit(dir: 'right' | 'down') {
|
||
try {
|
||
const r = await (dir === 'right' ? splitRight() : splitDown())
|
||
if (!r.ok) toast.info(r.message)
|
||
} catch (e) {
|
||
toast.error(`分屏失败:${String(e)}`)
|
||
}
|
||
}
|
||
|
||
/** 分屏网格的 CSS 布局类(与 splitLayout 一一对应) */
|
||
const splitGridClass = computed(() => {
|
||
switch (splitLayout.value) {
|
||
case 'v-split':
|
||
return 'grid-rows-2 grid-cols-1'
|
||
case 'h-split':
|
||
return 'grid-cols-2 grid-rows-1'
|
||
case 'grid':
|
||
return 'grid-cols-2 grid-rows-2'
|
||
default:
|
||
return 'grid-cols-1 grid-rows-1'
|
||
}
|
||
})
|
||
|
||
/**
|
||
* 实际渲染的面板列表:**全部会话常驻挂载**。
|
||
*
|
||
* 这是对文件头「全部保留实例,用 v-show 切换」承诺的落实。此前实现只渲染
|
||
* `panes` 里的会话,切标签会把其他会话的 TerminalPane 整个卸载——
|
||
* xterm 实例被 dispose、隐藏期间到达的输出因无订阅者被丢弃,
|
||
* 切回来就是一片空白(多标签基本不可用)。
|
||
*
|
||
* 现在的可见性规则:
|
||
* - 分屏激活时(`panes` 非空):只有分屏组内的会话可见;
|
||
* - 单面板时:只有激活会话可见。
|
||
* 不在可见集里的会话保持挂载(display:none),照常接收输出。
|
||
*/
|
||
const renderPanes = computed(() => {
|
||
const visible = new Set(
|
||
panes.value.length > 0
|
||
? panes.value.map(p => p.sessionId)
|
||
: activeSessionId.value
|
||
? [activeSessionId.value]
|
||
: []
|
||
)
|
||
return orderedSessions.value.map(s => ({
|
||
id: `pane-${s.id}`,
|
||
sessionId: s.id,
|
||
hidden: !visible.has(s.id)
|
||
}))
|
||
})
|
||
|
||
async function handleDetach() {
|
||
const id = activeSessionId.value
|
||
if (!id) return
|
||
try {
|
||
await store.detachSession(id)
|
||
toast.success('已在独立窗口中打开')
|
||
} catch (e) {
|
||
toast.error(`打开独立窗口失败:${String(e)}`)
|
||
}
|
||
}
|
||
|
||
function handleClear() {
|
||
const id = activeSessionId.value
|
||
if (!id) return
|
||
const pane = paneRefs.get(id)
|
||
if (!pane) return
|
||
const shellKind = store.shells.find(s => s.id === store.sessionById(id)?.targetId)?.kind
|
||
// 清屏是「让 shell 执行清屏」而不是「从 xterm 缓冲里删掉」——
|
||
// 后者只是视觉上清了,向上滚动仍能看到旧内容,且 shell 的行计数会错乱
|
||
void store.clearSession(id, shellKind)
|
||
pane.clear?.()
|
||
}
|
||
|
||
// ===== 标签重排 =====
|
||
|
||
/**
|
||
* 写回用户拖动后的标签顺序。
|
||
*
|
||
* 标签栏把拖动结果以「完整 id 列表」的形式抛上来,这里直接交给编排组合函数
|
||
* 的 `applyOrder` —— 由它负责过滤已消失的会话并补齐漏网的。
|
||
* 前端不做任何顺序推断(例如「谁到了谁前面」),因为拖动本身已经给出了完整答案,
|
||
* 再做推断只会引入「拖到末尾时位置漂移」这类边界问题。
|
||
*/
|
||
function handleReorder(ids: string[]) {
|
||
applyOrder(ids)
|
||
}
|
||
|
||
// ===== 右键菜单 =====
|
||
|
||
const contextMenu = ref<{ sessionId: string; x: number; y: number } | null>(null)
|
||
|
||
function closeContextMenu() {
|
||
contextMenu.value = null
|
||
}
|
||
|
||
/** 右键菜单的当前会话是否有选区(决定「复制」是否可用) */
|
||
const contextHasSelection = computed(() => {
|
||
const id = contextMenu.value?.sessionId
|
||
if (!id) return false
|
||
return !!paneRefs.get(id)?.getSelection?.()
|
||
})
|
||
|
||
const behavior = computed(() => store.settings?.selection ?? null)
|
||
|
||
/**
|
||
* 面板右键的统一入口。
|
||
*
|
||
* 三种行为共用这一个监听(`rightClick` 设置项决定走哪条):
|
||
* - `menu`(默认):弹出菜单。终端里的右键在不同软件里含义不同
|
||
* (Windows Terminal 粘贴、PuTTY 弹菜单),猜测意图容易误操作,
|
||
* 因此默认给显式菜单。
|
||
* - `paste`:直接粘贴。习惯 X11 的用户会期待这个。
|
||
* - `select-word`:选中光标下的词,随后仍弹菜单 —— 只选中不弹菜单
|
||
* 等于给了一个「无法后续操作」的选区,用户还得再右键一次。
|
||
*/
|
||
function onPaneContextMenu(payload: { sessionId: string; x: number; y: number }) {
|
||
const mode = behavior.value?.rightClick ?? 'menu'
|
||
|
||
if (mode === 'paste') {
|
||
// 粘贴的目标是「发出右键的那块面板」,而不是当前激活标签 ——
|
||
// 两者在分屏或标签快速切换时可能不一致
|
||
activeSessionId.value = payload.sessionId
|
||
void doPaste()
|
||
return
|
||
}
|
||
|
||
if (mode === 'select-word') {
|
||
paneRefs.get(payload.sessionId)?.selectWordAt?.(payload.x, payload.y)
|
||
}
|
||
|
||
contextMenu.value = payload
|
||
}
|
||
|
||
async function doCopy() {
|
||
const id = contextMenu.value?.sessionId ?? activeSessionId.value
|
||
if (!id) return
|
||
const text = paneRefs.get(id)?.getSelection?.()
|
||
if (!text) {
|
||
toast.info('没有选中内容')
|
||
return
|
||
}
|
||
const payload =
|
||
(behavior.value?.trimTrailingNewline ?? true) && text.endsWith('\n')
|
||
? text.replace(/\n+$/, '')
|
||
: text
|
||
try {
|
||
await navigator.clipboard.writeText(payload)
|
||
} catch (e) {
|
||
toast.error(`复制失败:${String(e)}`)
|
||
}
|
||
closeContextMenu()
|
||
}
|
||
|
||
/**
|
||
* 粘贴。
|
||
*
|
||
* 多行内容会先在终端里「攒着」而不是直接执行 —— 但 P0 不做确认弹窗,
|
||
* 因为 xterm 的 bracketed paste 模式(若 shell 启用)已经能让编辑器
|
||
* 正确处理多行。这里只负责把文本交给 PTY。
|
||
*/
|
||
async function doPaste() {
|
||
const id = contextMenu.value?.sessionId ?? activeSessionId.value
|
||
if (!id) return
|
||
try {
|
||
const text = await navigator.clipboard.readText()
|
||
if (!text) return
|
||
await store.write(id, text)
|
||
} catch (e) {
|
||
toast.error(`粘贴失败:${String(e)}`)
|
||
}
|
||
closeContextMenu()
|
||
}
|
||
|
||
function doSelectAll() {
|
||
const id = contextMenu.value?.sessionId ?? activeSessionId.value
|
||
if (!id) return
|
||
paneRefs.get(id)?.selectAll?.()
|
||
closeContextMenu()
|
||
}
|
||
|
||
function doClearFromMenu() {
|
||
const id = contextMenu.value?.sessionId
|
||
closeContextMenu()
|
||
if (id) {
|
||
activeSessionId.value = id
|
||
handleClear()
|
||
}
|
||
}
|
||
|
||
async function doCloseFromMenu() {
|
||
const id = contextMenu.value?.sessionId
|
||
closeContextMenu()
|
||
if (id) await closeTab(id)
|
||
}
|
||
|
||
function doRename() {
|
||
const id = contextMenu.value?.sessionId
|
||
closeContextMenu()
|
||
openRename(id)
|
||
}
|
||
|
||
/**
|
||
* 打开重命名对话框。
|
||
*
|
||
* 抽出来是因为有两处入口(右键菜单、工具栏「更多」菜单),原实现
|
||
* 在右键路径里**忘了打开对话框**——点了「重命名标签」什么都不发生。
|
||
* 两处共用同一个函数,这类「复制粘贴漏一行」的问题不会再出现。
|
||
*/
|
||
function openRename(id: string | null | undefined) {
|
||
if (!id) return
|
||
renameValue.value = store.sessionById(id)?.title ?? ''
|
||
renameTargetId.value = id
|
||
confirmRenameOpen.value = true
|
||
}
|
||
|
||
const confirmRenameOpen = ref(false)
|
||
const renameTargetId = ref<string | null>(null)
|
||
const renameValue = ref('')
|
||
|
||
watch(confirmRenameOpen, v => {
|
||
if (!v) renameTargetId.value = null
|
||
})
|
||
|
||
async function submitRename() {
|
||
const id = renameTargetId.value
|
||
if (!id) return
|
||
const title = renameValue.value.trim()
|
||
if (!title) {
|
||
toast.error('名称不能为空')
|
||
return
|
||
}
|
||
try {
|
||
await store.renameSession(id, title)
|
||
confirmRenameOpen.value = false
|
||
} catch (e) {
|
||
toast.error(`重命名失败:${String(e)}`)
|
||
}
|
||
}
|
||
|
||
// ===== 生命周期 =====
|
||
|
||
onMounted(() => {
|
||
// 点击任意处关闭右键菜单(冒泡阶段:面板自身的 click 也要能关掉菜单)
|
||
document.addEventListener('click', closeContextMenu)
|
||
})
|
||
|
||
onBeforeUnmount(() => {
|
||
document.removeEventListener('click', closeContextMenu)
|
||
})
|
||
|
||
/** 聚焦当前激活面板(供模块根在新建会话后调用,让键盘输入直接可用) */
|
||
async function focusActivePane() {
|
||
await nextTick()
|
||
paneRefs.get(activeSessionId.value ?? '')?.focus?.()
|
||
}
|
||
|
||
/**
|
||
* 暴露给模块根的动作集合。
|
||
*
|
||
* 这些动作由**模块级快捷键**触发(见 TerminalModule 的 useTerminalKeys),
|
||
* 但状态与实现属于终端页(搜索框开合、右键菜单目标、SFTP 面板开合…),
|
||
* 因此模块根做一次转发。用显式清单而不是把整个 setup 作用域暴露出去:
|
||
* 新增动作时必须两边同时改,不会被静默漏掉。
|
||
*
|
||
* 标签导航类的动作(切标签、关标签、编号跳转)不在此列 —— 它们的状态在
|
||
* `useTerminalStream` 里,模块根可以直接调用。
|
||
*/
|
||
defineExpose({
|
||
doCopy,
|
||
doPaste,
|
||
toggleSearch,
|
||
handleClear,
|
||
handleNewLocal,
|
||
handleSplit,
|
||
handleDetach,
|
||
openFiles,
|
||
openRename,
|
||
focusActivePane
|
||
})
|
||
</script>
|
||
|
||
<template>
|
||
<div class="flex flex-col h-full min-h-0">
|
||
<!--
|
||
===== 终端卡片:控制栏 + 画布 + 状态栏 =====
|
||
|
||
三层同属一张卡片 —— 卡片就是「终端窗口」本身。圆角与边框不再只是给
|
||
xterm 划边界(画布不是内容流,必须有边界),也是控制栏与状态栏的容器。
|
||
|
||
shadow-sm 与项目 `<Card>` 一致:终端卡片在页面里就是「一张卡片」,
|
||
别的页面卡片有阴影而这块没有,会让终端页看起来像没铺完的骨架。
|
||
-->
|
||
<div
|
||
class="flex-1 min-h-0 flex flex-col rounded-lg border border-border overflow-hidden bg-background shadow-sm"
|
||
>
|
||
<!--
|
||
控制栏:会话标签(左)+ 会话级操作(右)。
|
||
与状态栏同为 h-9;px-1.5 让首尾按钮不贴到卡片圆角上。
|
||
-->
|
||
<div class="shrink-0 flex items-center gap-1 h-9 px-1.5 border-b border-border">
|
||
<TerminalTabs
|
||
:sessions="orderedSessions"
|
||
:active-id="activeSessionId"
|
||
@select="selectSession"
|
||
@close="closeTab"
|
||
@new="handleNewLocal"
|
||
@connect="handleConnect"
|
||
@reorder="handleReorder"
|
||
@manage-hosts="emit('go-hosts')"
|
||
/>
|
||
|
||
<div class="w-px h-4 bg-border shrink-0" />
|
||
|
||
<TerminalToolbar
|
||
:session-id="activeSessionId"
|
||
:session="activeSession"
|
||
:searching="searching"
|
||
:search-hint="searchHint"
|
||
:is-ssh="activeSession?.kind === 'ssh'"
|
||
:logging="activeSession?.logging ?? false"
|
||
:font-size="effectiveAppearance?.fontSize ?? 14"
|
||
@open-files="openFiles"
|
||
@open-forwards="forwardsOpen = true"
|
||
@toggle-logging="toggleLogging"
|
||
@open-log-dir="openLogDir"
|
||
@open-templates="templatesOpen = true"
|
||
@open-ai="aiOpen = true"
|
||
@rename="openRename(activeSessionId)"
|
||
@toggle-search="toggleSearch"
|
||
@search="doSearch"
|
||
@search-next="searchNext($event)"
|
||
@search-prev="searchPrev($event)"
|
||
@font="bumpFont($event)"
|
||
@font-reset="resetFont"
|
||
@clear="handleClear"
|
||
@detach="handleDetach"
|
||
/>
|
||
</div>
|
||
|
||
<div class="flex-1 min-h-0 flex">
|
||
<!-- 主区 -->
|
||
<div class="flex-1 min-w-0 relative">
|
||
<!-- 加载态 -->
|
||
<div v-if="!props.ready" class="absolute inset-0 flex items-center justify-center">
|
||
<div class="flex flex-col items-center gap-3">
|
||
<Loader2 class="size-5 animate-spin text-muted-foreground" />
|
||
<p class="text-xs text-muted-foreground">正在初始化终端…</p>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 空态 -->
|
||
<div
|
||
v-else-if="orderedSessions.length === 0"
|
||
class="absolute inset-0 flex items-center justify-center"
|
||
>
|
||
<div class="flex flex-col items-center gap-4 text-center">
|
||
<TerminalSquare class="size-10 text-muted-foreground/25" />
|
||
<div>
|
||
<p class="text-sm text-muted-foreground mb-1">还没有打开的会话</p>
|
||
<p class="text-xs text-muted-foreground/70">
|
||
点左上角的「+」新建本地 Shell 或连接已保存的主机
|
||
</p>
|
||
</div>
|
||
<div class="flex items-center gap-2">
|
||
<Button size="sm" class="gap-1.5" @click="handleNewLocal()">
|
||
<Plus class="size-3.5" />新建本地会话
|
||
</Button>
|
||
<Button variant="outline" size="sm" class="gap-1.5" @click="emit('go-hosts')">
|
||
<Server class="size-3.5" />管理主机
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 面板:全部保留实例,用 v-show 切换(见 renderPanes 说明) -->
|
||
<template v-else>
|
||
<!--
|
||
分屏容器。
|
||
1 个可见面板时就是普通全屏;2~4 个时按 splitLayout 排成 2 列或 2×2。
|
||
这里用 CSS grid 而不是嵌套 flex:分屏的维度组合是可枚举的
|
||
(单/左右/上下/2×2),网格能用一组静态类表达全部情形,
|
||
而 flex 需要嵌套 + 条件样式,逻辑会散在模板里。
|
||
隐藏面板(display:none)不占据网格单元,因此可见面板数决定布局。
|
||
-->
|
||
<div class="absolute inset-0 grid gap-px bg-border" :class="splitGridClass">
|
||
<div
|
||
v-for="p in renderPanes"
|
||
:key="p.id"
|
||
v-show="!p.hidden"
|
||
class="relative min-w-0 min-h-0"
|
||
>
|
||
<TerminalPane
|
||
:ref="(el: any) => setPaneRef(p.sessionId, el)"
|
||
:session-id="p.sessionId"
|
||
:appearance="effectiveAppearance"
|
||
:visible="!p.hidden"
|
||
@focus="selectSession(p.sessionId)"
|
||
@contextmenu="onPaneContextMenu"
|
||
/>
|
||
<!-- 非聚焦面板的边框高亮:分屏时「输入会去哪里」必须一眼可见 -->
|
||
<div
|
||
v-if="isSplit && p.sessionId === activeSessionId"
|
||
class="pointer-events-none absolute inset-0 ring-1 ring-inset ring-primary/40"
|
||
/>
|
||
<!-- 分屏面板的关闭按钮(只移除面板,不杀会话) -->
|
||
<button
|
||
v-if="isSplit"
|
||
class="absolute top-0.5 right-0.5 z-10 size-5 rounded flex items-center justify-center
|
||
bg-background/80 text-muted-foreground hover:text-foreground
|
||
opacity-0 hover:opacity-100 transition-opacity"
|
||
title="关闭此面板(会话保留)"
|
||
@click.stop="selectSession(p.sessionId); closePane()"
|
||
>
|
||
<X class="size-3" />
|
||
</button>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 分屏方向切换(仅两面板时有意义) -->
|
||
<button
|
||
v-if="panes.length === 2"
|
||
class="absolute bottom-2 right-2 z-10 h-6 px-2 rounded border border-border
|
||
bg-background/90 text-[10px] text-muted-foreground hover:text-foreground"
|
||
:title="splitLayout === 'h-split' ? '改为上下排列' : '改为左右排列'"
|
||
@click="toggleSplitDirection"
|
||
>
|
||
{{ splitLayout === 'h-split' ? '⬍ 上下' : '⬌ 左右' }}
|
||
</button>
|
||
</template>
|
||
</div>
|
||
|
||
<!-- ===== 独立窗口的会话提示条:该会话在主窗口不可交互 ===== -->
|
||
<div
|
||
v-if="activeSession?.detached"
|
||
class="shrink-0 w-8 border-l border-border flex items-start justify-center pt-3"
|
||
>
|
||
<button
|
||
class="text-muted-foreground hover:text-foreground transition-colors"
|
||
title="该会话已在独立窗口中打开,点击收回"
|
||
@click="activeSessionId && store.attachSession(activeSessionId)"
|
||
>
|
||
<ChevronsRight class="size-3.5" />
|
||
</button>
|
||
</div>
|
||
</div>
|
||
|
||
<!-- 状态栏:会话的客观事实(身份/状态/cwd/编码/尺寸) -->
|
||
<TerminalStatusBar
|
||
v-if="store.settings?.layout.showStatusBar !== false"
|
||
:session="activeSession"
|
||
:font-size="effectiveAppearance?.fontSize ?? 14"
|
||
:cols="activeSession?.cols"
|
||
:rows="activeSession?.rows"
|
||
/>
|
||
</div>
|
||
|
||
<!-- ===== 右键菜单(与独立窗口共用同一份,见该组件的文件头) ===== -->
|
||
<TerminalContextMenu
|
||
v-if="contextMenu"
|
||
:x="contextMenu.x"
|
||
:y="contextMenu.y"
|
||
:can-copy="contextHasSelection"
|
||
@copy="doCopy"
|
||
@paste="doPaste"
|
||
@select-all="doSelectAll"
|
||
@clear="doClearFromMenu"
|
||
@rename="doRename"
|
||
@close="doCloseFromMenu"
|
||
/>
|
||
|
||
<!-- ===== 端口转发(P2,SSH 会话) ===== -->
|
||
<ForwardPanel
|
||
v-model:open="forwardsOpen"
|
||
:session-id="activeSessionId"
|
||
:session-label="activeSessionLabel"
|
||
/>
|
||
|
||
<!-- ===== 会话模板(P2) ===== -->
|
||
<TemplatePanel
|
||
v-model:open="templatesOpen"
|
||
:pane-ids="currentPaneIds"
|
||
@apply="applyTemplate"
|
||
/>
|
||
|
||
<!-- ===== AI 命令助手(P2) ===== -->
|
||
<AiPanel v-model:open="aiOpen" :session-id="activeSessionId" :get-context="getTerminalContext" />
|
||
|
||
<!-- ===== 关闭运行中会话的确认 ===== -->
|
||
<Dialog :open="confirmDialog !== null" @update:open="v => !v && resolveConfirm(false)">
|
||
<DialogContent class="max-w-sm" :show-close-button="false">
|
||
<DialogHeader>
|
||
<!-- break-all:标题含无可断行的长路径(如 powershell.exe 全路径),不 加会横向撑破容器 -->
|
||
<DialogTitle class="text-base flex items-start gap-2 break-all">
|
||
<AlertTriangle class="size-4 shrink-0 text-warning" />
|
||
<span class="min-w-0">{{ confirmDialog?.title }}</span>
|
||
</DialogTitle>
|
||
<DialogDescription class="text-xs break-all">{{ confirmDialog?.message }}</DialogDescription>
|
||
</DialogHeader>
|
||
<DialogFooter>
|
||
<Button variant="outline" size="sm" @click="resolveConfirm(false)">取消</Button>
|
||
<Button variant="destructive" size="sm" @click="resolveConfirm(true)">关闭会话</Button>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
|
||
<!-- ===== 重命名 ===== -->
|
||
<Dialog v-model:open="confirmRenameOpen">
|
||
<DialogContent class="max-w-sm">
|
||
<DialogHeader>
|
||
<DialogTitle class="text-base">重命名标签</DialogTitle>
|
||
</DialogHeader>
|
||
<input
|
||
v-model="renameValue"
|
||
class="w-full h-8 px-2.5 rounded-md border border-border bg-transparent
|
||
text-sm outline-none focus:border-primary/60"
|
||
@keydown.enter="submitRename"
|
||
/>
|
||
<DialogFooter>
|
||
<Button variant="outline" size="sm" @click="confirmRenameOpen = false">取消</Button>
|
||
<Button size="sm" @click="submitRename">保存</Button>
|
||
</DialogFooter>
|
||
</DialogContent>
|
||
</Dialog>
|
||
</div>
|
||
</template>
|