mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat(sessions): type-to-filter and keyboard navigation in the sessions dialog
This commit is contained in:
1 parent
e89b782fef
commit
f13463f82a
7 files changed
+549
-54
No files matched your search
@@ -5,7 +5,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import type { ReactNode } from 'react'
|
||||
import { SessionList } from './SessionList'
|
||||
|
||||
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, isFetchNextPageErrorRef, useRealSessionsHookRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
|
||||
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, isFetchNextPageErrorRef, isLoadingRef, isPlaceholderDataRef, useRealSessionsHookRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
|
||||
createSessionMock: vi.fn(),
|
||||
deleteSessionMock: vi.fn(),
|
||||
sessionsData: [] as Array<{ id: string; title: string; location: { directory: string }; parentID?: string; time: { updated: number } }>,
|
||||
@@ -14,8 +14,10 @@ const { createSessionMock, deleteSessionMock, sessionsData, createSessionState,
|
||||
hasNextPageRef: { current: false },
|
||||
isFetchingNextPageRef: { current: false },
|
||||
isFetchNextPageErrorRef: { current: false },
|
||||
isLoadingRef: { current: false },
|
||||
isPlaceholderDataRef: { current: false },
|
||||
useRealSessionsHookRef: { current: false },
|
||||
lastSessionsHookArgs: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number } } | undefined },
|
||||
lastSessionsHookArgs: { current: undefined as { directories: string[]; options?: { search?: string; limit?: number; keepPreviousResults?: boolean } } | undefined },
|
||||
sessionPinsData: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
|
||||
togglePinMock: vi.fn(),
|
||||
}))
|
||||
@@ -24,15 +26,19 @@ vi.mock('@/hooks/useOpenCode', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/hooks/useOpenCode')>()
|
||||
return {
|
||||
...actual,
|
||||
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number }) => {
|
||||
useSessionsAcrossDirectories: (directories: string[], options?: { search?: string; limit?: number; keepPreviousResults?: boolean }) => {
|
||||
if (useRealSessionsHookRef.current) {
|
||||
return actual.useSessionsAcrossDirectories(directories, options)
|
||||
}
|
||||
lastSessionsHookArgs.current = { directories, options }
|
||||
const data = options?.search ? [] : sessionsData
|
||||
const search = options?.search?.toLowerCase() ?? ''
|
||||
const data = search
|
||||
? sessionsData.filter((session) => session.title.toLowerCase().includes(search))
|
||||
: sessionsData
|
||||
return {
|
||||
data,
|
||||
isLoading: false,
|
||||
isLoading: isLoadingRef.current,
|
||||
isPlaceholderData: isPlaceholderDataRef.current,
|
||||
fetchNextPage: fetchNextPageMock,
|
||||
hasNextPage: hasNextPageRef.current,
|
||||
isFetchingNextPage: isFetchingNextPageRef.current,
|
||||
@@ -67,6 +73,8 @@ describe('SessionList', () => {
|
||||
hasNextPageRef.current = false
|
||||
isFetchingNextPageRef.current = false
|
||||
isFetchNextPageErrorRef.current = false
|
||||
isLoadingRef.current = false
|
||||
isPlaceholderDataRef.current = false
|
||||
useRealSessionsHookRef.current = false
|
||||
lastSessionsHookArgs.current = undefined
|
||||
sessionPinsData.splice(0, sessionPinsData.length)
|
||||
@@ -551,4 +559,257 @@ describe('SessionList', () => {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('filters rows by title immediately and keeps the search input focused', async () => {
|
||||
const user = userEvent.setup()
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_alpha', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 2 } },
|
||||
{ id: 'ses_beta', title: 'beta task', location: { directory: '/w/a' }, time: { updated: 1 } },
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search sessions...')
|
||||
await user.click(searchInput)
|
||||
await user.type(searchInput, 'alpha')
|
||||
|
||||
expect(screen.getByText('alpha task')).toBeTruthy()
|
||||
expect(screen.queryByText('beta task')).toBeNull()
|
||||
expect(searchInput).toHaveFocus()
|
||||
})
|
||||
|
||||
it('highlights the active session by default and the first match after typing', async () => {
|
||||
const user = userEvent.setup()
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_active', title: 'active task', location: { directory: '/w/a' }, time: { updated: 2 } },
|
||||
{ id: 'ses_other', title: 'other task', location: { directory: '/w/a' }, time: { updated: 1 } },
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
activeSessionID="ses_active"
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByRole('option', { selected: true }).textContent).toContain('active task')
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Search sessions...'), 'other')
|
||||
|
||||
expect(screen.getByRole('option', { selected: true }).textContent).toContain('other task')
|
||||
})
|
||||
|
||||
it('navigates with arrows and Ctrl+N/Ctrl+P, wrapping around, and selects with Enter', () => {
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_1', title: 'one', location: { directory: '/w/a' }, time: { updated: 3 } },
|
||||
{ id: 'ses_2', title: 'two', location: { directory: '/w/a' }, time: { updated: 2 } },
|
||||
{ id: 'ses_3', title: 'three', location: { directory: '/w/a' }, time: { updated: 1 } },
|
||||
)
|
||||
const onSelectSession = vi.fn()
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={onSelectSession}
|
||||
/>,
|
||||
)
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search sessions...')
|
||||
const highlightedTitle = () => screen.getByRole('option', { selected: true }).textContent ?? ''
|
||||
|
||||
expect(highlightedTitle()).toContain('one')
|
||||
|
||||
fireEvent.keyDown(searchInput, { key: 'ArrowDown' })
|
||||
expect(highlightedTitle()).toContain('two')
|
||||
|
||||
fireEvent.keyDown(searchInput, { key: 'ArrowUp' })
|
||||
expect(highlightedTitle()).toContain('one')
|
||||
|
||||
fireEvent.keyDown(searchInput, { key: 'ArrowUp' })
|
||||
expect(highlightedTitle()).toContain('three')
|
||||
|
||||
fireEvent.keyDown(searchInput, { key: 'n', ctrlKey: true })
|
||||
expect(highlightedTitle()).toContain('one')
|
||||
|
||||
fireEvent.keyDown(searchInput, { key: 'p', ctrlKey: true })
|
||||
expect(highlightedTitle()).toContain('three')
|
||||
|
||||
fireEvent.keyDown(searchInput, { key: 'Enter' })
|
||||
expect(onSelectSession).toHaveBeenCalledWith('ses_3')
|
||||
})
|
||||
|
||||
it('clamps PageDown and PageUp navigation to the ends of the list', () => {
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
...Array.from({ length: 15 }, (_, index) => ({
|
||||
id: `ses_${index}`,
|
||||
title: `session ${index}`,
|
||||
location: { directory: '/w/a' },
|
||||
time: { updated: 15 - index },
|
||||
})),
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
const searchInput = screen.getByPlaceholderText('Search sessions...')
|
||||
const highlightedTitle = () => screen.getByRole('option', { selected: true }).textContent ?? ''
|
||||
|
||||
expect(highlightedTitle()).toContain('session 0')
|
||||
|
||||
fireEvent.keyDown(searchInput, { key: 'PageDown' })
|
||||
expect(highlightedTitle()).toContain('session 10')
|
||||
|
||||
fireEvent.keyDown(searchInput, { key: 'PageDown' })
|
||||
expect(highlightedTitle()).toContain('session 14')
|
||||
|
||||
fireEvent.keyDown(searchInput, { key: 'PageUp' })
|
||||
expect(highlightedTitle()).toContain('session 4')
|
||||
|
||||
fireEvent.keyDown(searchInput, { key: 'PageUp' })
|
||||
expect(highlightedTitle()).toContain('session 0')
|
||||
})
|
||||
|
||||
it('keeps the search input rendered while the first page is loading', () => {
|
||||
isLoadingRef.current = true
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByPlaceholderText('Search sessions...')).toBeTruthy()
|
||||
expect(screen.getByText('Loading sessions...')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('keeps previous rows and the search input mounted while a new search query is fetching', async () => {
|
||||
const fetchMock = vi.fn()
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
|
||||
const initialItems = [
|
||||
{ id: 'ses_a', projectID: 'proj_1', title: 'alpha session', time: { created: 1, updated: 1 }, location: { directory: '/w/a' } },
|
||||
{ id: 'ses_b', projectID: 'proj_1', title: 'beta session', time: { created: 2, updated: 2 }, location: { directory: '/w/a' } },
|
||||
]
|
||||
|
||||
let resolveSearch: ((response: Response) => void) | undefined
|
||||
fetchMock.mockImplementation((input: RequestInfo | URL) => {
|
||||
const url = String(input)
|
||||
if (url.includes('search=beta')) {
|
||||
return new Promise<Response>((resolve) => {
|
||||
resolveSearch = resolve
|
||||
})
|
||||
}
|
||||
return Promise.resolve(new Response(JSON.stringify({ data: initialItems, cursor: {} }), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}))
|
||||
})
|
||||
|
||||
useRealSessionsHookRef.current = true
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
|
||||
try {
|
||||
render(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
{ wrapper },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('beta session')).toBeTruthy()
|
||||
})
|
||||
|
||||
await userEvent.setup().type(screen.getByPlaceholderText('Search sessions...'), 'beta')
|
||||
|
||||
await waitFor(() => {
|
||||
expect(resolveSearch).toBeDefined()
|
||||
})
|
||||
|
||||
expect(screen.getByText('beta session')).toBeTruthy()
|
||||
expect(screen.getByPlaceholderText('Search sessions...')).toBeTruthy()
|
||||
expect(screen.queryByText('Loading sessions...')).toBeNull()
|
||||
|
||||
resolveSearch?.(new Response(JSON.stringify({
|
||||
data: [{ id: 'ses_b', projectID: 'proj_1', title: 'beta session', time: { created: 2, updated: 2 }, location: { directory: '/w/a' } }],
|
||||
cursor: {},
|
||||
}), { status: 200, headers: { 'Content-Type': 'application/json' } }))
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.queryByText('alpha session')).toBeNull()
|
||||
})
|
||||
expect(screen.getByText('beta session')).toBeTruthy()
|
||||
} finally {
|
||||
queryClient.clear()
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('shows the searching state while a search is pending and the empty state once it settles', async () => {
|
||||
const user = userEvent.setup()
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_a', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 1 } },
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Search sessions...'), 'zzz')
|
||||
|
||||
expect(screen.getByText('Searching sessions...')).toBeTruthy()
|
||||
expect(screen.queryByText('No sessions found')).toBeNull()
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('No sessions found')).toBeTruthy()
|
||||
})
|
||||
expect(screen.queryByText('Searching sessions...')).toBeNull()
|
||||
})
|
||||
|
||||
it('does not paginate while placeholder data is shown', async () => {
|
||||
const user = userEvent.setup()
|
||||
isPlaceholderDataRef.current = true
|
||||
hasNextPageRef.current = true
|
||||
sessionsData.splice(0, sessionsData.length,
|
||||
{ id: 'ses_a', title: 'alpha task', location: { directory: '/w/a' }, time: { updated: 1 } },
|
||||
)
|
||||
|
||||
render(
|
||||
<SessionList
|
||||
directories={['/w/a']}
|
||||
onSelectSession={vi.fn()}
|
||||
/>,
|
||||
)
|
||||
|
||||
const scrollContainer = screen.getByRole('region', { name: 'Sessions' })
|
||||
Object.defineProperty(scrollContainer, 'scrollHeight', { value: 1000, configurable: true })
|
||||
Object.defineProperty(scrollContainer, 'clientHeight', { value: 500, configurable: true })
|
||||
Object.defineProperty(scrollContainer, 'scrollTop', { value: 300, configurable: true })
|
||||
|
||||
await user.type(screen.getByPlaceholderText('Search sessions...'), 'zzz')
|
||||
fireEvent.scroll(scrollContainer)
|
||||
|
||||
expect(screen.getByText('Searching sessions...')).toBeTruthy()
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 20))
|
||||
expect(fetchNextPageMock).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useState, useMemo, useEffect, useRef, type ReactNode } from "react";
|
||||
import { useCallback, useState, useMemo, useEffect, useRef, useId, type ReactNode } from "react";
|
||||
import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
|
||||
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
|
||||
import type { Session } from "@/api/types";
|
||||
@@ -11,6 +11,7 @@ import { Card } from "@/components/ui/card";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Search, Trash2, Pencil, X } from "lucide-react";
|
||||
import { useDebouncedValue } from "@/hooks/useDebouncedValue";
|
||||
|
||||
interface SessionListProps {
|
||||
directory?: string;
|
||||
@@ -50,7 +51,10 @@ export const SessionList = ({
|
||||
buildSessionKey(session.location.directory, session.id),
|
||||
[]);
|
||||
const [searchQuery, setSearchQuery] = useState("");
|
||||
const { data: sessions, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage, isFetchNextPageError } = useSessionsAcrossDirectories(directoriesList, { search: searchQuery, limit: 25 });
|
||||
const trimmedSearchQuery = searchQuery.trim();
|
||||
const debouncedSearchQuery = useDebouncedValue(trimmedSearchQuery, 150);
|
||||
const search = trimmedSearchQuery ? debouncedSearchQuery : '';
|
||||
const { data: sessions, isLoading, isPlaceholderData, fetchNextPage, hasNextPage, isFetchingNextPage, isFetchNextPageError } = useSessionsAcrossDirectories(directoriesList, { search, limit: 25, keepPreviousResults: true });
|
||||
const deleteSession = useDeleteSession(directoriesList);
|
||||
const createSession = useCreateSession(sessionCreateDirectory, (newSession) => {
|
||||
onSelectSession(newSession.id);
|
||||
@@ -67,16 +71,52 @@ export const SessionList = ({
|
||||
const [manageMode, setManageMode] = useState(false);
|
||||
const sessionListRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const filteredSessions = useMemo(
|
||||
const rootSessions = useMemo(
|
||||
() => selectRootSessions(sessions ?? [], { directories: directorySet, keyFn: getSessionSelectionKey }),
|
||||
[sessions, directorySet, getSessionSelectionKey],
|
||||
);
|
||||
|
||||
const filteredSessions = useMemo(() => {
|
||||
if (!trimmedSearchQuery) return rootSessions;
|
||||
const needle = trimmedSearchQuery.toLowerCase();
|
||||
return rootSessions.filter((session) => (session.title ?? '').toLowerCase().includes(needle));
|
||||
}, [rootSessions, trimmedSearchQuery]);
|
||||
|
||||
const { pinned: pinnedSessions, today: todaySessions, older: olderSessions } = useMemo(
|
||||
() => partitionSessions(filteredSessions, pinnedKeys, getSessionSelectionKey),
|
||||
[filteredSessions, pinnedKeys, getSessionSelectionKey],
|
||||
);
|
||||
|
||||
const navSessions = useMemo(
|
||||
() => [...pinnedSessions, ...todaySessions, ...olderSessions],
|
||||
[pinnedSessions, todaySessions, olderSessions],
|
||||
);
|
||||
|
||||
const [highlightedKey, setHighlightedKey] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setHighlightedKey(null);
|
||||
}, [trimmedSearchQuery]);
|
||||
|
||||
const highlightedSession = useMemo(() => {
|
||||
if (navSessions.length === 0) return undefined;
|
||||
if (highlightedKey) {
|
||||
const stored = navSessions.find((session) => getSessionSelectionKey(session) === highlightedKey);
|
||||
if (stored) return stored;
|
||||
}
|
||||
if (!trimmedSearchQuery && activeSessionID) {
|
||||
const active = navSessions.find((session) => session.id === activeSessionID);
|
||||
if (active) return active;
|
||||
}
|
||||
return navSessions[0];
|
||||
}, [navSessions, highlightedKey, trimmedSearchQuery, activeSessionID, getSessionSelectionKey]);
|
||||
|
||||
const highlightedSessionKey = highlightedSession ? getSessionSelectionKey(highlightedSession) : null;
|
||||
const highlightedIndex = highlightedSession ? navSessions.indexOf(highlightedSession) : -1;
|
||||
const listboxId = useId();
|
||||
const keyboardNavigationEnabled = !renderSessions && !manageMode;
|
||||
const isSearchPending = trimmedSearchQuery !== search || isPlaceholderData;
|
||||
|
||||
const handleTogglePin = (session: Session) => {
|
||||
const directory = session.location.directory;
|
||||
const key = getSessionSelectionKey(session);
|
||||
@@ -89,10 +129,10 @@ export const SessionList = ({
|
||||
|
||||
const handleSessionsScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {
|
||||
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
|
||||
if (scrollHeight - scrollTop - clientHeight <= 240 && hasNextPage && !isFetchingNextPage && !isFetchNextPageError) {
|
||||
if (scrollHeight - scrollTop - clientHeight <= 240 && hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isPlaceholderData) {
|
||||
void fetchNextPage();
|
||||
}
|
||||
}, [hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]);
|
||||
}, [hasNextPage, isFetchingNextPage, isFetchNextPageError, isPlaceholderData, fetchNextPage]);
|
||||
|
||||
useEffect(() => {
|
||||
const sessionList = sessionListRef.current;
|
||||
@@ -101,6 +141,7 @@ export const SessionList = ({
|
||||
: filteredSessions.length === 0;
|
||||
if (
|
||||
!isLoading
|
||||
&& !isPlaceholderData
|
||||
&& isNearBottom
|
||||
&& hasNextPage
|
||||
&& !isFetchingNextPage
|
||||
@@ -108,44 +149,72 @@ export const SessionList = ({
|
||||
) {
|
||||
void fetchNextPage();
|
||||
}
|
||||
}, [isLoading, filteredSessions, hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]);
|
||||
}, [isLoading, isPlaceholderData, filteredSessions, hasNextPage, isFetchingNextPage, isFetchNextPageError, fetchNextPage]);
|
||||
|
||||
if (isLoading && !renderSessions) {
|
||||
return <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
|
||||
}
|
||||
useEffect(() => {
|
||||
if (!highlightedSessionKey) return;
|
||||
const list = sessionListRef.current;
|
||||
if (!list) return;
|
||||
const highlighted = list.querySelector<HTMLElement>('[data-highlighted="true"]');
|
||||
if (highlighted && typeof highlighted.scrollIntoView === 'function') {
|
||||
highlighted.scrollIntoView({ block: 'nearest' });
|
||||
}
|
||||
}, [highlightedSessionKey]);
|
||||
|
||||
if (!sessions || sessions.length === 0) {
|
||||
if (isFetchNextPageError) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-2 p-4 text-sm text-muted-foreground">
|
||||
<p>Failed to load sessions.</p>
|
||||
<Button variant="outline" size="sm" onClick={handleRetryNextPage} disabled={isFetchingNextPage}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
const handleSearchKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
|
||||
if (!keyboardNavigationEnabled) return;
|
||||
if (event.nativeEvent.isComposing) return;
|
||||
if (event.altKey || event.metaKey) return;
|
||||
|
||||
const selectIndex = (index: number) => {
|
||||
const session = navSessions[index];
|
||||
if (!session) return false;
|
||||
setHighlightedKey(getSessionSelectionKey(session));
|
||||
return true;
|
||||
};
|
||||
const moveBy = (delta: number) => {
|
||||
const count = navSessions.length;
|
||||
if (count === 0) return false;
|
||||
return selectIndex(((highlightedIndex + delta) % count + count) % count);
|
||||
};
|
||||
const moveClamped = (delta: number) => {
|
||||
const count = navSessions.length;
|
||||
if (count === 0) return false;
|
||||
return selectIndex(Math.min(Math.max(highlightedIndex + delta, 0), count - 1));
|
||||
};
|
||||
|
||||
if (event.ctrlKey) {
|
||||
if (event.key.toLowerCase() === 'n') {
|
||||
if (moveBy(1)) event.preventDefault();
|
||||
} else if (event.key.toLowerCase() === 'p') {
|
||||
if (moveBy(-1)) event.preventDefault();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if ((hasNextPage || isFetchingNextPage) && !renderSessions) {
|
||||
return <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
|
||||
|
||||
switch (event.key) {
|
||||
case 'ArrowDown':
|
||||
if (moveBy(1)) event.preventDefault();
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
if (moveBy(-1)) event.preventDefault();
|
||||
break;
|
||||
case 'PageDown':
|
||||
if (moveClamped(10)) event.preventDefault();
|
||||
break;
|
||||
case 'PageUp':
|
||||
if (moveClamped(-10)) event.preventDefault();
|
||||
break;
|
||||
case 'Enter':
|
||||
if (highlightedSession) {
|
||||
event.preventDefault();
|
||||
onSelectSession(highlightedSession.id);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
if (!searchQuery.trim() && !renderSessions) {
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
<Card
|
||||
className="p-6 cursor-pointer hover:bg-accent hover:border-border transition-all border-dashed"
|
||||
onClick={() => createSession.mutate({ agent: undefined })}
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center gap-2 text-center">
|
||||
<p className="font-medium">No sessions yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Click here to start a new session
|
||||
</p>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const getDeleteTarget = (session: Session): DeleteSessionTarget => ({
|
||||
id: session.id,
|
||||
@@ -211,7 +280,7 @@ export const SessionList = ({
|
||||
|
||||
const renderSessionCard = (session: (typeof filteredSessions)[number], isPinned: boolean) => {
|
||||
const key = getSessionSelectionKey(session);
|
||||
return (
|
||||
const card = (
|
||||
<SessionCard
|
||||
key={key}
|
||||
session={session}
|
||||
@@ -225,8 +294,56 @@ export const SessionList = ({
|
||||
onDelete={(e) => handleDelete(session, e)}
|
||||
/>
|
||||
);
|
||||
if (!keyboardNavigationEnabled) return card;
|
||||
const index = navSessions.indexOf(session);
|
||||
const isHighlighted = highlightedSession === session;
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
id={`${listboxId}-option-${index}`}
|
||||
role="option"
|
||||
aria-selected={isHighlighted}
|
||||
data-highlighted={isHighlighted ? 'true' : undefined}
|
||||
className={isHighlighted ? 'rounded-lg ring-2 ring-primary/60' : undefined}
|
||||
>
|
||||
{card}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
if (!isLoading && !isPlaceholderData && (!sessions || sessions.length === 0)) {
|
||||
if (isFetchNextPageError) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center gap-2 p-4 text-sm text-muted-foreground">
|
||||
<p>Failed to load sessions.</p>
|
||||
<Button variant="outline" size="sm" onClick={handleRetryNextPage} disabled={isFetchingNextPage}>
|
||||
Retry
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if ((hasNextPage || isFetchingNextPage) && !renderSessions) {
|
||||
return <div className="p-4 text-sm text-muted-foreground">Loading sessions...</div>;
|
||||
}
|
||||
if (!searchQuery.trim() && !renderSessions) {
|
||||
return (
|
||||
<div className="flex-1 overflow-y-auto overflow-x-hidden px-4 pt-4 pb-4 min-h-0 [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]">
|
||||
<Card
|
||||
className="p-6 cursor-pointer hover:bg-accent hover:border-border transition-all border-dashed"
|
||||
onClick={() => createSession.mutate({ agent: undefined })}
|
||||
>
|
||||
<div className="flex flex-col items-center justify-center gap-2 text-center">
|
||||
<p className="font-medium">No sessions yet</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Click here to start a new session
|
||||
</p>
|
||||
</div>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full min-h-0">
|
||||
<div className="px-4 pt-2 flex-shrink-0">
|
||||
@@ -266,9 +383,14 @@ export const SessionList = ({
|
||||
placeholder="Search sessions..."
|
||||
value={searchQuery}
|
||||
onChange={(e) => setSearchQuery(e.target.value)}
|
||||
onKeyDown={handleSearchKeyDown}
|
||||
className="pl-9 h-9"
|
||||
autoComplete="off"
|
||||
name="session-search"
|
||||
role={keyboardNavigationEnabled ? 'combobox' : undefined}
|
||||
aria-expanded={keyboardNavigationEnabled ? true : undefined}
|
||||
aria-controls={keyboardNavigationEnabled ? listboxId : undefined}
|
||||
aria-activedescendant={keyboardNavigationEnabled && highlightedIndex >= 0 ? `${listboxId}-option-${highlightedIndex}` : undefined}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
@@ -293,8 +415,14 @@ export const SessionList = ({
|
||||
aria-label="Sessions"
|
||||
onScroll={handleSessionsScroll}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
{renderSessions ? (
|
||||
<div
|
||||
id={keyboardNavigationEnabled ? listboxId : undefined}
|
||||
role={keyboardNavigationEnabled ? 'listbox' : undefined}
|
||||
className="flex flex-col gap-4"
|
||||
>
|
||||
{isLoading && !renderSessions ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-4">Loading sessions...</div>
|
||||
) : renderSessions ? (
|
||||
renderSessions({
|
||||
sessions: filteredSessions,
|
||||
searchQuery,
|
||||
@@ -302,7 +430,7 @@ export const SessionList = ({
|
||||
})
|
||||
) : filteredSessions.length === 0 && !isFetchingNextPage ? (
|
||||
<div className="text-sm text-muted-foreground text-center py-4">
|
||||
No sessions found
|
||||
{isSearchPending ? 'Searching sessions...' : 'No sessions found'}
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
@@ -331,7 +459,7 @@ export const SessionList = ({
|
||||
{olderSessions.map((session) => renderSessionCard(session, false))}
|
||||
</>
|
||||
)}
|
||||
{isFetchNextPageError && (
|
||||
{isFetchNextPageError && (sessions?.length ?? 0) > 0 && (
|
||||
<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={handleRetryNextPage} disabled={isFetchingNextPage}>
|
||||
@@ -339,7 +467,7 @@ export const SessionList = ({
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{isFetchingNextPage && (
|
||||
{isFetchingNextPage && (sessions?.length ?? 0) > 0 && (
|
||||
<div className="text-sm text-muted-foreground text-center py-4">
|
||||
Loading more sessions...
|
||||
</div>
|
||||
|
||||
@@ -154,6 +154,83 @@ describe('useSessionsAcrossDirectories', () => {
|
||||
expect(queryClient.getQueryState(listKey)?.isInvalidated).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('does not keep previous results across a search change unless requested', async () => {
|
||||
let resolveSearch: ((value: { items: SessionInfo[] }) => void) | undefined
|
||||
mocks.listSessionPage.mockImplementation(({ search }: { search?: string }) => {
|
||||
if (search === 'deploy') {
|
||||
return new Promise<{ items: SessionInfo[] }>((resolve) => { resolveSearch = resolve })
|
||||
}
|
||||
return Promise.resolve({ items: [sessionInfo('ses_a1', '/w/a')] })
|
||||
})
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const { result, rerender } = renderHook(
|
||||
(props: { search?: string }) => useSessionsAcrossDirectories(['/w/a'], { search: props.search }),
|
||||
{ wrapper: createWrapper(queryClient), initialProps: { search: undefined as string | undefined } },
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_a1'])
|
||||
})
|
||||
|
||||
rerender({ search: 'deploy' })
|
||||
|
||||
await waitFor(() => expect(resolveSearch).toBeDefined())
|
||||
|
||||
expect(result.current.isPlaceholderData).toBe(false)
|
||||
expect(result.current.isLoading).toBe(true)
|
||||
expect(result.current.data).toHaveLength(0)
|
||||
|
||||
await act(async () => {
|
||||
resolveSearch?.({ items: [sessionInfo('ses_b1', '/w/a')] })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_b1'])
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps previous results across a search change when requested', async () => {
|
||||
let resolveSearch: ((value: { items: SessionInfo[] }) => void) | undefined
|
||||
mocks.listSessionPage.mockImplementation(({ search }: { search?: string }) => {
|
||||
if (search === 'deploy') {
|
||||
return new Promise<{ items: SessionInfo[] }>((resolve) => { resolveSearch = resolve })
|
||||
}
|
||||
return Promise.resolve({ items: [sessionInfo('ses_a1', '/w/a')] })
|
||||
})
|
||||
|
||||
const queryClient = createQueryClient()
|
||||
const { result, rerender } = renderHook(
|
||||
(props: { search?: string; keepPreviousResults?: boolean }) =>
|
||||
useSessionsAcrossDirectories(['/w/a'], {
|
||||
search: props.search,
|
||||
keepPreviousResults: props.keepPreviousResults,
|
||||
}),
|
||||
{
|
||||
wrapper: createWrapper(queryClient),
|
||||
initialProps: { search: undefined as string | undefined, keepPreviousResults: true },
|
||||
},
|
||||
)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_a1'])
|
||||
})
|
||||
|
||||
rerender({ search: 'deploy', keepPreviousResults: true })
|
||||
|
||||
await waitFor(() => expect(result.current.isPlaceholderData).toBe(true))
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_a1'])
|
||||
|
||||
await act(async () => {
|
||||
resolveSearch?.({ items: [sessionInfo('ses_b1', '/w/a')] })
|
||||
})
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data.map((session) => session.id)).toEqual(['ses_b1'])
|
||||
})
|
||||
expect(result.current.isPlaceholderData).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('useSession', () => {
|
||||
|
||||
@@ -41,6 +41,7 @@ const EMPTY_SESSIONS: SessionInfo[] = []
|
||||
interface UseSessionsAcrossDirectoriesOptions {
|
||||
search?: string
|
||||
limit?: number
|
||||
keepPreviousResults?: boolean
|
||||
}
|
||||
|
||||
type SessionPageParam = Record<string, string>
|
||||
@@ -55,6 +56,7 @@ export const useSessionsAcrossDirectories = (
|
||||
);
|
||||
const normalizedSearch = options?.search?.trim() || undefined;
|
||||
const limit = options?.limit ?? SESSION_LIST_PAGE_SIZE;
|
||||
const keepPreviousResults = options?.keepPreviousResults ?? false;
|
||||
const directoryKey = uniqueDirectories.join('|');
|
||||
|
||||
const query = useInfiniteQuery({
|
||||
@@ -97,6 +99,10 @@ export const useSessionsAcrossDirectories = (
|
||||
return { items, cursors };
|
||||
},
|
||||
initialPageParam: undefined as SessionPageParam | undefined,
|
||||
placeholderData: keepPreviousResults
|
||||
? (previousData, previousQuery) =>
|
||||
previousQuery?.queryKey[2] === directoryKey ? previousData : undefined
|
||||
: undefined,
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (Object.keys(lastPage.cursors).length > 0) {
|
||||
return lastPage.cursors;
|
||||
@@ -117,6 +123,7 @@ export const useSessionsAcrossDirectories = (
|
||||
return {
|
||||
data,
|
||||
isLoading: query.isLoading,
|
||||
isPlaceholderData: query.isPlaceholderData,
|
||||
isError: query.isError,
|
||||
fetchNextPage: query.fetchNextPage,
|
||||
hasNextPage: query.hasNextPage,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, afterEach } from 'vitest'
|
||||
import { stubMatchMedia } from '@/test/test-utils'
|
||||
import { getFocusedElement, hasOpenOverlay, restoreOverlayFocus } from './overlayFocus'
|
||||
import { getFocusedElement, hasOpenOverlay, isFinePointer, restoreOverlayFocus } from './overlayFocus'
|
||||
import { PROMPT_INPUT_SELECTOR, isPromptInput, isTextEntryElement } from './domTargets'
|
||||
|
||||
function createElement<K extends keyof HTMLElementTagNameMap>(
|
||||
@@ -26,6 +26,16 @@ describe('getFocusedElement', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('isFinePointer', () => {
|
||||
it('reflects the fine pointer media query', () => {
|
||||
stubMatchMedia(true)
|
||||
expect(isFinePointer()).toBe(true)
|
||||
|
||||
stubMatchMedia(false)
|
||||
expect(isFinePointer()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('restoreOverlayFocus', () => {
|
||||
it('focuses the chat prompt on desktop when focus was on a button', () => {
|
||||
stubMatchMedia(true)
|
||||
|
||||
@@ -12,7 +12,10 @@ export function getFocusedElement(): HTMLElement | null {
|
||||
: null
|
||||
}
|
||||
|
||||
function isFinePointer(): boolean {
|
||||
/**
|
||||
* Reports whether the current device uses a fine pointer, such as a mouse or trackpad.
|
||||
*/
|
||||
export function isFinePointer(): boolean {
|
||||
return (
|
||||
typeof window !== 'undefined' &&
|
||||
typeof window.matchMedia === 'function' &&
|
||||
|
||||
@@ -10,6 +10,7 @@ import { SquareFill } from "@/components/ui/square-fill";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { SessionList } from "@/components/session/SessionList";
|
||||
import { getSessionListPath } from '@/lib/navigation'
|
||||
import { isFinePointer } from '@/lib/overlayFocus'
|
||||
import { FetchError } from '@/api/fetchWrapper'
|
||||
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
@@ -829,9 +830,17 @@ export function SessionDetail() {
|
||||
|
||||
{/* Sessions Dialog */}
|
||||
<Dialog open={sessionsDialogOpen} onOpenChange={setSessionsDialogOpen}>
|
||||
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||
<DialogContent
|
||||
className="max-w-4xl max-h-[80vh]"
|
||||
onOpenAutoFocus={(event) => {
|
||||
if (!isFinePointer()) {
|
||||
event.preventDefault();
|
||||
(event.currentTarget as HTMLElement).focus();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<DialogTitle>Sessions</DialogTitle>
|
||||
<div className="overflow-y-auto max-h-[60vh] mt-4">
|
||||
<div className="mt-4 flex h-[60vh] min-h-0 flex-col">
|
||||
{sessionDirectory && (
|
||||
<SessionList
|
||||
directory={repoDirectory}
|
||||
|
||||
Reference in new issue
Block a user