Merge pull request #436 from chriswritescode-dev/feat/activity-switcher

feat(activity): surface active work across the session picker, tool rail and mobile
This commit is contained in:
Chris Scott authored and GitHub committed 2026-10-16 12:48:52 -04:00
commit 33d9523666
60 files changed
+3992 -491

No files matched your search

@@ -1,11 +1,13 @@
import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { Search } from 'lucide-react'
import { useEffect, useId, useMemo, useState } from 'react'
import type { Repo } from '@/api/types'
import { Input } from '@/components/ui/input'
import { useNavigableRepos } from '@/hooks/useSidebarRepoGroups'
import { cn, getRepoBranchLabel, getRepoDisplayName } from '@/lib/utils'
const PAGE_STEP = 10
import {
PickerSearchBar,
optionId,
usePickerCursor,
usePickerKeyNav,
} from '@/components/session/usePickerKeyboardNav'
interface ProjectPickerContentProps {
open: boolean
@@ -15,8 +17,9 @@ interface ProjectPickerContentProps {
searchInputRef: React.RefObject<HTMLInputElement | null>
}
function optionId(baseId: string, index: number): string {
return `${baseId}-option-${index}`
interface ProjectPickerRow {
key: string
repo: Repo
}
export function ProjectPickerContent({
@@ -27,12 +30,10 @@ export function ProjectPickerContent({
searchInputRef,
}: ProjectPickerContentProps) {
const { repos, isLoading } = useNavigableRepos()
const rowRefs = useRef(new Map<number, HTMLDivElement>())
const listId = useId()
const optionBaseId = useId()
const [query, setQuery] = useState('')
const [cursorIndex, setCursorIndex] = useState<number | null>(null)
const trimmedQuery = query.trim()
@@ -46,111 +47,49 @@ export function ProjectPickerContent({
})
}, [repos, trimmedQuery])
const defaultCursorIndex = useMemo(() => {
if (!trimmedQuery && currentRepo) {
const index = filteredRepos.findIndex((repo) => repo.id === currentRepo.id)
if (index >= 0) return index
}
return filteredRepos.length > 0 ? 0 : -1
}, [trimmedQuery, currentRepo, filteredRepos])
const effectiveCursorIndex = cursorIndex ?? defaultCursorIndex
const cursorRepo = effectiveCursorIndex >= 0 ? filteredRepos[effectiveCursorIndex] : undefined
useEffect(() => {
setCursorIndex(null)
}, [trimmedQuery])
const setRowRef = useCallback((key: number, node: HTMLDivElement | null) => {
if (node) rowRefs.current.set(key, node)
else rowRefs.current.delete(key)
}, [])
useEffect(() => {
if (!cursorRepo) return
const node = rowRefs.current.get(cursorRepo.id)
if (node && typeof node.scrollIntoView === 'function') {
node.scrollIntoView({ block: 'nearest' })
}
}, [cursorRepo])
const moveCursor = useCallback(
(index: number) => {
if (!filteredRepos[index]) return
setCursorIndex(index)
},
const rows = useMemo<ProjectPickerRow[]>(
() => filteredRepos.map((repo) => ({ key: String(repo.id), repo })),
[filteredRepos],
)
const handleSearchKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing) return
if (event.metaKey || event.altKey) return
const defaultCursorKey = useMemo(() => {
if (!trimmedQuery && currentRepo) {
const current = rows.find((row) => row.repo.id === currentRepo.id)
if (current) return current.key
}
return rows[0]?.key ?? null
}, [trimmedQuery, currentRepo, rows])
const key = event.key
const ctrlKey = event.key.toLowerCase()
const moveBy = (delta: number, wrap: boolean) => {
if (filteredRepos.length === 0) return
const base = effectiveCursorIndex < 0 ? (delta > 0 ? -1 : 0) : effectiveCursorIndex
const raw = base + delta
const next = wrap
? ((raw % filteredRepos.length) + filteredRepos.length) % filteredRepos.length
: Math.max(0, Math.min(filteredRepos.length - 1, raw))
moveCursor(next)
}
if (key === 'ArrowDown' || (event.ctrlKey && ctrlKey === 'n')) {
event.preventDefault()
moveBy(1, true)
return
}
if (key === 'ArrowUp' || (event.ctrlKey && ctrlKey === 'p')) {
event.preventDefault()
moveBy(-1, true)
return
}
if (key === 'PageDown') {
event.preventDefault()
moveBy(PAGE_STEP, false)
return
}
if (key === 'PageUp') {
event.preventDefault()
moveBy(-PAGE_STEP, false)
return
}
if (key === 'Enter') {
if (!cursorRepo) return
event.preventDefault()
onSelectRepo(cursorRepo)
}
},
[filteredRepos, effectiveCursorIndex, moveCursor, cursorRepo, onSelectRepo],
const { cursorIndex, cursorRow, registerRef, moveCursor, resetCursor } = usePickerCursor(
rows,
defaultCursorKey,
)
useEffect(() => {
resetCursor()
}, [trimmedQuery, resetCursor])
const handleSearchKeyDown = usePickerKeyNav({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow: (row) => onSelectRepo(row.repo),
})
return (
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
ref={searchInputRef}
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={effectiveCursorIndex >= 0 ? optionId(optionBaseId, effectiveCursorIndex) : undefined}
value={query}
onChange={(event) => setQuery(event.target.value)}
onKeyDown={handleSearchKeyDown}
placeholder="Search projects..."
className="h-9 pl-9"
autoComplete="off"
name="project-picker-search"
/>
</div>
</div>
<PickerSearchBar
inputRef={searchInputRef}
listId={listId}
open={open}
activeDescendantId={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
value={query}
onChange={setQuery}
onKeyDown={handleSearchKeyDown}
placeholder="Search projects..."
name="project-picker-search"
/>
<div
role="listbox"
@@ -158,19 +97,20 @@ export function ProjectPickerContent({
aria-label="Projects"
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
>
{filteredRepos.length === 0 ? (
{rows.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">
{isLoading ? 'Loading projects...' : 'No projects found'}
</div>
) : (
filteredRepos.map((repo, index) => {
const isCursor = index === effectiveCursorIndex
rows.map((row, index) => {
const { repo } = row
const isCursor = index === cursorIndex
const isCurrent = repo.id === currentRepo?.id
const branch = getRepoBranchLabel(repo)
return (
<div
key={repo.id}
ref={(node) => setRowRef(repo.id, node)}
key={row.key}
ref={(node) => registerRef(row.key, node)}
role="presentation"
onPointerMove={(event) => {
if (event.pointerType === 'mouse') moveCursor(index)
@@ -217,7 +157,7 @@ export function ProjectPickerContent({
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
↑↓ move · Enter open
{switchHint ? ` · ${switchHint} sessions` : ''}
{switchHint ? ` · ${switchHint} active` : ''}
</div>
</div>
)
@@ -4,7 +4,9 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import type { Repo, Session } from '@/api/types'
import type { ActiveWorkGroups, ActiveWorkItem, ActiveWorkState } from '@/lib/activeWork'
import { stubMatchMedia } from '@/test/test-utils'
import { DEFAULT_ACTIVITY_WINDOW_MINUTES } from '@/api/types/settings'
import { KeyboardShortcutsProvider } from '@/contexts/KeyboardShortcutsContext'
import { SessionPickerDialog } from './SessionPickerDialog'
@@ -23,8 +25,15 @@ const mocks = vi.hoisted(() => ({
getOpenCodeLocation: vi.fn(),
sessionPins: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
repos: [] as Repo[],
activeWorkGroups: { needsInput: [], running: [], recent: [] } as ActiveWorkGroups,
activeWorkWindowMs: 0,
preferences: undefined as
| { leaderKey?: string; keyboardShortcuts?: Record<string, string>; directShortcuts?: string[] }
| {
leaderKey?: string
keyboardShortcuts?: Record<string, string>
directShortcuts?: string[]
activityWindowMinutes?: number
}
| undefined,
}))
@@ -77,6 +86,15 @@ vi.mock('@/hooks/useSidebarRepoGroups', () => ({
useNavigableRepos: () => ({ repos: mocks.repos, isLoading: false, refetch: vi.fn() }),
}))
vi.mock('@/hooks/useActiveWork', () => ({
useActiveWork: (windowMs: number) => {
mocks.activeWorkWindowMs = windowMs
return { groups: mocks.activeWorkGroups, isLoading: false, isError: false }
},
useActivityWindowMinutes: () =>
mocks.preferences?.activityWindowMinutes ?? DEFAULT_ACTIVITY_WINDOW_MINUTES,
}))
vi.mock('@/stores/sessionStatusStore', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/stores/sessionStatusStore')>()
return { ...actual, useSessionStatusForSession: () => ({ type: 'idle' }) }
@@ -106,6 +124,24 @@ function repo(id: number, name: string, fullPath: string): Repo {
}
}
function activeWorkItem(
id: string,
title: string,
directory: string,
state: ActiveWorkState = 'recent',
): ActiveWorkItem {
const itemRepo = mocks.repos.find((candidate) => candidate.fullPath === directory) ?? mocks.repos[0]
const itemSession = session(id, title, directory)
return {
key: `${directory}:${id}`,
session: itemSession,
repo: itemRepo,
state,
updatedAt: itemSession.time.updated,
path: `/repos/${itemRepo.id}/sessions/${id}`,
}
}
function renderWithClient(ui: React.ReactElement) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
const directory = mocks.repos[0]?.fullPath
@@ -144,6 +180,10 @@ const openProjectsTab = () => {
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Projects' }))
}
const openActiveTab = () => {
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Active' }))
}
describe('SessionPickerDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
@@ -159,6 +199,8 @@ describe('SessionPickerDialog', () => {
mocks.sessionPins = []
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.sessionsData = []
mocks.activeWorkGroups = { needsInput: [], running: [], recent: [] }
mocks.activeWorkWindowMs = 0
mocks.preferences = undefined
})
@@ -492,10 +534,11 @@ describe('SessionPickerDialog', () => {
expect(screen.getByRole('option', { name: /Active session/ })).toHaveAttribute('aria-selected', 'true')
})
it('renders a Sessions/Projects tab switcher and defaults to the sessions tab', () => {
it('renders an Active/Sessions/Projects tab switcher and defaults to the sessions tab', () => {
renderPicker()
expect(screen.getByRole('tab', { name: 'Sessions' })).toHaveAttribute('aria-selected', 'true')
expect(screen.getByRole('tab', { name: 'Active' })).toHaveAttribute('aria-selected', 'false')
expect(screen.getByRole('tab', { name: 'Projects' })).toHaveAttribute('aria-selected', 'false')
expect(combobox()).toHaveAttribute('placeholder', 'Search sessions...')
})
@@ -578,6 +621,35 @@ describe('SessionPickerDialog', () => {
expect(onSelectRepo).toHaveBeenCalledWith(mocks.repos[0])
})
it('navigates the projects tab with wrapping arrows, PageUp/PageDown and Enter', async () => {
mocks.repos = Array.from({ length: 12 }, (_, index) =>
repo(index + 1, `repo-${index + 1}`, `/w/r${index + 1}`),
)
const { onSelectRepo } = renderPicker()
openProjectsTab()
expect(await screen.findByRole('option', { name: 'repo-1' })).toHaveAttribute(
'aria-selected',
'true',
)
fireEvent.keyDown(combobox(), { key: 'ArrowUp' })
expect(screen.getByRole('option', { name: 'repo-12' })).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
expect(screen.getByRole('option', { name: 'repo-1' })).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'PageDown' })
expect(screen.getByRole('option', { name: 'repo-11' })).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'Enter' })
expect(onSelectRepo).toHaveBeenCalledWith(mocks.repos[10])
fireEvent.keyDown(combobox(), { key: 'PageUp' })
expect(screen.getByRole('option', { name: 'repo-1' })).toHaveAttribute('aria-selected', 'true')
})
it('opens a repo on click in the projects tab', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
const { onSelectRepo } = renderPicker()
@@ -619,14 +691,19 @@ describe('SessionPickerDialog', () => {
expect(screen.getByText('No projects found')).toBeInTheDocument()
})
it('toggles between tabs with the default Ctrl+S binding in either search input', async () => {
it('cycles Active, Sessions and Projects with the default Ctrl+S binding', async () => {
renderPicker()
expect(screen.getByRole('tab', { name: 'Sessions', selected: true })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 's', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Projects', selected: true })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 's', ctrlKey: true })
expect(screen.getByRole('tab', { name: 'Sessions', selected: true })).toBeInTheDocument()
expect(await screen.findByRole('tab', { name: 'Active', selected: true })).toBeInTheDocument()
fireEvent.keyDown(combobox(), { key: 's', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Sessions', selected: true })).toBeInTheDocument()
})
it('honors a configured switch binding and shows it in the footer', async () => {
@@ -638,7 +715,7 @@ describe('SessionPickerDialog', () => {
fireEvent.keyDown(combobox(), { key: 'g', ctrlKey: true })
expect(await screen.findByRole('tab', { name: 'Projects', selected: true })).toBeInTheDocument()
expect(screen.getByText(/Ctrl\+G sessions/)).toBeInTheDocument()
expect(screen.getByText(/Ctrl\+G active/)).toBeInTheDocument()
})
it('shows the normalized leader, arrow and key in the footer for a leader switch binding', () => {
@@ -691,4 +768,113 @@ describe('SessionPickerDialog', () => {
expect(screen.getByRole('tab', { name: 'Sessions' })).toHaveAttribute('aria-selected', 'true'),
)
})
it('groups active work into needs input, running and recent sections with repo labels', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.activeWorkGroups = {
needsInput: [activeWorkItem('ses_ni', 'Needs input task', '/w/a', 'needs-input')],
running: [activeWorkItem('ses_run', 'Running task', '/w/b', 'running')],
recent: [activeWorkItem('ses_recent', 'Recent task', '/w/a', 'recent')],
}
renderPicker()
openActiveTab()
expect(await screen.findByText('Needs input')).toBeInTheDocument()
expect(screen.getByText('Running')).toBeInTheDocument()
expect(screen.getByText('Recent')).toBeInTheDocument()
expect(screen.getByRole('option', { name: /Needs input task/ }).textContent).toContain('alpha')
expect(screen.getByRole('option', { name: /Running task/ }).textContent).toContain('beta')
expect(screen.getByRole('option', { name: /Recent task/ }).textContent).toContain('alpha')
expect(mocks.activeWorkWindowMs).toBe(30 * 60 * 1000)
})
it('skips empty active work sections and shows the empty state for the configured window', async () => {
mocks.preferences = { activityWindowMinutes: 120 }
renderPicker()
openActiveTab()
expect(
await screen.findByText('No active or recent sessions in the last 2 hours'),
).toBeInTheDocument()
expect(screen.queryByText('Needs input')).not.toBeInTheDocument()
expect(screen.queryByText('Running')).not.toBeInTheDocument()
expect(screen.queryByText('Recent')).not.toBeInTheDocument()
})
it('formats a full-day active work window as hours in the empty state', async () => {
mocks.preferences = { activityWindowMinutes: 1440 }
renderPicker()
openActiveTab()
expect(
await screen.findByText('No active or recent sessions in the last 24 hours'),
).toBeInTheDocument()
expect(mocks.activeWorkWindowMs).toBe(1440 * 60 * 1000)
})
it('opens the cursor active row with Enter and selects its session and repo', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.activeWorkGroups = {
needsInput: [],
running: [activeWorkItem('ses_run', 'Running task', '/w/b', 'running')],
recent: [activeWorkItem('ses_recent', 'Recent task', '/w/a', 'recent')],
}
const { onSelectSession } = renderPicker()
openActiveTab()
const running = await screen.findByRole('option', { name: /Running task/ })
expect(running).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'ArrowDown' })
expect(screen.getByRole('option', { name: /Recent task/ })).toHaveAttribute('aria-selected', 'true')
fireEvent.keyDown(combobox(), { key: 'Enter' })
expect(onSelectSession).toHaveBeenCalledWith(expect.objectContaining({ id: 'ses_recent' }), mocks.repos[0])
})
it('filters active work rows by title and drops sections left empty', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.activeWorkGroups = {
needsInput: [activeWorkItem('ses_ni', 'Needs input task', '/w/a', 'needs-input')],
running: [],
recent: [activeWorkItem('ses_recent', 'Recent task', '/w/b', 'recent')],
}
renderPicker()
openActiveTab()
await screen.findByRole('option', { name: /Needs input task/ })
fireEvent.change(combobox(), { target: { value: 'recent' } })
expect(screen.queryByRole('option', { name: /Needs input task/ })).not.toBeInTheDocument()
expect(screen.getByRole('option', { name: /Recent task/ })).toBeInTheDocument()
expect(screen.queryByText('Needs input')).not.toBeInTheDocument()
expect(screen.getByText('Recent')).toBeInTheDocument()
})
it('pins an active work row from the shared row menu', async () => {
mocks.repos = [repo(1, 'alpha', '/w/a'), repo(2, 'beta', '/w/b')]
mocks.activeWorkGroups = {
needsInput: [],
running: [activeWorkItem('ses_run', 'Running task', '/w/b', 'running')],
recent: [],
}
renderPicker()
const user = userEvent.setup()
openActiveTab()
await screen.findByRole('option', { name: /Running task/ })
await user.click(screen.getByRole('button', { name: 'Session actions' }))
await user.click(await screen.findByText('Pin'))
expect(mocks.togglePinMock).toHaveBeenCalledWith({
sessionId: 'ses_run',
directory: '/w/b',
pinned: true,
})
})
})
@@ -1,9 +1,10 @@
import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { format, startOfDay } from 'date-fns'
import { MoreHorizontal, Pin, PinOff, Search } from 'lucide-react'
import { MoreHorizontal, Pin, PinOff } from 'lucide-react'
import { getOpenCodeLocation } from '@/api/opencode'
import type { Repo, Session } from '@/api/types'
import { ACTIVE_WORK_GROUPS, MS_PER_MINUTE, formatActivityEmptyMessage } from '@/lib/activeWork'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogTitle } from '@/components/ui/dialog'
import {
@@ -12,14 +13,20 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Input } from '@/components/ui/input'
import { SessionStatusIndicator } from '@/components/ui/session-status-indicator'
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
import { DeleteSessionDialog } from '@/components/session/DeleteSessionDialog'
import { ProjectPickerContent } from '@/components/session/ProjectPickerContent'
import {
PickerSearchBar,
optionId,
usePickerCursor,
usePickerKeyNav,
} from '@/components/session/usePickerKeyboardNav'
import { partitionSessions } from '@/components/session/session-partition'
import { buildRepoByDirectory } from '@/components/navigation/sidebar-session-tree'
import { useDeleteSession } from '@/hooks/useOpenCode'
import { useActiveWork, useActivityWindowMinutes } from '@/hooks/useActiveWork'
import { useSessionSearch } from '@/hooks/useSessionSearch'
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins'
import { usePersistentBoolean } from '@/hooks/usePersistentBoolean'
@@ -34,10 +41,22 @@ import { FINE_POINTER_MEDIA_QUERY, useMediaQuery } from '@/hooks/useMediaQuery'
const ALL_PROJECTS_STORAGE_KEY = 'oc:session-picker:all-projects'
const UNTITLED_SESSION_TITLE = 'Untitled Session'
const PAGE_STEP = 10
const NEAR_BOTTOM_PX = 240
type SessionPickerTab = 'sessions' | 'projects'
type SessionPickerTab = 'active' | 'sessions' | 'projects'
const SESSION_PICKER_TABS: SessionPickerTab[] = ['active', 'sessions', 'projects']
const SESSION_PICKER_TAB_LABELS: Record<SessionPickerTab, string> = {
active: 'Active',
sessions: 'Sessions',
projects: 'Projects',
}
function nextSessionPickerTab(tab: SessionPickerTab): SessionPickerTab {
const index = SESSION_PICKER_TABS.indexOf(tab)
return SESSION_PICKER_TABS[(index + 1) % SESSION_PICKER_TABS.length]
}
interface SessionPickerDialogProps {
open: boolean
@@ -53,6 +72,7 @@ interface SessionPickerRow {
key: string
session: Session
repo: Repo
updatedAt?: number
}
interface SessionPickerSection {
@@ -97,10 +117,6 @@ function buildSections(
return sections
}
function optionId(baseId: string, index: number): string {
return `${baseId}-option-${index}`
}
function stripTrailingSlashes(value: string): string {
return value.replace(/\/+$/, '')
}
@@ -153,11 +169,7 @@ function SessionPickerGutter({ sessionID, isActive }: { sessionID: string; isAct
const status = useSessionStatusForSession(sessionID)
if (status.type !== 'idle') {
return (
<SessionStatusIndicator
sessionID={sessionID}
size="sm"
className="[&>div]:gap-0 [&>div>div]:h-1.5 [&>div>div]:w-px"
/>
<SessionStatusIndicator sessionID={sessionID} size="sm" />
)
}
if (isActive) {
@@ -251,7 +263,7 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
>
{showRepo && <span className="max-w-32 truncate">{getRepoDisplayName(row.repo)}</span>}
{!showRepo && label && <span className="max-w-32 truncate">{label}</span>}
<span>{formatShortRelativeTime(new Date(row.session.time.updated))}</span>
<span>{formatShortRelativeTime(new Date(row.updatedAt ?? row.session.time.updated))}</span>
</span>
</div>
<div className="flex shrink-0 items-center pr-1">
@@ -283,6 +295,231 @@ const SessionPickerRowItem = memo(function SessionPickerRowItem({
)
})
interface SessionPickerRowActionsOptions {
directories: string[]
activeSessionID?: string
onSelectSession: (session: Session, repo: Repo) => void
onDeleteActiveSession: () => void
}
interface SessionPickerRowActions {
pinnedKeys: ReadonlySet<string>
pendingDeleteKey: string | null
clearPendingDelete: () => void
openRow: (row: SessionPickerRow | undefined) => void
deleteRow: (row: SessionPickerRow | undefined) => void
handleTogglePin: (row: SessionPickerRow) => void
handleRequestDelete: (session: Session) => void
deleteDialogProps: {
open: boolean
onOpenChange: (open: boolean) => void
onConfirm: () => void
onCancel: () => void
isDeleting: boolean
}
}
function useSessionPickerRowActions({
directories,
activeSessionID,
onSelectSession,
onDeleteActiveSession,
}: SessionPickerRowActionsOptions): SessionPickerRowActions {
const { data: sessionPins } = useSessionPins()
const togglePin = useToggleSessionPin()
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
const deleteSession = useDeleteSession(directories)
const [sessionToDelete, setSessionToDelete] = useState<Session | null>(null)
const [pendingDeleteKey, setPendingDeleteKey] = useState<string | null>(null)
const clearPendingDelete = useCallback(() => {
setPendingDeleteKey(null)
}, [])
const openRow = useCallback(
(row: SessionPickerRow | undefined) => {
if (!row) return
onSelectSession(row.session, row.repo)
},
[onSelectSession],
)
const performDelete = useCallback(
(session: Session) => {
if (session.id === activeSessionID) onDeleteActiveSession()
return deleteSession
.mutateAsync({ id: session.id, directory: session.location.directory })
.catch(() => undefined)
},
[deleteSession, activeSessionID, onDeleteActiveSession],
)
const deleteRow = useCallback(
(row: SessionPickerRow | undefined) => {
if (!row) return
if (pendingDeleteKey !== row.key) {
setPendingDeleteKey(row.key)
return
}
void performDelete(row.session).finally(() => {
setPendingDeleteKey(null)
})
},
[pendingDeleteKey, performDelete],
)
const handleTogglePin = useCallback(
(row: SessionPickerRow) => {
togglePin.mutate({
sessionId: row.session.id,
directory: row.session.location.directory,
pinned: !pinnedKeys.has(row.key),
})
},
[togglePin, pinnedKeys],
)
const handleRequestDelete = useCallback((session: Session) => {
setSessionToDelete(session)
}, [])
const confirmDelete = useCallback(() => {
if (!sessionToDelete) return
void performDelete(sessionToDelete).finally(() => {
setSessionToDelete(null)
})
}, [sessionToDelete, performDelete])
const deleteDialogProps = useMemo(
() => ({
open: sessionToDelete !== null,
onOpenChange: (nextOpen: boolean) => {
if (!nextOpen) setSessionToDelete(null)
},
onConfirm: () => {
void confirmDelete()
},
onCancel: () => setSessionToDelete(null),
isDeleting: deleteSession.isPending,
}),
[sessionToDelete, confirmDelete, deleteSession.isPending],
)
return {
pinnedKeys,
pendingDeleteKey,
clearPendingDelete,
openRow,
deleteRow,
handleTogglePin,
handleRequestDelete,
deleteDialogProps,
}
}
interface SessionPickerListProps {
listId: string
optionBaseId: string
ariaLabel: string
sections: SessionPickerSection[]
rows: SessionPickerRow[]
rowIndexByKey: ReadonlyMap<string, number>
cursorIndex: number
activeSessionID?: string
pinnedKeys: ReadonlySet<string>
pendingDeleteKey: string | null
showRepo: boolean
labelFor?: (row: SessionPickerRow) => string | undefined
emptyState: React.ReactNode
onOpenRow: (row: SessionPickerRow) => void
onHoverRow: (index: number) => void
onTogglePin: (row: SessionPickerRow) => void
onRequestDelete: (session: Session) => void
registerRef: (key: string, node: HTMLDivElement | null) => void
listRef?: React.RefObject<HTMLDivElement | null>
onScroll?: (event: React.UIEvent<HTMLDivElement>) => void
children?: React.ReactNode
}
function SessionPickerList({
listId,
optionBaseId,
ariaLabel,
sections,
rows,
rowIndexByKey,
cursorIndex,
activeSessionID,
pinnedKeys,
pendingDeleteKey,
showRepo,
labelFor,
emptyState,
onOpenRow,
onHoverRow,
onTogglePin,
onRequestDelete,
registerRef,
listRef,
onScroll,
children,
}: SessionPickerListProps) {
return (
<div
ref={listRef}
role="listbox"
id={listId}
aria-label={ariaLabel}
onScroll={onScroll}
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
>
{rows.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">{emptyState}</div>
) : (
<>
{sections.map((section) => (
<div
key={section.id}
role="group"
aria-labelledby={`${optionBaseId}-heading-${section.id}`}
>
<div
id={`${optionBaseId}-heading-${section.id}`}
className="pl-8 pr-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground"
>
{section.heading}
</div>
{section.rows.map((row) => {
const index = rowIndexByKey.get(row.key) ?? -1
return (
<SessionPickerRowItem
key={row.key}
row={row}
index={index}
optionId={optionId(optionBaseId, index)}
isCursor={index === cursorIndex}
isActive={row.session.id === activeSessionID}
isPinned={pinnedKeys.has(row.key)}
isPendingDelete={pendingDeleteKey === row.key}
showRepo={showRepo}
label={labelFor?.(row)}
onOpen={onOpenRow}
onHover={onHoverRow}
onTogglePin={onTogglePin}
onRequestDelete={onRequestDelete}
registerRef={registerRef}
/>
)
})}
</div>
))}
{children}
</>
)}
</div>
)
}
interface SessionPickerContentProps {
open: boolean
currentRepo: Repo | undefined
@@ -307,7 +544,6 @@ function SessionPickerContent({
const [allProjects, toggleAllProjects] = usePersistentBoolean(ALL_PROJECTS_STORAGE_KEY, false)
const { repos } = useNavigableRepos()
const listRef = useRef<HTMLDivElement>(null)
const rowRefs = useRef(new Map<string, HTMLDivElement>())
const listId = useId()
const optionBaseId = useId()
@@ -364,154 +600,65 @@ function SessionPickerContent({
[repoByDirectory, currentRepo],
)
const { data: sessionPins } = useSessionPins()
const togglePin = useToggleSessionPin()
const pinnedKeys = useMemo(() => buildPinnedSessionKeys(sessionPins ?? []), [sessionPins])
const deleteSession = useDeleteSession(directories)
const [cursorKey, setCursorKey] = useState<string | null>(null)
const [pendingDeleteKey, setPendingDeleteKey] = useState<string | null>(null)
const [sessionToDelete, setSessionToDelete] = useState<Session | null>(null)
const {
pinnedKeys,
pendingDeleteKey,
clearPendingDelete,
openRow,
deleteRow,
handleTogglePin,
handleRequestDelete,
deleteDialogProps,
} = useSessionPickerRowActions({
directories,
activeSessionID,
onSelectSession,
onDeleteActiveSession,
})
const sections = useMemo(
() => buildSections(filteredSessions, pinnedKeys, getSessionKey, resolveRepo),
[filteredSessions, pinnedKeys, resolveRepo],
)
const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
const rowIndexByKey = useMemo(
() => new Map(rows.map((row, index) => [row.key, index])),
[rows],
)
const activeRow = useMemo(
() => rows.find((row) => row.session.id === activeSessionID),
[rows, activeSessionID],
)
const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null
const cursorIndex = useMemo(() => {
if (cursorKey) {
const index = rowIndexByKey.get(cursorKey)
if (index !== undefined) return index
}
return defaultCursorKey ? rowIndexByKey.get(defaultCursorKey) ?? -1 : -1
}, [cursorKey, rowIndexByKey, defaultCursorKey])
const cursorRow = cursorIndex >= 0 ? rows[cursorIndex] : undefined
useEffect(() => {
setCursorKey(null)
setPendingDeleteKey(null)
}, [trimmedQuery, allProjects])
const setRowRef = useCallback((key: string, node: HTMLDivElement | null) => {
if (node) rowRefs.current.set(key, node)
else rowRefs.current.delete(key)
}, [])
useEffect(() => {
if (!cursorRow) return
const node = rowRefs.current.get(cursorRow.key)
if (node && typeof node.scrollIntoView === 'function') {
node.scrollIntoView({ block: 'nearest' })
}
}, [cursorRow])
const {
rowIndexByKey,
cursorIndex,
cursorRow,
registerRef,
moveCursor: moveCursorRaw,
resetCursor,
} = usePickerCursor(rows, defaultCursorKey)
const moveCursor = useCallback(
(index: number) => {
const row = rows[index]
if (!row) return
setCursorKey(row.key)
setPendingDeleteKey(null)
clearPendingDelete()
moveCursorRaw(index)
},
[rows],
[clearPendingDelete, moveCursorRaw],
)
const openRow = useCallback(
(row: SessionPickerRow | undefined) => {
if (!row) return
onSelectSession(row.session, row.repo)
},
[onSelectSession],
)
useEffect(() => {
resetCursor()
clearPendingDelete()
}, [trimmedQuery, allProjects, resetCursor, clearPendingDelete])
const performDelete = useCallback(
(session: Session) => {
if (session.id === activeSessionID) onDeleteActiveSession()
return deleteSession
.mutateAsync({ id: session.id, directory: session.location.directory })
.catch(() => undefined)
},
[deleteSession, activeSessionID, onDeleteActiveSession],
)
const deleteRow = useCallback(
(row: SessionPickerRow | undefined) => {
if (!row) return
if (pendingDeleteKey !== row.key) {
setPendingDeleteKey(row.key)
return
}
void performDelete(row.session).finally(() => {
setPendingDeleteKey(null)
})
},
[pendingDeleteKey, performDelete],
)
const handleSearchKeyDown = useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing) return
if (event.metaKey || event.altKey) return
const moveBy = (delta: number, wrap: boolean) => {
if (rows.length === 0) return
const base = cursorIndex < 0 ? (delta > 0 ? -1 : 0) : cursorIndex
const raw = base + delta
const next = wrap ? ((raw % rows.length) + rows.length) % rows.length : Math.max(0, Math.min(rows.length - 1, raw))
moveCursor(next)
}
const key = event.key
const ctrlKey = event.key.toLowerCase()
if (key === 'ArrowDown' || (event.ctrlKey && ctrlKey === 'n')) {
event.preventDefault()
moveBy(1, true)
return
}
if (key === 'ArrowUp' || (event.ctrlKey && ctrlKey === 'p')) {
event.preventDefault()
moveBy(-1, true)
return
}
if (key === 'PageDown') {
event.preventDefault()
moveBy(PAGE_STEP, false)
return
}
if (key === 'PageUp') {
event.preventDefault()
moveBy(-PAGE_STEP, false)
return
}
if (key === 'Enter') {
if (!cursorRow) return
event.preventDefault()
openRow(cursorRow)
return
}
if (event.ctrlKey && ctrlKey === 'a') {
event.preventDefault()
toggleAllProjects()
return
}
if (event.ctrlKey && ctrlKey === 'd') {
if (!cursorRow) return
event.preventDefault()
deleteRow(cursorRow)
}
},
[cursorIndex, rows, moveCursor, cursorRow, openRow, toggleAllProjects, deleteRow],
)
const handleSearchKeyDown = usePickerKeyNav({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow: openRow,
onDeleteRow: deleteRow,
onToggleAllProjects: toggleAllProjects,
})
const handleListScroll = useCallback(
(event: React.UIEvent<HTMLDivElement>) => {
@@ -534,144 +681,93 @@ function SessionPickerContent({
}
}, [open, isLoading, rows, canFetchNextPage, fetchNextPage])
const handleTogglePin = useCallback(
(row: SessionPickerRow) => {
togglePin.mutate({
sessionId: row.session.id,
directory: row.session.location.directory,
pinned: !pinnedKeys.has(row.key),
})
},
[togglePin, pinnedKeys],
const labelFor = useCallback(
(row: SessionPickerRow) =>
allProjects ? undefined : sessionWorktreeLabel(row.session, location?.project.canonical),
[allProjects, location?.project.canonical],
)
const handleRequestDelete = useCallback((session: Session) => {
setSessionToDelete(session)
}, [])
const confirmDelete = useCallback(() => {
if (!sessionToDelete) return
void performDelete(sessionToDelete).finally(() => {
setSessionToDelete(null)
})
}, [sessionToDelete, performDelete])
return (
<>
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
ref={searchInputRef}
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
value={query}
onChange={(event) => setQuery(event.target.value)}
onKeyDown={handleSearchKeyDown}
placeholder="Search sessions..."
className="h-9 pl-9"
autoComplete="off"
name="session-picker-search"
/>
</div>
<Button
type="button"
variant="outline"
size="sm"
aria-pressed={allProjects}
onClick={toggleAllProjects}
className="h-9 shrink-0"
>
{allProjects ? 'All projects' : 'This project'}
{hasFinePointer && (
<kbd className="ml-1 rounded border border-border bg-muted px-1 text-[10px] text-muted-foreground">
Ctrl+A
</kbd>
)}
</Button>
</div>
<PickerSearchBar
inputRef={searchInputRef}
listId={listId}
open={open}
activeDescendantId={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
value={query}
onChange={setQuery}
onKeyDown={handleSearchKeyDown}
placeholder="Search sessions..."
name="session-picker-search"
trailing={
<Button
type="button"
variant="outline"
size="sm"
aria-pressed={allProjects}
onClick={toggleAllProjects}
className="h-9 shrink-0"
>
{allProjects ? 'All projects' : 'This project'}
{hasFinePointer && (
<kbd className="ml-1 rounded border border-border bg-muted px-1 text-[10px] text-muted-foreground">
Ctrl+A
</kbd>
)}
</Button>
}
/>
<div
ref={listRef}
role="listbox"
id={listId}
aria-label="Sessions"
<SessionPickerList
listRef={listRef}
listId={listId}
optionBaseId={optionBaseId}
ariaLabel="Sessions"
sections={sections}
rows={rows}
rowIndexByKey={rowIndexByKey}
cursorIndex={cursorIndex}
activeSessionID={activeSessionID}
pinnedKeys={pinnedKeys}
pendingDeleteKey={pendingDeleteKey}
showRepo={allProjects}
labelFor={labelFor}
emptyState={
isPickerLoading
? 'Loading sessions...'
: isSearchPending
? 'Searching sessions...'
: trimmedQuery
? 'No sessions found'
: 'No sessions yet'
}
onOpenRow={openRow}
onHoverRow={moveCursor}
onTogglePin={handleTogglePin}
onRequestDelete={handleRequestDelete}
registerRef={registerRef}
onScroll={handleListScroll}
className="mt-3 min-h-0 flex-1 overflow-y-auto rounded-md"
>
{rows.length === 0 ? (
<div className="p-4 text-sm text-muted-foreground">
{isPickerLoading
? 'Loading sessions...'
: isSearchPending
? 'Searching sessions...'
: trimmedQuery
? 'No sessions found'
: 'No sessions yet'}
{isFetchNextPageError && (
<div className="flex flex-col items-center gap-2 py-4">
<p className="text-sm text-muted-foreground">Failed to load more sessions</p>
<Button
variant="outline"
size="sm"
onClick={() => {
void fetchNextPage()
}}
disabled={isFetchingNextPage}
>
Retry
</Button>
</div>
) : (
<>
{sections.map((section) => (
<div
key={section.id}
role="group"
aria-labelledby={`${optionBaseId}-heading-${section.id}`}
>
<div
id={`${optionBaseId}-heading-${section.id}`}
className="pl-8 pr-2 pt-2 pb-1 text-xs font-semibold text-muted-foreground"
>
{section.heading}
</div>
{section.rows.map((row) => {
const index = rowIndexByKey.get(row.key) ?? -1
return (
<SessionPickerRowItem
key={row.key}
row={row}
index={index}
optionId={optionId(optionBaseId, index)}
isCursor={index === cursorIndex}
isActive={row.session.id === activeSessionID}
isPinned={pinnedKeys.has(row.key)}
isPendingDelete={pendingDeleteKey === row.key}
showRepo={allProjects}
label={allProjects ? undefined : sessionWorktreeLabel(row.session, location?.project.canonical)}
onOpen={openRow}
onHover={moveCursor}
onTogglePin={handleTogglePin}
onRequestDelete={handleRequestDelete}
registerRef={setRowRef}
/>
)
})}
</div>
))}
{isFetchNextPageError && (
<div className="flex flex-col items-center gap-2 py-4">
<p className="text-sm text-muted-foreground">Failed to load more sessions</p>
<Button
variant="outline"
size="sm"
onClick={() => {
void fetchNextPage()
}}
disabled={isFetchingNextPage}
>
Retry
</Button>
</div>
)}
{isFetchingNextPage && rows.length > 0 && (
<div className="py-4 text-center text-sm text-muted-foreground">Loading more sessions...</div>
)}
</>
)}
</div>
{isFetchingNextPage && rows.length > 0 && (
<div className="py-4 text-center text-sm text-muted-foreground">Loading more sessions...</div>
)}
</SessionPickerList>
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
↑↓ move · Enter open · Ctrl+D delete · Ctrl+A {allProjects ? 'this project' : 'all projects'}
@@ -679,17 +775,158 @@ function SessionPickerContent({
</div>
</div>
<DeleteSessionDialog
open={sessionToDelete !== null}
onOpenChange={(nextOpen) => {
if (!nextOpen) setSessionToDelete(null)
}}
onConfirm={() => {
void confirmDelete()
}}
onCancel={() => setSessionToDelete(null)}
isDeleting={deleteSession.isPending}
/>
<DeleteSessionDialog {...deleteDialogProps} />
</>
)
}
interface ActivePickerContentProps {
open: boolean
activeSessionID?: string
onSelectSession: (session: Session, repo: Repo) => void
onDeleteActiveSession: () => void
switchHint: string
searchInputRef: React.RefObject<HTMLInputElement | null>
}
function ActivePickerContent({
open,
activeSessionID,
onSelectSession,
onDeleteActiveSession,
switchHint,
searchInputRef,
}: ActivePickerContentProps) {
const windowMinutes = useActivityWindowMinutes()
const { groups, isLoading, isError } = useActiveWork(windowMinutes * MS_PER_MINUTE)
const listId = useId()
const optionBaseId = useId()
const [query, setQuery] = useState('')
const trimmedQuery = query.trim()
const sections = useMemo(() => {
const needle = trimmedQuery.toLowerCase()
return ACTIVE_WORK_GROUPS.flatMap((definition) => {
const rows: SessionPickerRow[] = []
for (const item of groups[definition.key]) {
if (needle && !(item.session.title ?? '').toLowerCase().includes(needle)) continue
rows.push({ key: item.key, session: item.session, repo: item.repo, updatedAt: item.updatedAt })
}
return rows.length > 0 ? [{ id: definition.key, heading: definition.heading, rows }] : []
})
}, [groups, trimmedQuery])
const rows = useMemo(() => sections.flatMap((section) => section.rows), [sections])
const activeRow = useMemo(
() => rows.find((row) => row.session.id === activeSessionID),
[rows, activeSessionID],
)
const defaultCursorKey = !trimmedQuery && activeRow ? activeRow.key : rows[0]?.key ?? null
const {
rowIndexByKey,
cursorIndex,
cursorRow,
registerRef,
moveCursor: moveCursorRaw,
resetCursor,
} = usePickerCursor(rows, defaultCursorKey)
const directories = useMemo(
() => Array.from(new Set(rows.map((row) => row.session.location.directory))),
[rows],
)
const {
pinnedKeys,
pendingDeleteKey,
clearPendingDelete,
openRow,
deleteRow,
handleTogglePin,
handleRequestDelete,
deleteDialogProps,
} = useSessionPickerRowActions({
directories,
activeSessionID,
onSelectSession,
onDeleteActiveSession,
})
const moveCursor = useCallback(
(index: number) => {
clearPendingDelete()
moveCursorRaw(index)
},
[clearPendingDelete, moveCursorRaw],
)
useEffect(() => {
resetCursor()
clearPendingDelete()
}, [trimmedQuery, resetCursor, clearPendingDelete])
const handleSearchKeyDown = usePickerKeyNav({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow: openRow,
onDeleteRow: deleteRow,
})
const emptyState = isLoading
? 'Loading sessions...'
: isError
? 'Failed to load active sessions'
: trimmedQuery
? 'No sessions found'
: formatActivityEmptyMessage(windowMinutes)
return (
<>
<div className="mt-4 flex min-h-0 flex-1 flex-col">
<PickerSearchBar
inputRef={searchInputRef}
listId={listId}
open={open}
activeDescendantId={cursorIndex >= 0 ? optionId(optionBaseId, cursorIndex) : undefined}
value={query}
onChange={setQuery}
onKeyDown={handleSearchKeyDown}
placeholder="Search sessions..."
name="active-picker-search"
/>
<SessionPickerList
listId={listId}
optionBaseId={optionBaseId}
ariaLabel="Active sessions"
sections={sections}
rows={rows}
rowIndexByKey={rowIndexByKey}
cursorIndex={cursorIndex}
activeSessionID={activeSessionID}
pinnedKeys={pinnedKeys}
pendingDeleteKey={pendingDeleteKey}
showRepo
emptyState={emptyState}
onOpenRow={openRow}
onHoverRow={moveCursor}
onTogglePin={handleTogglePin}
onRequestDelete={handleRequestDelete}
registerRef={registerRef}
/>
<div className="mt-2 shrink-0 px-4 text-xs text-muted-foreground pointer-coarse:hidden sm:px-0">
↑↓ move · Enter open · Ctrl+D delete
{switchHint ? ` · ${switchHint} sessions` : ''}
</div>
</div>
<DeleteSessionDialog {...deleteDialogProps} />
</>
)
}
@@ -704,6 +941,7 @@ export function SessionPickerDialog({
onSelectRepo,
}: SessionPickerDialogProps) {
const searchInputRef = useRef<HTMLInputElement>(null)
const activeSearchInputRef = useRef<HTMLInputElement>(null)
const projectSearchInputRef = useRef<HTMLInputElement>(null)
const focusSearchAfterSwitchRef = useRef(false)
const hasFinePointer = useMediaQuery(FINE_POINTER_MEDIA_QUERY)
@@ -729,7 +967,7 @@ export function SessionPickerDialog({
const toggleTab = useCallback(() => {
focusSearchAfterSwitchRef.current = true
setTab((current) => (current === 'sessions' ? 'projects' : 'sessions'))
setTab((current) => nextSessionPickerTab(current))
}, [])
useShortcutActions({ switchPickerTab: open ? toggleTab : undefined })
@@ -743,6 +981,7 @@ export function SessionPickerDialog({
const frame = requestAnimationFrame(() => {
focusSearchAfterSwitchRef.current = false
if (tab === 'projects') projectSearchInputRef.current?.focus()
else if (tab === 'active') activeSearchInputRef.current?.focus()
else searchInputRef.current?.focus()
})
return () => cancelAnimationFrame(frame)
@@ -769,12 +1008,26 @@ export function SessionPickerDialog({
className="flex min-h-0 w-full min-w-0 flex-1 flex-col gap-0"
>
<div className="shrink-0 px-4 pt-4 sm:px-0 sm:pt-6">
<DialogTitle className="sr-only">{tab === 'sessions' ? 'Sessions' : 'Projects'}</DialogTitle>
<DialogTitle className="sr-only">{SESSION_PICKER_TAB_LABELS[tab]}</DialogTitle>
<TabsList>
<TabsTrigger value="active">Active</TabsTrigger>
<TabsTrigger value="sessions">Sessions</TabsTrigger>
<TabsTrigger value="projects">Projects</TabsTrigger>
</TabsList>
</div>
<TabsContent
value="active"
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
>
<ActivePickerContent
open={open}
activeSessionID={activeSessionID}
onSelectSession={onSelectSession}
onDeleteActiveSession={onDeleteActiveSession}
switchHint={switchHint}
searchInputRef={activeSearchInputRef}
/>
</TabsContent>
<TabsContent
value="sessions"
className="mt-0 flex min-h-0 w-full min-w-0 flex-1 flex-col px-0"
@@ -0,0 +1,209 @@
/* eslint-disable react-refresh/only-export-components */
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { Search } from 'lucide-react'
import { Input } from '@/components/ui/input'
const PAGE_STEP = 10
export interface PickerRow {
key: string
}
export function optionId(baseId: string, index: number): string {
return `${baseId}-option-${index}`
}
export interface PickerCursorState<Row extends PickerRow> {
rowIndexByKey: Map<string, number>
cursorIndex: number
cursorRow: Row | undefined
registerRef: (key: string, node: HTMLDivElement | null) => void
moveCursor: (index: number) => void
resetCursor: () => void
}
export function usePickerCursor<Row extends PickerRow>(
rows: Row[],
defaultCursorKey: string | null,
): PickerCursorState<Row> {
const rowRefs = useRef(new Map<string, HTMLDivElement>())
const [cursorKey, setCursorKey] = useState<string | null>(null)
const rowIndexByKey = useMemo(
() => new Map(rows.map((row, index) => [row.key, index])),
[rows],
)
const cursorIndex = useMemo(() => {
if (cursorKey) {
const index = rowIndexByKey.get(cursorKey)
if (index !== undefined) return index
}
return defaultCursorKey ? rowIndexByKey.get(defaultCursorKey) ?? -1 : -1
}, [cursorKey, rowIndexByKey, defaultCursorKey])
const cursorRow = cursorIndex >= 0 ? rows[cursorIndex] : undefined
const registerRef = useCallback((key: string, node: HTMLDivElement | null) => {
if (node) rowRefs.current.set(key, node)
else rowRefs.current.delete(key)
}, [])
useEffect(() => {
if (!cursorRow) return
const node = rowRefs.current.get(cursorRow.key)
if (node && typeof node.scrollIntoView === 'function') {
node.scrollIntoView({ block: 'nearest' })
}
}, [cursorRow])
const moveCursor = useCallback(
(index: number) => {
const row = rows[index]
if (!row) return
setCursorKey(row.key)
},
[rows],
)
const resetCursor = useCallback(() => {
setCursorKey(null)
}, [])
return {
rowIndexByKey,
cursorIndex,
cursorRow,
registerRef,
moveCursor,
resetCursor,
}
}
export interface PickerKeyNavOptions<Row extends PickerRow> {
rows: Row[]
cursorIndex: number
cursorRow: Row | undefined
moveCursor: (index: number) => void
onOpenRow: (row: Row) => void
onDeleteRow?: (row: Row) => void
onToggleAllProjects?: () => void
}
export function usePickerKeyNav<Row extends PickerRow>({
rows,
cursorIndex,
cursorRow,
moveCursor,
onOpenRow,
onDeleteRow,
onToggleAllProjects,
}: PickerKeyNavOptions<Row>): (event: React.KeyboardEvent<HTMLInputElement>) => void {
return useCallback(
(event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.nativeEvent.isComposing) return
if (event.metaKey || event.altKey) return
const moveBy = (delta: number, wrap: boolean) => {
if (rows.length === 0) return
const base = cursorIndex < 0 ? (delta > 0 ? -1 : 0) : cursorIndex
const raw = base + delta
const next = wrap
? ((raw % rows.length) + rows.length) % rows.length
: Math.max(0, Math.min(rows.length - 1, raw))
moveCursor(next)
}
const key = event.key
const ctrlKey = event.key.toLowerCase()
if (key === 'ArrowDown' || (event.ctrlKey && ctrlKey === 'n')) {
event.preventDefault()
moveBy(1, true)
return
}
if (key === 'ArrowUp' || (event.ctrlKey && ctrlKey === 'p')) {
event.preventDefault()
moveBy(-1, true)
return
}
if (key === 'PageDown') {
event.preventDefault()
moveBy(PAGE_STEP, false)
return
}
if (key === 'PageUp') {
event.preventDefault()
moveBy(-PAGE_STEP, false)
return
}
if (key === 'Enter') {
if (!cursorRow) return
event.preventDefault()
onOpenRow(cursorRow)
return
}
if (onToggleAllProjects && event.ctrlKey && ctrlKey === 'a') {
event.preventDefault()
onToggleAllProjects()
return
}
if (onDeleteRow && event.ctrlKey && ctrlKey === 'd') {
if (!cursorRow) return
event.preventDefault()
onDeleteRow(cursorRow)
}
},
[rows, cursorIndex, cursorRow, moveCursor, onOpenRow, onDeleteRow, onToggleAllProjects],
)
}
export interface PickerSearchBarProps {
inputRef: React.RefObject<HTMLInputElement | null>
listId: string
open: boolean
activeDescendantId: string | undefined
value: string
onChange: (value: string) => void
onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void
placeholder: string
name: string
trailing?: React.ReactNode
}
export function PickerSearchBar({
inputRef,
listId,
open,
activeDescendantId,
value,
onChange,
onKeyDown,
placeholder,
name,
trailing,
}: PickerSearchBarProps) {
return (
<div className="flex shrink-0 items-center gap-2 px-4 sm:px-0">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input
ref={inputRef}
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={activeDescendantId}
value={value}
onChange={(event) => onChange(event.target.value)}
onKeyDown={onKeyDown}
placeholder={placeholder}
className="h-9 pl-9"
autoComplete="off"
name={name}
/>
</div>
{trailing}
</div>
)
}