|
| 1 | +import { Fragment } from "react"; |
| 2 | + |
| 3 | +import { agentLabel } from "../format"; |
| 4 | +import { HIGHLIGHT_END, HIGHLIGHT_START, type SearchHit } from "../ipc"; |
| 5 | + |
| 6 | +/** Split a snippet on the highlight markers into plain/highlighted runs. */ |
| 7 | +function Snippet({ text }: { text: string }) { |
| 8 | + const nodes: React.ReactNode[] = []; |
| 9 | + let rest = text; |
| 10 | + let key = 0; |
| 11 | + while (rest.length > 0) { |
| 12 | + const start = rest.indexOf(HIGHLIGHT_START); |
| 13 | + if (start === -1) { |
| 14 | + nodes.push(<Fragment key={key++}>{rest}</Fragment>); |
| 15 | + break; |
| 16 | + } |
| 17 | + if (start > 0) nodes.push(<Fragment key={key++}>{rest.slice(0, start)}</Fragment>); |
| 18 | + const end = rest.indexOf(HIGHLIGHT_END, start + HIGHLIGHT_START.length); |
| 19 | + if (end === -1) { |
| 20 | + nodes.push(<Fragment key={key++}>{rest.slice(start + HIGHLIGHT_START.length)}</Fragment>); |
| 21 | + break; |
| 22 | + } |
| 23 | + const matched = rest.slice(start + HIGHLIGHT_START.length, end); |
| 24 | + nodes.push(<mark key={key++}>{matched}</mark>); |
| 25 | + rest = rest.slice(end + HIGHLIGHT_END.length); |
| 26 | + } |
| 27 | + return <span className="hit__snippet">{nodes}</span>; |
| 28 | +} |
| 29 | + |
| 30 | +const FIELD_LABEL: Record<string, string> = { |
| 31 | + title: "title", |
| 32 | + text: "message", |
| 33 | + patch: "patch", |
| 34 | + content_json: "tool", |
| 35 | +}; |
| 36 | + |
| 37 | +export default function SearchResults({ |
| 38 | + hits, |
| 39 | + query, |
| 40 | + selectedId, |
| 41 | + onOpen, |
| 42 | +}: { |
| 43 | + hits: SearchHit[]; |
| 44 | + query: string; |
| 45 | + selectedId: string | null; |
| 46 | + onOpen: (id: string) => void; |
| 47 | +}) { |
| 48 | + if (query.trim() === "") return null; |
| 49 | + if (hits.length === 0) { |
| 50 | + return <p className="sessions__empty">No matches for “{query.trim()}”.</p>; |
| 51 | + } |
| 52 | + return ( |
| 53 | + <ul className="results" role="listbox" aria-label="search results"> |
| 54 | + {hits.map((hit, index) => ( |
| 55 | + <li |
| 56 | + key={`${hit.source_id}-${index}`} |
| 57 | + role="option" |
| 58 | + aria-selected={hit.session_id === selectedId} |
| 59 | + className={`results__item${hit.session_id === selectedId ? " is-active" : ""}`} |
| 60 | + onClick={() => onOpen(hit.session_id)} |
| 61 | + > |
| 62 | + <div className="results__meta"> |
| 63 | + <span className="results__title">{hit.title ?? "(untitled)"}</span> |
| 64 | + <span className="chip chip--agent">{agentLabel(hit.agent_id)}</span> |
| 65 | + <span className="results__field">{FIELD_LABEL[hit.field] ?? hit.field}</span> |
| 66 | + </div> |
| 67 | + <Snippet text={hit.snippet} /> |
| 68 | + </li> |
| 69 | + ))} |
| 70 | + </ul> |
| 71 | + ); |
| 72 | +} |
0 commit comments