| 1 | "use client"; |
| 2 | |
| 3 | import { LoaderCircle } from |
| 4 | import { useEffect, useRef |
| 5 | |
| 6 | import { Button } |
| 7 | |
| 8 | import { loadCodeSearchPage } |
| 9 | import { |
| 10 | CodeSearchFile, |
| 11 | type CodeSearchMatch, |
| 12 | type CodeSearchRepository, |
| 13 | } from "./code-search-file"; |
| 14 | |
| 15 | /** Appends the next page of matches each time the end of the list comes near the viewport. */ |
| 16 | export function CodeSearchMore({ |
| 17 | query, |
| 18 | repository, |
| 19 | cursor, |
| 20 | }: { |
| 21 | query: string |
| 22 | repository?: CodeSearchRepository |
| 23 | cursor: string |
| 24 | }) { |
| 25 | const sentinel = |
| 26 | const [files, |
| 27 | const [next, |
| 28 | const [error, |
| 29 | |
| 30 | useEffect(() => |
| 31 | const node = |
| 32 | if (!node || |
| 33 | |
| 34 | let cancelled = |
| 35 | // A fresh observer per page reports at once if the sentinel is still in view, so a short page keeps loading. |
| 36 | const observer = |
| 37 | ([entry]) => |
| 38 | if (!entry.isIntersecting |
| 39 | observer.disconnect(); |
| 40 | |
| 41 | loadCodeSearchPage({ query, |
| 42 | .then((result) |
| 43 | if (cancelled) return |
| 44 | if (!result?.data |
| 45 | setError(result?.serverError |
| 46 | return; |
| 47 | } |
| 48 | const { files, |
| 49 | setFiles((loaded) |
| 50 | setNext(nextCursor); |
| 51 | }) |
| 52 | .catch(() => |
| 53 | if (!cancelled) |
| 54 | }); |
| 55 | }, |
| 56 | { rootMargin: "800px 0px" |
| 57 | ); |
| 58 | |
| 59 | observer.observe(node |
| 60 | return () => |
| 61 | cancelled = true; |
| 62 | observer.disconnect(); |
| 63 | }; |
| 64 | }, [query, |
| 65 | |
| 66 | return ( |
| 67 | <> |
| 68 | {/* The index can reorder between pages, so a path may repeat; the list only grows, so a position is a stable key. */ |
| 69 | {files.map(( |
| 70 | <CodeSearchFile key={ |
| 71 | ))} |
| 72 | {error ? ( |
| 73 | <div className="flex items-center justify-center gap-3 py-4 text-sm text-muted-foreground |
| 74 | {error} |
| 75 | <Button |
| 76 | variant="outline" |
| 77 | size="sm" |
| 78 | onClick={() => |
| 79 | > |
| 80 | Retry |
| 81 | </Button> |
| 82 | </div> |
| 83 | ) : ( |
| 84 | next !== null && |
| 85 | <div |
| 86 | ref={sentinel} |
| 87 | className="flex justify-center py-4 text-muted-foreground" |
| 88 | > |
| 89 | <LoaderCircle |
| 90 | className="size-5 animate-spin" |
| 91 | aria-label="Loading more results" |
| 92 | /> |
| 93 | </div> |
| 94 | ) |
| 95 | )} |
| 96 | </> |
| 97 | ); |
| 98 | } |