generated from Dicken/dickendock
Bugfixes (Dark Mode, Dropdown-Kontrast, IP-Suche), Lesezeichen-Ausbau (Farbe, Beschreibung, Favicon), Zuletzt-besucht, Spaeter-lesen, kombinierter Import-Export, Scanner-Reconciliation, Admin-Ueberarbeitung
This commit is contained in:
39
README.md
39
README.md
@@ -199,32 +199,49 @@ POST /api/services erfordert existierende deviceId
|
|||||||
PATCH /api/services/reorder Body: [{ id, order }, ...]
|
PATCH /api/services/reorder Body: [{ id, order }, ...]
|
||||||
PATCH /api/services/:id
|
PATCH /api/services/:id
|
||||||
DELETE /api/services/:id
|
DELETE /api/services/:id
|
||||||
GET /api/services/export ?format=csv|xlsx|json (Default csv)
|
|
||||||
POST /api/services/import Body: { format, content: base64 }. Legt nur
|
|
||||||
neue Dienste an (Abgleich über Gerät+Port),
|
|
||||||
überschreibt/dupliziert nie Bestehendes.
|
|
||||||
|
|
||||||
GET /api/bookmarks
|
GET /api/bookmarks
|
||||||
POST /api/bookmarks Titel/Favicon werden automatisch geladen,
|
POST /api/bookmarks Titel/Favicon/Beschreibung werden automatisch
|
||||||
falls kein displayName angegeben ist
|
geladen, falls nicht angegeben
|
||||||
PATCH /api/bookmarks/reorder Body: [{ id, order }, ...]
|
PATCH /api/bookmarks/reorder Body: [{ id, order }, ...]
|
||||||
PATCH /api/bookmarks/:id
|
PATCH /api/bookmarks/:id
|
||||||
DELETE /api/bookmarks/:id
|
DELETE /api/bookmarks/:id
|
||||||
|
|
||||||
GET /api/categories
|
GET /api/categories
|
||||||
POST /api/categories
|
POST /api/categories optional color (Hex, z. B. "#3b82f6")
|
||||||
PATCH /api/categories/reorder Body: [{ id, order }, ...]
|
PATCH /api/categories/reorder Body: [{ id, order }, ...]
|
||||||
PATCH /api/categories/:id Umbenennen (aktualisiert automatisch alle Dienste mit altem Namen)
|
PATCH /api/categories/:id Umbenennen (aktualisiert automatisch alle Dienste mit altem Namen)
|
||||||
DELETE /api/categories/:id Dienste behalten ihre category nicht mehr (null),
|
DELETE /api/categories/:id Dienste behalten ihre category nicht mehr (null),
|
||||||
werden aber nicht gelöscht
|
werden aber nicht gelöscht
|
||||||
|
|
||||||
POST /api/scan/devices/:id Netzwerk-Scan für ein Gerät (DNS, Ports, Titel,
|
POST /api/scan/devices/:id Netzwerk-Scan für ein Gerät; Antwort enthält
|
||||||
Favicon, Softwareerkennung); legt/aktualisiert Dienste
|
zusätzlich staleServices (nicht mehr gefundene
|
||||||
POST /api/scan/fritzbox Liest Geräteliste der FritzBox per TR-064
|
Dienste, werden NICHT automatisch gelöscht)
|
||||||
(erfordert FRITZBOX_HOST/USERNAME/PASSWORD)
|
POST /api/scan/fritzbox Liest Geräteliste der FritzBox per TR-064;
|
||||||
|
Antwort enthält zusätzlich staleDevices
|
||||||
|
|
||||||
GET /api/logs optional ?limit= (Default 100, Max 500)
|
GET /api/logs optional ?limit= (Default 100, Max 500)
|
||||||
|
|
||||||
|
GET /api/transfer/export ?format=csv|xlsx|json (Default csv). Geräte
|
||||||
|
UND Dienste in einer Datei, Spalte "type"
|
||||||
|
unterscheidet die Zeilen.
|
||||||
|
POST /api/transfer/import Body: { format, content: base64 }. Legt nur
|
||||||
|
neue Geräte/Dienste an, überschreibt/
|
||||||
|
dupliziert nie Bestehendes.
|
||||||
|
|
||||||
|
GET /api/recent-visits optional ?limit=
|
||||||
|
POST /api/recent-visits Body: { itemType: "service"|"bookmark", itemId }
|
||||||
|
DELETE /api/recent-visits
|
||||||
|
|
||||||
|
GET /api/settings
|
||||||
|
PATCH /api/settings Body: { recentVisitsLimit }
|
||||||
|
|
||||||
|
GET /api/read-later
|
||||||
|
POST /api/read-later Titel/Favicon werden automatisch geladen
|
||||||
|
PATCH /api/read-later/:id
|
||||||
|
DELETE /api/read-later/:id
|
||||||
|
POST /api/read-later/:id/promote verschiebt zu Lesezeichen (als Favorit)
|
||||||
|
|
||||||
POST /api/reset Löscht ALLE Geräte + Dienste (Cascade). Erfordert
|
POST /api/reset Löscht ALLE Geräte + Dienste (Cascade). Erfordert
|
||||||
Body { "confirm": true }, sonst 400.
|
Body { "confirm": true }, sonst 400.
|
||||||
|
|
||||||
|
|||||||
@@ -64,6 +64,7 @@ export function ensureSchema(): void {
|
|||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
name TEXT NOT NULL,
|
name TEXT NOT NULL,
|
||||||
"order" REAL NOT NULL DEFAULT 0,
|
"order" REAL NOT NULL DEFAULT 0,
|
||||||
|
color TEXT,
|
||||||
created_at TEXT NOT NULL,
|
created_at TEXT NOT NULL,
|
||||||
updated_at TEXT NOT NULL
|
updated_at TEXT NOT NULL
|
||||||
);
|
);
|
||||||
@@ -92,14 +93,36 @@ export function ensureSchema(): void {
|
|||||||
created_at TEXT NOT NULL,
|
created_at TEXT NOT NULL,
|
||||||
updated_at TEXT NOT NULL
|
updated_at TEXT NOT NULL
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS recent_visits (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
item_type TEXT NOT NULL,
|
||||||
|
item_id TEXT NOT NULL,
|
||||||
|
visited_at TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS app_settings (
|
||||||
|
key TEXT PRIMARY KEY,
|
||||||
|
value TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS read_later (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
url TEXT NOT NULL,
|
||||||
|
display_name TEXT NOT NULL,
|
||||||
|
favicon TEXT,
|
||||||
|
saved_at TEXT NOT NULL,
|
||||||
|
updated_at TEXT NOT NULL
|
||||||
|
);
|
||||||
`);
|
`);
|
||||||
|
|
||||||
// Leichte Migration für Datenbanken, die vor Einführung von "visible"
|
// Leichte Migration für Datenbanken, die vor Einführung von "visible"/
|
||||||
// angelegt wurden: CREATE TABLE IF NOT EXISTS rüstet bei bereits
|
// "color" angelegt wurden: CREATE TABLE IF NOT EXISTS rüstet bei bereits
|
||||||
// existierenden Tabellen keine neuen Spalten nach, das übernehmen wir hier
|
// existierenden Tabellen keine neuen Spalten nach, das übernehmen wir hier
|
||||||
// manuell. Bestehende Dienste werden dabei auf sichtbar (1) gesetzt, damit
|
// manuell. Bestehende Dienste werden dabei auf sichtbar (1) gesetzt, damit
|
||||||
// sich am bisherigen Verhalten nichts unerwartet ändert.
|
// sich am bisherigen Verhalten nichts unerwartet ändert.
|
||||||
ensureColumn("services", "visible", "INTEGER NOT NULL DEFAULT 1");
|
ensureColumn("services", "visible", "INTEGER NOT NULL DEFAULT 1");
|
||||||
|
ensureColumn("categories", "color", "TEXT");
|
||||||
}
|
}
|
||||||
|
|
||||||
function ensureColumn(table: string, column: string, definition: string): void {
|
function ensureColumn(table: string, column: string, definition: string): void {
|
||||||
|
|||||||
@@ -85,6 +85,7 @@ export function updateBookmark(id: string, input: BookmarkUpdateInput): Bookmark
|
|||||||
...(input.description !== undefined && { description: input.description }),
|
...(input.description !== undefined && { description: input.description }),
|
||||||
...(input.category !== undefined && { category: input.category }),
|
...(input.category !== undefined && { category: input.category }),
|
||||||
...(input.icon !== undefined && { icon: input.icon }),
|
...(input.icon !== undefined && { icon: input.icon }),
|
||||||
|
...(input.favicon !== undefined && { favicon: input.favicon }),
|
||||||
...(input.favorite !== undefined && { favorite: input.favorite }),
|
...(input.favorite !== undefined && { favorite: input.favorite }),
|
||||||
...(input.alias !== undefined && { alias: JSON.stringify(input.alias) }),
|
...(input.alias !== undefined && { alias: JSON.stringify(input.alias) }),
|
||||||
...(input.order !== undefined && { order: input.order }),
|
...(input.order !== undefined && { order: input.order }),
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ function nowIso(): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function mapRow(row: typeof categories.$inferSelect): Category {
|
function mapRow(row: typeof categories.$inferSelect): Category {
|
||||||
return { id: row.id, name: row.name, order: row.order };
|
return { id: row.id, name: row.name, order: row.order, color: row.color };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function listCategories(): Category[] {
|
export function listCategories(): Category[] {
|
||||||
@@ -42,6 +42,7 @@ export function createCategory(input: CategoryCreateInput): Category {
|
|||||||
id,
|
id,
|
||||||
name: input.name,
|
name: input.name,
|
||||||
order: nextOrder,
|
order: nextOrder,
|
||||||
|
color: input.color ?? null,
|
||||||
createdAt: timestamp,
|
createdAt: timestamp,
|
||||||
updatedAt: timestamp,
|
updatedAt: timestamp,
|
||||||
})
|
})
|
||||||
@@ -71,6 +72,7 @@ export function updateCategory(id: string, input: CategoryUpdateInput): Category
|
|||||||
db.update(categories)
|
db.update(categories)
|
||||||
.set({
|
.set({
|
||||||
...(input.name !== undefined && { name: input.name }),
|
...(input.name !== undefined && { name: input.name }),
|
||||||
|
...(input.color !== undefined && { color: input.color }),
|
||||||
updatedAt: timestamp,
|
updatedAt: timestamp,
|
||||||
})
|
})
|
||||||
.where(eq(categories.id, id))
|
.where(eq(categories.id, id))
|
||||||
|
|||||||
77
apps/backend/src/db/repositories/readLater.ts
Normal file
77
apps/backend/src/db/repositories/readLater.ts
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { desc, eq } from "drizzle-orm";
|
||||||
|
import { db } from "../client.js";
|
||||||
|
import { readLater } from "../schema.js";
|
||||||
|
|
||||||
|
export interface ReadLaterItem {
|
||||||
|
id: string;
|
||||||
|
url: string;
|
||||||
|
displayName: string;
|
||||||
|
favicon: string | null;
|
||||||
|
savedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapRow(row: typeof readLater.$inferSelect): ReadLaterItem {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
url: row.url,
|
||||||
|
displayName: row.displayName,
|
||||||
|
favicon: row.favicon,
|
||||||
|
savedAt: row.savedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listReadLater(): ReadLaterItem[] {
|
||||||
|
return db.select().from(readLater).orderBy(desc(readLater.savedAt)).all().map(mapRow);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getReadLaterItem(id: string): ReadLaterItem | null {
|
||||||
|
const row = db.select().from(readLater).where(eq(readLater.id, id)).get();
|
||||||
|
return row ? mapRow(row) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createReadLaterItem(input: {
|
||||||
|
url: string;
|
||||||
|
displayName: string;
|
||||||
|
favicon?: string | null;
|
||||||
|
}): ReadLaterItem {
|
||||||
|
const id = randomUUID();
|
||||||
|
const timestamp = new Date().toISOString();
|
||||||
|
|
||||||
|
db.insert(readLater)
|
||||||
|
.values({
|
||||||
|
id,
|
||||||
|
url: input.url,
|
||||||
|
displayName: input.displayName,
|
||||||
|
favicon: input.favicon ?? null,
|
||||||
|
savedAt: timestamp,
|
||||||
|
updatedAt: timestamp,
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
|
||||||
|
return getReadLaterItem(id)!;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function updateReadLaterItem(
|
||||||
|
id: string,
|
||||||
|
input: { url?: string; displayName?: string }
|
||||||
|
): ReadLaterItem | null {
|
||||||
|
const existing = getReadLaterItem(id);
|
||||||
|
if (!existing) return null;
|
||||||
|
|
||||||
|
db.update(readLater)
|
||||||
|
.set({
|
||||||
|
...(input.url !== undefined && { url: input.url }),
|
||||||
|
...(input.displayName !== undefined && { displayName: input.displayName }),
|
||||||
|
updatedAt: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.where(eq(readLater.id, id))
|
||||||
|
.run();
|
||||||
|
|
||||||
|
return getReadLaterItem(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function deleteReadLaterItem(id: string): boolean {
|
||||||
|
const result = db.delete(readLater).where(eq(readLater.id, id)).run();
|
||||||
|
return result.changes > 0;
|
||||||
|
}
|
||||||
78
apps/backend/src/db/repositories/recentVisits.ts
Normal file
78
apps/backend/src/db/repositories/recentVisits.ts
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
import { randomUUID } from "node:crypto";
|
||||||
|
import { desc, eq } from "drizzle-orm";
|
||||||
|
import type { Bookmark, Service } from "@launchpad/shared";
|
||||||
|
import { db } from "../client.js";
|
||||||
|
import { recentVisits } from "../schema.js";
|
||||||
|
import * as serviceRepo from "./services.js";
|
||||||
|
import * as bookmarkRepo from "./bookmarks.js";
|
||||||
|
import { getSetting } from "./settings.js";
|
||||||
|
|
||||||
|
export type VisitedItem = (Service & { kind: "service" }) | (Bookmark & { kind: "bookmark" });
|
||||||
|
|
||||||
|
export function recordVisit(itemType: "service" | "bookmark", itemId: string): void {
|
||||||
|
db.insert(recentVisits)
|
||||||
|
.values({
|
||||||
|
id: randomUUID(),
|
||||||
|
itemType,
|
||||||
|
itemId,
|
||||||
|
visitedAt: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
.run();
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_LIMIT = 5;
|
||||||
|
|
||||||
|
export function getRecentVisitsLimit(): number {
|
||||||
|
const stored = getSetting("recentVisitsLimit");
|
||||||
|
const parsed = stored ? Number(stored) : DEFAULT_LIMIT;
|
||||||
|
return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_LIMIT;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Liefert die zuletzt besuchten Dienste/Lesezeichen, jedes Element nur
|
||||||
|
* einmal (neuester Besuch zählt), aufgelöst zu den echten Objekten. Bereits
|
||||||
|
* gelöschte Ziele werden übersprungen. Limit kommt aus den Einstellungen
|
||||||
|
* (Admin -> Einstellungen), Default 5.
|
||||||
|
*/
|
||||||
|
export function listRecentVisits(limitOverride?: number): VisitedItem[] {
|
||||||
|
const limit = limitOverride ?? getRecentVisitsLimit();
|
||||||
|
|
||||||
|
// Etwas mehr als das Limit an Rohzeilen lesen, falls Duplikate/gelöschte
|
||||||
|
// Ziele darunter sind – reicht in der Praxis (Homelab-Größenordnung) locker.
|
||||||
|
const rows = db
|
||||||
|
.select()
|
||||||
|
.from(recentVisits)
|
||||||
|
.orderBy(desc(recentVisits.visitedAt))
|
||||||
|
.limit(limit * 5 + 20)
|
||||||
|
.all();
|
||||||
|
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const result: VisitedItem[] = [];
|
||||||
|
|
||||||
|
for (const row of rows) {
|
||||||
|
const key = `${row.itemType}:${row.itemId}`;
|
||||||
|
if (seen.has(key)) continue;
|
||||||
|
seen.add(key);
|
||||||
|
|
||||||
|
if (row.itemType === "service") {
|
||||||
|
const service = serviceRepo.getService(row.itemId);
|
||||||
|
if (service) result.push({ ...service, kind: "service" });
|
||||||
|
} else if (row.itemType === "bookmark") {
|
||||||
|
const bookmark = bookmarkRepo.getBookmark(row.itemId);
|
||||||
|
if (bookmark) result.push({ ...bookmark, kind: "bookmark" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.length >= limit) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function clearRecentVisits(): void {
|
||||||
|
db.delete(recentVisits).run();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Räumt Verweise auf eine gelöschte Ressource auf (verhindert totes Wachstum). */
|
||||||
|
export function pruneVisitsFor(itemId: string): void {
|
||||||
|
db.delete(recentVisits).where(eq(recentVisits.itemId, itemId)).run();
|
||||||
|
}
|
||||||
22
apps/backend/src/db/repositories/settings.ts
Normal file
22
apps/backend/src/db/repositories/settings.ts
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { db } from "../client.js";
|
||||||
|
import { appSettings } from "../schema.js";
|
||||||
|
|
||||||
|
export function getSetting(key: string): string | null {
|
||||||
|
const row = db.select().from(appSettings).where(eq(appSettings.key, key)).get();
|
||||||
|
return row?.value ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setSetting(key: string, value: string): void {
|
||||||
|
const existing = getSetting(key);
|
||||||
|
if (existing === null) {
|
||||||
|
db.insert(appSettings).values({ key, value }).run();
|
||||||
|
} else {
|
||||||
|
db.update(appSettings).set({ value }).where(eq(appSettings.key, key)).run();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function listSettings(): Record<string, string> {
|
||||||
|
const rows = db.select().from(appSettings).all();
|
||||||
|
return Object.fromEntries(rows.map((r) => [r.key, r.value]));
|
||||||
|
}
|
||||||
@@ -59,6 +59,7 @@ export const categories = sqliteTable("categories", {
|
|||||||
id: text("id").primaryKey(),
|
id: text("id").primaryKey(),
|
||||||
name: text("name").notNull(),
|
name: text("name").notNull(),
|
||||||
order: real("order").notNull().default(0),
|
order: real("order").notNull().default(0),
|
||||||
|
color: text("color"),
|
||||||
createdAt: text("created_at").notNull(),
|
createdAt: text("created_at").notNull(),
|
||||||
updatedAt: text("updated_at").notNull(),
|
updatedAt: text("updated_at").notNull(),
|
||||||
});
|
});
|
||||||
@@ -97,3 +98,34 @@ export const bookmarks = sqliteTable("bookmarks", {
|
|||||||
createdAt: text("created_at").notNull(),
|
createdAt: text("created_at").notNull(),
|
||||||
updatedAt: text("updated_at").notNull(),
|
updatedAt: text("updated_at").notNull(),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Zuletzt aus der Suche geöffnete Dienste/Lesezeichen, für die
|
||||||
|
* "Zuletzt besucht"-Leiste auf der Startseite.
|
||||||
|
*/
|
||||||
|
export const recentVisits = sqliteTable("recent_visits", {
|
||||||
|
id: text("id").primaryKey(),
|
||||||
|
itemType: text("item_type").notNull(), // "service" | "bookmark"
|
||||||
|
itemId: text("item_id").notNull(),
|
||||||
|
visitedAt: text("visited_at").notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Freie Schlüssel-Wert-Einstellungen, z. B. Anzahl "Zuletzt besucht". */
|
||||||
|
export const appSettings = sqliteTable("app_settings", {
|
||||||
|
key: text("key").primaryKey(),
|
||||||
|
value: text("value").notNull(),
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Später lesen": schnell von der Startseite abgelegte Links, unabhängig
|
||||||
|
* von Lesezeichen/Diensten. Können später zu einem Lesezeichen befördert
|
||||||
|
* oder gelöscht werden.
|
||||||
|
*/
|
||||||
|
export const readLater = sqliteTable("read_later", {
|
||||||
|
id: text("id").primaryKey(),
|
||||||
|
url: text("url").notNull(),
|
||||||
|
displayName: text("display_name").notNull(),
|
||||||
|
favicon: text("favicon"),
|
||||||
|
savedAt: text("saved_at").notNull(),
|
||||||
|
updatedAt: text("updated_at").notNull(),
|
||||||
|
});
|
||||||
|
|||||||
@@ -10,7 +10,11 @@ import { scanRoutes } from "./routes/scan.js";
|
|||||||
import { logRoutes } from "./routes/logs.js";
|
import { logRoutes } from "./routes/logs.js";
|
||||||
import { pluginRoutes } from "./routes/plugins.js";
|
import { pluginRoutes } from "./routes/plugins.js";
|
||||||
import { resetRoutes } from "./routes/reset.js";
|
import { resetRoutes } from "./routes/reset.js";
|
||||||
|
import { transferRoutes } from "./routes/transfer.js";
|
||||||
import { bookmarkRoutes } from "./routes/bookmarks.js";
|
import { bookmarkRoutes } from "./routes/bookmarks.js";
|
||||||
|
import { recentVisitsRoutes } from "./routes/recentVisits.js";
|
||||||
|
import { settingsRoutes } from "./routes/settings.js";
|
||||||
|
import { readLaterRoutes } from "./routes/readLater.js";
|
||||||
import { loadPlugins } from "./plugins/loader.js";
|
import { loadPlugins } from "./plugins/loader.js";
|
||||||
import * as serviceRepo from "./db/repositories/services.js";
|
import * as serviceRepo from "./db/repositories/services.js";
|
||||||
import * as bookmarkRepo from "./db/repositories/bookmarks.js";
|
import * as bookmarkRepo from "./db/repositories/bookmarks.js";
|
||||||
@@ -64,7 +68,11 @@ async function main() {
|
|||||||
await app.register(logRoutes);
|
await app.register(logRoutes);
|
||||||
await app.register(pluginRoutes);
|
await app.register(pluginRoutes);
|
||||||
await app.register(resetRoutes);
|
await app.register(resetRoutes);
|
||||||
|
await app.register(transferRoutes);
|
||||||
await app.register(bookmarkRoutes);
|
await app.register(bookmarkRoutes);
|
||||||
|
await app.register(recentVisitsRoutes);
|
||||||
|
await app.register(settingsRoutes);
|
||||||
|
await app.register(readLaterRoutes);
|
||||||
|
|
||||||
app.get("/", async () => {
|
app.get("/", async () => {
|
||||||
return { name: "LaunchPad API", status: "running" };
|
return { name: "LaunchPad API", status: "running" };
|
||||||
|
|||||||
@@ -26,15 +26,19 @@ export async function bookmarkRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
|
|
||||||
let displayName = parsed.data.displayName;
|
let displayName = parsed.data.displayName;
|
||||||
let favicon: string | null = null;
|
let favicon: string | null = null;
|
||||||
|
let description = parsed.data.description;
|
||||||
|
|
||||||
// Titel/Favicon automatisch ziehen, falls kein Name angegeben wurde oder
|
// Titel/Favicon/Beschreibung automatisch ziehen, falls nicht angegeben
|
||||||
// schlicht um ein Favicon zu bekommen (derselbe Mechanismus wie beim
|
// (derselbe Mechanismus wie beim Netzwerk-Scanner, siehe
|
||||||
// Netzwerk-Scanner, siehe apps/backend/src/scanner/http.ts).
|
// apps/backend/src/scanner/http.ts).
|
||||||
try {
|
try {
|
||||||
const probe = await probeHttp(parsed.data.url, 5000);
|
const probe = await probeHttp(parsed.data.url, 5000);
|
||||||
if (!displayName) {
|
if (!displayName) {
|
||||||
displayName = probe.title ?? bookmarkRepo.extractHostname(parsed.data.url);
|
displayName = probe.title ?? bookmarkRepo.extractHostname(parsed.data.url);
|
||||||
}
|
}
|
||||||
|
if (!description) {
|
||||||
|
description = probe.description;
|
||||||
|
}
|
||||||
favicon = probe.faviconUrl ?? null;
|
favicon = probe.faviconUrl ?? null;
|
||||||
} catch {
|
} catch {
|
||||||
if (!displayName) {
|
if (!displayName) {
|
||||||
@@ -46,7 +50,10 @@ export async function bookmarkRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
categoryRepo.ensureCategory(parsed.data.category);
|
categoryRepo.ensureCategory(parsed.data.category);
|
||||||
}
|
}
|
||||||
|
|
||||||
const bookmark = bookmarkRepo.createBookmark(parsed.data, { displayName, favicon });
|
const bookmark = bookmarkRepo.createBookmark(
|
||||||
|
{ ...parsed.data, description },
|
||||||
|
{ displayName, favicon }
|
||||||
|
);
|
||||||
return reply.code(201).send(bookmark);
|
return reply.code(201).send(bookmark);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
71
apps/backend/src/routes/readLater.ts
Normal file
71
apps/backend/src/routes/readLater.ts
Normal file
@@ -0,0 +1,71 @@
|
|||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import * as readLaterRepo from "../db/repositories/readLater.js";
|
||||||
|
import * as bookmarkRepo from "../db/repositories/bookmarks.js";
|
||||||
|
import { probeHttp } from "../scanner/http.js";
|
||||||
|
|
||||||
|
export async function readLaterRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
app.get("/api/read-later", async () => {
|
||||||
|
return readLaterRepo.listReadLater();
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/read-later", async (request, reply) => {
|
||||||
|
const body = request.body as { url?: string } | undefined;
|
||||||
|
if (!body?.url) {
|
||||||
|
return reply.code(400).send({ error: "url erforderlich" });
|
||||||
|
}
|
||||||
|
|
||||||
|
let name: string;
|
||||||
|
let favicon: string | null = null;
|
||||||
|
try {
|
||||||
|
const probe = await probeHttp(body.url, 5000);
|
||||||
|
name = probe.title ?? new URL(body.url).hostname;
|
||||||
|
favicon = probe.faviconUrl ?? null;
|
||||||
|
} catch {
|
||||||
|
try {
|
||||||
|
name = new URL(body.url).hostname;
|
||||||
|
} catch {
|
||||||
|
name = body.url;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const item = readLaterRepo.createReadLaterItem({ url: body.url, displayName: name, favicon });
|
||||||
|
return reply.code(201).send(item);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.patch("/api/read-later/:id", async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string };
|
||||||
|
const body = request.body as { url?: string; displayName?: string } | undefined;
|
||||||
|
const item = readLaterRepo.updateReadLaterItem(id, body ?? {});
|
||||||
|
if (!item) {
|
||||||
|
return reply.code(404).send({ error: "Eintrag nicht gefunden" });
|
||||||
|
}
|
||||||
|
return item;
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete("/api/read-later/:id", async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string };
|
||||||
|
const deleted = readLaterRepo.deleteReadLaterItem(id);
|
||||||
|
if (!deleted) {
|
||||||
|
return reply.code(404).send({ error: "Eintrag nicht gefunden" });
|
||||||
|
}
|
||||||
|
return reply.code(204).send();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Verschiebt einen "Später lesen"-Eintrag in die Lesezeichen (als Favorit)
|
||||||
|
// und entfernt ihn aus der Liste.
|
||||||
|
app.post("/api/read-later/:id/promote", async (request, reply) => {
|
||||||
|
const { id } = request.params as { id: string };
|
||||||
|
const item = readLaterRepo.getReadLaterItem(id);
|
||||||
|
if (!item) {
|
||||||
|
return reply.code(404).send({ error: "Eintrag nicht gefunden" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const bookmark = bookmarkRepo.createBookmark(
|
||||||
|
{ url: item.url, favorite: true },
|
||||||
|
{ displayName: item.displayName, favicon: item.favicon }
|
||||||
|
);
|
||||||
|
readLaterRepo.deleteReadLaterItem(id);
|
||||||
|
|
||||||
|
return reply.code(201).send(bookmark);
|
||||||
|
});
|
||||||
|
}
|
||||||
27
apps/backend/src/routes/recentVisits.ts
Normal file
27
apps/backend/src/routes/recentVisits.ts
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import * as recentVisitsRepo from "../db/repositories/recentVisits.js";
|
||||||
|
|
||||||
|
export async function recentVisitsRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
app.get("/api/recent-visits", async (request) => {
|
||||||
|
const query = request.query as { limit?: string };
|
||||||
|
const limit = query.limit ? Number(query.limit) : undefined;
|
||||||
|
return recentVisitsRepo.listRecentVisits(limit);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/recent-visits", async (request, reply) => {
|
||||||
|
const body = request.body as { itemType?: string; itemId?: string } | undefined;
|
||||||
|
if (body?.itemType !== "service" && body?.itemType !== "bookmark") {
|
||||||
|
return reply.code(400).send({ error: "itemType muss 'service' oder 'bookmark' sein" });
|
||||||
|
}
|
||||||
|
if (!body.itemId) {
|
||||||
|
return reply.code(400).send({ error: "itemId erforderlich" });
|
||||||
|
}
|
||||||
|
recentVisitsRepo.recordVisit(body.itemType, body.itemId);
|
||||||
|
return reply.code(201).send({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
app.delete("/api/recent-visits", async () => {
|
||||||
|
recentVisitsRepo.clearRecentVisits();
|
||||||
|
return { ok: true };
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -21,6 +21,10 @@ export async function scanRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Bestehende Dienste dieses Geräts VOR dem Scan merken, um danach zu
|
||||||
|
// erkennen, welche davon diesmal nicht mehr gefunden wurden ("stale").
|
||||||
|
const servicesBeforeScan = serviceRepo.listServicesByDevice(device.id);
|
||||||
|
|
||||||
const discovered = await scanDeviceServices(device);
|
const discovered = await scanDeviceServices(device);
|
||||||
|
|
||||||
// Jede erkannte Kategorie auch in der categories-Tabelle anlegen, damit
|
// Jede erkannte Kategorie auch in der categories-Tabelle anlegen, damit
|
||||||
@@ -60,11 +64,17 @@ export async function scanRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
const updated = 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);
|
const ports = discovered.map((d) => d.port).sort((a, b) => a - b);
|
||||||
|
|
||||||
|
// Dienste, die es vorher gab, aber diesmal nicht mehr gefunden wurden
|
||||||
|
// (Port nicht mehr offen) – werden NICHT automatisch gelöscht, sondern
|
||||||
|
// zur manuellen Durchsicht zurückgegeben (siehe Admin -> Scanner).
|
||||||
|
const foundPorts = new Set(discovered.map((d) => d.port));
|
||||||
|
const staleServices = servicesBeforeScan.filter((s) => !foundPorts.has(s.port));
|
||||||
|
|
||||||
logRepo.logScan({
|
logRepo.logScan({
|
||||||
type: "device",
|
type: "device",
|
||||||
targetId: device.id,
|
targetId: device.id,
|
||||||
level: "info",
|
level: "info",
|
||||||
message: `${device.hostname} (${device.ip}): ${discovered.length} Dienst(e) gefunden (Ports: ${ports.join(", ") || "keine"}), ${created} neu, ${updated} aktualisiert`,
|
message: `${device.hostname} (${device.ip}): ${discovered.length} Dienst(e) gefunden (Ports: ${ports.join(", ") || "keine"}), ${created} neu, ${updated} aktualisiert${staleServices.length > 0 ? `, ${staleServices.length} nicht mehr gefunden` : ""}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -74,6 +84,7 @@ export async function scanRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
created,
|
created,
|
||||||
updated,
|
updated,
|
||||||
services: results.map((r) => r.service),
|
services: results.map((r) => r.service),
|
||||||
|
staleServices,
|
||||||
};
|
};
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const detail = err instanceof Error ? err.message : String(err);
|
const detail = err instanceof Error ? err.message : String(err);
|
||||||
@@ -106,6 +117,8 @@ export async function scanRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
const port = process.env.FRITZBOX_PORT ? Number(process.env.FRITZBOX_PORT) : 49000;
|
const port = process.env.FRITZBOX_PORT ? Number(process.env.FRITZBOX_PORT) : 49000;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
const devicesBeforeScan = deviceRepo.listDevices().filter((d) => d.source === "fritzbox");
|
||||||
|
|
||||||
const hosts = await fetchFritzBoxHosts({ host, port, username, password });
|
const hosts = await fetchFritzBoxHosts({ host, port, username, password });
|
||||||
const devices = hosts.map((h) =>
|
const devices = hosts.map((h) =>
|
||||||
deviceRepo.upsertDeviceFromScan({
|
deviceRepo.upsertDeviceFromScan({
|
||||||
@@ -117,13 +130,19 @@ export async function scanRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// Geräte, die die FritzBox früher gemeldet hatte, diesmal aber nicht
|
||||||
|
// mehr in der Liste sind – nicht automatisch gelöscht, nur zur
|
||||||
|
// manuellen Durchsicht zurückgegeben.
|
||||||
|
const foundIps = new Set(hosts.map((h) => h.ip));
|
||||||
|
const staleDevices = devicesBeforeScan.filter((d) => !foundIps.has(d.ip));
|
||||||
|
|
||||||
logRepo.logScan({
|
logRepo.logScan({
|
||||||
type: "fritzbox",
|
type: "fritzbox",
|
||||||
level: "info",
|
level: "info",
|
||||||
message: `FritzBox-Scan: ${hosts.length} Gerät(e) gefunden`,
|
message: `FritzBox-Scan: ${hosts.length} Gerät(e) gefunden${staleDevices.length > 0 ? `, ${staleDevices.length} nicht mehr gemeldet` : ""}`,
|
||||||
});
|
});
|
||||||
|
|
||||||
return { found: hosts.length, devices };
|
return { found: hosts.length, devices, staleDevices };
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const detail = err instanceof Error ? err.message : String(err);
|
const detail = err instanceof Error ? err.message : String(err);
|
||||||
logRepo.logScan({
|
logRepo.logScan({
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import type { FastifyInstance } from "fastify";
|
import type { FastifyInstance } from "fastify";
|
||||||
import * as XLSX from "xlsx";
|
|
||||||
import { ServiceCreateSchema, ServiceReorderSchema, ServiceUpdateSchema } from "@launchpad/shared";
|
import { ServiceCreateSchema, ServiceReorderSchema, ServiceUpdateSchema } from "@launchpad/shared";
|
||||||
import * as deviceRepo from "../db/repositories/devices.js";
|
import * as deviceRepo from "../db/repositories/devices.js";
|
||||||
import * as serviceRepo from "../db/repositories/services.js";
|
import * as serviceRepo from "../db/repositories/services.js";
|
||||||
import * as categoryRepo from "../db/repositories/categories.js";
|
|
||||||
|
|
||||||
interface ServiceListQuery {
|
interface ServiceListQuery {
|
||||||
deviceId?: string;
|
deviceId?: string;
|
||||||
@@ -11,45 +9,6 @@ interface ServiceListQuery {
|
|||||||
favorite?: string;
|
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> {
|
export async function serviceRoutes(app: FastifyInstance): Promise<void> {
|
||||||
app.get("/api/services", async (request) => {
|
app.get("/api/services", async (request) => {
|
||||||
const query = request.query as ServiceListQuery;
|
const query = request.query as ServiceListQuery;
|
||||||
@@ -84,136 +43,6 @@ export async function serviceRoutes(app: FastifyInstance): Promise<void> {
|
|||||||
return reply.code(201).send(service);
|
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.
|
// Muss vor der /:id-Route stehen, damit "reorder" nicht als ID interpretiert wird.
|
||||||
app.patch("/api/services/reorder", async (request, reply) => {
|
app.patch("/api/services/reorder", async (request, reply) => {
|
||||||
const parsed = ServiceReorderSchema.safeParse(request.body);
|
const parsed = ServiceReorderSchema.safeParse(request.body);
|
||||||
|
|||||||
26
apps/backend/src/routes/settings.ts
Normal file
26
apps/backend/src/routes/settings.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import * as settingsRepo from "../db/repositories/settings.js";
|
||||||
|
|
||||||
|
export async function settingsRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
app.get("/api/settings", async () => {
|
||||||
|
const all = settingsRepo.listSettings();
|
||||||
|
return {
|
||||||
|
recentVisitsLimit: Number(all.recentVisitsLimit ?? 5),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
app.patch("/api/settings", async (request, reply) => {
|
||||||
|
const body = request.body as { recentVisitsLimit?: number } | undefined;
|
||||||
|
|
||||||
|
if (body?.recentVisitsLimit !== undefined) {
|
||||||
|
const value = Number(body.recentVisitsLimit);
|
||||||
|
if (!Number.isFinite(value) || value < 0 || value > 50) {
|
||||||
|
return reply.code(400).send({ error: "recentVisitsLimit muss zwischen 0 und 50 liegen" });
|
||||||
|
}
|
||||||
|
settingsRepo.setSetting("recentVisitsLimit", String(Math.round(value)));
|
||||||
|
}
|
||||||
|
|
||||||
|
const all = settingsRepo.listSettings();
|
||||||
|
return { recentVisitsLimit: Number(all.recentVisitsLimit ?? 5) };
|
||||||
|
});
|
||||||
|
}
|
||||||
250
apps/backend/src/routes/transfer.ts
Normal file
250
apps/backend/src/routes/transfer.ts
Normal file
@@ -0,0 +1,250 @@
|
|||||||
|
import type { FastifyInstance } from "fastify";
|
||||||
|
import * as XLSX from "xlsx";
|
||||||
|
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 TransferRow {
|
||||||
|
type: "device" | "service";
|
||||||
|
displayName: string;
|
||||||
|
hostname: string;
|
||||||
|
ip: string;
|
||||||
|
mac: string;
|
||||||
|
manufacturer: string;
|
||||||
|
model: string;
|
||||||
|
category: string;
|
||||||
|
alias: string;
|
||||||
|
favorite: string;
|
||||||
|
visible: string;
|
||||||
|
order: number | string;
|
||||||
|
port: string | number;
|
||||||
|
https: string;
|
||||||
|
url: string;
|
||||||
|
deviceHostname: string;
|
||||||
|
deviceIp: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildExportRows(): TransferRow[] {
|
||||||
|
const devices = deviceRepo.listDevices();
|
||||||
|
const services = serviceRepo.listServices();
|
||||||
|
const deviceById = new Map(devices.map((d) => [d.id, d]));
|
||||||
|
|
||||||
|
const deviceRows: TransferRow[] = devices.map((d) => ({
|
||||||
|
type: "device",
|
||||||
|
displayName: d.hostname,
|
||||||
|
hostname: d.hostname,
|
||||||
|
ip: d.ip,
|
||||||
|
mac: d.mac ?? "",
|
||||||
|
manufacturer: d.manufacturer ?? "",
|
||||||
|
model: d.model ?? "",
|
||||||
|
category: "",
|
||||||
|
alias: "",
|
||||||
|
favorite: "",
|
||||||
|
visible: "",
|
||||||
|
order: "",
|
||||||
|
port: "",
|
||||||
|
https: "",
|
||||||
|
url: "",
|
||||||
|
deviceHostname: "",
|
||||||
|
deviceIp: "",
|
||||||
|
}));
|
||||||
|
|
||||||
|
const serviceRows: TransferRow[] = services.map((s) => {
|
||||||
|
const device = deviceById.get(s.deviceId);
|
||||||
|
return {
|
||||||
|
type: "service",
|
||||||
|
displayName: s.displayName,
|
||||||
|
hostname: s.hostname,
|
||||||
|
ip: "",
|
||||||
|
mac: "",
|
||||||
|
manufacturer: "",
|
||||||
|
model: "",
|
||||||
|
category: s.category ?? "",
|
||||||
|
alias: s.alias.join(";"),
|
||||||
|
favorite: s.favorite ? "true" : "false",
|
||||||
|
visible: s.visible ? "true" : "false",
|
||||||
|
order: s.order,
|
||||||
|
port: s.port,
|
||||||
|
https: s.https ? "true" : "false",
|
||||||
|
url: s.url,
|
||||||
|
deviceHostname: device?.hostname ?? "",
|
||||||
|
deviceIp: device?.ip ?? "",
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
return [...deviceRows, ...serviceRows];
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function transferRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
app.get("/api/transfer/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-export.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, "LaunchPad");
|
||||||
|
const buffer = XLSX.write(workbook, { type: "buffer", bookType: "xlsx" }) as Buffer;
|
||||||
|
reply.header("Content-Disposition", 'attachment; filename="launchpad-export.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-export.csv"');
|
||||||
|
reply.type("text/csv; charset=utf-8");
|
||||||
|
return reply.send(csv);
|
||||||
|
});
|
||||||
|
|
||||||
|
app.post("/api/transfer/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 devicesImported = 0;
|
||||||
|
let devicesSkipped = 0;
|
||||||
|
let servicesImported = 0;
|
||||||
|
let servicesSkipped = 0;
|
||||||
|
const errors: string[] = [];
|
||||||
|
|
||||||
|
// Geräte-Zeilen zuerst verarbeiten, damit Dienst-Zeilen aus derselben
|
||||||
|
// Datei sie bereits über deviceHostname/deviceIp finden können.
|
||||||
|
const deviceRows = rows.filter((r) => String(r.type ?? "").trim() === "device");
|
||||||
|
const serviceRows = rows.filter((r) => String(r.type ?? "").trim() === "service");
|
||||||
|
|
||||||
|
for (const row of deviceRows) {
|
||||||
|
try {
|
||||||
|
const hostname = String(row.hostname ?? row.displayName ?? "").trim();
|
||||||
|
const ip = String(row.ip ?? "").trim();
|
||||||
|
if (!hostname || !ip) {
|
||||||
|
errors.push(`Geräte-Zeile übersprungen (hostname/ip fehlt): ${JSON.stringify(row)}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const allDevices = deviceRepo.listDevices();
|
||||||
|
const existing =
|
||||||
|
allDevices.find((d) => d.ip === ip) ?? allDevices.find((d) => d.hostname === hostname);
|
||||||
|
|
||||||
|
if (existing) {
|
||||||
|
devicesSkipped++;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
deviceRepo.createDevice({
|
||||||
|
hostname,
|
||||||
|
ip,
|
||||||
|
mac: row.mac ? String(row.mac).trim() : undefined,
|
||||||
|
manufacturer: row.manufacturer ? String(row.manufacturer).trim() : undefined,
|
||||||
|
model: row.model ? String(row.model).trim() : undefined,
|
||||||
|
});
|
||||||
|
devicesImported++;
|
||||||
|
} catch (err) {
|
||||||
|
errors.push(err instanceof Error ? err.message : String(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const row of serviceRows) {
|
||||||
|
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(`Dienst-Zeile übersprungen (Pflichtfelder fehlen): ${JSON.stringify(row)}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
});
|
||||||
|
devicesImported++;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existingService = serviceRepo
|
||||||
|
.listServicesByDevice(device.id)
|
||||||
|
.find((s) => s.port === port);
|
||||||
|
if (existingService) {
|
||||||
|
servicesSkipped++;
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
servicesImported++;
|
||||||
|
} catch (err) {
|
||||||
|
errors.push(err instanceof Error ? err.message : String(err));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
devicesImported,
|
||||||
|
devicesSkipped,
|
||||||
|
servicesImported,
|
||||||
|
servicesSkipped,
|
||||||
|
errors,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ export interface HttpProbeResult {
|
|||||||
status?: number;
|
status?: number;
|
||||||
title?: string;
|
title?: string;
|
||||||
faviconUrl?: string;
|
faviconUrl?: string;
|
||||||
|
description?: string;
|
||||||
server?: string;
|
server?: string;
|
||||||
bodySnippet?: string;
|
bodySnippet?: string;
|
||||||
}
|
}
|
||||||
@@ -46,6 +47,7 @@ export function probeHttp(baseUrl: string, timeoutMs = 2000): Promise<HttpProbeR
|
|||||||
status: res.statusCode,
|
status: res.statusCode,
|
||||||
title: extractTitle(body),
|
title: extractTitle(body),
|
||||||
faviconUrl: extractFaviconUrl(body, baseUrl),
|
faviconUrl: extractFaviconUrl(body, baseUrl),
|
||||||
|
description: extractDescription(body),
|
||||||
server: Array.isArray(serverHeader) ? serverHeader[0] : serverHeader,
|
server: Array.isArray(serverHeader) ? serverHeader[0] : serverHeader,
|
||||||
bodySnippet: body,
|
bodySnippet: body,
|
||||||
});
|
});
|
||||||
@@ -82,3 +84,12 @@ function extractFaviconUrl(html: string, baseUrl: string): string | undefined {
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function extractDescription(html: string): string | undefined {
|
||||||
|
// <meta name="description" content="..."> in beiden Attribut-Reihenfolgen
|
||||||
|
const match =
|
||||||
|
html.match(/<meta[^>]+name=["']description["'][^>]+content=["']([^"']*)["']/i) ??
|
||||||
|
html.match(/<meta[^>]+content=["']([^"']*)["'][^>]+name=["']description["']/i);
|
||||||
|
const description = match?.[1]?.trim();
|
||||||
|
return description ? description : undefined;
|
||||||
|
}
|
||||||
|
|||||||
@@ -8,9 +8,22 @@ CERT_FILE="$CERT_DIR/fullchain.pem"
|
|||||||
KEY_FILE="$CERT_DIR/privkey.pem"
|
KEY_FILE="$CERT_DIR/privkey.pem"
|
||||||
CERT_HOST_FILE="$CERT_DIR/.cert-host"
|
CERT_HOST_FILE="$CERT_DIR/.cert-host"
|
||||||
HOST="${LAUNCHPAD_HOST:-localhost}"
|
HOST="${LAUNCHPAD_HOST:-localhost}"
|
||||||
|
EXTRA_HOST="${LAUNCHPAD_EXTRA_HOST:-}"
|
||||||
|
|
||||||
mkdir -p "$CERT_DIR"
|
mkdir -p "$CERT_DIR"
|
||||||
|
|
||||||
|
# Baut einen SAN-Eintrag (IP:... oder DNS:...) für einen einzelnen Hostwert.
|
||||||
|
san_entry_for() {
|
||||||
|
case "$1" in
|
||||||
|
*[0-9]*.*[0-9]*.*[0-9]*.*[0-9]*)
|
||||||
|
echo "IP:$1"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "DNS:$1"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
if [ -f "$CERT_FILE" ] && [ -f "$KEY_FILE" ] && [ ! -f "$CA_CERT" ]; then
|
if [ -f "$CERT_FILE" ] && [ -f "$KEY_FILE" ] && [ ! -f "$CA_CERT" ]; then
|
||||||
# fullchain.pem/privkey.pem wurden vom Nutzer eingebunden (z. B. eigenes
|
# fullchain.pem/privkey.pem wurden vom Nutzer eingebunden (z. B. eigenes
|
||||||
# Zertifikat) und es gibt keine von uns erzeugte CA dazu -> nichts anfassen.
|
# Zertifikat) und es gibt keine von uns erzeugte CA dazu -> nichts anfassen.
|
||||||
@@ -27,24 +40,22 @@ else
|
|||||||
-out "$CA_CERT" 2>/dev/null
|
-out "$CA_CERT" 2>/dev/null
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Server-Zertifikat nur neu erzeugen, wenn es noch keins gibt oder sich
|
# Kombinierte Kennung aus HOST + EXTRA_HOST, um zu erkennen ob sich einer
|
||||||
# LAUNCHPAD_HOST geändert hat (dann würde die alte SAN nicht mehr passen).
|
# von beiden geändert hat -> dann Server-Zertifikat neu ausstellen. Die CA
|
||||||
|
# selbst bleibt davon unberührt (bereits erteiltes Gerätevertrauen gilt weiter).
|
||||||
|
HOST_SIGNATURE="$HOST|$EXTRA_HOST"
|
||||||
NEED_NEW_LEAF=false
|
NEED_NEW_LEAF=false
|
||||||
if [ ! -f "$CERT_FILE" ] || [ ! -f "$KEY_FILE" ]; then
|
if [ ! -f "$CERT_FILE" ] || [ ! -f "$KEY_FILE" ]; then
|
||||||
NEED_NEW_LEAF=true
|
NEED_NEW_LEAF=true
|
||||||
elif [ "$(cat "$CERT_HOST_FILE" 2>/dev/null)" != "$HOST" ]; then
|
elif [ "$(cat "$CERT_HOST_FILE" 2>/dev/null)" != "$HOST_SIGNATURE" ]; then
|
||||||
NEED_NEW_LEAF=true
|
NEED_NEW_LEAF=true
|
||||||
fi
|
fi
|
||||||
|
|
||||||
if [ "$NEED_NEW_LEAF" = "true" ]; then
|
if [ "$NEED_NEW_LEAF" = "true" ]; then
|
||||||
case "$HOST" in
|
SAN="$(san_entry_for "$HOST"),DNS:localhost,IP:127.0.0.1"
|
||||||
*[0-9]*.*[0-9]*.*[0-9]*.*[0-9]*)
|
if [ -n "$EXTRA_HOST" ] && [ "$EXTRA_HOST" != "$HOST" ]; then
|
||||||
SAN="IP:$HOST,DNS:localhost,IP:127.0.0.1"
|
SAN="$SAN,$(san_entry_for "$EXTRA_HOST")"
|
||||||
;;
|
fi
|
||||||
*)
|
|
||||||
SAN="DNS:$HOST,DNS:localhost,IP:127.0.0.1"
|
|
||||||
;;
|
|
||||||
esac
|
|
||||||
|
|
||||||
EXTFILE=$(mktemp)
|
EXTFILE=$(mktemp)
|
||||||
printf "subjectAltName=%s\nbasicConstraints=CA:FALSE\nkeyUsage=digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n" "$SAN" > "$EXTFILE"
|
printf "subjectAltName=%s\nbasicConstraints=CA:FALSE\nkeyUsage=digitalSignature,keyEncipherment\nextendedKeyUsage=serverAuth\n" "$SAN" > "$EXTFILE"
|
||||||
@@ -56,8 +67,8 @@ else
|
|||||||
-out "$CERT_FILE" 2>/dev/null
|
-out "$CERT_FILE" 2>/dev/null
|
||||||
|
|
||||||
rm -f "$EXTFILE" "$CERT_DIR/server.csr"
|
rm -f "$EXTFILE" "$CERT_DIR/server.csr"
|
||||||
echo "$HOST" > "$CERT_HOST_FILE"
|
echo "$HOST_SIGNATURE" > "$CERT_HOST_FILE"
|
||||||
echo "[entrypoint] Server-Zertifikat für '$HOST' erzeugt und mit lokaler CA signiert."
|
echo "[entrypoint] Server-Zertifikat erzeugt (SAN: $SAN), mit lokaler CA signiert."
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
|||||||
24
apps/frontend/src/hooks/useReadLater.ts
Normal file
24
apps/frontend/src/hooks/useReadLater.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
export interface ReadLaterItem {
|
||||||
|
id: string;
|
||||||
|
url: string;
|
||||||
|
displayName: string;
|
||||||
|
favicon: string | null;
|
||||||
|
savedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchReadLater(): Promise<ReadLaterItem[]> {
|
||||||
|
const res = await fetch("/api/read-later");
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Später-lesen-Liste konnte nicht geladen werden (HTTP ${res.status})`);
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useReadLater() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["read-later"],
|
||||||
|
queryFn: fetchReadLater,
|
||||||
|
});
|
||||||
|
}
|
||||||
29
apps/frontend/src/hooks/useRecentVisits.ts
Normal file
29
apps/frontend/src/hooks/useRecentVisits.ts
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import type { Bookmark, Service } from "@launchpad/shared";
|
||||||
|
|
||||||
|
export type RecentVisitItem =
|
||||||
|
| (Service & { kind: "service" })
|
||||||
|
| (Bookmark & { kind: "bookmark" });
|
||||||
|
|
||||||
|
async function fetchRecentVisits(): Promise<RecentVisitItem[]> {
|
||||||
|
const res = await fetch("/api/recent-visits");
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Zuletzt besucht konnte nicht geladen werden (HTTP ${res.status})`);
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useRecentVisits() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["recent-visits"],
|
||||||
|
queryFn: fetchRecentVisits,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function recordVisit(itemType: "service" | "bookmark", itemId: string): Promise<void> {
|
||||||
|
await fetch("/api/recent-visits", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ itemType, itemId }),
|
||||||
|
});
|
||||||
|
}
|
||||||
20
apps/frontend/src/hooks/useSettings.ts
Normal file
20
apps/frontend/src/hooks/useSettings.ts
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
|
||||||
|
export interface AppSettings {
|
||||||
|
recentVisitsLimit: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchSettings(): Promise<AppSettings> {
|
||||||
|
const res = await fetch("/api/settings");
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Einstellungen konnten nicht geladen werden (HTTP ${res.status})`);
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useSettings() {
|
||||||
|
return useQuery({
|
||||||
|
queryKey: ["settings"],
|
||||||
|
queryFn: fetchSettings,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -16,3 +16,17 @@ body {
|
|||||||
"Segoe UI",
|
"Segoe UI",
|
||||||
sans-serif;
|
sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Sagt dem Browser, dass native Formularelemente (select/option, Checkbox,
|
||||||
|
* Datepicker …) im jeweiligen Theme gerendert werden sollen. Ohne das
|
||||||
|
* bleiben z. B. <option>-Listen in <select> auf vielen Browsern immer hell
|
||||||
|
* (weißer Text auf weißem Grund im Dark Mode), weil Tailwind-Klassen auf
|
||||||
|
* das native Dropdown-Popup keinen Einfluss haben.
|
||||||
|
*/
|
||||||
|
:root {
|
||||||
|
color-scheme: light;
|
||||||
|
}
|
||||||
|
.dark {
|
||||||
|
color-scheme: dark;
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,6 +5,23 @@ import { RouterProvider } from "@tanstack/react-router";
|
|||||||
import { router } from "./router.js";
|
import { router } from "./router.js";
|
||||||
import "./index.css";
|
import "./index.css";
|
||||||
|
|
||||||
|
// Muss VOR dem ersten Render laufen und unabhängig davon, welche Route
|
||||||
|
// zuerst geladen wird (z. B. Direktlink auf /admin/...) – vorher hing das
|
||||||
|
// Anwenden der Dark-Mode-Klasse an useTheme(), das nur auf Home/Einstellungen
|
||||||
|
// aufgerufen wurde, wodurch andere Admin-Seiten beim Direktaufruf immer hell
|
||||||
|
// starteten, egal was gespeichert war.
|
||||||
|
function applyStoredTheme() {
|
||||||
|
const stored = window.localStorage.getItem("launchpad-theme");
|
||||||
|
const theme =
|
||||||
|
stored === "light" || stored === "dark"
|
||||||
|
? stored
|
||||||
|
: window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||||
|
? "dark"
|
||||||
|
: "light";
|
||||||
|
document.documentElement.classList.toggle("dark", theme === "dark");
|
||||||
|
}
|
||||||
|
applyStoredTheme();
|
||||||
|
|
||||||
const queryClient = new QueryClient({
|
const queryClient = new QueryClient({
|
||||||
defaultOptions: {
|
defaultOptions: {
|
||||||
queries: {
|
queries: {
|
||||||
|
|||||||
@@ -1,15 +1,21 @@
|
|||||||
import { useEffect, useMemo, useRef, useState } from "react";
|
import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { Link } from "@tanstack/react-router";
|
import { Link } from "@tanstack/react-router";
|
||||||
import { SearchInput, StatusBadge, ResultsList, FavoritesBar } from "@launchpad/ui";
|
import { SearchInput, StatusBadge, ResultsList, FavoritesBar, Favicon, Button } from "@launchpad/ui";
|
||||||
import { rankServices, type SearchResult } from "@launchpad/shared";
|
import { rankServices, type SearchResult } from "@launchpad/shared";
|
||||||
import { useServices } from "../hooks/useServices.js";
|
import { useServices } from "../hooks/useServices.js";
|
||||||
import { useBookmarks } from "../hooks/useBookmarks.js";
|
import { useBookmarks } from "../hooks/useBookmarks.js";
|
||||||
import { useBackendHealth } from "../hooks/useBackendHealth.js";
|
import { useBackendHealth } from "../hooks/useBackendHealth.js";
|
||||||
import { useTheme } from "../hooks/useTheme.js";
|
import { useTheme } from "../hooks/useTheme.js";
|
||||||
|
import { useCategories } from "../hooks/useCategories.js";
|
||||||
|
import { useRecentVisits, recordVisit } from "../hooks/useRecentVisits.js";
|
||||||
|
import { useReadLater } from "../hooks/useReadLater.js";
|
||||||
|
|
||||||
function openItem(item: SearchResult) {
|
function openItem(item: SearchResult | { url: string; id?: string; kind?: "service" | "bookmark" }) {
|
||||||
window.open(item.url, "_blank", "noopener,noreferrer");
|
window.open(item.url, "_blank", "noopener,noreferrer");
|
||||||
|
if ("kind" in item && item.kind && item.id) {
|
||||||
|
recordVisit(item.kind, item.id);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function toggleFavoriteRequest(item: SearchResult): Promise<void> {
|
async function toggleFavoriteRequest(item: SearchResult): Promise<void> {
|
||||||
@@ -36,6 +42,55 @@ async function reorderRequest(kind: "service" | "bookmark", orderedIds: string[]
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 [url, setUrl] = useState("");
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: () => saveReadLaterRequest(url.trim()),
|
||||||
|
onSuccess: () => {
|
||||||
|
setUrl("");
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["read-later"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleSubmit(e: FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!url.trim()) return;
|
||||||
|
mutation.mutate();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={handleSubmit} className="flex gap-2">
|
||||||
|
<input
|
||||||
|
value={url}
|
||||||
|
onChange={(e) => setUrl(e.target.value)}
|
||||||
|
placeholder="Link zum Später-Lesen hier einfügen …"
|
||||||
|
className="flex-1 rounded-xl border border-black/10 bg-white/70 px-3 py-2 text-sm
|
||||||
|
text-black outline-none placeholder:text-black/30 focus:border-black/30
|
||||||
|
dark:border-white/10 dark:bg-white/5 dark:text-white dark:placeholder:text-white/30
|
||||||
|
dark:focus:border-white/30"
|
||||||
|
/>
|
||||||
|
<Button type="submit" variant="secondary" disabled={mutation.isPending || !url.trim()}>
|
||||||
|
{mutation.isPending ? "…" : "Merken"}
|
||||||
|
</Button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function HomePage() {
|
export function HomePage() {
|
||||||
const [theme, toggleTheme] = useTheme();
|
const [theme, toggleTheme] = useTheme();
|
||||||
const [query, setQuery] = useState("");
|
const [query, setQuery] = useState("");
|
||||||
@@ -43,11 +98,22 @@ export function HomePage() {
|
|||||||
const { health, error: healthError } = useBackendHealth();
|
const { health, error: healthError } = useBackendHealth();
|
||||||
const { data: services, isLoading: servicesLoading, isError: servicesError } = useServices();
|
const { data: services, isLoading: servicesLoading, isError: servicesError } = useServices();
|
||||||
const { data: bookmarks, isLoading: bookmarksLoading } = useBookmarks();
|
const { data: bookmarks, isLoading: bookmarksLoading } = useBookmarks();
|
||||||
|
const { data: categories } = useCategories();
|
||||||
|
const { data: recentVisits } = useRecentVisits();
|
||||||
|
const { data: readLaterItems } = useReadLater();
|
||||||
const inputRef = useRef<HTMLInputElement>(null);
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const isSearching = query.trim().length > 0;
|
const isSearching = query.trim().length > 0;
|
||||||
const isLoading = servicesLoading || bookmarksLoading;
|
const isLoading = servicesLoading || bookmarksLoading;
|
||||||
|
|
||||||
|
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({
|
const toggleFavorite = useMutation({
|
||||||
mutationFn: toggleFavoriteRequest,
|
mutationFn: toggleFavoriteRequest,
|
||||||
onSuccess: (_data, item) => {
|
onSuccess: (_data, item) => {
|
||||||
@@ -136,8 +202,8 @@ export function HomePage() {
|
|||||||
const hasFavorites = favoriteServices.length > 0 || favoriteBookmarks.length > 0;
|
const hasFavorites = favoriteServices.length > 0 || favoriteBookmarks.length > 0;
|
||||||
|
|
||||||
return (
|
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">
|
<div className="flex h-dvh flex-col overflow-hidden bg-gradient-to-b from-white to-neutral-100 dark:from-black dark:to-neutral-950">
|
||||||
<div className="fixed right-6 top-6 flex items-center gap-2">
|
<div className="fixed right-6 top-6 z-10 flex items-center gap-2">
|
||||||
<Link
|
<Link
|
||||||
to="/admin"
|
to="/admin"
|
||||||
aria-label="Adminbereich öffnen"
|
aria-label="Adminbereich öffnen"
|
||||||
@@ -156,75 +222,137 @@ export function HomePage() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col items-center gap-2 text-center">
|
{/* Nicht-scrollender Kopfbereich: Titel, Favoriten, Suchfeld, Später-lesen, Zuletzt besucht */}
|
||||||
<h1 className="text-4xl font-semibold tracking-tight text-black dark:text-white">
|
<div className="flex shrink-0 flex-col items-center gap-4 px-6 pb-3 pt-6 sm:pt-10">
|
||||||
LaunchPad
|
<div className="flex flex-col items-center gap-0.5 text-center">
|
||||||
</h1>
|
<h1 className="text-xl font-semibold tracking-tight text-black dark:text-white sm:text-2xl">
|
||||||
<p className="text-black/50 dark:text-white/50">
|
LaunchPad
|
||||||
Tippe, um deine Homelab-Dienste sofort zu öffnen.
|
</h1>
|
||||||
</p>
|
<p className="text-xs text-black/50 dark:text-white/50 sm:text-sm">
|
||||||
</div>
|
Tippe, um deine Homelab-Dienste sofort zu öffnen.
|
||||||
|
|
||||||
<div className="w-full max-w-xl">
|
|
||||||
{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}
|
|
||||||
|
|
||||||
<SearchInput
|
|
||||||
ref={inputRef}
|
|
||||||
value={query}
|
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
|
||||||
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 …</p>
|
|
||||||
) : servicesError ? (
|
|
||||||
<p className="mt-4 text-center text-sm text-red-500">
|
|
||||||
Dienste konnten nicht geladen werden.
|
|
||||||
</p>
|
</p>
|
||||||
) : (
|
</div>
|
||||||
<ResultsList
|
|
||||||
results={results}
|
<div className="w-full max-w-xl">
|
||||||
selectedIndex={selectedIndex}
|
{hasFavorites ? (
|
||||||
onHover={setSelectedIndex}
|
<div className="mb-3 flex flex-col gap-2">
|
||||||
onOpen={openItem}
|
{favoriteServices.length > 0 ? (
|
||||||
onToggleFavorite={(item) => toggleFavorite.mutate(item)}
|
<FavoritesBar
|
||||||
emptyLabel={
|
items={favoriteServices}
|
||||||
allItems.length === 0
|
label="Dienste"
|
||||||
? "Noch nichts angelegt. Füge Dienste oder Lesezeichen im Adminbereich hinzu."
|
categoryColors={categoryColors}
|
||||||
: "Keine Treffer für deine Suche."
|
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"
|
||||||
|
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}
|
||||||
|
|
||||||
|
<SearchInput
|
||||||
|
ref={inputRef}
|
||||||
|
value={query}
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
placeholder="Dienst oder Lesezeichen suchen … z. B. „frigate“"
|
||||||
|
hint="⌘K"
|
||||||
|
autoFocus
|
||||||
/>
|
/>
|
||||||
)}
|
|
||||||
|
{!isSearching ? (
|
||||||
|
<div className="mt-3 flex flex-col gap-3">
|
||||||
|
<ReadLaterBox />
|
||||||
|
|
||||||
|
{readLaterItems && readLaterItems.length > 0 ? (
|
||||||
|
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||||
|
{readLaterItems.slice(0, 6).map((item) => (
|
||||||
|
<button
|
||||||
|
key={item.id}
|
||||||
|
onClick={() => window.open(item.url, "_blank", "noopener,noreferrer")}
|
||||||
|
title={item.displayName}
|
||||||
|
className="flex items-center gap-1.5 rounded-full border border-black/10
|
||||||
|
bg-white/50 px-2.5 py-1 text-xs text-black/60 hover:bg-black/5
|
||||||
|
dark:border-white/10 dark:bg-white/5 dark:text-white/60 dark:hover:bg-white/10"
|
||||||
|
>
|
||||||
|
<Favicon src={item.favicon} fallbackLetter={item.displayName} size="sm" />
|
||||||
|
<span className="max-w-[8rem] truncate">{item.displayName}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
{recentVisits && recentVisits.length > 0 ? (
|
||||||
|
<div>
|
||||||
|
<div className="mb-1.5 text-center text-xs font-medium uppercase tracking-wide text-black/30 dark:text-white/30">
|
||||||
|
Zuletzt besucht
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-wrap items-center justify-center gap-2">
|
||||||
|
{recentVisits.map((item) => (
|
||||||
|
<button
|
||||||
|
key={`${item.kind}-${item.id}`}
|
||||||
|
onClick={() => openItem(item)}
|
||||||
|
title={item.displayName}
|
||||||
|
className="flex items-center gap-1.5 rounded-full border border-black/10
|
||||||
|
bg-white/50 px-2.5 py-1 text-xs text-black/60 hover:bg-black/5
|
||||||
|
dark:border-white/10 dark:bg-white/5 dark:text-white/60 dark:hover:bg-white/10"
|
||||||
|
>
|
||||||
|
<Favicon src={item.favicon} fallbackLetter={item.displayName} size="sm" />
|
||||||
|
<span className="max-w-[8rem] truncate">{item.displayName}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="flex flex-col items-center gap-1 pb-8">
|
{/* Scrollender Bereich: NUR die Trefferliste scrollt, nicht die ganze Seite */}
|
||||||
|
{isSearching ? (
|
||||||
|
<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>
|
||||||
|
) : (
|
||||||
|
<div className="flex-1" />
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex shrink-0 flex-col items-center gap-1 pb-4">
|
||||||
<StatusBadge online={isOnline} label={isOnline ? "Backend verbunden" : "Backend nicht erreichbar"} />
|
<StatusBadge online={isOnline} label={isOnline ? "Backend verbunden" : "Backend nicht erreichbar"} />
|
||||||
{health ? (
|
{health ? (
|
||||||
<span className="text-xs text-black/30 dark:text-white/30">
|
<span className="text-xs text-black/30 dark:text-white/30">
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { useState, type DragEvent, type FormEvent } from "react";
|
import { useMemo, useState, type DragEvent, type FormEvent } from "react";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { Button, Favicon } from "@launchpad/ui";
|
import { Button, Favicon } from "@launchpad/ui";
|
||||||
import type { Bookmark } from "@launchpad/shared";
|
import type { Bookmark } from "@launchpad/shared";
|
||||||
@@ -274,12 +274,14 @@ function EditForm({ bookmark, onDone }: { bookmark: Bookmark; onDone: () => void
|
|||||||
|
|
||||||
function BookmarkRow({
|
function BookmarkRow({
|
||||||
bookmark,
|
bookmark,
|
||||||
|
draggable,
|
||||||
onDragStart,
|
onDragStart,
|
||||||
onDragOver,
|
onDragOver,
|
||||||
onDrop,
|
onDrop,
|
||||||
isDragging,
|
isDragging,
|
||||||
}: {
|
}: {
|
||||||
bookmark: Bookmark;
|
bookmark: Bookmark;
|
||||||
|
draggable: boolean;
|
||||||
onDragStart: (e: DragEvent<HTMLTableRowElement>) => void;
|
onDragStart: (e: DragEvent<HTMLTableRowElement>) => void;
|
||||||
onDragOver: (e: DragEvent<HTMLTableRowElement>) => void;
|
onDragOver: (e: DragEvent<HTMLTableRowElement>) => void;
|
||||||
onDrop: (e: DragEvent<HTMLTableRowElement>) => void;
|
onDrop: (e: DragEvent<HTMLTableRowElement>) => void;
|
||||||
@@ -304,14 +306,17 @@ function BookmarkRow({
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<tr
|
<tr
|
||||||
draggable
|
draggable={draggable}
|
||||||
onDragStart={onDragStart}
|
onDragStart={onDragStart}
|
||||||
onDragOver={onDragOver}
|
onDragOver={onDragOver}
|
||||||
onDrop={onDrop}
|
onDrop={onDrop}
|
||||||
className={`border-b border-black/5 last:border-0 dark:border-white/5 ${isDragging ? "opacity-40" : ""}`}
|
className={`border-b border-black/5 last:border-0 dark:border-white/5 ${isDragging ? "opacity-40" : ""}`}
|
||||||
>
|
>
|
||||||
<td className="px-2 py-3 text-center">
|
<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>
|
</span>
|
||||||
</td>
|
</td>
|
||||||
@@ -361,11 +366,44 @@ function BookmarkRow({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SortColumn = "displayName" | "hostname" | "category" | 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function BookmarksPage() {
|
export function BookmarksPage() {
|
||||||
const { data: bookmarks, isLoading, isError } = useBookmarks();
|
const { data: bookmarks, isLoading, isError } = useBookmarks();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [draggedId, setDraggedId] = useState<string | null>(null);
|
const [draggedId, setDraggedId] = useState<string | null>(null);
|
||||||
const [localOrder, setLocalOrder] = useState<Bookmark[] | null>(null);
|
const [localOrder, setLocalOrder] = useState<Bookmark[] | null>(null);
|
||||||
|
const [sortColumn, setSortColumn] = useState<SortColumn>(null);
|
||||||
|
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
|
||||||
|
|
||||||
const reorderMutation = useMutation({
|
const reorderMutation = useMutation({
|
||||||
mutationFn: reorderBookmarksRequest,
|
mutationFn: reorderBookmarksRequest,
|
||||||
@@ -376,7 +414,38 @@ export function BookmarksPage() {
|
|||||||
onError: () => setLocalOrder(null),
|
onError: () => setLocalOrder(null),
|
||||||
});
|
});
|
||||||
|
|
||||||
const list = localOrder ?? bookmarks ?? [];
|
const baseList = localOrder ?? bookmarks ?? [];
|
||||||
|
|
||||||
|
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 "hostname":
|
||||||
|
cmp = a.hostname.localeCompare(b.hostname);
|
||||||
|
break;
|
||||||
|
case "category":
|
||||||
|
cmp = (a.category ?? "").localeCompare(b.category ?? "");
|
||||||
|
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) {
|
function handleDragStart(id: string) {
|
||||||
return (_e: DragEvent<HTMLTableRowElement>) => setDraggedId(id);
|
return (_e: DragEvent<HTMLTableRowElement>) => setDraggedId(id);
|
||||||
@@ -385,7 +454,7 @@ export function BookmarksPage() {
|
|||||||
function handleDragOver(targetId: string) {
|
function handleDragOver(targetId: string) {
|
||||||
return (e: DragEvent<HTMLTableRowElement>) => {
|
return (e: DragEvent<HTMLTableRowElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
if (!draggedId || draggedId === targetId) return;
|
if (!dragEnabled || !draggedId || draggedId === targetId) return;
|
||||||
const current = localOrder ?? bookmarks ?? [];
|
const current = localOrder ?? bookmarks ?? [];
|
||||||
const fromIndex = current.findIndex((b) => b.id === draggedId);
|
const fromIndex = current.findIndex((b) => b.id === draggedId);
|
||||||
const toIndex = current.findIndex((b) => b.id === targetId);
|
const toIndex = current.findIndex((b) => b.id === targetId);
|
||||||
@@ -400,6 +469,7 @@ export function BookmarksPage() {
|
|||||||
function handleDrop() {
|
function handleDrop() {
|
||||||
return (e: DragEvent<HTMLTableRowElement>) => {
|
return (e: DragEvent<HTMLTableRowElement>) => {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
if (!dragEnabled) return;
|
||||||
setDraggedId(null);
|
setDraggedId(null);
|
||||||
const current = localOrder ?? bookmarks ?? [];
|
const current = localOrder ?? bookmarks ?? [];
|
||||||
reorderMutation.mutate(current.map((b, index) => ({ id: b.id, order: index })));
|
reorderMutation.mutate(current.map((b, index) => ({ id: b.id, order: index })));
|
||||||
@@ -410,11 +480,19 @@ export function BookmarksPage() {
|
|||||||
<div>
|
<div>
|
||||||
<AdminPageHeader
|
<AdminPageHeader
|
||||||
title="Lesezeichen"
|
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."
|
description="Eigenständig von Diensten – erscheinen zusammen mit ihnen in der Suche, aber als eigene Favoriten-Gruppe auf der Startseite. Spaltenköpfe anklickbar zum Sortieren; Drag & Drop (⠿⠿) nur in der Standard-Reihenfolge."
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<AddBookmarkForm />
|
<AddBookmarkForm />
|
||||||
|
|
||||||
|
{sortColumn ? (
|
||||||
|
<div className="mb-3">
|
||||||
|
<Button size="sm" variant="ghost" onClick={() => setSortColumn(null)}>
|
||||||
|
← Zur manuellen Reihenfolge (Drag & Drop) zurück
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<p className="text-sm text-black/40 dark:text-white/40">Lade Lesezeichen …</p>
|
<p className="text-sm text-black/40 dark:text-white/40">Lade Lesezeichen …</p>
|
||||||
) : isError ? (
|
) : isError ? (
|
||||||
@@ -428,10 +506,10 @@ export function BookmarksPage() {
|
|||||||
uppercase tracking-wide text-black/40 dark:border-white/10 dark:bg-white/5 dark:text-white/40">
|
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-2 py-2" />
|
<th className="px-2 py-2" />
|
||||||
<th className="px-4 py-2 font-medium">Lesezeichen</th>
|
<SortableHeader label="Lesezeichen" column="displayName" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
<th className="px-4 py-2 font-medium">Kategorie</th>
|
<SortableHeader label="Kategorie" column="category" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
<th className="px-4 py-2 font-medium">Beschreibung</th>
|
<th className="px-4 py-2 font-medium">Beschreibung</th>
|
||||||
<th className="px-4 py-2 font-medium">URL</th>
|
<SortableHeader label="URL" column="hostname" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
<th className="px-4 py-2" />
|
<th className="px-4 py-2" />
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -440,6 +518,7 @@ export function BookmarksPage() {
|
|||||||
<BookmarkRow
|
<BookmarkRow
|
||||||
key={bookmark.id}
|
key={bookmark.id}
|
||||||
bookmark={bookmark}
|
bookmark={bookmark}
|
||||||
|
draggable={dragEnabled}
|
||||||
isDragging={draggedId === bookmark.id}
|
isDragging={draggedId === bookmark.id}
|
||||||
onDragStart={handleDragStart(bookmark.id)}
|
onDragStart={handleDragStart(bookmark.id)}
|
||||||
onDragOver={handleDragOver(bookmark.id)}
|
onDragOver={handleDragOver(bookmark.id)}
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
|
import { Link } from "@tanstack/react-router";
|
||||||
import { useServices } from "../../hooks/useServices.js";
|
import { useServices } from "../../hooks/useServices.js";
|
||||||
import { useDevices } from "../../hooks/useDevices.js";
|
import { useDevices } from "../../hooks/useDevices.js";
|
||||||
import { useCategories } from "../../hooks/useCategories.js";
|
import { useCategories } from "../../hooks/useCategories.js";
|
||||||
|
import { useBookmarks } from "../../hooks/useBookmarks.js";
|
||||||
import { AdminPageHeader } from "./AdminPageHeader.js";
|
import { AdminPageHeader } from "./AdminPageHeader.js";
|
||||||
|
|
||||||
function StatCard({ label, value }: { label: string; value: number | string }) {
|
function StatCard({ label, value }: { label: string; value: number | string }) {
|
||||||
@@ -16,9 +18,11 @@ export function DashboardPage() {
|
|||||||
const { data: services } = useServices();
|
const { data: services } = useServices();
|
||||||
const { data: devices } = useDevices();
|
const { data: devices } = useDevices();
|
||||||
const { data: categories } = useCategories();
|
const { data: categories } = useCategories();
|
||||||
|
const { data: bookmarks } = useBookmarks();
|
||||||
|
|
||||||
const onlineDevices = devices?.filter((d) => d.online).length ?? 0;
|
const onlineDevices = devices?.filter((d) => d.online).length ?? 0;
|
||||||
const favoriteServices = services?.filter((s) => s.favorite).length ?? 0;
|
const favoriteServices = services?.filter((s) => s.favorite).length ?? 0;
|
||||||
|
const favoriteBookmarks = bookmarks?.filter((b) => b.favorite).length ?? 0;
|
||||||
|
|
||||||
const recentlyScanned = [...(devices ?? [])]
|
const recentlyScanned = [...(devices ?? [])]
|
||||||
.filter((d) => d.lastScan)
|
.filter((d) => d.lastScan)
|
||||||
@@ -30,13 +34,25 @@ export function DashboardPage() {
|
|||||||
<AdminPageHeader
|
<AdminPageHeader
|
||||||
title="Dashboard"
|
title="Dashboard"
|
||||||
description="Überblick über dein Homelab."
|
description="Überblick über dein Homelab."
|
||||||
|
actions={
|
||||||
|
<Link
|
||||||
|
to="/"
|
||||||
|
className="flex items-center gap-1.5 rounded-lg border border-black/10 px-3 py-1.5
|
||||||
|
text-sm text-black/70 transition-colors hover:bg-black/5 dark:border-white/10
|
||||||
|
dark:text-white/70 dark:hover:bg-white/10"
|
||||||
|
>
|
||||||
|
<span aria-hidden>🏠</span> Startseite
|
||||||
|
</Link>
|
||||||
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
|
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-6">
|
||||||
<StatCard label="Geräte" value={devices?.length ?? 0} />
|
<StatCard label="Geräte" value={devices?.length ?? 0} />
|
||||||
<StatCard label="davon online" value={onlineDevices} />
|
<StatCard label="davon online" value={onlineDevices} />
|
||||||
<StatCard label="Dienste" value={services?.length ?? 0} />
|
<StatCard label="Dienste" value={services?.length ?? 0} />
|
||||||
<StatCard label="Favoriten" value={favoriteServices} />
|
<StatCard label="Lesezeichen" value={bookmarks?.length ?? 0} />
|
||||||
|
<StatCard label="Favoriten (Dienste)" value={favoriteServices} />
|
||||||
|
<StatCard label="Favoriten (Lesezeichen)" value={favoriteBookmarks} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="mt-8">
|
<div className="mt-8">
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useState, type FormEvent } from "react";
|
import { useMemo, useState, type FormEvent } from "react";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { Button } from "@launchpad/ui";
|
import { Button, Favicon } from "@launchpad/ui";
|
||||||
|
import type { Service } from "@launchpad/shared";
|
||||||
import { useDevices, type DeviceWithServices } from "../../hooks/useDevices.js";
|
import { useDevices, type DeviceWithServices } from "../../hooks/useDevices.js";
|
||||||
import { AdminPageHeader } from "./AdminPageHeader.js";
|
import { AdminPageHeader } from "./AdminPageHeader.js";
|
||||||
|
|
||||||
@@ -17,6 +18,18 @@ async function createDevice(input: { hostname: string; ip: string }) {
|
|||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function patchDevice(id: string, patch: Record<string, unknown>) {
|
||||||
|
const res = await fetch(`/api/devices/${id}`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify(patch),
|
||||||
|
});
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(`Gerät konnte nicht aktualisiert werden (HTTP ${res.status})`);
|
||||||
|
}
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
async function deleteDevice(id: string) {
|
async function deleteDevice(id: string) {
|
||||||
const res = await fetch(`/api/devices/${id}`, { method: "DELETE" });
|
const res = await fetch(`/api/devices/${id}`, { method: "DELETE" });
|
||||||
if (!res.ok && res.status !== 404) {
|
if (!res.ok && res.status !== 404) {
|
||||||
@@ -24,11 +37,19 @@ async function deleteDevice(id: string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function deleteServiceRequest(id: string) {
|
||||||
|
const res = await fetch(`/api/services/${id}`, { method: "DELETE" });
|
||||||
|
if (!res.ok && res.status !== 404) {
|
||||||
|
throw new Error(`Dienst konnte nicht gelöscht werden (HTTP ${res.status})`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
interface ScanResult {
|
interface ScanResult {
|
||||||
scannedPorts: number;
|
scannedPorts: number;
|
||||||
ports: number[];
|
ports: number[];
|
||||||
created: number;
|
created: number;
|
||||||
updated: number;
|
updated: number;
|
||||||
|
staleServices: Service[];
|
||||||
}
|
}
|
||||||
|
|
||||||
async function scanDevice(id: string): Promise<ScanResult> {
|
async function scanDevice(id: string): Promise<ScanResult> {
|
||||||
@@ -40,9 +61,150 @@ async function scanDevice(id: string): Promise<ScanResult> {
|
|||||||
return body;
|
return body;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function EditDeviceForm({ device, onDone }: { device: DeviceWithServices; onDone: () => void }) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [hostname, setHostname] = useState(device.hostname);
|
||||||
|
const [ip, setIp] = useState(device.ip);
|
||||||
|
const [mac, setMac] = useState(device.mac ?? "");
|
||||||
|
const [manufacturer, setManufacturer] = useState(device.manufacturer ?? "");
|
||||||
|
const [model, setModel] = useState(device.model ?? "");
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: () =>
|
||||||
|
patchDevice(device.id, {
|
||||||
|
hostname: hostname.trim(),
|
||||||
|
ip: ip.trim(),
|
||||||
|
mac: mac.trim() || undefined,
|
||||||
|
manufacturer: manufacturer.trim() || undefined,
|
||||||
|
model: model.trim() || undefined,
|
||||||
|
}),
|
||||||
|
onSuccess: () => {
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["devices"] });
|
||||||
|
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={6} 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">Hostname</label>
|
||||||
|
<input
|
||||||
|
value={hostname}
|
||||||
|
onChange={(e) => setHostname(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">IP</label>
|
||||||
|
<input
|
||||||
|
value={ip}
|
||||||
|
onChange={(e) => setIp(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">
|
||||||
|
MAC-Adresse
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
value={mac}
|
||||||
|
onChange={(e) => setMac(e.target.value)}
|
||||||
|
placeholder="AA:BB:CC:DD:EE:FF"
|
||||||
|
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>
|
||||||
|
<label className="mb-1 block text-xs text-black/50 dark:text-white/50">Hersteller</label>
|
||||||
|
<input
|
||||||
|
value={manufacturer}
|
||||||
|
onChange={(e) => setManufacturer(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">Modell</label>
|
||||||
|
<input
|
||||||
|
value={model}
|
||||||
|
onChange={(e) => setModel(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 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 StaleServicesReview({ staleServices, onDone }: { staleServices: Service[]; onDone: () => void }) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [handled, setHandled] = useState<Set<string>>(new Set());
|
||||||
|
|
||||||
|
const deleteMutation = useMutation({
|
||||||
|
mutationFn: (id: string) => deleteServiceRequest(id),
|
||||||
|
onSuccess: (_data, id) => {
|
||||||
|
setHandled((prev) => new Set(prev).add(id));
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["services"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const remaining = staleServices.filter((s) => !handled.has(s.id));
|
||||||
|
if (remaining.length === 0) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-2 rounded-xl border border-amber-500/30 bg-amber-500/5 p-3 text-xs">
|
||||||
|
<p className="mb-2 font-medium text-amber-700 dark:text-amber-400">
|
||||||
|
{remaining.length} Dienst(e) beim letzten Scan nicht mehr gefunden (Port nicht mehr offen):
|
||||||
|
</p>
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{remaining.map((s) => (
|
||||||
|
<li key={s.id} className="flex items-center justify-between gap-2">
|
||||||
|
<span className="text-black/70 dark:text-white/70">
|
||||||
|
{s.displayName} ({s.hostname}:{s.port})
|
||||||
|
</span>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<Button size="sm" variant="ghost" onClick={() => setHandled((prev) => new Set(prev).add(s.id))}>
|
||||||
|
Behalten
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="danger"
|
||||||
|
onClick={() => deleteMutation.mutate(s.id)}
|
||||||
|
disabled={deleteMutation.isPending}
|
||||||
|
>
|
||||||
|
Entfernen
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<button onClick={onDone} className="mt-2 text-black/40 underline dark:text-white/40">
|
||||||
|
Hinweis schließen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function DeviceRow({ device }: { device: DeviceWithServices }) {
|
function DeviceRow({ device }: { device: DeviceWithServices }) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [scanMessage, setScanMessage] = useState<string | null>(null);
|
const [scanMessage, setScanMessage] = useState<string | null>(null);
|
||||||
|
const [staleServices, setStaleServices] = useState<Service[]>([]);
|
||||||
|
const [expanded, setExpanded] = useState(false);
|
||||||
|
const [editing, setEditing] = useState(false);
|
||||||
|
|
||||||
const scanMutation = useMutation({
|
const scanMutation = useMutation({
|
||||||
mutationFn: () => scanDevice(device.id),
|
mutationFn: () => scanDevice(device.id),
|
||||||
@@ -51,6 +213,7 @@ function DeviceRow({ device }: { device: DeviceWithServices }) {
|
|||||||
setScanMessage(
|
setScanMessage(
|
||||||
`Ports offen: ${portsText} · ${result.created} neu · ${result.updated} aktualisiert`
|
`Ports offen: ${portsText} · ${result.created} neu · ${result.updated} aktualisiert`
|
||||||
);
|
);
|
||||||
|
setStaleServices(result.staleServices);
|
||||||
queryClient.invalidateQueries({ queryKey: ["devices"] });
|
queryClient.invalidateQueries({ queryKey: ["devices"] });
|
||||||
queryClient.invalidateQueries({ queryKey: ["services"] });
|
queryClient.invalidateQueries({ queryKey: ["services"] });
|
||||||
},
|
},
|
||||||
@@ -62,56 +225,113 @@ function DeviceRow({ device }: { device: DeviceWithServices }) {
|
|||||||
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["devices"] }),
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["devices"] }),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (editing) {
|
||||||
|
return <EditDeviceForm device={device} onDone={() => setEditing(false)} />;
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<tr className="border-b border-black/5 last:border-0 dark:border-white/5">
|
<>
|
||||||
<td className="px-4 py-3">
|
<tr className="border-b border-black/5 last:border-0 dark:border-white/5">
|
||||||
<div className="font-medium text-black dark:text-white">{device.hostname}</div>
|
<td className="px-4 py-3">
|
||||||
<div className="text-xs text-black/40 dark:text-white/40">{device.ip}</div>
|
<button
|
||||||
</td>
|
onClick={() => setExpanded((e) => !e)}
|
||||||
<td className="px-4 py-3">
|
className="flex items-center gap-1.5 text-left"
|
||||||
<span
|
title={expanded ? "Dienste ausblenden" : "Dienste anzeigen"}
|
||||||
className={`inline-flex items-center gap-1.5 text-xs ${
|
>
|
||||||
device.online ? "text-emerald-600 dark:text-emerald-400" : "text-black/40 dark:text-white/40"
|
<span className="text-black/30 dark:text-white/30">{expanded ? "▾" : "▸"}</span>
|
||||||
}`}
|
<span className="font-medium text-black dark:text-white">{device.hostname}</span>
|
||||||
>
|
</button>
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3 font-mono text-black/60 dark:text-white/60">{device.ip}</td>
|
||||||
|
<td className="px-4 py-3 font-mono text-xs text-black/40 dark:text-white/40">
|
||||||
|
{device.mac ?? "–"}
|
||||||
|
</td>
|
||||||
|
<td className="px-4 py-3">
|
||||||
<span
|
<span
|
||||||
className={`h-1.5 w-1.5 rounded-full ${device.online ? "bg-emerald-500" : "bg-black/20 dark:bg-white/20"}`}
|
className={`inline-flex items-center gap-1.5 text-xs ${
|
||||||
/>
|
device.online ? "text-emerald-600 dark:text-emerald-400" : "text-black/40 dark:text-white/40"
|
||||||
{device.online ? "Online" : "Offline"}
|
}`}
|
||||||
</span>
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3 text-black/60 dark:text-white/60">{device.services.length}</td>
|
|
||||||
<td className="px-4 py-3 text-xs text-black/40 dark:text-white/40">
|
|
||||||
{device.lastScan ? new Date(device.lastScan).toLocaleString("de-DE") : "nie gescannt"}
|
|
||||||
</td>
|
|
||||||
<td className="px-4 py-3">
|
|
||||||
<div className="flex items-center justify-end gap-2">
|
|
||||||
{scanMessage ? (
|
|
||||||
<span className="max-w-[22rem] truncate text-xs text-black/40 dark:text-white/40" title={scanMessage}>
|
|
||||||
{scanMessage}
|
|
||||||
</span>
|
|
||||||
) : null}
|
|
||||||
<Button
|
|
||||||
size="sm"
|
|
||||||
onClick={() => {
|
|
||||||
setScanMessage(null);
|
|
||||||
scanMutation.mutate();
|
|
||||||
}}
|
|
||||||
disabled={scanMutation.isPending}
|
|
||||||
>
|
>
|
||||||
{scanMutation.isPending ? "Scanne …" : "Jetzt scannen"}
|
<span
|
||||||
</Button>
|
className={`h-1.5 w-1.5 rounded-full ${device.online ? "bg-emerald-500" : "bg-black/20 dark:bg-white/20"}`}
|
||||||
<Button
|
/>
|
||||||
size="sm"
|
{device.online ? "Online" : "Offline"}
|
||||||
variant="danger"
|
</span>
|
||||||
onClick={() => deleteMutation.mutate()}
|
<div className="text-[10px] text-black/30 dark:text-white/30">
|
||||||
disabled={deleteMutation.isPending}
|
{device.lastScan
|
||||||
>
|
? `zuletzt gesehen: ${new Date(device.lastScan).toLocaleString("de-DE")}`
|
||||||
Löschen
|
: "nie gescannt"}
|
||||||
</Button>
|
</div>
|
||||||
</div>
|
</td>
|
||||||
</td>
|
<td className="px-4 py-3 text-black/60 dark:text-white/60">{device.services.length}</td>
|
||||||
</tr>
|
<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"
|
||||||
|
onClick={() => {
|
||||||
|
setScanMessage(null);
|
||||||
|
scanMutation.mutate();
|
||||||
|
}}
|
||||||
|
disabled={scanMutation.isPending}
|
||||||
|
>
|
||||||
|
{scanMutation.isPending ? "Scanne …" : "Jetzt scannen"}
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="danger"
|
||||||
|
onClick={() => deleteMutation.mutate()}
|
||||||
|
disabled={deleteMutation.isPending}
|
||||||
|
>
|
||||||
|
Löschen
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
|
||||||
|
{(scanMessage || staleServices.length > 0) && (
|
||||||
|
<tr className="border-b border-black/5 dark:border-white/5">
|
||||||
|
<td colSpan={6} className="px-4 pb-3">
|
||||||
|
{scanMessage ? (
|
||||||
|
<p className="text-xs text-black/40 dark:text-white/40">{scanMessage}</p>
|
||||||
|
) : null}
|
||||||
|
{staleServices.length > 0 ? (
|
||||||
|
<StaleServicesReview staleServices={staleServices} onDone={() => setStaleServices([])} />
|
||||||
|
) : null}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{expanded && (
|
||||||
|
<tr className="border-b border-black/5 bg-black/[0.015] dark:border-white/5 dark:bg-white/[0.02]">
|
||||||
|
<td colSpan={6} className="px-4 py-3">
|
||||||
|
{device.services.length === 0 ? (
|
||||||
|
<p className="text-xs text-black/40 dark:text-white/40">Keine Dienste auf diesem Gerät.</p>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{device.services.map((s) => (
|
||||||
|
<a
|
||||||
|
key={s.id}
|
||||||
|
href={s.url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="flex items-center gap-1.5 rounded-full border border-black/10 bg-white/60
|
||||||
|
px-2.5 py-1 text-xs text-black/70 hover:bg-black/5 dark:border-white/10
|
||||||
|
dark:bg-white/5 dark:text-white/70 dark:hover:bg-white/10"
|
||||||
|
>
|
||||||
|
<Favicon src={s.favicon} fallbackLetter={s.displayName} size="sm" />
|
||||||
|
{s.displayName}
|
||||||
|
<span className="text-black/30 dark:text-white/30">:{s.port}</span>
|
||||||
|
</a>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,14 +393,83 @@ function AddDeviceForm() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SortColumn = "hostname" | "ip" | "mac" | "online" | "services" | 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>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function DevicesPage() {
|
export function DevicesPage() {
|
||||||
const { data: devices, isLoading, isError } = useDevices();
|
const { data: devices, isLoading, isError } = useDevices();
|
||||||
|
const [sortColumn, setSortColumn] = useState<SortColumn>(null);
|
||||||
|
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
|
||||||
|
|
||||||
|
const list = useMemo(() => {
|
||||||
|
const base = devices ?? [];
|
||||||
|
if (!sortColumn) return base;
|
||||||
|
const sorted = [...base].sort((a, b) => {
|
||||||
|
let cmp = 0;
|
||||||
|
switch (sortColumn) {
|
||||||
|
case "hostname":
|
||||||
|
cmp = a.hostname.localeCompare(b.hostname);
|
||||||
|
break;
|
||||||
|
case "ip":
|
||||||
|
cmp = a.ip.localeCompare(b.ip, undefined, { numeric: true });
|
||||||
|
break;
|
||||||
|
case "mac":
|
||||||
|
cmp = (a.mac ?? "").localeCompare(b.mac ?? "");
|
||||||
|
break;
|
||||||
|
case "online":
|
||||||
|
cmp = Number(a.online) - Number(b.online);
|
||||||
|
break;
|
||||||
|
case "services":
|
||||||
|
cmp = a.services.length - b.services.length;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return sortDirection === "asc" ? cmp : -cmp;
|
||||||
|
});
|
||||||
|
return sorted;
|
||||||
|
}, [devices, sortColumn, sortDirection]);
|
||||||
|
|
||||||
|
function handleHeaderClick(column: SortColumn) {
|
||||||
|
if (sortColumn === column) {
|
||||||
|
setSortDirection((d) => (d === "asc" ? "desc" : "asc"));
|
||||||
|
} else {
|
||||||
|
setSortColumn(column);
|
||||||
|
setSortDirection("asc");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<AdminPageHeader
|
<AdminPageHeader
|
||||||
title="Geräte"
|
title="Geräte"
|
||||||
description="Alle bekannten Geräte in deinem Netzwerk. Scans laufen nur auf Knopfdruck."
|
description="Alle bekannten Geräte in deinem Netzwerk. Scans laufen nur auf Knopfdruck. Klick auf den Gerätenamen zeigt die zugehörigen Dienste."
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="mb-6">
|
<div className="mb-6">
|
||||||
@@ -191,22 +480,23 @@ export function DevicesPage() {
|
|||||||
<p className="text-sm text-black/40 dark:text-white/40">Lade Geräte …</p>
|
<p className="text-sm text-black/40 dark:text-white/40">Lade Geräte …</p>
|
||||||
) : isError ? (
|
) : isError ? (
|
||||||
<p className="text-sm text-red-500">Geräte konnten nicht geladen werden.</p>
|
<p className="text-sm text-red-500">Geräte konnten nicht geladen werden.</p>
|
||||||
) : devices && devices.length > 0 ? (
|
) : list.length > 0 ? (
|
||||||
<div className="overflow-hidden rounded-2xl border border-black/10 dark:border-white/10">
|
<div className="overflow-hidden rounded-2xl border border-black/10 dark:border-white/10">
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full min-w-[640px] text-sm">
|
<table className="w-full min-w-[760px] text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="border-b border-black/10 bg-black/[0.02] text-left text-xs
|
<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">
|
uppercase tracking-wide text-black/40 dark:border-white/10 dark:bg-white/5 dark:text-white/40">
|
||||||
<th className="px-4 py-2 font-medium">Gerät</th>
|
<SortableHeader label="Gerät" column="hostname" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
<th className="px-4 py-2 font-medium">Status</th>
|
<SortableHeader label="IP" column="ip" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
<th className="px-4 py-2 font-medium">Dienste</th>
|
<SortableHeader label="MAC" column="mac" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
<th className="px-4 py-2 font-medium">Letzter Scan</th>
|
<SortableHeader label="Status" column="online" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
|
<SortableHeader label="Dienste" column="services" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
<th className="px-4 py-2" />
|
<th className="px-4 py-2" />
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{devices.map((device) => (
|
{list.map((device) => (
|
||||||
<DeviceRow key={device.id} device={device} />
|
<DeviceRow key={device.id} device={device} />
|
||||||
))}
|
))}
|
||||||
</tbody>
|
</tbody>
|
||||||
|
|||||||
@@ -1,16 +1,29 @@
|
|||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { Button } from "@launchpad/ui";
|
import { Button } from "@launchpad/ui";
|
||||||
|
import type { Device } from "@launchpad/shared";
|
||||||
import { useDevices } from "../../hooks/useDevices.js";
|
import { useDevices } from "../../hooks/useDevices.js";
|
||||||
import { AdminPageHeader } from "./AdminPageHeader.js";
|
import { AdminPageHeader } from "./AdminPageHeader.js";
|
||||||
|
|
||||||
async function scanFritzBox() {
|
interface FritzBoxScanResult {
|
||||||
|
found: number;
|
||||||
|
staleDevices: Device[];
|
||||||
|
}
|
||||||
|
|
||||||
|
async function scanFritzBox(): Promise<FritzBoxScanResult> {
|
||||||
const res = await fetch("/api/scan/fritzbox", { method: "POST" });
|
const res = await fetch("/api/scan/fritzbox", { method: "POST" });
|
||||||
const body = await res.json();
|
const body = await res.json();
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
throw new Error(body.error ?? `FritzBox-Scan fehlgeschlagen (HTTP ${res.status})`);
|
throw new Error(body.error ?? `FritzBox-Scan fehlgeschlagen (HTTP ${res.status})`);
|
||||||
}
|
}
|
||||||
return body as { found: number };
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteDeviceRequest(id: string) {
|
||||||
|
const res = await fetch(`/api/devices/${id}`, { method: "DELETE" });
|
||||||
|
if (!res.ok && res.status !== 404) {
|
||||||
|
throw new Error(`Gerät konnte nicht gelöscht werden (HTTP ${res.status})`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function scanDeviceById(id: string) {
|
async function scanDeviceById(id: string) {
|
||||||
@@ -22,15 +35,67 @@ async function scanDeviceById(id: string) {
|
|||||||
return body as { created: number; updated: number };
|
return body as { created: number; updated: number };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function StaleDevicesReview({ staleDevices, onDone }: { staleDevices: Device[]; onDone: () => void }) {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [handled, setHandled] = useState<Set<string>>(new Set());
|
||||||
|
|
||||||
|
const deleteMutation = useMutation({
|
||||||
|
mutationFn: (id: string) => deleteDeviceRequest(id),
|
||||||
|
onSuccess: (_data, id) => {
|
||||||
|
setHandled((prev) => new Set(prev).add(id));
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["devices"] });
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const remaining = staleDevices.filter((d) => !handled.has(d.id));
|
||||||
|
if (remaining.length === 0) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="mt-3 rounded-xl border border-amber-500/30 bg-amber-500/5 p-3 text-xs">
|
||||||
|
<p className="mb-2 font-medium text-amber-700 dark:text-amber-400">
|
||||||
|
{remaining.length} Gerät(e), die die FritzBox früher gemeldet hatte, diesmal aber nicht
|
||||||
|
mehr:
|
||||||
|
</p>
|
||||||
|
<ul className="space-y-1">
|
||||||
|
{remaining.map((d) => (
|
||||||
|
<li key={d.id} className="flex items-center justify-between gap-2">
|
||||||
|
<span className="text-black/70 dark:text-white/70">
|
||||||
|
{d.hostname} ({d.ip})
|
||||||
|
</span>
|
||||||
|
<div className="flex gap-1">
|
||||||
|
<Button size="sm" variant="ghost" onClick={() => setHandled((prev) => new Set(prev).add(d.id))}>
|
||||||
|
Behalten
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="danger"
|
||||||
|
onClick={() => deleteMutation.mutate(d.id)}
|
||||||
|
disabled={deleteMutation.isPending}
|
||||||
|
>
|
||||||
|
Löschen
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<button onClick={onDone} className="mt-2 text-black/40 underline dark:text-white/40">
|
||||||
|
Hinweis schließen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export function ScannerPage() {
|
export function ScannerPage() {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const { data: devices } = useDevices();
|
const { data: devices } = useDevices();
|
||||||
const [bulkStatus, setBulkStatus] = useState<string | null>(null);
|
const [bulkStatus, setBulkStatus] = useState<string | null>(null);
|
||||||
const [bulkRunning, setBulkRunning] = useState(false);
|
const [bulkRunning, setBulkRunning] = useState(false);
|
||||||
|
const [staleDevices, setStaleDevices] = useState<Device[]>([]);
|
||||||
|
|
||||||
const fritzboxMutation = useMutation({
|
const fritzboxMutation = useMutation({
|
||||||
mutationFn: scanFritzBox,
|
mutationFn: scanFritzBox,
|
||||||
onSuccess: (result) => {
|
onSuccess: (result) => {
|
||||||
|
setStaleDevices(result.staleDevices);
|
||||||
queryClient.invalidateQueries({ queryKey: ["devices"] });
|
queryClient.invalidateQueries({ queryKey: ["devices"] });
|
||||||
queryClient.invalidateQueries({ queryKey: ["logs"] });
|
queryClient.invalidateQueries({ queryKey: ["logs"] });
|
||||||
return result;
|
return result;
|
||||||
@@ -94,6 +159,9 @@ export function ScannerPage() {
|
|||||||
{fritzboxMutation.isError ? (
|
{fritzboxMutation.isError ? (
|
||||||
<p className="mt-2 text-sm text-red-500">{(fritzboxMutation.error as Error).message}</p>
|
<p className="mt-2 text-sm text-red-500">{(fritzboxMutation.error as Error).message}</p>
|
||||||
) : null}
|
) : null}
|
||||||
|
{staleDevices.length > 0 ? (
|
||||||
|
<StaleDevicesReview staleDevices={staleDevices} onDone={() => setStaleDevices([])} />
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="rounded-2xl border border-black/10 p-5 dark:border-white/10">
|
<div className="rounded-2xl border border-black/10 p-5 dark:border-white/10">
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { useMemo, useRef, useState, type DragEvent } from "react";
|
import { useMemo, useState, type DragEvent } from "react";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { Button } from "@launchpad/ui";
|
import { Button, Favicon } from "@launchpad/ui";
|
||||||
import type { Service } from "@launchpad/shared";
|
import type { Service } from "@launchpad/shared";
|
||||||
import { useServices } from "../../hooks/useServices.js";
|
import { useServices } from "../../hooks/useServices.js";
|
||||||
import { useCategories } from "../../hooks/useCategories.js";
|
import { useCategories } from "../../hooks/useCategories.js";
|
||||||
|
import { useDevices } from "../../hooks/useDevices.js";
|
||||||
import { AdminPageHeader } from "./AdminPageHeader.js";
|
import { AdminPageHeader } from "./AdminPageHeader.js";
|
||||||
|
|
||||||
interface ServicePatch {
|
interface ServicePatch {
|
||||||
@@ -101,7 +102,7 @@ function CategorySelect({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const EDIT_FORM_COLSPAN = 9;
|
const EDIT_FORM_COLSPAN = 11;
|
||||||
|
|
||||||
function EditForm({ service, onDone }: { service: Service; onDone: () => void }) {
|
function EditForm({ service, onDone }: { service: Service; onDone: () => void }) {
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
@@ -233,6 +234,7 @@ function EditForm({ service, onDone }: { service: Service; onDone: () => void })
|
|||||||
|
|
||||||
function ServiceRow({
|
function ServiceRow({
|
||||||
service,
|
service,
|
||||||
|
deviceMac,
|
||||||
draggable,
|
draggable,
|
||||||
onDragStart,
|
onDragStart,
|
||||||
onDragOver,
|
onDragOver,
|
||||||
@@ -240,6 +242,7 @@ function ServiceRow({
|
|||||||
isDragging,
|
isDragging,
|
||||||
}: {
|
}: {
|
||||||
service: Service;
|
service: Service;
|
||||||
|
deviceMac: string | null;
|
||||||
draggable: boolean;
|
draggable: boolean;
|
||||||
onDragStart: (e: DragEvent<HTMLTableRowElement>) => void;
|
onDragStart: (e: DragEvent<HTMLTableRowElement>) => void;
|
||||||
onDragOver: (e: DragEvent<HTMLTableRowElement>) => void;
|
onDragOver: (e: DragEvent<HTMLTableRowElement>) => void;
|
||||||
@@ -307,16 +310,24 @@ function ServiceRow({
|
|||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-3">
|
<td className="px-4 py-3">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<span className="font-medium text-black dark:text-white">{service.displayName}</span>
|
<Favicon src={service.favicon} fallbackLetter={service.displayName} size="sm" />
|
||||||
{!service.visible ? (
|
<div className="flex items-center gap-2">
|
||||||
<span className="rounded-full bg-black/10 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-black/50 dark:bg-white/10 dark:text-white/50">
|
<span className="font-medium text-black dark:text-white">{service.displayName}</span>
|
||||||
ausgeblendet
|
{!service.visible ? (
|
||||||
</span>
|
<span className="rounded-full bg-black/10 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-black/50 dark:bg-white/10 dark:text-white/50">
|
||||||
) : null}
|
ausgeblendet
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs text-black/40 dark:text-white/40">{service.hostname}</div>
|
</td>
|
||||||
|
<td className="px-4 py-3 font-mono text-xs text-black/60 dark:text-white/60">
|
||||||
|
{service.hostname}
|
||||||
</td>
|
</td>
|
||||||
<td className="px-4 py-3 text-black/60 dark:text-white/60">{service.category ?? "–"}</td>
|
<td className="px-4 py-3 text-black/60 dark:text-white/60">{service.category ?? "–"}</td>
|
||||||
|
<td className="px-4 py-3 font-mono text-xs text-black/40 dark:text-white/40">
|
||||||
|
{deviceMac ?? "–"}
|
||||||
|
</td>
|
||||||
<td className="px-4 py-3 text-black/60 dark:text-white/60">
|
<td className="px-4 py-3 text-black/60 dark:text-white/60">
|
||||||
{service.alias.length > 0 ? service.alias.join(", ") : "–"}
|
{service.alias.length > 0 ? service.alias.join(", ") : "–"}
|
||||||
</td>
|
</td>
|
||||||
@@ -356,7 +367,7 @@ function ServiceRow({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
type SortColumn = "displayName" | "category" | "alias" | "port" | "https" | null;
|
type SortColumn = "displayName" | "hostname" | "category" | "alias" | "port" | "https" | null;
|
||||||
|
|
||||||
function SortableHeader({
|
function SortableHeader({
|
||||||
label,
|
label,
|
||||||
@@ -387,106 +398,21 @@ function SortableHeader({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
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() {
|
export function ServicesPage() {
|
||||||
const { data: services, isLoading, isError } = useServices();
|
const { data: services, isLoading, isError } = useServices();
|
||||||
|
const { data: devices } = useDevices();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const [draggedId, setDraggedId] = useState<string | null>(null);
|
const [draggedId, setDraggedId] = useState<string | null>(null);
|
||||||
const [localOrder, setLocalOrder] = useState<Service[] | null>(null);
|
const [localOrder, setLocalOrder] = useState<Service[] | null>(null);
|
||||||
const [sortColumn, setSortColumn] = useState<SortColumn>(null);
|
const [sortColumn, setSortColumn] = useState<SortColumn>(null);
|
||||||
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
|
const [sortDirection, setSortDirection] = useState<"asc" | "desc">("asc");
|
||||||
|
|
||||||
|
const macByDeviceId = useMemo(() => {
|
||||||
|
const map: Record<string, string | null> = {};
|
||||||
|
for (const d of devices ?? []) map[d.id] = d.mac;
|
||||||
|
return map;
|
||||||
|
}, [devices]);
|
||||||
|
|
||||||
const reorderMutation = useMutation({
|
const reorderMutation = useMutation({
|
||||||
mutationFn: reorderServicesRequest,
|
mutationFn: reorderServicesRequest,
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
@@ -507,6 +433,9 @@ export function ServicesPage() {
|
|||||||
case "displayName":
|
case "displayName":
|
||||||
cmp = a.displayName.localeCompare(b.displayName);
|
cmp = a.displayName.localeCompare(b.displayName);
|
||||||
break;
|
break;
|
||||||
|
case "hostname":
|
||||||
|
cmp = a.hostname.localeCompare(b.hostname);
|
||||||
|
break;
|
||||||
case "category":
|
case "category":
|
||||||
cmp = (a.category ?? "").localeCompare(b.category ?? "");
|
cmp = (a.category ?? "").localeCompare(b.category ?? "");
|
||||||
break;
|
break;
|
||||||
@@ -578,8 +507,6 @@ export function ServicesPage() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<ImportExportBar />
|
|
||||||
|
|
||||||
{sortColumn ? (
|
{sortColumn ? (
|
||||||
<div className="mb-3">
|
<div className="mb-3">
|
||||||
<Button size="sm" variant="ghost" onClick={() => setSortColumn(null)}>
|
<Button size="sm" variant="ghost" onClick={() => setSortColumn(null)}>
|
||||||
@@ -595,14 +522,16 @@ export function ServicesPage() {
|
|||||||
) : list.length > 0 ? (
|
) : list.length > 0 ? (
|
||||||
<div className="overflow-hidden rounded-2xl border border-black/10 dark:border-white/10">
|
<div className="overflow-hidden rounded-2xl border border-black/10 dark:border-white/10">
|
||||||
<div className="overflow-x-auto">
|
<div className="overflow-x-auto">
|
||||||
<table className="w-full min-w-[860px] text-sm">
|
<table className="w-full min-w-[1020px] text-sm">
|
||||||
<thead>
|
<thead>
|
||||||
<tr className="border-b border-black/10 bg-black/[0.02] text-left text-xs
|
<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">
|
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-2 py-2" />
|
<th className="px-2 py-2" />
|
||||||
<SortableHeader label="Dienst" column="displayName" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
<SortableHeader label="Dienst" column="displayName" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
|
<SortableHeader label="Host/IP" column="hostname" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
<SortableHeader label="Kategorie" column="category" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
<SortableHeader label="Kategorie" column="category" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
|
<th className="px-4 py-2 font-medium">MAC</th>
|
||||||
<SortableHeader label="Alias" column="alias" 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="Port" column="port" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
<SortableHeader label="Protokoll" column="https" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
<SortableHeader label="Protokoll" column="https" activeColumn={sortColumn} direction={sortDirection} onClick={handleHeaderClick} />
|
||||||
@@ -615,6 +544,7 @@ export function ServicesPage() {
|
|||||||
<ServiceRow
|
<ServiceRow
|
||||||
key={service.id}
|
key={service.id}
|
||||||
service={service}
|
service={service}
|
||||||
|
deviceMac={macByDeviceId[service.deviceId] ?? null}
|
||||||
draggable={dragEnabled}
|
draggable={dragEnabled}
|
||||||
isDragging={draggedId === service.id}
|
isDragging={draggedId === service.id}
|
||||||
onDragStart={handleDragStart(service.id)}
|
onDragStart={handleDragStart(service.id)}
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
import { useState } from "react";
|
import { useRef, useState } from "react";
|
||||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
import { Button } from "@launchpad/ui";
|
import { Button } from "@launchpad/ui";
|
||||||
import { useBackendHealth } from "../../hooks/useBackendHealth.js";
|
import { useBackendHealth } from "../../hooks/useBackendHealth.js";
|
||||||
import { useTheme } from "../../hooks/useTheme.js";
|
import { useTheme } from "../../hooks/useTheme.js";
|
||||||
|
import { useSettings } from "../../hooks/useSettings.js";
|
||||||
import { AdminPageHeader } from "./AdminPageHeader.js";
|
import { AdminPageHeader } from "./AdminPageHeader.js";
|
||||||
|
|
||||||
function InfoRow({ label, value }: { label: string; value: string }) {
|
function InfoRow({ label, value }: { label: string; value: string }) {
|
||||||
@@ -14,6 +15,210 @@ function InfoRow({ label, value }: { label: string; value: string }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function RecentVisitsLimitSetting() {
|
||||||
|
const { data: settings } = useSettings();
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const [value, setValue] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const mutation = useMutation({
|
||||||
|
mutationFn: async (limit: number) => {
|
||||||
|
const res = await fetch("/api/settings", {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ recentVisitsLimit: limit }),
|
||||||
|
});
|
||||||
|
if (!res.ok) throw new Error(`Speichern fehlgeschlagen (HTTP ${res.status})`);
|
||||||
|
return res.json();
|
||||||
|
},
|
||||||
|
onSuccess: () => queryClient.invalidateQueries({ queryKey: ["settings"] }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const displayed = value ?? String(settings?.recentVisitsLimit ?? 5);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex items-center justify-between py-2">
|
||||||
|
<div>
|
||||||
|
<span className="text-sm text-black/50 dark:text-white/50">
|
||||||
|
Anzahl „Zuletzt besucht"
|
||||||
|
</span>
|
||||||
|
<p className="text-xs text-black/30 dark:text-white/30">0 = Leiste ausblenden</p>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
min={0}
|
||||||
|
max={50}
|
||||||
|
value={displayed}
|
||||||
|
onChange={(e) => setValue(e.target.value)}
|
||||||
|
onBlur={() => {
|
||||||
|
const n = Number(value);
|
||||||
|
if (value !== null && Number.isFinite(n)) mutation.mutate(n);
|
||||||
|
}}
|
||||||
|
className="w-20 rounded-lg border border-black/10 bg-white px-2 py-1 text-sm
|
||||||
|
text-black dark:border-white/10 dark:bg-white/10 dark:text-white"
|
||||||
|
/>
|
||||||
|
{mutation.isPending ? <span className="text-xs text-black/30 dark:text-white/30">speichere …</span> : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readFileAsBase64(file: File): Promise<string> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const reader = new FileReader();
|
||||||
|
reader.onload = () => resolve((reader.result as string).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 TransferResult {
|
||||||
|
devicesImported: number;
|
||||||
|
devicesSkipped: number;
|
||||||
|
servicesImported: number;
|
||||||
|
servicesSkipped: number;
|
||||||
|
errors: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function ImportExportSection() {
|
||||||
|
const queryClient = useQueryClient();
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [result, setResult] = useState<TransferResult | null>(null);
|
||||||
|
|
||||||
|
const importMutation = useMutation({
|
||||||
|
mutationFn: async (file: File): Promise<TransferResult> => {
|
||||||
|
const content = await readFileAsBase64(file);
|
||||||
|
const format = detectFormat(file.name);
|
||||||
|
const res = await fetch("/api/transfer/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: ["devices"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["services"] });
|
||||||
|
queryClient.invalidateQueries({ queryKey: ["categories"] });
|
||||||
|
},
|
||||||
|
onError: (err: Error) =>
|
||||||
|
setResult({
|
||||||
|
devicesImported: 0,
|
||||||
|
devicesSkipped: 0,
|
||||||
|
servicesImported: 0,
|
||||||
|
servicesSkipped: 0,
|
||||||
|
errors: [err.message],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-2xl border border-black/10 p-5 dark:border-white/10">
|
||||||
|
<h2 className="mb-1 font-medium text-black dark:text-white">Import / Export</h2>
|
||||||
|
<p className="mb-4 text-sm text-black/50 dark:text-white/50">
|
||||||
|
Exportiert Geräte und Dienste in einer Datei. Import legt ausschließlich neue Einträge
|
||||||
|
an – bereits vorhandene Geräte (Abgleich über IP/Hostname) und Dienste (Abgleich über
|
||||||
|
Gerät + Port) werden übersprungen, nie überschrieben oder verdoppelt.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<div className="mb-4 flex flex-wrap gap-2">
|
||||||
|
<a href="/api/transfer/export?format=csv" download>
|
||||||
|
<Button size="sm">CSV exportieren</Button>
|
||||||
|
</a>
|
||||||
|
<a href="/api/transfer/export?format=xlsx" download>
|
||||||
|
<Button size="sm">Excel exportieren</Button>
|
||||||
|
</a>
|
||||||
|
<a href="/api/transfer/export?format=json" download>
|
||||||
|
<Button size="sm">JSON exportieren</Button>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="mb-4">
|
||||||
|
<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
|
||||||
|
variant="primary"
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
disabled={importMutation.isPending}
|
||||||
|
>
|
||||||
|
{importMutation.isPending ? "Importiere …" : "Datei importieren (CSV/Excel/JSON)"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{result ? (
|
||||||
|
<p className="mb-4 text-xs text-black/50 dark:text-white/50">
|
||||||
|
{result.devicesImported} Gerät(e) + {result.servicesImported} Dienst(e) importiert,{" "}
|
||||||
|
{result.devicesSkipped + result.servicesSkipped} übersprungen (bereits vorhanden)
|
||||||
|
{result.errors.length > 0
|
||||||
|
? `, ${result.errors.length} Fehler: ${result.errors.join(" | ")}`
|
||||||
|
: "."}
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
|
||||||
|
<details className="text-xs text-black/50 dark:text-white/50">
|
||||||
|
<summary className="cursor-pointer font-medium text-black/70 dark:text-white/70">
|
||||||
|
Format-Anleitung für den Import anzeigen
|
||||||
|
</summary>
|
||||||
|
<div className="mt-2 space-y-2">
|
||||||
|
<p>
|
||||||
|
Eine Zeile pro Eintrag, mit einer Spalte{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">type</code> ={" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">device</code> oder{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">service</code>. Am
|
||||||
|
einfachsten: erst exportieren, die Datei als Vorlage nehmen.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<strong>Geräte-Zeilen</strong> brauchen:{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">hostname</code>,{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">ip</code> (Pflicht),
|
||||||
|
optional <code className="rounded bg-black/5 px-1 dark:bg-white/10">mac</code>,{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">manufacturer</code>,{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">model</code>.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<strong>Dienst-Zeilen</strong> brauchen:{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">displayName</code>,{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">hostname</code>,{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">port</code>,{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">url</code> (Pflicht),
|
||||||
|
plus <code className="rounded bg-black/5 px-1 dark:bg-white/10">deviceHostname</code>{" "}
|
||||||
|
und <code className="rounded bg-black/5 px-1 dark:bg-white/10">deviceIp</code>, um
|
||||||
|
sie einem Gerät zuzuordnen (wird bei Bedarf automatisch angelegt). Optional:{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">category</code>,{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">alias</code> (mit{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">;</code> getrennt),{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">favorite</code>,{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">visible</code>,{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">https</code> (jeweils{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">true</code>/
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">false</code>),{" "}
|
||||||
|
<code className="rounded bg-black/5 px-1 dark:bg-white/10">order</code> (Zahl).
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
async function resetEverything() {
|
async function resetEverything() {
|
||||||
const res = await fetch("/api/reset", {
|
const res = await fetch("/api/reset", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
@@ -82,7 +287,7 @@ export function SettingsPage() {
|
|||||||
<div>
|
<div>
|
||||||
<AdminPageHeader title="Einstellungen" />
|
<AdminPageHeader title="Einstellungen" />
|
||||||
|
|
||||||
<div className="max-w-lg space-y-6">
|
<div className="max-w-2xl space-y-6">
|
||||||
<div className="rounded-2xl border border-black/10 p-5 dark:border-white/10">
|
<div className="rounded-2xl border border-black/10 p-5 dark:border-white/10">
|
||||||
<h2 className="mb-2 font-medium text-black dark:text-white">Darstellung</h2>
|
<h2 className="mb-2 font-medium text-black dark:text-white">Darstellung</h2>
|
||||||
<div className="flex items-center justify-between py-2">
|
<div className="flex items-center justify-between py-2">
|
||||||
@@ -96,8 +301,22 @@ export function SettingsPage() {
|
|||||||
{theme === "dark" ? "🌙 Dunkel" : "☀️ Hell"} – wechseln
|
{theme === "dark" ? "🌙 Dunkel" : "☀️ Hell"} – wechseln
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
<RecentVisitsLimitSetting />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div className="rounded-2xl border border-black/10 p-5 dark:border-white/10">
|
||||||
|
<h2 className="mb-2 font-medium text-black dark:text-white">HTTPS</h2>
|
||||||
|
<p className="mb-3 text-sm text-black/50 dark:text-white/50">
|
||||||
|
Root-CA-Zertifikat herunterladen und auf deinen Geräten als vertrauenswürdig
|
||||||
|
einstufen, um die Browser-Warnung dauerhaft loszuwerden (einmal pro Gerät).
|
||||||
|
</p>
|
||||||
|
<a href="/ca.crt" download>
|
||||||
|
<Button variant="primary">Root-Zertifikat herunterladen (ca.crt)</Button>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<ImportExportSection />
|
||||||
|
|
||||||
<div className="rounded-2xl border border-black/10 p-5 dark:border-white/10">
|
<div className="rounded-2xl border border-black/10 p-5 dark:border-white/10">
|
||||||
<h2 className="mb-2 font-medium text-black dark:text-white">Backend</h2>
|
<h2 className="mb-2 font-medium text-black dark:text-white">Backend</h2>
|
||||||
{error ? (
|
{error ? (
|
||||||
|
|||||||
@@ -272,3 +272,70 @@ komplett offline funktionierende Variante ersetzt.
|
|||||||
> erfolgreich – die eigentliche UI-Interaktion (Drag & Drop, Dropdown-
|
> erfolgreich – die eigentliche UI-Interaktion (Drag & Drop, Dropdown-
|
||||||
> Verhalten) konnte mangels Browser in dieser Umgebung nicht geklickt
|
> Verhalten) konnte mangels Browser in dieser Umgebung nicht geklickt
|
||||||
> werden, nur durch Code-Review abgesichert.
|
> werden, nur durch Code-Review abgesichert.
|
||||||
|
|
||||||
|
## Vierte Feature-Runde: Bugfixes, Lesezeichen-Ausbau, Admin-Überarbeitung
|
||||||
|
|
||||||
|
**Bugfixes:**
|
||||||
|
- Dark-Mode wird jetzt in `main.tsx` sofort beim Start angewendet (vorher nur
|
||||||
|
wenn eine Seite `useTheme()` aufrief) – behebt hellen Start bei Direktlink
|
||||||
|
auf `/admin/...`
|
||||||
|
- `color-scheme`-CSS-Property gesetzt – native `<select>`-Dropdowns folgen
|
||||||
|
jetzt automatisch dem Theme (vorher weiße Schrift auf weißem Grund im Dark
|
||||||
|
Mode möglich)
|
||||||
|
- Suche findet jetzt auch Teiltreffer im Hostnamen (z. B. "47" findet
|
||||||
|
"192.168.1.47"), zusätzliche Ranking-Stufe in `rankService`
|
||||||
|
- `packages/ui` hatte keine DOM-Typen in der TS-Konfiguration (seit Commit 6)
|
||||||
|
– `navigator.clipboard` für den neuen Copy-Button hat das aufgedeckt, jetzt
|
||||||
|
behoben
|
||||||
|
|
||||||
|
**Neue Backend-Entitäten:**
|
||||||
|
- Kategorie-Farbe (`color`-Spalte, Migration für Bestandsinstallationen)
|
||||||
|
- "Zuletzt besucht" (`recent_visits`-Tabelle, per Einstellung konfigurierbare
|
||||||
|
Anzahl)
|
||||||
|
- Key-Value-Einstellungen (`app_settings`-Tabelle)
|
||||||
|
- "Später lesen" (`read_later`-Tabelle, inkl. "zu Lesezeichen befördern")
|
||||||
|
- Lesezeichen: automatische Beschreibungs-Extraktion (Meta-Tag), Favicon jetzt
|
||||||
|
editierbar
|
||||||
|
- Kombinierter Geräte+Dienste-Import/Export (`/api/transfer/*`, ersetzt die
|
||||||
|
bisherigen `/api/services/export|import`) mit `type`-Spalte pro Zeile
|
||||||
|
- Scan-Reconciliation: `/api/scan/devices/:id` und `/api/scan/fritzbox` geben
|
||||||
|
jetzt zusätzlich `staleServices`/`staleDevices` zurück (Einträge, die beim
|
||||||
|
letzten Scan nicht mehr gefunden wurden) – nichts wird automatisch
|
||||||
|
gelöscht, nur zur manuellen Durchsicht zurückgegeben
|
||||||
|
- CA-Zertifikat unterstützt jetzt zwei Hostnamen gleichzeitig
|
||||||
|
(`LAUNCHPAD_HOST` + optional `LAUNCHPAD_EXTRA_HOST`, z. B. IP + LXC-Name)
|
||||||
|
|
||||||
|
**Frontend – Startseite:**
|
||||||
|
- Nur noch die Trefferliste scrollt auf Mobilgeräten (`h-dvh` + Flexbox-
|
||||||
|
Scroll-Trick), nicht mehr die ganze Seite
|
||||||
|
- Copy-Icon pro Suchtreffer (Zwischenablage)
|
||||||
|
- Kompaktere Kopfzeile, Favoriten jetzt reine Icon-Chips (Name als Tooltip)
|
||||||
|
- Favicons: heller Hintergrund + automatischer Fallback bei Ladefehlern
|
||||||
|
- Kategorie-Farbe als Punkt (Suche) bzw. Ring (Favoriten)
|
||||||
|
- "Später lesen"-Eingabefeld + "Zuletzt besucht"-Leiste unterhalb der Suche
|
||||||
|
- Favoriten direkt hier per Drag & Drop sortierbar (vorher nur im
|
||||||
|
Adminbereich)
|
||||||
|
|
||||||
|
**Frontend – Adminbereich:**
|
||||||
|
- Einstellungen: CA-Download-Link, Import/Export (inkl. aufklappbarer
|
||||||
|
Format-Anleitung), Anzahl-Regler für "Zuletzt besucht"
|
||||||
|
- Dienste: Favicon in der Tabelle, neue MAC-Spalte (vom Gerät abgeleitet),
|
||||||
|
eigene sortierbare Host/IP-Spalte
|
||||||
|
- Geräte: MAC/Hersteller/Modell editierbar, alle Spalten sortierbar,
|
||||||
|
aufklappbare Dienste-Liste pro Gerät, "zuletzt gesehen"-Zeitstempel,
|
||||||
|
Stale-Service-Review direkt nach einem Scan (Behalten/Entfernen)
|
||||||
|
- Lesezeichen: sortierbare Spalten (gleiches Muster wie Dienste)
|
||||||
|
- Scanner: Stale-Device-Review nach FritzBox-Scan (Behalten/Löschen)
|
||||||
|
- Dashboard: Favoriten getrennt nach Diensten/Lesezeichen, neue
|
||||||
|
Lesezeichen-Kachel, "🏠 Startseite"-Schnellzugriff
|
||||||
|
|
||||||
|
> Verifiziert: vollständiger `pnpm build` (`tsc --noEmit` + `vite build`)
|
||||||
|
> nach jedem größeren Schritt erfolgreich; alle neuen Backend-Endpunkte
|
||||||
|
> (Kategorie-Farbe inkl. Validierung, Lesezeichen mit Auto-Beschreibung,
|
||||||
|
> Einstellungen, Zuletzt-besucht, Später-lesen inkl. Beförderung zu
|
||||||
|
> Lesezeichen, kombinierter Import/Export inkl. Idempotenz, Scan-
|
||||||
|
> Reconciliation) per echtem HTTP-Roundtrip getestet; finaler Smoke-Test
|
||||||
|
> bestätigt alle Routen nach dem vollständigen Umbau erreichbar. Die
|
||||||
|
> eigentliche UI-Interaktion (Klicks, Drag & Drop, Formulare) konnte mangels
|
||||||
|
> Browser in dieser Umgebung nicht getestet werden – nur Build-Erfolg und
|
||||||
|
> Code-Review.
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ export interface Category {
|
|||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
order: number;
|
order: number;
|
||||||
|
/** Hex-Farbe (z. B. "#3b82f6"), zeigt sich als Punkt in Suche/Favoriten. */
|
||||||
|
color: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ScanLogEntry {
|
export interface ScanLogEntry {
|
||||||
@@ -118,7 +120,8 @@ export type SearchResult =
|
|||||||
* 3. Hostname beginnt mit Suchtext
|
* 3. Hostname beginnt mit Suchtext
|
||||||
* 4. Displayname enthält Suchtext
|
* 4. Displayname enthält Suchtext
|
||||||
* 5. Alias enthält Suchtext
|
* 5. Alias enthält Suchtext
|
||||||
* 6. Beschreibung enthält Suchtext
|
* 6. Hostname enthält Suchtext (z. B. "47" findet "192.168.1.47")
|
||||||
|
* 7. Beschreibung enthält Suchtext
|
||||||
*
|
*
|
||||||
* Niedrigere Werte sind relevanter. `null` bedeutet: kein Treffer.
|
* Niedrigere Werte sind relevanter. `null` bedeutet: kein Treffer.
|
||||||
* Funktioniert generisch für alles, was die Rankable-Form erfüllt
|
* Funktioniert generisch für alles, was die Rankable-Form erfüllt
|
||||||
@@ -138,7 +141,8 @@ export function rankService<T extends Rankable>(item: T, query: string): number
|
|||||||
if (hostname.startsWith(q)) return 3;
|
if (hostname.startsWith(q)) return 3;
|
||||||
if (displayName.includes(q)) return 4;
|
if (displayName.includes(q)) return 4;
|
||||||
if (alias.some((a) => a.includes(q))) return 5;
|
if (alias.some((a) => a.includes(q))) return 5;
|
||||||
if (description.includes(q)) return 6;
|
if (hostname.includes(q)) return 6;
|
||||||
|
if (description.includes(q)) return 7;
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -62,6 +62,10 @@ export type ServiceReorderInput = z.infer<typeof ServiceReorderSchema>;
|
|||||||
|
|
||||||
export const CategoryCreateSchema = z.object({
|
export const CategoryCreateSchema = z.object({
|
||||||
name: z.string().min(1, "name darf nicht leer sein"),
|
name: z.string().min(1, "name darf nicht leer sein"),
|
||||||
|
color: z
|
||||||
|
.string()
|
||||||
|
.regex(/^#[0-9a-fA-F]{6}$/, "Farbe muss ein Hex-Code sein, z. B. #3b82f6")
|
||||||
|
.optional(),
|
||||||
});
|
});
|
||||||
export type CategoryCreateInput = z.infer<typeof CategoryCreateSchema>;
|
export type CategoryCreateInput = z.infer<typeof CategoryCreateSchema>;
|
||||||
|
|
||||||
@@ -87,6 +91,7 @@ export const BookmarkCreateSchema = z.object({
|
|||||||
description: z.string().optional(),
|
description: z.string().optional(),
|
||||||
category: z.string().optional(),
|
category: z.string().optional(),
|
||||||
icon: z.string().optional(),
|
icon: z.string().optional(),
|
||||||
|
favicon: z.string().optional(),
|
||||||
favorite: z.boolean().optional(),
|
favorite: z.boolean().optional(),
|
||||||
alias: z.array(z.string()).optional(),
|
alias: z.array(z.string()).optional(),
|
||||||
order: z.number().optional(),
|
order: z.number().optional(),
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
import { useState, useEffect } from "react";
|
||||||
|
|
||||||
export interface FaviconProps {
|
export interface FaviconProps {
|
||||||
src?: string | null;
|
src?: string | null;
|
||||||
fallbackLetter: string;
|
fallbackLetter: string;
|
||||||
@@ -12,13 +14,21 @@ const SIZE_CLASSES: Record<NonNullable<FaviconProps["size"]>, string> = {
|
|||||||
/**
|
/**
|
||||||
* Zeigt ein Favicon mit einem immer hellen Hintergrund (unabhängig vom
|
* Zeigt ein Favicon mit einem immer hellen Hintergrund (unabhängig vom
|
||||||
* Dark/Light-Theme der App) – viele Favicons sind selbst dunkel/schwarz und
|
* Dark/Light-Theme der App) – viele Favicons sind selbst dunkel/schwarz und
|
||||||
* wären auf dunklem Hintergrund sonst kaum zu erkennen. Ohne Favicon wird
|
* wären auf dunklem Hintergrund sonst kaum zu erkennen. Ohne Favicon oder bei
|
||||||
|
* einem fehlgeschlagenen Ladeversuch (kaputte URL, 404, CORS) wird
|
||||||
* stattdessen der erste Buchstabe des Namens gezeigt.
|
* stattdessen der erste Buchstabe des Namens gezeigt.
|
||||||
*/
|
*/
|
||||||
export function Favicon({ src, fallbackLetter, size = "md" }: FaviconProps) {
|
export function Favicon({ src, fallbackLetter, size = "md" }: FaviconProps) {
|
||||||
const dimension = SIZE_CLASSES[size];
|
const dimension = SIZE_CLASSES[size];
|
||||||
|
const [failed, setFailed] = useState(false);
|
||||||
|
|
||||||
if (!src) {
|
// Bei geändertem src (z. B. anderer Listeneintrag durch Virtualisierung/Key-Wiederverwendung)
|
||||||
|
// erneut versuchen statt dauerhaft im Fehlerzustand zu bleiben.
|
||||||
|
useEffect(() => {
|
||||||
|
setFailed(false);
|
||||||
|
}, [src]);
|
||||||
|
|
||||||
|
if (!src || failed) {
|
||||||
return (
|
return (
|
||||||
<span
|
<span
|
||||||
className={`flex ${dimension} shrink-0 items-center justify-center rounded
|
className={`flex ${dimension} shrink-0 items-center justify-center rounded
|
||||||
@@ -35,7 +45,12 @@ export function Favicon({ src, fallbackLetter, size = "md" }: FaviconProps) {
|
|||||||
className={`flex ${dimension} shrink-0 items-center justify-center rounded
|
className={`flex ${dimension} shrink-0 items-center justify-center rounded
|
||||||
bg-white p-0.5 ring-1 ring-black/5`}
|
bg-white p-0.5 ring-1 ring-black/5`}
|
||||||
>
|
>
|
||||||
<img src={src} alt="" className="h-full w-full object-contain" />
|
<img
|
||||||
|
src={src}
|
||||||
|
alt=""
|
||||||
|
className="h-full w-full object-contain"
|
||||||
|
onError={() => setFailed(true)}
|
||||||
|
/>
|
||||||
</span>
|
</span>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,23 +7,33 @@ export interface FavoriteItem {
|
|||||||
favicon: string | null;
|
favicon: string | null;
|
||||||
hostname: string;
|
hostname: string;
|
||||||
port?: number;
|
port?: number;
|
||||||
|
category?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FavoritesBarProps {
|
export interface FavoritesBarProps {
|
||||||
items: FavoriteItem[];
|
items: FavoriteItem[];
|
||||||
label?: string;
|
label?: string;
|
||||||
|
/** Kategoriename -> Hex-Farbe, zeigt sich als Ring um das Icon. */
|
||||||
|
categoryColors?: Record<string, string>;
|
||||||
onOpen: (item: FavoriteItem) => void;
|
onOpen: (item: FavoriteItem) => void;
|
||||||
/** Wenn gesetzt, sind die Chips per Drag & Drop sortierbar. */
|
/** Wenn gesetzt, sind die Chips per Drag & Drop sortierbar. */
|
||||||
onReorder?: (orderedIds: string[]) => void;
|
onReorder?: (orderedIds: string[]) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Zeigt Favoriten als anklickbare, per Drag & Drop sortierbare Chips – immer
|
* Zeigt Favoriten als kompakte, nur-Icon-Chips – Name erscheint als Tooltip
|
||||||
* sichtbar, unabhängig vom Suchfeld. Dienste und Lesezeichen werden über
|
* beim Hover, nicht als sichtbarer Text (bewusst platzsparend). Anklickbar,
|
||||||
* getrennte FavoritesBar-Instanzen gerendert (siehe HomePage), daher rein
|
* per Drag & Drop sortierbar. Dienste und Lesezeichen werden über getrennte
|
||||||
* generisch über FavoriteItem statt fest an Service gebunden.
|
* FavoritesBar-Instanzen gerendert (siehe HomePage), daher rein generisch
|
||||||
|
* über FavoriteItem statt fest an Service gebunden.
|
||||||
*/
|
*/
|
||||||
export function FavoritesBar({ items, label, onOpen, onReorder }: FavoritesBarProps) {
|
export function FavoritesBar({
|
||||||
|
items,
|
||||||
|
label,
|
||||||
|
categoryColors,
|
||||||
|
onOpen,
|
||||||
|
onReorder,
|
||||||
|
}: FavoritesBarProps) {
|
||||||
const [draggedId, setDraggedId] = useState<string | null>(null);
|
const [draggedId, setDraggedId] = useState<string | null>(null);
|
||||||
const [localOrder, setLocalOrder] = useState<FavoriteItem[] | null>(null);
|
const [localOrder, setLocalOrder] = useState<FavoriteItem[] | null>(null);
|
||||||
|
|
||||||
@@ -71,30 +81,33 @@ export function FavoritesBar({ items, label, onOpen, onReorder }: FavoritesBarPr
|
|||||||
aria-label={label ?? "Favoriten"}
|
aria-label={label ?? "Favoriten"}
|
||||||
className="flex flex-wrap items-center justify-center gap-2"
|
className="flex flex-wrap items-center justify-center gap-2"
|
||||||
>
|
>
|
||||||
{list.map((item) => (
|
{list.map((item) => {
|
||||||
<button
|
const ringColor = item.category ? categoryColors?.[item.category] : undefined;
|
||||||
key={item.id}
|
return (
|
||||||
type="button"
|
<button
|
||||||
draggable={!!onReorder}
|
key={item.id}
|
||||||
onDragStart={handleDragStart(item.id)}
|
type="button"
|
||||||
onDragOver={handleDragOver(item.id)}
|
draggable={!!onReorder}
|
||||||
onDrop={handleDrop}
|
onDragStart={handleDragStart(item.id)}
|
||||||
onClick={() => onOpen(item)}
|
onDragOver={handleDragOver(item.id)}
|
||||||
title={
|
onDrop={handleDrop}
|
||||||
item.port !== undefined
|
onClick={() => onOpen(item)}
|
||||||
? `${item.displayName} (${item.hostname}:${item.port})`
|
title={
|
||||||
: `${item.displayName} (${item.hostname})`
|
item.port !== undefined
|
||||||
}
|
? `${item.displayName} (${item.hostname}:${item.port})`
|
||||||
className={`flex items-center gap-2 rounded-full border border-black/10 bg-white/70
|
: `${item.displayName} (${item.hostname})`
|
||||||
px-3 py-1.5 text-sm text-black transition-colors hover:bg-black/5
|
}
|
||||||
dark:border-white/10 dark:bg-white/5 dark:text-white dark:hover:bg-white/10 ${
|
style={ringColor ? { boxShadow: `0 0 0 2px ${ringColor}` } : undefined}
|
||||||
onReorder ? "cursor-grab active:cursor-grabbing" : ""
|
className={`flex h-10 w-10 items-center justify-center rounded-full border
|
||||||
} ${draggedId === item.id ? "opacity-40" : ""}`}
|
border-black/10 bg-white/70 transition-colors hover:bg-black/5
|
||||||
>
|
dark:border-white/10 dark:bg-white/5 dark:hover:bg-white/10 ${
|
||||||
<Favicon src={item.favicon} fallbackLetter={item.displayName} size="sm" />
|
onReorder ? "cursor-grab active:cursor-grabbing" : ""
|
||||||
<span className="max-w-[10rem] truncate">{item.displayName}</span>
|
} ${draggedId === item.id ? "opacity-40" : ""}`}
|
||||||
</button>
|
>
|
||||||
))}
|
<Favicon src={item.favicon} fallbackLetter={item.displayName} size="md" />
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { KeyboardEvent } from "react";
|
import { useState, type KeyboardEvent } from "react";
|
||||||
import type { SearchResult } from "@launchpad/shared";
|
import type { SearchResult } from "@launchpad/shared";
|
||||||
import { Favicon } from "./Favicon.js";
|
import { Favicon } from "./Favicon.js";
|
||||||
|
|
||||||
@@ -6,6 +6,8 @@ export interface ResultsListProps {
|
|||||||
results: SearchResult[];
|
results: SearchResult[];
|
||||||
selectedIndex: number;
|
selectedIndex: number;
|
||||||
emptyLabel?: string;
|
emptyLabel?: string;
|
||||||
|
/** Kategoriename -> Hex-Farbe, für den kleinen Farbpunkt neben dem Kategorie-Badge. */
|
||||||
|
categoryColors?: Record<string, string>;
|
||||||
onHover: (index: number) => void;
|
onHover: (index: number) => void;
|
||||||
onOpen: (item: SearchResult) => void;
|
onOpen: (item: SearchResult) => void;
|
||||||
onToggleFavorite?: (item: SearchResult) => void;
|
onToggleFavorite?: (item: SearchResult) => void;
|
||||||
@@ -16,11 +18,16 @@ export interface ResultsListProps {
|
|||||||
* und Lesezeichen gemeinsam, unterscheidbar an einem kleinen Badge. Die
|
* und Lesezeichen gemeinsam, unterscheidbar an einem kleinen Badge. Die
|
||||||
* Tastatur-Navigation (Pfeiltasten/Enter) wird vom Elternelement gesteuert;
|
* Tastatur-Navigation (Pfeiltasten/Enter) wird vom Elternelement gesteuert;
|
||||||
* diese Komponente ist rein darstellend + klick-/tastaturbar.
|
* diese Komponente ist rein darstellend + klick-/tastaturbar.
|
||||||
|
*
|
||||||
|
* Füllt die Höhe des Elternelements aus (h-full) und scrollt selbst intern –
|
||||||
|
* das Elternelement muss dafür `flex-1 min-h-0` sein (klassischer
|
||||||
|
* Flexbox-Scroll-Trick), damit nur die Liste scrollt und nicht die ganze Seite.
|
||||||
*/
|
*/
|
||||||
export function ResultsList({
|
export function ResultsList({
|
||||||
results,
|
results,
|
||||||
selectedIndex,
|
selectedIndex,
|
||||||
emptyLabel = "Keine Treffer gefunden.",
|
emptyLabel = "Keine Treffer gefunden.",
|
||||||
|
categoryColors,
|
||||||
onHover,
|
onHover,
|
||||||
onOpen,
|
onOpen,
|
||||||
onToggleFavorite,
|
onToggleFavorite,
|
||||||
@@ -28,7 +35,7 @@ export function ResultsList({
|
|||||||
if (results.length === 0) {
|
if (results.length === 0) {
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
className="mt-4 rounded-2xl border border-black/5 bg-white/50 px-5 py-8 text-center
|
className="rounded-2xl border border-black/5 bg-white/50 px-5 py-8 text-center
|
||||||
text-sm text-black/40 dark:border-white/5 dark:bg-white/5 dark:text-white/40"
|
text-sm text-black/40 dark:border-white/5 dark:bg-white/5 dark:text-white/40"
|
||||||
>
|
>
|
||||||
{emptyLabel}
|
{emptyLabel}
|
||||||
@@ -39,14 +46,14 @@ export function ResultsList({
|
|||||||
return (
|
return (
|
||||||
<ul
|
<ul
|
||||||
role="listbox"
|
role="listbox"
|
||||||
className="mt-4 flex max-h-[60vh] flex-col overflow-y-auto rounded-2xl border
|
className="flex h-full flex-col overflow-y-auto rounded-2xl border border-black/10
|
||||||
border-black/10 bg-white/80 shadow-lg backdrop-blur-md dark:border-white/10
|
bg-white/80 shadow-lg backdrop-blur-md dark:border-white/10 dark:bg-white/5"
|
||||||
dark:bg-white/5"
|
|
||||||
>
|
>
|
||||||
{results.map((item, index) => {
|
{results.map((item, index) => {
|
||||||
const active = index === selectedIndex;
|
const active = index === selectedIndex;
|
||||||
const subtitle =
|
const subtitle =
|
||||||
item.kind === "service" ? `${item.hostname}:${item.port}` : item.hostname;
|
item.kind === "service" ? `${item.hostname}:${item.port}` : item.hostname;
|
||||||
|
const categoryColor = item.category ? categoryColors?.[item.category] : undefined;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li key={`${item.kind}-${item.id}`} role="option" aria-selected={active}>
|
<li key={`${item.kind}-${item.id}`} role="option" aria-selected={active}>
|
||||||
@@ -83,11 +90,20 @@ export function ResultsList({
|
|||||||
</span>
|
</span>
|
||||||
|
|
||||||
{item.category ? (
|
{item.category ? (
|
||||||
<span className="shrink-0 text-xs text-black/30 dark:text-white/30">
|
<span className="flex shrink-0 items-center gap-1 text-xs text-black/30 dark:text-white/30">
|
||||||
|
{categoryColor ? (
|
||||||
|
<span
|
||||||
|
className="h-2 w-2 shrink-0 rounded-full"
|
||||||
|
style={{ backgroundColor: categoryColor }}
|
||||||
|
aria-hidden
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
{item.category}
|
{item.category}
|
||||||
</span>
|
</span>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
|
<CopyButton url={item.url} />
|
||||||
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
onClick={(e) => {
|
onClick={(e) => {
|
||||||
@@ -112,3 +128,31 @@ export function ResultsList({
|
|||||||
</ul>
|
</ul>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function CopyButton({ url }: { url: string }) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
navigator.clipboard
|
||||||
|
.writeText(url)
|
||||||
|
.then(() => {
|
||||||
|
setCopied(true);
|
||||||
|
setTimeout(() => setCopied(false), 1500);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
/* Zwischenablage evtl. ohne Berechtigung (z. B. unsicherer Kontext) - stillschweigend ignorieren */
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
aria-label="Adresse kopieren"
|
||||||
|
title={copied ? "Kopiert!" : "Adresse kopieren"}
|
||||||
|
className="shrink-0 text-sm leading-none text-black/20 transition-colors hover:text-black/60
|
||||||
|
dark:text-white/20 dark:hover:text-white/60"
|
||||||
|
>
|
||||||
|
{copied ? "✓" : "⧉"}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -5,7 +5,8 @@
|
|||||||
"rootDir": "src",
|
"rootDir": "src",
|
||||||
"jsx": "react-jsx",
|
"jsx": "react-jsx",
|
||||||
"module": "ESNext",
|
"module": "ESNext",
|
||||||
"moduleResolution": "Bundler"
|
"moduleResolution": "Bundler",
|
||||||
|
"lib": ["ES2022", "DOM", "DOM.Iterable"]
|
||||||
},
|
},
|
||||||
"include": ["src"]
|
"include": ["src"]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user