67 lines
2.2 KiB
React
67 lines
2.2 KiB
React
import { useEffect, useState } from "react";
|
|
import { Link, useSearchParams } from "react-router-dom";
|
|
import { api } from "../api.js";
|
|
import { matterOpenHref } from "./content.jsx";
|
|
import { ErrorNote } from "./widgets.jsx";
|
|
|
|
export function Search() {
|
|
const [params] = useSearchParams();
|
|
const query = params.get("q") || "";
|
|
const [items, setItems] = useState([]);
|
|
const [error, setError] = useState("");
|
|
|
|
useEffect(() => {
|
|
if (query.trim().length < 2) {
|
|
setItems([]);
|
|
return;
|
|
}
|
|
api(`/api/v1/search?q=${encodeURIComponent(query)}`)
|
|
.then((data) => {
|
|
setItems(data.items);
|
|
setError("");
|
|
})
|
|
.catch((err) => setError(err.message));
|
|
}, [query]);
|
|
|
|
return (
|
|
<main className="page">
|
|
<h1>Suche</h1>
|
|
<p className="muted">Nur Titel und Notiztexte, die du lesen darfst. „{query}“</p>
|
|
<ErrorNote error={error} />
|
|
<ul className="index">
|
|
{items.map((item) => (
|
|
<li key={`${item.kind}-${item.id}`}>
|
|
<Result item={item} />
|
|
<span>{label(item.kind)}</span>
|
|
</li>
|
|
))}
|
|
</ul>
|
|
{!items.length && !error ? <p className="muted">Keine sichtbaren Treffer.</p> : null}
|
|
</main>
|
|
);
|
|
}
|
|
|
|
function Result({ item }) {
|
|
if (item.kind === "case") return <Link to={`/cases/${item.id}`}>{item.title}</Link>;
|
|
if (item.kind === "matter") return <Link to={matterOpenHref(item)}>{item.title}</Link>;
|
|
const context = item.contexts?.[0];
|
|
if (!context) return <span>{item.title}</span>;
|
|
const search = new URLSearchParams();
|
|
if (context.binding_id) search.set("eintrag", context.binding_id);
|
|
if (context.chapter_id) search.set("kapitel", context.chapter_id);
|
|
const query = search.toString();
|
|
if (context.kind === "case") {
|
|
return <Link to={`/cases/${context.id}${query ? `?${query}` : ""}`}>{item.title}</Link>;
|
|
}
|
|
return <Link to={`/matters/${context.id}${query ? `?${query}` : ""}`}>{item.title}</Link>;
|
|
}
|
|
|
|
function label(kind) {
|
|
if (kind === "case") return "Akte";
|
|
if (kind === "matter") return "Vorgang";
|
|
if (kind === "note") return "Notiz";
|
|
if (kind === "file") return "Datei";
|
|
if (kind === "external_ref") return "Referenz";
|
|
return kind;
|
|
}
|