Lesezeichen, Import/Export, Favoriten-Sortierung im Frontend, Favicon-Fix, sortierbare Spalten, Kategorie-Dropdown

This commit is contained in:
2026-07-19 21:56:25 +02:00
parent 31e17ff77b
commit dc91a9aba9
24 changed files with 1655 additions and 180 deletions

View File

@@ -0,0 +1,17 @@
import { useQuery } from "@tanstack/react-query";
import type { Bookmark } from "@launchpad/shared";
async function fetchBookmarks(): Promise<Bookmark[]> {
const res = await fetch("/api/bookmarks");
if (!res.ok) {
throw new Error(`Lesezeichen konnten nicht geladen werden (HTTP ${res.status})`);
}
return res.json();
}
export function useBookmarks() {
return useQuery({
queryKey: ["bookmarks"],
queryFn: fetchBookmarks,
});
}

View File

@@ -4,6 +4,7 @@ import { AdminLayout } from "./routes/admin/AdminLayout.js";
import { DashboardPage } from "./routes/admin/DashboardPage.js";
import { DevicesPage } from "./routes/admin/DevicesPage.js";
import { ServicesPage } from "./routes/admin/ServicesPage.js";
import { BookmarksPage } from "./routes/admin/BookmarksPage.js";
import { CategoriesPage } from "./routes/admin/CategoriesPage.js";
import { ScannerPage } from "./routes/admin/ScannerPage.js";
import { PluginsPage } from "./routes/admin/PluginsPage.js";
@@ -53,6 +54,12 @@ const adminServicesRoute = createRoute({
component: ServicesPage,
});
const adminBookmarksRoute = createRoute({
getParentRoute: () => adminRoute,
path: "/bookmarks",
component: BookmarksPage,
});
const adminCategoriesRoute = createRoute({
getParentRoute: () => adminRoute,
path: "/categories",
@@ -90,6 +97,7 @@ const routeTree = rootRoute.addChildren([
adminDashboardRoute,
adminDevicesRoute,
adminServicesRoute,
adminBookmarksRoute,
adminCategoriesRoute,
adminScannerRoute,
adminPluginsRoute,

View File

@@ -2,25 +2,38 @@ import { useEffect, useMemo, useRef, useState } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Link } from "@tanstack/react-router";
import { SearchInput, StatusBadge, ResultsList, FavoritesBar } from "@launchpad/ui";
import { rankServices, type Service } from "@launchpad/shared";
import { rankServices, type SearchResult } from "@launchpad/shared";
import { useServices } from "../hooks/useServices.js";
import { useBookmarks } from "../hooks/useBookmarks.js";
import { useBackendHealth } from "../hooks/useBackendHealth.js";
import { useTheme } from "../hooks/useTheme.js";
function openService(service: Service) {
window.open(service.url, "_blank", "noopener,noreferrer");
function openItem(item: SearchResult) {
window.open(item.url, "_blank", "noopener,noreferrer");
}
async function toggleServiceFavorite(service: Service): Promise<Service> {
const res = await fetch(`/api/services/${service.id}`, {
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: !service.favorite }),
body: JSON.stringify({ favorite: !item.favorite }),
});
if (!res.ok) {
throw new Error(`Favorit konnte nicht aktualisiert werden (HTTP ${res.status})`);
}
return res.json();
}
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})`);
}
}
export function HomePage() {
@@ -28,36 +41,56 @@ export function HomePage() {
const [query, setQuery] = useState("");
const [selectedIndex, setSelectedIndex] = useState(0);
const { health, error: healthError } = useBackendHealth();
const { data: services, isLoading, isError } = useServices();
const { data: services, isLoading: servicesLoading, isError: servicesError } = useServices();
const { data: bookmarks, isLoading: bookmarksLoading } = useBookmarks();
const inputRef = useRef<HTMLInputElement>(null);
const queryClient = useQueryClient();
const isSearching = query.trim().length > 0;
const isLoading = servicesLoading || bookmarksLoading;
const toggleFavorite = useMutation({
mutationFn: toggleServiceFavorite,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["services"] });
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.
const visibleServices = useMemo(
() => (services ?? []).filter((s) => s.visible),
[services]
);
const allItems: SearchResult[] = useMemo(() => {
const visibleServices: SearchResult[] = (services ?? [])
.filter((s) => s.visible)
.map((s) => ({ ...s, kind: "service" as const }));
const bookmarkItems: SearchResult[] = (bookmarks ?? []).map((b) => ({
...b,
kind: "bookmark" as const,
}));
return [...visibleServices, ...bookmarkItems];
}, [services, bookmarks]);
const results = useMemo(
() => rankServices(visibleServices, query),
[visibleServices, query]
);
const results = useMemo(() => rankServices(allItems, query), [allItems, query]);
const favoriteServices = useMemo(
() =>
visibleServices
.filter((s) => s.favorite)
(services ?? [])
.filter((s) => s.visible && s.favorite)
.sort((a, b) => a.order - b.order),
[visibleServices]
[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
@@ -88,7 +121,7 @@ export function HomePage() {
} else if (e.key === "Enter") {
e.preventDefault();
const target = results[selectedIndex];
if (target) openService(target);
if (target) openItem(target);
} else if (e.key === "Escape") {
inputRef.current?.blur();
setQuery("");
@@ -100,6 +133,7 @@ export function HomePage() {
}, [results, selectedIndex, query]);
const isOnline = !healthError && health?.status === "ok";
const hasFavorites = favoriteServices.length > 0 || favoriteBookmarks.length > 0;
return (
<div className="flex min-h-screen flex-col items-center justify-start gap-8 bg-gradient-to-b from-white to-neutral-100 px-6 pt-[15vh] dark:from-black dark:to-neutral-950">
@@ -132,9 +166,30 @@ export function HomePage() {
</div>
<div className="w-full max-w-xl">
{favoriteServices.length > 0 ? (
<div className="mb-4">
<FavoritesBar services={favoriteServices} onOpen={openService} />
{hasFavorites ? (
<div className="mb-4 flex flex-col gap-3">
{favoriteServices.length > 0 ? (
<FavoritesBar
items={favoriteServices}
label="Dienste"
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="Lesezeichen"
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}
@@ -142,29 +197,27 @@ export function HomePage() {
ref={inputRef}
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Dienst suchen … z. B. „frigate“"
placeholder="Dienst oder Lesezeichen suchen … z. B. „frigate“"
hint="⌘K"
autoFocus
/>
{!isSearching ? null : isLoading ? (
<p className="mt-4 text-center text-sm text-black/40 dark:text-white/40">
Lade Dienste
</p>
) : isError ? (
<p className="mt-4 text-center text-sm text-black/40 dark:text-white/40">Lade </p>
) : servicesError ? (
<p className="mt-4 text-center text-sm text-red-500">
Dienste konnten nicht geladen werden.
</p>
) : (
<ResultsList
services={results}
results={results}
selectedIndex={selectedIndex}
onHover={setSelectedIndex}
onOpen={openService}
onToggleFavorite={(service) => toggleFavorite.mutate(service)}
onOpen={openItem}
onToggleFavorite={(item) => toggleFavorite.mutate(item)}
emptyLabel={
(visibleServices?.length ?? 0) === 0
? "Noch keine Dienste angelegt. Füge welche im Adminbereich hinzu."
allItems.length === 0
? "Noch nichts angelegt. Füge Dienste oder Lesezeichen im Adminbereich hinzu."
: "Keine Treffer für deine Suche."
}
/>

View File

@@ -7,6 +7,7 @@ const NAV_ITEMS = [
{ to: "/admin/dashboard", label: "Dashboard", icon: "📊" },
{ to: "/admin/devices", label: "Geräte", icon: "🖥️" },
{ to: "/admin/services", label: "Dienste", icon: "🔗" },
{ to: "/admin/bookmarks", label: "Lesezeichen", icon: "🔖" },
{ to: "/admin/scanner", label: "Scanner", icon: "🔍" },
{ to: "/admin/categories", label: "Kategorien", icon: "🏷️" },
{ to: "/admin/plugins", label: "Plugins", icon: "🧩" },

View File

@@ -0,0 +1,460 @@
import { useState, type DragEvent, type FormEvent } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button, Favicon } from "@launchpad/ui";
import type { Bookmark } from "@launchpad/shared";
import { useBookmarks } from "../../hooks/useBookmarks.js";
import { useCategories } from "../../hooks/useCategories.js";
import { AdminPageHeader } from "./AdminPageHeader.js";
interface BookmarkPatch {
url?: string;
displayName?: string;
description?: string | null;
category?: string | null;
favorite?: boolean;
alias?: string[];
order?: number;
}
async function createBookmarkRequest(input: {
url: string;
category?: string;
description?: string;
}): Promise<Bookmark> {
const res = await fetch("/api/bookmarks", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(input),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? `Lesezeichen konnte nicht angelegt werden (HTTP ${res.status})`);
}
return res.json();
}
async function patchBookmark(id: string, patch: BookmarkPatch): Promise<Bookmark> {
const res = await fetch(`/api/bookmarks/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(patch),
});
if (!res.ok) {
throw new Error(`Lesezeichen konnte nicht aktualisiert werden (HTTP ${res.status})`);
}
return res.json();
}
async function deleteBookmarkRequest(id: string) {
const res = await fetch(`/api/bookmarks/${id}`, { method: "DELETE" });
if (!res.ok && res.status !== 404) {
throw new Error(`Lesezeichen konnte nicht gelöscht werden (HTTP ${res.status})`);
}
}
async function reorderBookmarksRequest(entries: { id: string; order: number }[]) {
const res = await fetch("/api/bookmarks/reorder", {
method: "PATCH",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(entries),
});
if (!res.ok) {
throw new Error(`Reihenfolge konnte nicht gespeichert werden (HTTP ${res.status})`);
}
return res.json();
}
const NEW_CATEGORY_VALUE = "__new__";
function CategorySelect({ value, onChange }: { value: string; onChange: (v: string) => void }) {
const { data: categories } = useCategories();
const isKnown = !value || categories?.some((c) => c.name === value);
const [isNew, setIsNew] = useState(!isKnown);
return (
<div className="flex flex-col gap-1">
<select
value={isNew ? NEW_CATEGORY_VALUE : value}
onChange={(e) => {
if (e.target.value === NEW_CATEGORY_VALUE) {
setIsNew(true);
onChange("");
} else {
setIsNew(false);
onChange(e.target.value);
}
}}
className="rounded-lg border border-black/10 bg-white px-2 py-1 text-sm
dark:border-white/10 dark:bg-white/10 dark:text-white"
>
<option value=""> Keine </option>
{categories?.map((c) => (
<option key={c.id} value={c.name}>
{c.name}
</option>
))}
<option value={NEW_CATEGORY_VALUE}>+ Neue Kategorie </option>
</select>
{isNew ? (
<input
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder="Name der neuen Kategorie"
className="rounded-lg border border-black/10 bg-white px-2 py-1 text-sm
dark:border-white/10 dark:bg-white/10 dark:text-white"
/>
) : null}
</div>
);
}
function AddBookmarkForm() {
const queryClient = useQueryClient();
const [url, setUrl] = useState("");
const [category, setCategory] = useState("");
const [description, setDescription] = useState("");
const mutation = useMutation({
mutationFn: () =>
createBookmarkRequest({
url: url.trim(),
category: category.trim() || undefined,
description: description.trim() || undefined,
}),
onSuccess: () => {
setUrl("");
setCategory("");
setDescription("");
queryClient.invalidateQueries({ queryKey: ["bookmarks"] });
queryClient.invalidateQueries({ queryKey: ["categories"] });
},
});
function handleSubmit(e: FormEvent) {
e.preventDefault();
if (!url.trim()) return;
mutation.mutate();
}
return (
<form onSubmit={handleSubmit} className="mb-6 flex flex-wrap items-end gap-2">
<div>
<label className="mb-1 block text-xs font-medium text-black/50 dark:text-white/50">URL</label>
<input
value={url}
onChange={(e) => setUrl(e.target.value)}
placeholder="https://example.com"
className="w-64 rounded-lg border border-black/10 bg-white px-3 py-1.5 text-sm
text-black outline-none focus:border-black/30 dark:border-white/10
dark:bg-white/5 dark:text-white dark:focus:border-white/30"
/>
</div>
<div>
<label className="mb-1 block text-xs font-medium text-black/50 dark:text-white/50">
Kategorie
</label>
<CategorySelect value={category} onChange={setCategory} />
</div>
<div>
<label className="mb-1 block text-xs font-medium text-black/50 dark:text-white/50">
Beschreibung
</label>
<input
value={description}
onChange={(e) => setDescription(e.target.value)}
placeholder="optional"
className="w-48 rounded-lg border border-black/10 bg-white px-3 py-1.5 text-sm
text-black outline-none focus:border-black/30 dark:border-white/10
dark:bg-white/5 dark:text-white dark:focus:border-white/30"
/>
</div>
<Button type="submit" variant="primary" disabled={mutation.isPending}>
{mutation.isPending ? "Lade Titel/Favicon …" : "Anlegen"}
</Button>
{mutation.isError ? (
<span className="text-xs text-red-500">{(mutation.error as Error).message}</span>
) : null}
<span className="w-full text-xs text-black/40 dark:text-white/40">
Titel und Favicon werden automatisch von der Seite geladen, falls verfügbar.
</span>
</form>
);
}
const EDIT_FORM_COLSPAN = 7;
function EditForm({ bookmark, onDone }: { bookmark: Bookmark; onDone: () => void }) {
const queryClient = useQueryClient();
const [displayName, setDisplayName] = useState(bookmark.displayName);
const [url, setUrl] = useState(bookmark.url);
const [category, setCategory] = useState(bookmark.category ?? "");
const [description, setDescription] = useState(bookmark.description ?? "");
const [alias, setAlias] = useState(bookmark.alias.join(", "));
const mutation = useMutation({
mutationFn: () =>
patchBookmark(bookmark.id, {
displayName: displayName.trim(),
url: url.trim(),
category: category.trim() || null,
description: description.trim() || null,
alias: alias
.split(",")
.map((a) => a.trim())
.filter(Boolean),
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["bookmarks"] });
queryClient.invalidateQueries({ queryKey: ["categories"] });
onDone();
},
});
return (
<tr className="border-b border-black/5 bg-black/[0.02] last:border-0 dark:border-white/5 dark:bg-white/5">
<td colSpan={EDIT_FORM_COLSPAN} className="px-4 py-3">
<div className="flex flex-wrap items-end gap-3">
<div>
<label className="mb-1 block text-xs text-black/50 dark:text-white/50">Name</label>
<input
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
className="rounded-lg border border-black/10 bg-white px-2 py-1 text-sm
dark:border-white/10 dark:bg-white/10 dark:text-white"
/>
</div>
<div>
<label className="mb-1 block text-xs text-black/50 dark:text-white/50">URL</label>
<input
value={url}
onChange={(e) => setUrl(e.target.value)}
className="w-56 rounded-lg border border-black/10 bg-white px-2 py-1 text-sm
dark:border-white/10 dark:bg-white/10 dark:text-white"
/>
</div>
<div>
<label className="mb-1 block text-xs text-black/50 dark:text-white/50">Kategorie</label>
<CategorySelect value={category} onChange={setCategory} />
</div>
<div>
<label className="mb-1 block text-xs text-black/50 dark:text-white/50">
Beschreibung
</label>
<input
value={description}
onChange={(e) => setDescription(e.target.value)}
className="w-48 rounded-lg border border-black/10 bg-white px-2 py-1 text-sm
dark:border-white/10 dark:bg-white/10 dark:text-white"
/>
</div>
<div>
<label className="mb-1 block text-xs text-black/50 dark:text-white/50">
Alias (kommagetrennt)
</label>
<input
value={alias}
onChange={(e) => setAlias(e.target.value)}
className="w-40 rounded-lg border border-black/10 bg-white px-2 py-1 text-sm
dark:border-white/10 dark:bg-white/10 dark:text-white"
/>
</div>
<div className="flex gap-2">
<Button size="sm" variant="primary" onClick={() => mutation.mutate()} disabled={mutation.isPending}>
Speichern
</Button>
<Button size="sm" variant="ghost" onClick={onDone}>
Abbrechen
</Button>
</div>
</div>
</td>
</tr>
);
}
function BookmarkRow({
bookmark,
onDragStart,
onDragOver,
onDrop,
isDragging,
}: {
bookmark: Bookmark;
onDragStart: (e: DragEvent<HTMLTableRowElement>) => void;
onDragOver: (e: DragEvent<HTMLTableRowElement>) => void;
onDrop: (e: DragEvent<HTMLTableRowElement>) => void;
isDragging: boolean;
}) {
const queryClient = useQueryClient();
const [editing, setEditing] = useState(false);
const favoriteMutation = useMutation({
mutationFn: () => patchBookmark(bookmark.id, { favorite: !bookmark.favorite }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["bookmarks"] }),
});
const deleteMutation = useMutation({
mutationFn: () => deleteBookmarkRequest(bookmark.id),
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["bookmarks"] }),
});
if (editing) {
return <EditForm bookmark={bookmark} onDone={() => setEditing(false)} />;
}
return (
<tr
draggable
onDragStart={onDragStart}
onDragOver={onDragOver}
onDrop={onDrop}
className={`border-b border-black/5 last:border-0 dark:border-white/5 ${isDragging ? "opacity-40" : ""}`}
>
<td className="px-2 py-3 text-center">
<span className="cursor-grab select-none text-black/30 dark:text-white/30" aria-hidden>
</span>
</td>
<td className="px-2 py-3">
<button
onClick={() => favoriteMutation.mutate()}
aria-label={bookmark.favorite ? "Favorit entfernen" : "Als Favorit markieren"}
className={`text-lg ${bookmark.favorite ? "text-amber-500" : "text-black/15 hover:text-amber-400 dark:text-white/15"}`}
>
</button>
</td>
<td className="px-4 py-3">
<div className="flex items-center gap-2">
<Favicon src={bookmark.favicon} fallbackLetter={bookmark.displayName} size="sm" />
<div>
<div className="font-medium text-black dark:text-white">{bookmark.displayName}</div>
<div className="text-xs text-black/40 dark:text-white/40">{bookmark.hostname}</div>
</div>
</div>
</td>
<td className="px-4 py-3 text-black/60 dark:text-white/60">{bookmark.category ?? ""}</td>
<td className="px-4 py-3 text-black/60 dark:text-white/60">
{bookmark.description ?? ""}
</td>
<td className="px-4 py-3">
<a
href={bookmark.url}
target="_blank"
rel="noopener noreferrer"
className="text-black/60 underline decoration-black/20 hover:text-black dark:text-white/60 dark:decoration-white/20 dark:hover:text-white"
>
öffnen
</a>
</td>
<td className="px-4 py-3">
<div className="flex items-center justify-end gap-2">
<Button size="sm" onClick={() => setEditing(true)}>
Bearbeiten
</Button>
<Button size="sm" variant="danger" onClick={() => deleteMutation.mutate()} disabled={deleteMutation.isPending}>
Löschen
</Button>
</div>
</td>
</tr>
);
}
export function BookmarksPage() {
const { data: bookmarks, isLoading, isError } = useBookmarks();
const queryClient = useQueryClient();
const [draggedId, setDraggedId] = useState<string | null>(null);
const [localOrder, setLocalOrder] = useState<Bookmark[] | null>(null);
const reorderMutation = useMutation({
mutationFn: reorderBookmarksRequest,
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["bookmarks"] });
setLocalOrder(null);
},
onError: () => setLocalOrder(null),
});
const list = localOrder ?? bookmarks ?? [];
function handleDragStart(id: string) {
return (_e: DragEvent<HTMLTableRowElement>) => setDraggedId(id);
}
function handleDragOver(targetId: string) {
return (e: DragEvent<HTMLTableRowElement>) => {
e.preventDefault();
if (!draggedId || draggedId === targetId) return;
const current = localOrder ?? bookmarks ?? [];
const fromIndex = current.findIndex((b) => b.id === draggedId);
const toIndex = current.findIndex((b) => b.id === targetId);
if (fromIndex === -1 || toIndex === -1) return;
const next = [...current];
const [moved] = next.splice(fromIndex, 1);
next.splice(toIndex, 0, moved);
setLocalOrder(next);
};
}
function handleDrop() {
return (e: DragEvent<HTMLTableRowElement>) => {
e.preventDefault();
setDraggedId(null);
const current = localOrder ?? bookmarks ?? [];
reorderMutation.mutate(current.map((b, index) => ({ id: b.id, order: index })));
};
}
return (
<div>
<AdminPageHeader
title="Lesezeichen"
description="Eigenständig von Diensten erscheinen zusammen mit ihnen in der Suche, aber als eigene Favoriten-Gruppe auf der Startseite. Per Drag & Drop sortierbar."
/>
<AddBookmarkForm />
{isLoading ? (
<p className="text-sm text-black/40 dark:text-white/40">Lade Lesezeichen </p>
) : isError ? (
<p className="text-sm text-red-500">Lesezeichen konnten nicht geladen werden.</p>
) : list.length > 0 ? (
<div className="overflow-hidden rounded-2xl border border-black/10 dark:border-white/10">
<div className="overflow-x-auto">
<table className="w-full min-w-[720px] text-sm">
<thead>
<tr className="border-b border-black/10 bg-black/[0.02] text-left text-xs
uppercase tracking-wide text-black/40 dark:border-white/10 dark:bg-white/5 dark:text-white/40">
<th className="px-2 py-2" />
<th className="px-2 py-2" />
<th className="px-4 py-2 font-medium">Lesezeichen</th>
<th className="px-4 py-2 font-medium">Kategorie</th>
<th className="px-4 py-2 font-medium">Beschreibung</th>
<th className="px-4 py-2 font-medium">URL</th>
<th className="px-4 py-2" />
</tr>
</thead>
<tbody>
{list.map((bookmark) => (
<BookmarkRow
key={bookmark.id}
bookmark={bookmark}
isDragging={draggedId === bookmark.id}
onDragStart={handleDragStart(bookmark.id)}
onDragOver={handleDragOver(bookmark.id)}
onDrop={handleDrop()}
/>
))}
</tbody>
</table>
</div>
</div>
) : (
<p className="text-sm text-black/40 dark:text-white/40">
Noch keine Lesezeichen angelegt. Füge oben eine URL hinzu.
</p>
)}
</div>
);
}

View File

@@ -26,6 +26,7 @@ async function deleteDevice(id: string) {
interface ScanResult {
scannedPorts: number;
ports: number[];
created: number;
updated: number;
}
@@ -46,8 +47,9 @@ function DeviceRow({ device }: { device: DeviceWithServices }) {
const scanMutation = useMutation({
mutationFn: () => scanDevice(device.id),
onSuccess: (result) => {
const portsText = result.ports.length > 0 ? result.ports.join(", ") : "keine";
setScanMessage(
`${result.scannedPorts} Port(s) offen · ${result.created} neu · ${result.updated} aktualisiert`
`Ports offen: ${portsText} · ${result.created} neu · ${result.updated} aktualisiert`
);
queryClient.invalidateQueries({ queryKey: ["devices"] });
queryClient.invalidateQueries({ queryKey: ["services"] });
@@ -85,7 +87,7 @@ function DeviceRow({ device }: { device: DeviceWithServices }) {
<td className="px-4 py-3">
<div className="flex items-center justify-end gap-2">
{scanMessage ? (
<span className="max-w-[16rem] truncate text-xs text-black/40 dark:text-white/40" title={scanMessage}>
<span className="max-w-[22rem] truncate text-xs text-black/40 dark:text-white/40" title={scanMessage}>
{scanMessage}
</span>
) : null}

View File

@@ -1,8 +1,9 @@
import { useState, type DragEvent } from "react";
import { useMemo, useRef, useState, type DragEvent } from "react";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Button } from "@launchpad/ui";
import type { Service } from "@launchpad/shared";
import { useServices } from "../../hooks/useServices.js";
import { useCategories } from "../../hooks/useCategories.js";
import { AdminPageHeader } from "./AdminPageHeader.js";
interface ServicePatch {
@@ -49,6 +50,57 @@ async function reorderServicesRequest(entries: { id: string; order: number }[])
return res.json();
}
const NEW_CATEGORY_VALUE = "__new__";
function CategorySelect({
value,
onChange,
}: {
value: string;
onChange: (value: string) => void;
}) {
const { data: categories } = useCategories();
const isKnown = !value || categories?.some((c) => c.name === value);
const [isNew, setIsNew] = useState(!isKnown);
return (
<div className="flex flex-col gap-1">
<select
value={isNew ? NEW_CATEGORY_VALUE : value}
onChange={(e) => {
if (e.target.value === NEW_CATEGORY_VALUE) {
setIsNew(true);
onChange("");
} else {
setIsNew(false);
onChange(e.target.value);
}
}}
className="rounded-lg border border-black/10 bg-white px-2 py-1 text-sm
dark:border-white/10 dark:bg-white/10 dark:text-white"
>
<option value=""> Keine </option>
{categories?.map((c) => (
<option key={c.id} value={c.name}>
{c.name}
</option>
))}
<option value={NEW_CATEGORY_VALUE}>+ Neue Kategorie </option>
</select>
{isNew ? (
<input
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder="Name der neuen Kategorie"
autoFocus
className="rounded-lg border border-black/10 bg-white px-2 py-1 text-sm
dark:border-white/10 dark:bg-white/10 dark:text-white"
/>
) : null}
</div>
);
}
const EDIT_FORM_COLSPAN = 9;
function EditForm({ service, onDone }: { service: Service; onDone: () => void }) {
@@ -81,6 +133,7 @@ function EditForm({ service, onDone }: { service: Service; onDone: () => void })
}),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["services"] });
queryClient.invalidateQueries({ queryKey: ["categories"] });
onDone();
},
});
@@ -100,12 +153,7 @@ function EditForm({ service, onDone }: { service: Service; onDone: () => void })
</div>
<div>
<label className="mb-1 block text-xs text-black/50 dark:text-white/50">Kategorie</label>
<input
value={category}
onChange={(e) => setCategory(e.target.value)}
className="rounded-lg border border-black/10 bg-white px-2 py-1 text-sm
dark:border-white/10 dark:bg-white/10 dark:text-white"
/>
<CategorySelect value={category} onChange={setCategory} />
</div>
<div>
<label className="mb-1 block text-xs text-black/50 dark:text-white/50">
@@ -185,12 +233,14 @@ function EditForm({ service, onDone }: { service: Service; onDone: () => void })
function ServiceRow({
service,
draggable,
onDragStart,
onDragOver,
onDrop,
isDragging,
}: {
service: Service;
draggable: boolean;
onDragStart: (e: DragEvent<HTMLTableRowElement>) => void;
onDragOver: (e: DragEvent<HTMLTableRowElement>) => void;
onDrop: (e: DragEvent<HTMLTableRowElement>) => void;
@@ -220,7 +270,7 @@ function ServiceRow({
return (
<tr
draggable
draggable={draggable}
onDragStart={onDragStart}
onDragOver={onDragOver}
onDrop={onDrop}
@@ -229,7 +279,10 @@ function ServiceRow({
} ${isDragging ? "opacity-40" : ""}`}
>
<td className="px-2 py-3 text-center">
<span className="cursor-grab select-none text-black/30 dark:text-white/30" aria-hidden>
<span
className={`select-none ${draggable ? "cursor-grab text-black/30 dark:text-white/30" : "text-black/10 dark:text-white/10"}`}
aria-hidden
>
</span>
</td>
@@ -303,11 +356,136 @@ function ServiceRow({
);
}
type SortColumn = "displayName" | "category" | "alias" | "port" | "https" | null;
function SortableHeader({
label,
column,
activeColumn,
direction,
onClick,
}: {
label: string;
column: SortColumn;
activeColumn: SortColumn;
direction: "asc" | "desc";
onClick: (column: SortColumn) => void;
}) {
const active = activeColumn === column;
return (
<th className="px-4 py-2 font-medium">
<button
onClick={() => onClick(column)}
className={`flex items-center gap-1 hover:text-black dark:hover:text-white ${
active ? "text-black dark:text-white" : ""
}`}
>
{label}
<span className="text-[10px]">{active ? (direction === "asc" ? "▲" : "▼") : "⇅"}</span>
</button>
</th>
);
}
function readFileAsBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => {
const result = reader.result as string;
resolve(result.split(",")[1] ?? "");
};
reader.onerror = () => reject(new Error("Datei konnte nicht gelesen werden"));
reader.readAsDataURL(file);
});
}
function detectFormat(filename: string): "csv" | "xlsx" | "json" {
if (filename.toLowerCase().endsWith(".xlsx")) return "xlsx";
if (filename.toLowerCase().endsWith(".json")) return "json";
return "csv";
}
interface ImportResult {
imported: number;
skipped: number;
errors: string[];
}
function ImportExportBar() {
const queryClient = useQueryClient();
const fileInputRef = useRef<HTMLInputElement>(null);
const [result, setResult] = useState<ImportResult | null>(null);
const importMutation = useMutation({
mutationFn: async (file: File): Promise<ImportResult> => {
const content = await readFileAsBase64(file);
const format = detectFormat(file.name);
const res = await fetch("/api/services/import", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ format, content }),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw new Error(body.error ?? `Import fehlgeschlagen (HTTP ${res.status})`);
}
return res.json();
},
onSuccess: (data) => {
setResult(data);
queryClient.invalidateQueries({ queryKey: ["services"] });
queryClient.invalidateQueries({ queryKey: ["devices"] });
queryClient.invalidateQueries({ queryKey: ["categories"] });
},
onError: (err: Error) => setResult({ imported: 0, skipped: 0, errors: [err.message] }),
});
return (
<div className="mb-6 flex flex-wrap items-center gap-2">
<span className="text-xs font-medium text-black/50 dark:text-white/50">Export:</span>
<a href="/api/services/export?format=csv" download>
<Button size="sm">CSV</Button>
</a>
<a href="/api/services/export?format=xlsx" download>
<Button size="sm">Excel</Button>
</a>
<a href="/api/services/export?format=json" download>
<Button size="sm">JSON</Button>
</a>
<span className="ml-4 text-xs font-medium text-black/50 dark:text-white/50">Import:</span>
<input
ref={fileInputRef}
type="file"
accept=".csv,.xlsx,.json"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) importMutation.mutate(file);
e.target.value = "";
}}
/>
<Button size="sm" onClick={() => fileInputRef.current?.click()} disabled={importMutation.isPending}>
{importMutation.isPending ? "Importiere …" : "Datei wählen (CSV/Excel/JSON)"}
</Button>
{result ? (
<span className="w-full text-xs text-black/50 dark:text-white/50">
{result.imported} importiert, {result.skipped} übersprungen (bereits vorhanden)
{result.errors.length > 0 ? `, ${result.errors.length} Fehler: ${result.errors.join(" | ")}` : "."}
</span>
) : null}
</div>
);
}
export function ServicesPage() {
const { data: services, isLoading, isError } = useServices();
const queryClient = useQueryClient();
const [draggedId, setDraggedId] = useState<string | null>(null);
const [localOrder, setLocalOrder] = useState<Service[] | null>(null);
const [sortColumn, setSortColumn] = useState<SortColumn>(null);
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
const reorderMutation = useMutation({
mutationFn: reorderServicesRequest,
@@ -318,9 +496,46 @@ export function ServicesPage() {
onError: () => setLocalOrder(null),
});
const list = localOrder ?? services ?? [];
const baseList = localOrder ?? services ?? [];
const hiddenCount = services?.filter((s) => !s.visible).length ?? 0;
const list = useMemo(() => {
if (!sortColumn) return baseList;
const sorted = [...baseList].sort((a, b) => {
let cmp = 0;
switch (sortColumn) {
case "displayName":
cmp = a.displayName.localeCompare(b.displayName);
break;
case "category":
cmp = (a.category ?? "").localeCompare(b.category ?? "");
break;
case "alias":
cmp = a.alias.join(",").localeCompare(b.alias.join(","));
break;
case "port":
cmp = a.port - b.port;
break;
case "https":
cmp = Number(a.https) - Number(b.https);
break;
}
return sortDirection === "asc" ? cmp : -cmp;
});
return sorted;
}, [baseList, sortColumn, sortDirection]);
function handleHeaderClick(column: SortColumn) {
if (sortColumn === column) {
setSortDirection((d) => (d === "asc" ? "desc" : "asc"));
} else {
setSortColumn(column);
setSortDirection("asc");
}
}
const dragEnabled = sortColumn === null;
function handleDragStart(id: string) {
return (_e: DragEvent<HTMLTableRowElement>) => setDraggedId(id);
}
@@ -328,7 +543,7 @@ export function ServicesPage() {
function handleDragOver(targetId: string) {
return (e: DragEvent<HTMLTableRowElement>) => {
e.preventDefault();
if (!draggedId || draggedId === targetId) return;
if (!dragEnabled || !draggedId || draggedId === targetId) return;
const current = localOrder ?? services ?? [];
const fromIndex = current.findIndex((s) => s.id === draggedId);
@@ -345,6 +560,7 @@ export function ServicesPage() {
function handleDrop() {
return (e: DragEvent<HTMLTableRowElement>) => {
e.preventDefault();
if (!dragEnabled) return;
setDraggedId(null);
const current = localOrder ?? services ?? [];
reorderMutation.mutate(current.map((s, index) => ({ id: s.id, order: index })));
@@ -357,11 +573,21 @@ export function ServicesPage() {
title="Dienste"
description={
hiddenCount > 0
? `Per Drag & Drop sortierbar (⠿⠿). Name, Kategorie, Alias, IP/Port/Protokoll und Reihenfolge bleiben bei erneuten Scans erhalten. ${hiddenCount} Dienst(e) sind aktuell in der Suche ausgeblendet (🙈).`
: "Per Drag & Drop sortierbar (⠿⠿). Name, Kategorie, Alias, IP/Port/Protokoll und Reihenfolge bleiben bei erneuten Scans erhalten."
? `Spaltenköpfe anklickbar zum Sortieren; Drag & Drop (⠿⠿) nur in der Standard-Reihenfolge. Name, Kategorie, Alias, IP/Port/Protokoll und Reihenfolge bleiben bei erneuten Scans erhalten. ${hiddenCount} Dienst(e) sind aktuell in der Suche ausgeblendet (🙈).`
: "Spaltenköpfe anklickbar zum Sortieren; Drag & Drop (⠿⠿) nur in der Standard-Reihenfolge. Name, Kategorie, Alias, IP/Port/Protokoll und Reihenfolge bleiben bei erneuten Scans erhalten."
}
/>
<ImportExportBar />
{sortColumn ? (
<div className="mb-3">
<Button size="sm" variant="ghost" onClick={() => setSortColumn(null)}>
Zur manuellen Reihenfolge (Drag & Drop) zurück
</Button>
</div>
) : null}
{isLoading ? (
<p className="text-sm text-black/40 dark:text-white/40">Lade Dienste </p>
) : isError ? (
@@ -375,11 +601,11 @@ export function ServicesPage() {
uppercase tracking-wide text-black/40 dark:border-white/10 dark:bg-white/5 dark:text-white/40">
<th className="px-2 py-2" />
<th className="px-2 py-2" />
<th className="px-4 py-2 font-medium">Dienst</th>
<th className="px-4 py-2 font-medium">Kategorie</th>
<th className="px-4 py-2 font-medium">Alias</th>
<th className="px-4 py-2 font-medium">Port</th>
<th className="px-4 py-2 font-medium">Protokoll</th>
<SortableHeader label="Dienst" column="displayName" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
<SortableHeader label="Kategorie" column="category" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
<SortableHeader label="Alias" column="alias" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
<SortableHeader label="Port" column="port" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
<SortableHeader label="Protokoll" column="https" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
<th className="px-4 py-2 font-medium">URL</th>
<th className="px-4 py-2" />
</tr>
@@ -389,6 +615,7 @@ export function ServicesPage() {
<ServiceRow
key={service.id}
service={service}
draggable={dragEnabled}
isDragging={draggedId === service.id}
onDragStart={handleDragStart(service.id)}
onDragOver={handleDragOver(service.id)}
@@ -402,7 +629,7 @@ export function ServicesPage() {
) : (
<p className="text-sm text-black/40 dark:text-white/40">
Noch keine Dienste vorhanden. Scanne ein Gerät unter Geräte, um automatisch welche
zu finden.
zu finden, oder importiere eine Liste oben.
</p>
)}
</div>