mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
87 lines
2.5 KiB
TypeScript
87 lines
2.5 KiB
TypeScript
import { useMemo, useState } from 'react'
|
|
import { useSessionsAcrossDirectories } from '@/hooks/useOpenCode'
|
|
import { useWalkthroughHelperSessionIds } from '@/hooks/useChangeWalkthrough'
|
|
import { useDebouncedValue } from '@/hooks/useDebouncedValue'
|
|
import { selectRootSessions } from '@/components/session/session-partition'
|
|
import { getSessionKey } from '@/lib/sessionKey'
|
|
|
|
const DEFAULT_LIMIT = 25
|
|
|
|
export interface UseSessionSearchOptions {
|
|
limit?: number
|
|
allDirectories?: boolean
|
|
project?: { id: string; subpath: string }
|
|
serverId?: string
|
|
initialQuery?: string
|
|
}
|
|
|
|
export function useSessionSearch(directories: string[], options: UseSessionSearchOptions = {}) {
|
|
const limit = options.limit ?? DEFAULT_LIMIT
|
|
const allDirectories = options.allDirectories ?? false
|
|
const project = options.project
|
|
const serverId = options.serverId
|
|
const [query, setQuery] = useState(options.initialQuery ?? '')
|
|
const trimmedQuery = query.trim()
|
|
const debouncedQuery = useDebouncedValue(trimmedQuery, 150)
|
|
const search = trimmedQuery ? debouncedQuery : ''
|
|
const {
|
|
data: sessions,
|
|
isLoading,
|
|
isPending,
|
|
isError,
|
|
isPlaceholderData,
|
|
fetchNextPage,
|
|
hasNextPage,
|
|
isFetchingNextPage,
|
|
isFetchNextPageError,
|
|
} = useSessionsAcrossDirectories(directories, {
|
|
search,
|
|
limit,
|
|
keepPreviousResults: true,
|
|
allDirectories,
|
|
project,
|
|
serverId,
|
|
})
|
|
|
|
const directorySet = useMemo(() => new Set(directories), [directories])
|
|
const helperSessionIds = useWalkthroughHelperSessionIds()
|
|
|
|
const rootSessions = useMemo(
|
|
() =>
|
|
selectRootSessions(sessions ?? [], {
|
|
directories: project ? undefined : directorySet,
|
|
keyFn: getSessionKey,
|
|
}).filter((session) => !helperSessionIds.has(session.id)),
|
|
[sessions, directorySet, project, helperSessionIds],
|
|
)
|
|
|
|
const filteredSessions = useMemo(() => {
|
|
if (!trimmedQuery) return rootSessions
|
|
const needle = trimmedQuery.toLowerCase()
|
|
return rootSessions.filter((session) => (session.title ?? '').toLowerCase().includes(needle))
|
|
}, [rootSessions, trimmedQuery])
|
|
|
|
const isSearchPending = trimmedQuery !== search || isPlaceholderData
|
|
const canFetchNextPage = Boolean(
|
|
hasNextPage && !isFetchingNextPage && !isFetchNextPageError && !isSearchPending,
|
|
)
|
|
|
|
return {
|
|
query,
|
|
setQuery,
|
|
trimmedQuery,
|
|
sessions,
|
|
filteredSessions,
|
|
isSearchPending,
|
|
isLoading,
|
|
isPending,
|
|
isError,
|
|
isPlaceholderData,
|
|
fetchNextPage,
|
|
hasNextPage,
|
|
isFetchingNextPage,
|
|
isFetchNextPageError,
|
|
canFetchNextPage,
|
|
}
|
|
}
|