generated from Dicken/dickendock
487 lines
19 KiB
TypeScript
487 lines
19 KiB
TypeScript
import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
|
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
|
import { Link } from "@tanstack/react-router";
|
|
import { SearchInput, StatusBadge, ResultsList, FavoritesBar, Favicon, Button } from "@launchpad/ui";
|
|
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
|
|
import { faGear, faPlus } from "@fortawesome/free-solid-svg-icons";
|
|
import { rankSearchResults, type SearchResult } from "@launchpad/shared";
|
|
import { useServices } from "../hooks/useServices.js";
|
|
import { useBookmarks } from "../hooks/useBookmarks.js";
|
|
import { useDevices } from "../hooks/useDevices.js";
|
|
import { useSettings } from "../hooks/useSettings.js";
|
|
import { useBackendHealth } from "../hooks/useBackendHealth.js";
|
|
import { useCategories } from "../hooks/useCategories.js";
|
|
import { useRecentVisits, recordVisit } from "../hooks/useRecentVisits.js";
|
|
import { useReadLater } from "../hooks/useReadLater.js";
|
|
|
|
async function toggleFavoriteRequest(item: SearchResult): Promise<void> {
|
|
const path = item.kind === "service" ? `/api/services/${item.id}` : `/api/bookmarks/${item.id}`;
|
|
const res = await fetch(path, {
|
|
method: "PATCH",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ favorite: !item.favorite }),
|
|
});
|
|
if (!res.ok) {
|
|
throw new Error(`Favorit konnte nicht aktualisiert werden (HTTP ${res.status})`);
|
|
}
|
|
}
|
|
|
|
async function reorderRequest(kind: "service" | "bookmark", orderedIds: string[]): Promise<void> {
|
|
const path = kind === "service" ? "/api/services/reorder" : "/api/bookmarks/reorder";
|
|
const res = await fetch(path, {
|
|
method: "PATCH",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(orderedIds.map((id, index) => ({ id, order: index }))),
|
|
});
|
|
if (!res.ok) {
|
|
throw new Error(`Reihenfolge konnte nicht gespeichert werden (HTTP ${res.status})`);
|
|
}
|
|
}
|
|
|
|
async function saveReadLaterRequest(url: string) {
|
|
const res = await fetch("/api/read-later", {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ url }),
|
|
});
|
|
if (!res.ok) {
|
|
const body = await res.json().catch(() => ({}));
|
|
throw new Error(body.error ?? `Konnte nicht gespeichert werden (HTTP ${res.status})`);
|
|
}
|
|
return res.json();
|
|
}
|
|
|
|
function ReadLaterBox() {
|
|
const queryClient = useQueryClient();
|
|
const [open, setOpen] = useState(false);
|
|
const [url, setUrl] = useState("");
|
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
|
|
const mutation = useMutation({
|
|
mutationFn: () => saveReadLaterRequest(url.trim()),
|
|
onSuccess: () => {
|
|
setUrl("");
|
|
setOpen(false);
|
|
queryClient.invalidateQueries({ queryKey: ["read-later"] });
|
|
},
|
|
});
|
|
|
|
function handleSubmit(e: FormEvent) {
|
|
e.preventDefault();
|
|
if (!url.trim()) return;
|
|
mutation.mutate();
|
|
}
|
|
|
|
if (!open) {
|
|
return (
|
|
<button
|
|
type="button"
|
|
onClick={() => {
|
|
setOpen(true);
|
|
setTimeout(() => inputRef.current?.focus(), 0);
|
|
}}
|
|
className="flex items-center gap-1.5 text-xs text-black/40 transition-colors
|
|
hover:text-black/70 dark:text-white/40 dark:hover:text-white/70"
|
|
>
|
|
<FontAwesomeIcon icon={faPlus} className="text-[10px]" />
|
|
Link merken
|
|
</button>
|
|
);
|
|
}
|
|
|
|
return (
|
|
<form onSubmit={handleSubmit} className="flex w-full gap-2">
|
|
<input
|
|
ref={inputRef}
|
|
value={url}
|
|
onChange={(e) => setUrl(e.target.value)}
|
|
onKeyDown={(e) => {
|
|
if (e.key === "Escape") {
|
|
setUrl("");
|
|
setOpen(false);
|
|
}
|
|
}}
|
|
placeholder="Link zum Später-Lesen hier einfügen …"
|
|
className="flex-1 rounded-xl border border-black/10 bg-white/70 px-3 py-1.5 text-sm
|
|
text-black outline-none placeholder:text-black/30 focus:border-indigo-400/60
|
|
dark:border-white/10 dark:bg-white/5 dark:text-white dark:placeholder:text-white/30
|
|
dark:focus:border-indigo-400/40"
|
|
/>
|
|
<Button type="submit" variant="secondary" size="sm" disabled={mutation.isPending || !url.trim()}>
|
|
{mutation.isPending ? "…" : "Merken"}
|
|
</Button>
|
|
</form>
|
|
);
|
|
}
|
|
|
|
export function HomePage() {
|
|
const [query, setQuery] = useState(
|
|
() => new URLSearchParams(window.location.search).get("q") ?? ""
|
|
);
|
|
const [selectedIndex, setSelectedIndex] = useState(0);
|
|
const [resultsVisible, setResultsVisible] = useState(
|
|
() => new URLSearchParams(window.location.search).get("q") !== null
|
|
);
|
|
const { health, error: healthError } = useBackendHealth();
|
|
const { data: services, isLoading: servicesLoading, isError: servicesError } = useServices();
|
|
const { data: bookmarks, isLoading: bookmarksLoading } = useBookmarks();
|
|
const { data: devices } = useDevices();
|
|
const { data: settings } = useSettings();
|
|
const { data: categories } = useCategories();
|
|
const { data: recentVisits } = useRecentVisits();
|
|
const { data: readLaterItems } = useReadLater();
|
|
const inputRef = useRef<HTMLInputElement>(null);
|
|
const searchContainerRef = useRef<HTMLDivElement>(null);
|
|
const queryClient = useQueryClient();
|
|
const isSearching = query.trim().length > 0;
|
|
const isLoading = servicesLoading || bookmarksLoading;
|
|
|
|
function openItem(item: SearchResult | { url: string; id?: string; kind?: "service" | "bookmark" }) {
|
|
if ("kind" in item && item.kind === "device") return; // Geräte haben keine eigene URL, nicht anklickbar
|
|
window.open(item.url, "_blank", "noopener,noreferrer");
|
|
if ("kind" in item && (item.kind === "service" || item.kind === "bookmark") && item.id) {
|
|
recordVisit(item.kind, item.id).then(() => {
|
|
queryClient.invalidateQueries({ queryKey: ["recent-visits"] });
|
|
});
|
|
}
|
|
}
|
|
|
|
const categoryColors = useMemo(() => {
|
|
const map: Record<string, string> = {};
|
|
for (const c of categories ?? []) {
|
|
if (c.color) map[c.name] = c.color;
|
|
}
|
|
return map;
|
|
}, [categories]);
|
|
|
|
const toggleFavorite = useMutation({
|
|
mutationFn: toggleFavoriteRequest,
|
|
onSuccess: (_data, item) => {
|
|
queryClient.invalidateQueries({ queryKey: [item.kind === "service" ? "services" : "bookmarks"] });
|
|
},
|
|
});
|
|
|
|
const reorderServices = useMutation({
|
|
mutationFn: (ids: string[]) => reorderRequest("service", ids),
|
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["services"] }),
|
|
});
|
|
|
|
const reorderBookmarks = useMutation({
|
|
mutationFn: (ids: string[]) => reorderRequest("bookmark", ids),
|
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["bookmarks"] }),
|
|
});
|
|
|
|
// Ausgeblendete Dienste (z. B. Fehlerseiten/nicht erreichbare Scan-Treffer,
|
|
// siehe Admin -> Dienste) tauchen in der Suche nicht auf. Geräte und
|
|
// Später-lesen-Einträge sind jetzt ebenfalls durchsuchbar (siehe
|
|
// rankSearchResults: Dienste stehen dabei immer zuerst, Geräte immer
|
|
// zuletzt - Geräte haben keine eigene URL zum Öffnen, siehe ResultsList).
|
|
const allItems: SearchResult[] = useMemo(() => {
|
|
const deviceHostnameById = new Map((devices ?? []).map((d) => [d.id, d.hostname]));
|
|
const deviceOnlineById = new Map((devices ?? []).map((d) => [d.id, d.online]));
|
|
const visibleServices: SearchResult[] = (services ?? [])
|
|
.filter((s) => s.visible)
|
|
.map((s) => ({
|
|
...s,
|
|
kind: "service" as const,
|
|
deviceHostname: deviceHostnameById.get(s.deviceId) ?? null,
|
|
deviceOnline: deviceOnlineById.get(s.deviceId) ?? false,
|
|
}));
|
|
const bookmarkItems: SearchResult[] = (bookmarks ?? []).map((b) => ({
|
|
...b,
|
|
kind: "bookmark" as const,
|
|
}));
|
|
const deviceItems: SearchResult[] = (devices ?? []).map((d) => ({
|
|
kind: "device" as const,
|
|
id: d.id,
|
|
displayName: d.hostname,
|
|
hostname: d.hostname,
|
|
ip: d.ip,
|
|
mac: d.mac,
|
|
online: d.online,
|
|
favicon: null,
|
|
category: null,
|
|
favorite: false,
|
|
order: 0,
|
|
alias: [d.ip, d.mac].filter((v): v is string => !!v),
|
|
description: d.ip,
|
|
}));
|
|
const readLaterSearchItems: SearchResult[] = (readLaterItems ?? []).map((r) => ({
|
|
kind: "readlater" as const,
|
|
id: r.id,
|
|
displayName: r.displayName,
|
|
hostname: "",
|
|
url: r.url,
|
|
favicon: r.favicon,
|
|
category: null,
|
|
favorite: false,
|
|
order: 0,
|
|
alias: [],
|
|
description: null,
|
|
}));
|
|
return [...visibleServices, ...bookmarkItems, ...deviceItems, ...readLaterSearchItems];
|
|
}, [services, bookmarks, devices, readLaterItems]);
|
|
|
|
const results = useMemo(() => rankSearchResults(allItems, query), [allItems, query]);
|
|
|
|
const favoriteServices = useMemo(
|
|
() =>
|
|
(services ?? [])
|
|
.filter((s) => s.visible && s.favorite)
|
|
.sort((a, b) => a.order - b.order),
|
|
[services]
|
|
);
|
|
|
|
const favoriteBookmarks = useMemo(
|
|
() => (bookmarks ?? []).filter((b) => b.favorite).sort((a, b) => a.order - b.order),
|
|
[bookmarks]
|
|
);
|
|
|
|
// Auswahl zurücksetzen, sobald sich die Trefferliste ändert
|
|
useEffect(() => {
|
|
setSelectedIndex(0);
|
|
}, [results.length, query]);
|
|
|
|
// Beim Tippen wieder einblenden (z. B. nachdem per Klick-außerhalb
|
|
// zugeklappt wurde und man weitertippt).
|
|
useEffect(() => {
|
|
if (isSearching) setResultsVisible(true);
|
|
}, [isSearching]);
|
|
|
|
// Klick außerhalb von Suchfeld+Trefferliste klappt das Dropdown wieder ein
|
|
// (Desktop-Verhalten, Text bleibt erhalten). Bewusst gegen das tatsächlich
|
|
// gerenderte Listbox-Element geprüft (closest('[role="listbox"]')), nicht
|
|
// gegen dessen umgebende Scroll-Wrapper-Divs - die sind aus Layoutgründen
|
|
// auf volle Resthöhe gestreckt (siehe max-h-full-Trick in ResultsList),
|
|
// ein Ref darauf hätte fast den ganzen Bildschirm als "innerhalb" gezählt.
|
|
useEffect(() => {
|
|
function onPointerDown(e: MouseEvent) {
|
|
const target = e.target as HTMLElement;
|
|
const insideSearch = searchContainerRef.current?.contains(target) ?? false;
|
|
const insideResults = target.closest('[role="listbox"]') !== null;
|
|
if (!insideSearch && !insideResults) {
|
|
setResultsVisible(false);
|
|
}
|
|
}
|
|
document.addEventListener("mousedown", onPointerDown);
|
|
return () => document.removeEventListener("mousedown", onPointerDown);
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
function onKeyDown(e: KeyboardEvent) {
|
|
const isSlash = e.key === "/" && document.activeElement !== inputRef.current;
|
|
const isCmdK = (e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k";
|
|
|
|
if (isSlash || isCmdK) {
|
|
e.preventDefault();
|
|
inputRef.current?.focus();
|
|
return;
|
|
}
|
|
|
|
if (document.activeElement !== inputRef.current) return;
|
|
if (query.trim().length === 0) return; // keine sichtbare Liste, nichts zu steuern
|
|
|
|
if (e.key === "ArrowDown") {
|
|
e.preventDefault();
|
|
setSelectedIndex((i) => Math.min(i + 1, Math.max(results.length - 1, 0)));
|
|
} else if (e.key === "ArrowUp") {
|
|
e.preventDefault();
|
|
setSelectedIndex((i) => Math.max(i - 1, 0));
|
|
} else if (e.key === "Enter") {
|
|
e.preventDefault();
|
|
const target = results[selectedIndex];
|
|
if (target) openItem(target);
|
|
} else if (e.key === "Escape") {
|
|
inputRef.current?.blur();
|
|
setQuery("");
|
|
}
|
|
}
|
|
|
|
window.addEventListener("keydown", onKeyDown);
|
|
return () => window.removeEventListener("keydown", onKeyDown);
|
|
}, [results, selectedIndex, query]);
|
|
|
|
const isOnline = !healthError && health?.status === "ok";
|
|
const hasFavorites = favoriteServices.length > 0 || favoriteBookmarks.length > 0;
|
|
const readLaterLimit = settings?.readLaterLimit ?? 5;
|
|
const hasReadLaterChips = readLaterItems && readLaterItems.length > 0 && readLaterLimit > 0;
|
|
const showShelf = !isSearching || !resultsVisible;
|
|
const showResults = isSearching && resultsVisible;
|
|
|
|
return (
|
|
<div
|
|
className={`flex flex-col bg-gradient-to-b from-white to-neutral-100 dark:from-black
|
|
dark:to-neutral-950 ${showResults ? "h-dvh overflow-hidden" : "min-h-dvh"}`}
|
|
>
|
|
<div className="fixed right-6 top-6 z-10 flex items-center gap-2">
|
|
<Link
|
|
to="/admin"
|
|
aria-label="Adminbereich öffnen"
|
|
className="rounded-full border border-black/10 p-2 text-black/60 transition-colors
|
|
hover:bg-black/5 dark:border-white/10 dark:text-white/60 dark:hover:bg-white/5"
|
|
>
|
|
<FontAwesomeIcon icon={faGear} />
|
|
</Link>
|
|
</div>
|
|
|
|
{/* Kopfbereich: Titel, Suchfeld, Favoriten/Später-lesen/Zuletzt-besucht.
|
|
Nur im "aktiv suchend"-Zustand shrink-0 + scrollender Bereich
|
|
darunter - sonst normaler Dokumentfluss, damit der Footer direkt
|
|
nach dem Inhalt folgt statt mit einer riesigen Lücke ganz unten zu
|
|
kleben (siehe showResults-Fallunterscheidung oben). */}
|
|
<div className={`flex flex-col items-center gap-6 px-6 pb-6 pt-10 sm:pt-14 ${showResults ? "shrink-0" : ""}`}>
|
|
<div className="flex flex-col items-center gap-1 text-center">
|
|
<h1 className="text-xl font-semibold tracking-tight text-black dark:text-white sm:text-2xl">
|
|
LaunchPad
|
|
</h1>
|
|
<p className="text-sm text-black/40 dark:text-white/40">
|
|
Tippe, um deine Homelab-Dienste sofort zu öffnen.
|
|
</p>
|
|
</div>
|
|
|
|
<div ref={searchContainerRef} className="w-full max-w-xl">
|
|
<SearchInput
|
|
ref={inputRef}
|
|
value={query}
|
|
onChange={(e) => setQuery(e.target.value)}
|
|
onClear={() => {
|
|
setQuery("");
|
|
inputRef.current?.focus();
|
|
}}
|
|
onFocus={() => setResultsVisible(true)}
|
|
placeholder="Dienst oder Lesezeichen suchen … z. B. „frigate“"
|
|
hint="⌘K"
|
|
autoFocus
|
|
/>
|
|
</div>
|
|
|
|
{showShelf ? (
|
|
<div
|
|
className="w-full max-w-xl divide-y divide-black/[0.06] rounded-2xl border
|
|
border-black/[0.06] bg-black/[0.015] dark:divide-white/[0.06] dark:border-white/[0.06]
|
|
dark:bg-white/[0.02]"
|
|
>
|
|
{hasFavorites ? (
|
|
<div className="flex flex-col gap-2 p-2.5">
|
|
{favoriteServices.length > 0 ? (
|
|
<FavoritesBar
|
|
items={favoriteServices}
|
|
label="Favoriten · Dienste"
|
|
categoryColors={categoryColors}
|
|
onOpen={(item) => {
|
|
const service = favoriteServices.find((s) => s.id === item.id);
|
|
if (service) openItem({ ...service, kind: "service" });
|
|
}}
|
|
onReorder={(ids) => reorderServices.mutate(ids)}
|
|
/>
|
|
) : null}
|
|
{favoriteBookmarks.length > 0 ? (
|
|
<FavoritesBar
|
|
items={favoriteBookmarks}
|
|
label="Favoriten · Lesezeichen"
|
|
categoryColors={categoryColors}
|
|
onOpen={(item) => {
|
|
const bookmark = favoriteBookmarks.find((b) => b.id === item.id);
|
|
if (bookmark) openItem({ ...bookmark, kind: "bookmark" });
|
|
}}
|
|
onReorder={(ids) => reorderBookmarks.mutate(ids)}
|
|
/>
|
|
) : null}
|
|
</div>
|
|
) : null}
|
|
|
|
{recentVisits && recentVisits.length > 0 ? (
|
|
<div className="p-2.5">
|
|
<FavoritesBar
|
|
items={recentVisits}
|
|
label="Zuletzt besucht"
|
|
categoryColors={categoryColors}
|
|
onOpen={(item) => {
|
|
const original = recentVisits.find((r) => r.id === item.id);
|
|
if (original) openItem(original);
|
|
}}
|
|
/>
|
|
</div>
|
|
) : null}
|
|
|
|
<div className="p-2.5">
|
|
<div className="mb-2.5 flex items-center justify-between gap-2">
|
|
<span className="text-xs font-medium uppercase tracking-wide text-black/35 dark:text-white/35">
|
|
Später lesen
|
|
</span>
|
|
<ReadLaterBox />
|
|
</div>
|
|
{hasReadLaterChips ? (
|
|
<div className="flex flex-wrap gap-1.5">
|
|
{readLaterItems!.slice(0, readLaterLimit).map((item) => (
|
|
<button
|
|
key={item.id}
|
|
onClick={() => window.open(item.url, "_blank", "noopener,noreferrer")}
|
|
title={item.displayName}
|
|
className="group flex w-12 flex-col items-center gap-0.5 rounded-lg p-1
|
|
transition-colors hover:bg-black/[0.04] dark:hover:bg-white/[0.06]"
|
|
>
|
|
<span
|
|
className="flex h-8 w-8 items-center justify-center rounded-lg border
|
|
border-black/10 bg-white/80 shadow-sm transition-transform
|
|
group-hover:scale-105 dark:border-white/10 dark:bg-white/5"
|
|
>
|
|
<Favicon src={item.favicon} fallbackLetter={item.displayName} size="md" />
|
|
</span>
|
|
<span className="line-clamp-2 w-full text-center text-[10px] leading-tight text-black/55 dark:text-white/55">
|
|
{item.displayName}
|
|
</span>
|
|
</button>
|
|
))}
|
|
</div>
|
|
) : (
|
|
<p className="text-xs text-black/30 dark:text-white/30">
|
|
Noch nichts gemerkt.
|
|
</p>
|
|
)}
|
|
</div>
|
|
</div>
|
|
) : null}
|
|
</div>
|
|
|
|
{/* Scrollender Bereich: NUR die Trefferliste scrollt, nicht die ganze Seite */}
|
|
{showResults ? (
|
|
<div className="min-h-0 flex-1 px-6 pb-4">
|
|
<div className="mx-auto h-full max-w-xl">
|
|
{isLoading ? (
|
|
<p className="text-center text-sm text-black/40 dark:text-white/40">Lade …</p>
|
|
) : servicesError ? (
|
|
<p className="text-center text-sm text-red-500">
|
|
Dienste konnten nicht geladen werden.
|
|
</p>
|
|
) : (
|
|
<ResultsList
|
|
results={results}
|
|
selectedIndex={selectedIndex}
|
|
categoryColors={categoryColors}
|
|
onHover={setSelectedIndex}
|
|
onOpen={openItem}
|
|
onToggleFavorite={(item) => toggleFavorite.mutate(item)}
|
|
emptyLabel={
|
|
allItems.length === 0
|
|
? "Noch nichts angelegt. Füge Dienste oder Lesezeichen im Adminbereich hinzu."
|
|
: "Keine Treffer für deine Suche."
|
|
}
|
|
/>
|
|
)}
|
|
</div>
|
|
</div>
|
|
) : null}
|
|
|
|
<div className={`flex flex-col items-center gap-1 pb-6 pt-2 ${showResults ? "shrink-0" : "mt-4"}`}>
|
|
<StatusBadge online={isOnline} label={isOnline ? "Backend verbunden" : "Backend nicht erreichbar"} />
|
|
{health ? (
|
|
<span className="text-xs text-black/30 dark:text-white/30">
|
|
v{health.version} · läuft seit {health.uptimeSeconds}s
|
|
</span>
|
|
) : null}
|
|
</div>
|
|
</div>
|
|
);
|
|
}
|