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

@@ -17,7 +17,8 @@
"better-sqlite3": "^11.3.0",
"dotenv": "^16.4.5",
"drizzle-orm": "^0.33.0",
"fastify": "^4.28.1"
"fastify": "^4.28.1",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@types/better-sqlite3": "^7.6.11",

View File

@@ -76,6 +76,22 @@ export function ensureSchema(): void {
message TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS bookmarks (
id TEXT PRIMARY KEY,
url TEXT NOT NULL,
display_name TEXT NOT NULL,
hostname TEXT NOT NULL,
description TEXT,
category TEXT,
icon TEXT,
favicon TEXT,
favorite INTEGER NOT NULL DEFAULT 0,
alias TEXT NOT NULL DEFAULT '[]',
"order" REAL NOT NULL DEFAULT 0,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
`);
// Leichte Migration für Datenbanken, die vor Einführung von "visible"

View File

@@ -0,0 +1,115 @@
import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import type { Bookmark, BookmarkCreateInput, BookmarkUpdateInput } from "@launchpad/shared";
import { db } from "../client.js";
import { bookmarks } from "../schema.js";
function nowIso(): string {
return new Date().toISOString();
}
function mapRow(row: typeof bookmarks.$inferSelect): Bookmark {
return {
id: row.id,
url: row.url,
displayName: row.displayName,
hostname: row.hostname,
description: row.description,
category: row.category,
icon: row.icon,
favicon: row.favicon,
favorite: row.favorite,
alias: JSON.parse(row.alias) as string[],
order: row.order,
};
}
export function extractHostname(url: string): string {
try {
return new URL(url).hostname;
} catch {
return url;
}
}
export function listBookmarks(): Bookmark[] {
return db.select().from(bookmarks).all().map(mapRow);
}
export function getBookmark(id: string): Bookmark | null {
const row = db.select().from(bookmarks).where(eq(bookmarks.id, id)).get();
return row ? mapRow(row) : null;
}
export interface CreateBookmarkOptions {
displayName: string;
favicon?: string | null;
}
export function createBookmark(
input: BookmarkCreateInput,
resolved: CreateBookmarkOptions
): Bookmark {
const id = randomUUID();
const timestamp = nowIso();
db.insert(bookmarks)
.values({
id,
url: input.url,
displayName: resolved.displayName,
hostname: extractHostname(input.url),
description: input.description ?? null,
category: input.category ?? null,
icon: input.icon ?? null,
favicon: resolved.favicon ?? null,
favorite: input.favorite ?? false,
alias: JSON.stringify(input.alias ?? []),
order: input.order ?? 0,
createdAt: timestamp,
updatedAt: timestamp,
})
.run();
return getBookmark(id)!;
}
export function updateBookmark(id: string, input: BookmarkUpdateInput): Bookmark | null {
const existing = getBookmark(id);
if (!existing) return null;
db.update(bookmarks)
.set({
...(input.url !== undefined && { url: input.url, hostname: extractHostname(input.url) }),
...(input.displayName !== undefined && { displayName: input.displayName }),
...(input.description !== undefined && { description: input.description }),
...(input.category !== undefined && { category: input.category }),
...(input.icon !== undefined && { icon: input.icon }),
...(input.favorite !== undefined && { favorite: input.favorite }),
...(input.alias !== undefined && { alias: JSON.stringify(input.alias) }),
...(input.order !== undefined && { order: input.order }),
updatedAt: nowIso(),
})
.where(eq(bookmarks.id, id))
.run();
return getBookmark(id);
}
export function deleteBookmark(id: string): boolean {
const result = db.delete(bookmarks).where(eq(bookmarks.id, id)).run();
return result.changes > 0;
}
export function reorderBookmarks(input: { id: string; order: number }[]): Bookmark[] {
db.transaction((tx) => {
for (const entry of input) {
tx.update(bookmarks)
.set({ order: entry.order, updatedAt: nowIso() })
.where(eq(bookmarks.id, entry.id))
.run();
}
});
return listBookmarks();
}

View File

@@ -75,3 +75,25 @@ export const scanLogs = sqliteTable("scan_logs", {
message: text("message").notNull(),
createdAt: text("created_at").notNull(),
});
/**
* Manuell angelegtes Lesezeichen im Unterschied zu Diensten nicht an ein
* gescanntes Gerät gebunden, eigenständige Tabelle. Erscheint zusammen mit
* Diensten in der Suche (siehe packages/shared rankServices), wird aber
* separat verwaltet (Admin -> Lesezeichen).
*/
export const bookmarks = sqliteTable("bookmarks", {
id: text("id").primaryKey(),
url: text("url").notNull(),
displayName: text("display_name").notNull(),
hostname: text("hostname").notNull(), // aus der URL abgeleitet
description: text("description"),
category: text("category"),
icon: text("icon"),
favicon: text("favicon"),
favorite: integer("favorite", { mode: "boolean" }).notNull().default(false),
alias: text("alias").notNull().default("[]"),
order: real("order").notNull().default(0),
createdAt: text("created_at").notNull(),
updatedAt: text("updated_at").notNull(),
});

View File

@@ -10,8 +10,10 @@ import { scanRoutes } from "./routes/scan.js";
import { logRoutes } from "./routes/logs.js";
import { pluginRoutes } from "./routes/plugins.js";
import { resetRoutes } from "./routes/reset.js";
import { bookmarkRoutes } from "./routes/bookmarks.js";
import { loadPlugins } from "./plugins/loader.js";
import * as serviceRepo from "./db/repositories/services.js";
import * as bookmarkRepo from "./db/repositories/bookmarks.js";
import * as categoryRepo from "./db/repositories/categories.js";
const PORT = Number(process.env.PORT ?? 3001);
@@ -40,10 +42,10 @@ async function main() {
// der Suche als Kategorie auftaucht.
const existingCategoryNames = Array.from(
new Set(
serviceRepo
.listServices()
.map((s) => s.category)
.filter((c): c is string => !!c)
[
...serviceRepo.listServices().map((s) => s.category),
...bookmarkRepo.listBookmarks().map((b) => b.category),
].filter((c): c is string => !!c)
)
);
const syncedCount = categoryRepo.syncCategoriesFromServiceValues(existingCategoryNames);
@@ -62,6 +64,7 @@ async function main() {
await app.register(logRoutes);
await app.register(pluginRoutes);
await app.register(resetRoutes);
await app.register(bookmarkRoutes);
app.get("/", async () => {
return { name: "LaunchPad API", status: "running" };

View File

@@ -0,0 +1,86 @@
import type { FastifyInstance } from "fastify";
import { BookmarkCreateSchema, BookmarkReorderSchema, BookmarkUpdateSchema } from "@launchpad/shared";
import * as bookmarkRepo from "../db/repositories/bookmarks.js";
import * as categoryRepo from "../db/repositories/categories.js";
import { probeHttp } from "../scanner/http.js";
export async function bookmarkRoutes(app: FastifyInstance): Promise<void> {
app.get("/api/bookmarks", async () => {
return bookmarkRepo.listBookmarks();
});
app.get("/api/bookmarks/:id", async (request, reply) => {
const { id } = request.params as { id: string };
const bookmark = bookmarkRepo.getBookmark(id);
if (!bookmark) {
return reply.code(404).send({ error: "Lesezeichen nicht gefunden" });
}
return bookmark;
});
app.post("/api/bookmarks", async (request, reply) => {
const parsed = BookmarkCreateSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: "Ungültige Eingabe", issues: parsed.error.issues });
}
let displayName = parsed.data.displayName;
let favicon: string | null = null;
// Titel/Favicon automatisch ziehen, falls kein Name angegeben wurde oder
// schlicht um ein Favicon zu bekommen (derselbe Mechanismus wie beim
// Netzwerk-Scanner, siehe apps/backend/src/scanner/http.ts).
try {
const probe = await probeHttp(parsed.data.url, 5000);
if (!displayName) {
displayName = probe.title ?? bookmarkRepo.extractHostname(parsed.data.url);
}
favicon = probe.faviconUrl ?? null;
} catch {
if (!displayName) {
displayName = bookmarkRepo.extractHostname(parsed.data.url);
}
}
if (parsed.data.category) {
categoryRepo.ensureCategory(parsed.data.category);
}
const bookmark = bookmarkRepo.createBookmark(parsed.data, { displayName, favicon });
return reply.code(201).send(bookmark);
});
// Muss vor der /:id-Route stehen, damit "reorder" nicht als ID interpretiert wird.
app.patch("/api/bookmarks/reorder", async (request, reply) => {
const parsed = BookmarkReorderSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: "Ungültige Eingabe", issues: parsed.error.issues });
}
return bookmarkRepo.reorderBookmarks(parsed.data);
});
app.patch("/api/bookmarks/:id", async (request, reply) => {
const { id } = request.params as { id: string };
const parsed = BookmarkUpdateSchema.safeParse(request.body);
if (!parsed.success) {
return reply.code(400).send({ error: "Ungültige Eingabe", issues: parsed.error.issues });
}
if (parsed.data.category) {
categoryRepo.ensureCategory(parsed.data.category);
}
const bookmark = bookmarkRepo.updateBookmark(id, parsed.data);
if (!bookmark) {
return reply.code(404).send({ error: "Lesezeichen nicht gefunden" });
}
return bookmark;
});
app.delete("/api/bookmarks/:id", async (request, reply) => {
const { id } = request.params as { id: string };
const deleted = bookmarkRepo.deleteBookmark(id);
if (!deleted) {
return reply.code(404).send({ error: "Lesezeichen nicht gefunden" });
}
return reply.code(204).send();
});
}

View File

@@ -58,17 +58,19 @@ export async function scanRoutes(app: FastifyInstance): Promise<void> {
const created = results.filter((r) => r.created).length;
const updated = results.filter((r) => !r.created).length;
const ports = discovered.map((d) => d.port).sort((a, b) => a - b);
logRepo.logScan({
type: "device",
targetId: device.id,
level: "info",
message: `${device.hostname} (${device.ip}): ${discovered.length} Dienst(e) gefunden, ${created} neu, ${updated} aktualisiert`,
message: `${device.hostname} (${device.ip}): ${discovered.length} Dienst(e) gefunden (Ports: ${ports.join(", ") || "keine"}), ${created} neu, ${updated} aktualisiert`,
});
return {
deviceId: device.id,
scannedPorts: discovered.length,
ports,
created,
updated,
services: results.map((r) => r.service),

View File

@@ -1,7 +1,9 @@
import type { FastifyInstance } from "fastify";
import * as XLSX from "xlsx";
import { ServiceCreateSchema, ServiceReorderSchema, ServiceUpdateSchema } from "@launchpad/shared";
import * as deviceRepo from "../db/repositories/devices.js";
import * as serviceRepo from "../db/repositories/services.js";
import * as categoryRepo from "../db/repositories/categories.js";
interface ServiceListQuery {
deviceId?: string;
@@ -9,6 +11,45 @@ interface ServiceListQuery {
favorite?: string;
}
interface ExportRow {
displayName: string;
category: string;
alias: string;
favorite: string;
visible: string;
order: number;
hostname: string;
port: number;
https: string;
url: string;
deviceHostname: string;
deviceIp: string;
}
function buildExportRows(): ExportRow[] {
const services = serviceRepo.listServices();
const devices = deviceRepo.listDevices();
const deviceById = new Map(devices.map((d) => [d.id, d]));
return services.map((s) => {
const device = deviceById.get(s.deviceId);
return {
displayName: s.displayName,
category: s.category ?? "",
alias: s.alias.join(";"),
favorite: s.favorite ? "true" : "false",
visible: s.visible ? "true" : "false",
order: s.order,
hostname: s.hostname,
port: s.port,
https: s.https ? "true" : "false",
url: s.url,
deviceHostname: device?.hostname ?? "",
deviceIp: device?.ip ?? "",
};
});
}
export async function serviceRoutes(app: FastifyInstance): Promise<void> {
app.get("/api/services", async (request) => {
const query = request.query as ServiceListQuery;
@@ -43,6 +84,136 @@ export async function serviceRoutes(app: FastifyInstance): Promise<void> {
return reply.code(201).send(service);
});
// Müssen vor der /:id-Route stehen, damit "export"/"import" nicht als ID interpretiert wird.
app.get("/api/services/export", async (request, reply) => {
const query = request.query as { format?: string };
const format = query.format === "xlsx" ? "xlsx" : query.format === "json" ? "json" : "csv";
const rows = buildExportRows();
if (format === "json") {
reply.header("Content-Disposition", 'attachment; filename="launchpad-services.json"');
reply.type("application/json");
return rows;
}
const worksheet = XLSX.utils.json_to_sheet(rows);
if (format === "xlsx") {
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, "Dienste");
const buffer = XLSX.write(workbook, { type: "buffer", bookType: "xlsx" }) as Buffer;
reply.header("Content-Disposition", 'attachment; filename="launchpad-services.xlsx"');
reply.type("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
return reply.send(buffer);
}
const csv = XLSX.utils.sheet_to_csv(worksheet);
reply.header("Content-Disposition", 'attachment; filename="launchpad-services.csv"');
reply.type("text/csv; charset=utf-8");
return reply.send(csv);
});
app.post("/api/services/import", async (request, reply) => {
const body = request.body as { format?: string; content?: string } | undefined;
if (!body?.content) {
return reply.code(400).send({ error: "Kein Dateiinhalt übermittelt" });
}
let rows: Record<string, unknown>[];
try {
if (body.format === "json") {
const text = Buffer.from(body.content, "base64").toString("utf-8");
rows = JSON.parse(text);
} else {
const buffer = Buffer.from(body.content, "base64");
const workbook = XLSX.read(buffer, { type: "buffer" });
const sheetName = workbook.SheetNames[0];
rows = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { defval: "" });
}
} catch (err) {
return reply.code(400).send({
error: "Datei konnte nicht gelesen werden",
detail: err instanceof Error ? err.message : String(err),
});
}
let imported = 0;
let skipped = 0;
const errors: string[] = [];
for (const row of rows) {
try {
const deviceHostname = String(row.deviceHostname ?? "").trim();
const deviceIp = String(row.deviceIp ?? "").trim();
const hostname = String(row.hostname ?? deviceHostname).trim();
const port = Number(row.port);
const displayName = String(row.displayName ?? "").trim();
const url = String(row.url ?? "").trim();
if (!displayName || !hostname || !port || !url) {
errors.push(`Zeile übersprungen (Pflichtfelder fehlen): ${JSON.stringify(row)}`);
continue;
}
// Gerät über IP finden, sonst über Hostname, sonst neu anlegen.
const allDevices = deviceRepo.listDevices();
let device = deviceIp ? allDevices.find((d) => d.ip === deviceIp) : undefined;
if (!device && deviceHostname) {
device = allDevices.find((d) => d.hostname === deviceHostname);
}
if (!device) {
device = deviceRepo.createDevice({
hostname: deviceHostname || hostname,
ip: deviceIp || hostname,
});
}
// Bereits vorhanden (gleiches Gerät + Port)? -> überspringen, nicht
// doppelt anlegen und nichts Bestehendes verändern/löschen.
const existing = serviceRepo.listServicesByDevice(device.id).find((s) => s.port === port);
if (existing) {
skipped++;
continue;
}
const category = row.category ? String(row.category).trim() : undefined;
serviceRepo.createService({
deviceId: device.id,
displayName,
hostname,
url,
https: String(row.https ?? "").toLowerCase() === "true",
port,
category: category || undefined,
alias: row.alias
? String(row.alias)
.split(";")
.map((a) => a.trim())
.filter(Boolean)
: undefined,
favorite: String(row.favorite ?? "").toLowerCase() === "true",
order:
row.order !== undefined && row.order !== "" ? Number(row.order) : undefined,
visible:
row.visible !== undefined && row.visible !== ""
? String(row.visible).toLowerCase() === "true"
: undefined,
});
if (category) {
categoryRepo.ensureCategory(category);
}
imported++;
} catch (err) {
errors.push(err instanceof Error ? err.message : String(err));
}
}
return { imported, skipped, errors };
});
// Muss vor der /:id-Route stehen, damit "reorder" nicht als ID interpretiert wird.
app.patch("/api/services/reorder", async (request, reply) => {
const parsed = ServiceReorderSchema.safeParse(request.body);

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>