import React, { useMemo, useState } from 'react'; import { Box, Text, useInput } from 'ink'; import type { WorkspaceRecord } from '../context/workspaceIndex.js'; import { theme } from './theme.js'; interface Props { workspaces: WorkspaceRecord[]; currentPath: string; currentSessionId: string; onSelect: (cwd: string, sessionId: string) => void; onCancel: () => void; } export function WorkspacePicker({ workspaces, currentPath, currentSessionId, onSelect, onCancel }: Props): JSX.Element { const available = useMemo(() => workspaces.filter((workspace) => workspace.sessions.length > 0), [workspaces]); const [workspaceIndex, setWorkspaceIndex] = useState(0); const [selectedWorkspace, setSelectedWorkspace] = useState(null); const [sessionIndex, setSessionIndex] = useState(0); const items = selectedWorkspace?.sessions ?? available; const index = selectedWorkspace ? sessionIndex : workspaceIndex; const setIndex = selectedWorkspace ? setSessionIndex : setWorkspaceIndex; useInput((input, key) => { if (key.escape || (key.ctrl && input === 'c')) { if (selectedWorkspace) { setSelectedWorkspace(null); setSessionIndex(0); } else onCancel(); return; } if (!items.length) return; if (key.upArrow) { setIndex((value) => (value - 1 + items.length) % items.length); return; } if (key.downArrow) { setIndex((value) => (value + 1) % items.length); return; } if (!key.return) return; if (!selectedWorkspace) { const workspace = available[workspaceIndex]; if (workspace) { if (!workspace.available) return; setSelectedWorkspace(workspace); const activeIndex = workspace.sessions.findIndex((session) => session.id === workspace.activeSessionId); setSessionIndex(Math.max(0, activeIndex)); } return; } const session = selectedWorkspace.sessions[sessionIndex]; if (session) onSelect(selectedWorkspace.displayPath, session.id); }); return ( {selectedWorkspace ? `${selectedWorkspace.displayName} · 选择会话` : `选择工作区(${available.length})`} {!items.length ? 暂无可恢复的工作区会话 : null} {selectedWorkspace ? selectedWorkspace.sessions.map((session, itemIndex) => ( {itemIndex === sessionIndex ? '> ' : ' '}{session.title} {selectedWorkspace.displayPath === currentPath && session.id === currentSessionId ? ' (当前)' : ''} {session.lastMessagePreview ? {session.lastMessagePreview.slice(0, 72)} : null} )) : available.map((workspace, itemIndex) => ( {itemIndex === workspaceIndex ? '> ' : ' '}{workspace.displayName} · {workspace.sessions.length} 个会话 {!workspace.available ? ' · 未连接' : ''} ))} {!selectedWorkspace && available[workspaceIndex]?.available === false ? '该工作区未连接,重新挂载磁盘后才能打开 · ESC 取消' : `↑↓ 选择 · Enter 确认${selectedWorkspace ? ' · ESC 返回工作区' : ' · ESC 取消'}`} ); }