| 1 | import { useState } from "react"; |
| 2 | import { useQuery } from "@tanstack/react-query"; |
| 3 | import { Link } from "@tanstack/react-router"; |
| 4 | import { api } from "../api"; |
| 5 | import { S } from "../i18n"; |
| 6 | import { useKb, useKbId } from "../kb"; |
| 7 | import { Pager, pageSlice } from "../ui"; |
| 8 | |
| 9 | const RESULT_PAGE = 10; |
| 10 | |
| 11 | export function Search() { |
| 12 | const kbId = useKbId(); |
| 13 | const { kb } = useKb(); |
| 14 | const [input, setInput] = useState(""); |
| 15 | const [query, setQuery] = useState(""); |
| 16 | const [page, setPage] = useState(0); |
| 17 | |
| 18 | const results = useQuery({ |
| 19 | queryKey: ["search", kb?.id, query], |
| 20 | queryFn: () => api.search(kb!.id, query), |
| 21 | enabled: !!kb && query.length > 0, |
| 22 | }); |
| 23 | |
| 24 | return ( |
| 25 | <div className="h-full overflow-y-auto p-6"> |
| 26 | <div className="max-w-2xl mx-auto"> |
| 27 | <div className="flex gap-2 mb-6"> |
| 28 | <input |
| 29 | className="input-dark flex-1 px-4 py-2.5 text-sm" |
| 30 | placeholder={S.search.placeholder} |
| 31 | value={input} |
| 32 | onChange={(e) => setInput(e.target.value)} |
| 33 | onKeyDown={(e) => { |
| 34 | if (e.key === "Enter" && !e.nativeEvent.isComposing) { |
| 35 | setQuery(input.trim()); |
| 36 | setPage(0); |
| 37 | } |
| 38 | }} |
| 39 | /> |
| 40 | <button |
| 41 | onClick={() => { |
| 42 | setQuery(input.trim()); |
| 43 | setPage(0); |
| 44 | }} |
| 45 | disabled={!input.trim()} |
| 46 | className="u-btn u-btn-primary px-5 py-2 text-sm" |
| 47 | > |
| 48 | {S.search.button} |
| 49 | </button> |
| 50 | </div> |
| 51 | |
| 52 | {results.isFetching && <p className="text-sm text-neutral-500">{S.search.searching}</p>} |
| 53 | {results.isError && ( |
| 54 | <p className="text-sm text-rose-400">{(results.error as Error).message}</p> |
| 55 | )} |
| 56 | {results.data && results.data.results.length === 0 && ( |
| 57 | <p className="text-sm text-neutral-500">{S.search.noResults}</p> |
| 58 | )} |
| 59 | |
| 60 | <div className="space-y-3"> |
| 61 | {pageSlice(results.data?.results ?? [], page, RESULT_PAGE).rows.map((r) => ( |
| 62 | <Link |
| 63 | key={r.id} |
| 64 | to="/kb/$kbId/doc/$docId" |
| 65 | params={{ kbId, docId: r.document_id }} |
| 66 | search={{ chunk: r.id }} |
| 67 | className="block glass rounded-xl p-4 glass-hover" |
| 68 | > |
| 69 | <div className="mb-1.5 text-xs text-neutral-500"> |
| 70 | {S.search.chunkOf(r.filename, r.seq + 1)} |
| 71 | </div> |
| 72 | <p className="text-sm text-neutral-300 leading-relaxed line-clamp-4 whitespace-pre-wrap"> |
| 73 | {r.text} |
| 74 | </p> |
| 75 | </Link> |
| 76 | ))} |
| 77 | </div> |
| 78 | <Pager |
| 79 | total={results.data?.results.length ?? 0} |
| 80 | pageSize={RESULT_PAGE} |
| 81 | page={page} |
| 82 | onPage={setPage} |
| 83 | /> |
| 84 | </div> |
| 85 | </div> |
| 86 | ); |
| 87 | } |