'use client'; import { ResizablePanel, ResizablePanelGroup, } from "@/components/ui/resizable"; import { Separator } from "@/components/ui/separator"; import useCaptureEvent from "@/hooks/useCaptureEvent"; import { useNonEmptyQueryParam } from "@/hooks/useNonEmptyQueryParam"; import { useSearchHistory } from "@/hooks/useSearchHistory"; import { SearchQueryParams } from "@/lib/types"; import { createPathWithQueryParams, measure, unwrapServiceError } from "@/lib/utils"; import { InfoCircledIcon, SymbolIcon } from "@radix-ui/react-icons"; import { useQuery } from "@tanstack/react-query"; import { useRouter } from "next/navigation"; import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { search } from "../../api/(client)/client"; import { TopBar } from "../components/topBar"; import { CodePreviewPanel } from "./components/codePreviewPanel"; import { FilterPanel } from "./components/filterPanel"; import { SearchResultsPanel } from "./components/searchResultsPanel"; import { useDomain } from "@/hooks/useDomain"; import { useToast } from "@/components/hooks/use-toast"; import { RepositoryInfo, SearchResultFile } from "@/features/search/types"; import { AnimatedResizableHandle } from "@/components/ui/animatedResizableHandle"; import { useFilteredMatches } from "./components/filterPanel/useFilterMatches"; import { Button } from "@/components/ui/button"; import { ImperativePanelHandle } from "react-resizable-panels"; import { FilterIcon } from "lucide-react"; import { useHotkeys } from "react-hotkeys-hook"; import { useLocalStorage } from "@uidotdev/usehooks"; import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip"; import { KeyboardShortcutHint } from "@/app/components/keyboardShortcutHint"; const DEFAULT_MAX_MATCH_COUNT = 10000; export default function SearchPage() { // We need a suspense boundary here since we are accessing query params // in the top level page. // @see : https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout return ( ) } const SearchPageInternal = () => { const router = useRouter(); const searchQuery = useNonEmptyQueryParam(SearchQueryParams.query) ?? ""; const { setSearchHistory } = useSearchHistory(); const captureEvent = useCaptureEvent(); const domain = useDomain(); const { toast } = useToast(); // Encodes the number of matches to return in the search response. const _maxMatchCount = parseInt(useNonEmptyQueryParam(SearchQueryParams.matches) ?? `${DEFAULT_MAX_MATCH_COUNT}`); const maxMatchCount = isNaN(_maxMatchCount) ? DEFAULT_MAX_MATCH_COUNT : _maxMatchCount; const { data: searchResponse, isLoading: isSearchLoading, error } = useQuery({ queryKey: ["search", searchQuery, maxMatchCount], queryFn: () => measure(() => unwrapServiceError(search({ query: searchQuery, matches: maxMatchCount, contextLines: 3, whole: false, }, domain)), "client.search"), select: ({ data, durationMs }) => ({ ...data, durationMs, }), enabled: searchQuery.length > 0, refetchOnWindowFocus: false, retry: false, staleTime: Infinity, }); useEffect(() => { if (error) { toast({ description: `❌ Search failed. Reason: ${error.message}`, }); } }, [error, toast]); // Write the query to the search history useEffect(() => { if (searchQuery.length === 0) { return; } const now = new Date().toUTCString(); setSearchHistory((searchHistory) => [ { query: searchQuery, date: now, }, ...searchHistory.filter(search => search.query !== searchQuery), ]) }, [searchQuery, setSearchHistory]); useEffect(() => { if (!searchResponse) { return; } const fileLanguages = searchResponse.files?.map(file => file.language) || []; captureEvent("search_finished", { durationMs: searchResponse.durationMs, fileCount: searchResponse.zoektStats.fileCount, matchCount: searchResponse.zoektStats.matchCount, filesSkipped: searchResponse.zoektStats.filesSkipped, contentBytesLoaded: searchResponse.zoektStats.contentBytesLoaded, indexBytesLoaded: searchResponse.zoektStats.indexBytesLoaded, crashes: searchResponse.zoektStats.crashes, shardFilesConsidered: searchResponse.zoektStats.shardFilesConsidered, filesConsidered: searchResponse.zoektStats.filesConsidered, filesLoaded: searchResponse.zoektStats.filesLoaded, shardsScanned: searchResponse.zoektStats.shardsScanned, shardsSkipped: searchResponse.zoektStats.shardsSkipped, shardsSkippedFilter: searchResponse.zoektStats.shardsSkippedFilter, ngramMatches: searchResponse.zoektStats.ngramMatches, ngramLookups: searchResponse.zoektStats.ngramLookups, wait: searchResponse.zoektStats.wait, matchTreeConstruction: searchResponse.zoektStats.matchTreeConstruction, matchTreeSearch: searchResponse.zoektStats.matchTreeSearch, regexpsConsidered: searchResponse.zoektStats.regexpsConsidered, flushReason: searchResponse.zoektStats.flushReason, fileLanguages, }); }, [captureEvent, searchQuery, searchResponse]); const { fileMatches, searchDurationMs, totalMatchCount, isBranchFilteringEnabled, repositoryInfo, matchCount } = useMemo(() => { if (!searchResponse) { return { fileMatches: [], searchDurationMs: 0, totalMatchCount: 0, isBranchFilteringEnabled: false, repositoryInfo: {}, matchCount: 0, }; } return { fileMatches: searchResponse.files ?? [], searchDurationMs: Math.round(searchResponse.durationMs), totalMatchCount: searchResponse.zoektStats.matchCount, isBranchFilteringEnabled: searchResponse.isBranchFilteringEnabled, repositoryInfo: searchResponse.repositoryInfo.reduce((acc, repo) => { acc[repo.id] = repo; return acc; }, {} as Record), matchCount: searchResponse.stats.matchCount, } }, [searchResponse]); const isMoreResultsButtonVisible = useMemo(() => { return totalMatchCount > maxMatchCount; }, [totalMatchCount, maxMatchCount]); const onLoadMoreResults = useCallback(() => { const url = createPathWithQueryParams(`/${domain}/search`, [SearchQueryParams.query, searchQuery], [SearchQueryParams.matches, `${maxMatchCount * 2}`], ) router.push(url); }, [maxMatchCount, router, searchQuery, domain]); return ( {/* TopBar */} {(isSearchLoading) ? ( Searching... ) : ( )} ); } interface PanelGroupProps { fileMatches: SearchResultFile[]; isMoreResultsButtonVisible?: boolean; onLoadMoreResults: () => void; isBranchFilteringEnabled: boolean; repoInfo: Record; searchDurationMs: number; numMatches: number; } const PanelGroup = ({ fileMatches, isMoreResultsButtonVisible, onLoadMoreResults, isBranchFilteringEnabled, repoInfo, searchDurationMs, numMatches, }: PanelGroupProps) => { const [previewedFile, setPreviewedFile] = useState(undefined); const filteredFileMatches = useFilteredMatches(fileMatches); const filterPanelRef = useRef(null); const [selectedMatchIndex, setSelectedMatchIndex] = useState(0); const [isFilterPanelCollapsed, setIsFilterPanelCollapsed] = useLocalStorage('isFilterPanelCollapsed', false); useHotkeys("mod+b", () => { if (isFilterPanelCollapsed) { filterPanelRef.current?.expand(); } else { filterPanelRef.current?.collapse(); } }, { enableOnFormTags: true, enableOnContentEditable: true, description: "Toggle filter panel", }); return ( {/* ~~ Filter panel ~~ */} setIsFilterPanelCollapsed(true)} onExpand={() => setIsFilterPanelCollapsed(false)} > {isFilterPanelCollapsed && ( { filterPanelRef.current?.expand(); }} > Open filter panel )} {/* ~~ Search results ~~ */} { fileMatches.length > 0 ? ( {`[${searchDurationMs} ms] Found ${numMatches} matches in ${fileMatches.length} ${fileMatches.length > 1 ? 'files' : 'file'}`} ) : ( No results ) } {isMoreResultsButtonVisible && ( (load more) )} {filteredFileMatches.length > 0 ? ( { setSelectedMatchIndex(matchIndex ?? 0); setPreviewedFile(fileMatch); }} isLoadMoreButtonVisible={!!isMoreResultsButtonVisible} onLoadMoreButtonClicked={onLoadMoreResults} isBranchFilteringEnabled={isBranchFilteringEnabled} repoInfo={repoInfo} /> ) : ( No results found )} {previewedFile && ( <> {/* ~~ Code preview ~~ */} setPreviewedFile(undefined)} > setPreviewedFile(undefined)} selectedMatchIndex={selectedMatchIndex} onSelectedMatchIndexChange={setSelectedMatchIndex} /> > )} ) }
Searching...
{`[${searchDurationMs} ms] Found ${numMatches} matches in ${fileMatches.length} ${fileMatches.length > 1 ? 'files' : 'file'}`}
No results
No results found