diff --git a/web/index.html b/web/index.html index 4d45d67..2cae07f 100644 --- a/web/index.html +++ b/web/index.html @@ -5,7 +5,8 @@ Homelab Manager - + + diff --git a/web/public/apple-touch-icon.png b/web/public/apple-touch-icon.png index 141e9db..b339d7a 100644 Binary files a/web/public/apple-touch-icon.png and b/web/public/apple-touch-icon.png differ diff --git a/web/public/favicon-32.png b/web/public/favicon-32.png new file mode 100644 index 0000000..3afd22c Binary files /dev/null and b/web/public/favicon-32.png differ diff --git a/web/public/icon-192.png b/web/public/icon-192.png index fd04e10..ad79c0b 100644 Binary files a/web/public/icon-192.png and b/web/public/icon-192.png differ diff --git a/web/public/icon-512.png b/web/public/icon-512.png index 78cf380..d4b3b75 100644 Binary files a/web/public/icon-512.png and b/web/public/icon-512.png differ diff --git a/web/public/icon-maskable-512.png b/web/public/icon-maskable-512.png index 34dc6e9..9b96edd 100644 Binary files a/web/public/icon-maskable-512.png and b/web/public/icon-maskable-512.png differ diff --git a/web/src/App.tsx b/web/src/App.tsx index 527418a..d8bd871 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -44,6 +44,7 @@ import AppShell from "./layout/AppShell"; import DialogHost from "./components/DialogHost"; import { setDateTimeSettings } from "./utils/date"; import { setPageSize } from "./utils/pageSize"; +import ToastHost from "./components/ToastHost"; const roleRank: Record = { viewer: 0, operator: 1, admin: 2 }; @@ -171,6 +172,7 @@ export default function App() { + ); } diff --git a/web/src/components/Notice.tsx b/web/src/components/Notice.tsx new file mode 100644 index 0000000..2a6b820 --- /dev/null +++ b/web/src/components/Notice.tsx @@ -0,0 +1,32 @@ +import { useEffect, useRef } from "react"; +import { toast } from "../utils/toast"; + +function Notice({ message, kind, className = "" }: { message: string | null | undefined; kind: "danger" | "success"; className?: string }) { + const ref = useRef(null); + + // A message that appears where you are looking needs nothing more. One that appears out of view — above after scrolling, or + // far down a long page — would otherwise go unseen, so it is also raised as a toast. + useEffect(() => { + if (!message) return; + const rect = ref.current?.getBoundingClientRect(); + const inView = !!rect && rect.height > 0 && rect.bottom > 0 && rect.top < window.innerHeight; + if (!inView) (kind === "danger" ? toast.error : toast.success)(message); + }, [message, kind]); + + if (!message) return null; + return ( +
+ {message} +
+ ); +} + +/** The usual red message under a page title. Also shown as a toast when it appears out of view. */ +export function ErrorNotice({ error, className }: { error: string | null | undefined; className?: string }) { + return ; +} + +/** The usual green message after something worked. Also shown as a toast when it appears out of view. */ +export function SuccessNotice({ notice, className }: { notice: string | null | undefined; className?: string }) { + return ; +} diff --git a/web/src/components/ServerPorts.tsx b/web/src/components/ServerPorts.tsx index c669ca7..a984357 100644 --- a/web/src/components/ServerPorts.tsx +++ b/web/src/components/ServerPorts.tsx @@ -8,6 +8,7 @@ import { readableError } from "../utils/errors"; import Pagination from "./Pagination"; import SortableTh from "./SortableTh"; import { confirmDialog } from "../utils/dialogs"; +import { ErrorNotice } from "./Notice"; const PRESETS: { key: string; label: string; from: number; to: number }[] = [ { key: "well-known", label: "1–1024 (well-known)", from: 1, to: 1024 }, @@ -235,7 +236,7 @@ export default function ServerPorts({
- {error &&
{error}
} + {data && (
diff --git a/web/src/components/ServerTags.tsx b/web/src/components/ServerTags.tsx index 8a72ce5..bae6740 100644 --- a/web/src/components/ServerTags.tsx +++ b/web/src/components/ServerTags.tsx @@ -3,6 +3,7 @@ import { Link } from "react-router-dom"; import { api } from "../api/client"; import { normalizeTagInput, tagBadge, useTagColors } from "../utils/tags"; import { readableError } from "../utils/errors"; +import { ErrorNotice } from "./Notice"; export function TagBadges({ tags, linked = false }: { tags: string[]; linked?: boolean }) { const colors = useTagColors(); @@ -99,7 +100,7 @@ export default function ServerTags({ return (
- {error &&
{error}
} +
{draftTags.map((tag) => { diff --git a/web/src/components/TableToolbar.tsx b/web/src/components/TableToolbar.tsx new file mode 100644 index 0000000..82a517f --- /dev/null +++ b/web/src/components/TableToolbar.tsx @@ -0,0 +1,80 @@ +import type { ReactNode } from "react"; +import { IconSearch } from "@tabler/icons-react"; + +/** The search box every table uses, so they look and behave alike. Esc clears it. */ +export function SearchBox({ + value, + onChange, + placeholder = "Search…", + className = "", +}: { + value: string; + onChange: (value: string) => void; + placeholder?: string; + className?: string; +}) { + return ( +
+ + + + onChange(e.target.value)} + onKeyDown={(e) => e.key === "Escape" && value && onChange("")} + /> +
+ ); +} + +/** + * The strip across the top of a table card: search and filters on the left, how many rows are showing, then the table's own + * actions (Add, Sync…) and Export CSV last on the right. Every table that can be searched uses this, in this order. + */ +export default function TableToolbar({ + search, + onSearch, + placeholder, + filters, + actions, + onExport, + exportDisabled, + shown, + total, +}: { + search: string; + onSearch: (value: string) => void; + placeholder?: string; + /** Selects and tick-boxes that narrow the rows, shown beside the search box. */ + filters?: ReactNode; + /** Buttons for this table (Add, Sync…), shown before Export CSV. */ + actions?: ReactNode; + onExport?: () => void; + exportDisabled?: boolean; + /** Rows showing now, and rows there are in all — shown as "12 of 40" once something narrows them. */ + shown?: number; + total?: number; +}) { + const narrowed = shown !== undefined && total !== undefined && shown !== total; + return ( +
+
+ + {filters} + {narrowed && {shown} of {total}} +
+ {actions} + {onExport && ( + + )} +
+
+
+ ); +} diff --git a/web/src/components/ToastHost.tsx b/web/src/components/ToastHost.tsx new file mode 100644 index 0000000..9948b1f --- /dev/null +++ b/web/src/components/ToastHost.tsx @@ -0,0 +1,48 @@ +import { useEffect, useState } from "react"; +import { createPortal } from "react-dom"; +import { IconAlertTriangle, IconCircleCheck, IconInfoCircle, IconX } from "@tabler/icons-react"; +import { dismissToast, subscribeToasts, type ToastItem } from "../utils/toast"; + +const LIFETIME_MS = { success: 4_500, info: 6_000, error: 9_000 } as const; + +function ToastView({ item }: { item: ToastItem }) { + const [paused, setPaused] = useState(false); + + // Goes away by itself — unless the pointer is on it, so a long message can be read. + useEffect(() => { + if (paused) return; + const timer = setTimeout(() => dismissToast(item.id), LIFETIME_MS[item.kind]); + return () => clearTimeout(timer); + }, [paused, item.id, item.kind]); + + const Icon = item.kind === "success" ? IconCircleCheck : item.kind === "error" ? IconAlertTriangle : IconInfoCircle; + return ( +
setPaused(true)} + onMouseLeave={() => setPaused(false)} + > + +
{item.message}
+ +
+ ); +} + +/** Draws the toasts raised through utils/toast. Mount once, near the root. */ +export default function ToastHost() { + const [items, setItems] = useState([]); + useEffect(() => subscribeToasts(setItems), []); + if (items.length === 0) return null; + return createPortal( +
+ {items.map((t) => ( + + ))} +
, + document.body, + ); +} diff --git a/web/src/hooks/useTableSearch.ts b/web/src/hooks/useTableSearch.ts new file mode 100644 index 0000000..6f7a848 --- /dev/null +++ b/web/src/hooks/useTableSearch.ts @@ -0,0 +1,43 @@ +import { useMemo, useState } from "react"; + +const haystacks = new WeakMap(); + +/** Every readable value in a row — text and numbers, however deep — as one lowercase string to search in. */ +function haystackOf(row: unknown): string { + if (row !== null && typeof row === "object") { + const cached = haystacks.get(row); + if (cached !== undefined) return cached; + } + const parts: string[] = []; + const walk = (value: unknown, depth: number) => { + if (typeof value === "string") parts.push(value); + else if (typeof value === "number") parts.push(String(value)); + else if (depth < 3 && Array.isArray(value)) for (const v of value) walk(v, depth + 1); + else if (depth < 3 && value !== null && typeof value === "object") for (const v of Object.values(value)) walk(v, depth + 1); + }; + walk(row, 0); + const text = parts.join(" \n").toLowerCase(); + if (row !== null && typeof row === "object") haystacks.set(row, text); + return text; +} + +/** + * Text search over a table's rows. Several words must all appear (in any column, in any order), so "elsa running" finds a running + * container on elsa. Returns the rows unchanged while the box is empty, and `null`/`undefined` as they came while loading. + */ +export function useTableSearch(items: T[] | null | undefined) { + const [query, setQuery] = useState(""); + const terms = query.trim().toLowerCase().split(/\s+/).filter(Boolean); + const key = terms.join(" "); + + const filtered = useMemo(() => { + if (!items || key === "") return items; + const wanted = key.split(" "); + return items.filter((row) => { + const hay = haystackOf(row); + return wanted.every((t) => hay.includes(t)); + }); + }, [items, key]); + + return { query, setQuery, filtered, active: key !== "" }; +} diff --git a/web/src/layout/AppShell.tsx b/web/src/layout/AppShell.tsx index c452174..7d6ccbf 100644 --- a/web/src/layout/AppShell.tsx +++ b/web/src/layout/AppShell.tsx @@ -39,6 +39,7 @@ import { import { api, type CurrentUser, type MaintenanceWindow } from "../api/client"; import { formatRemaining } from "../utils/duration"; import { getTheme, setTheme, type Theme } from "../utils/theme"; +import { DENSITIES, getDensity, setDensity, type Density } from "../utils/density"; import CommandPalette from "../components/CommandPalette"; import { isLightColor, useEnvironment } from "../utils/environment"; import { alertBadge, useAlertsReport } from "../hooks/useAlertsReport"; @@ -178,6 +179,7 @@ function isCurrent(pathname: string, to: string): boolean { export default function AppShell({ user, children }: { user: CurrentUser; children: ReactNode }) { const [sidebarOpen, setSidebarOpen] = useState(false); const [theme, setThemeState] = useState(() => getTheme()); + const [density, setDensityState] = useState(() => getDensity()); const [maintenance, setMaintenance] = useState([]); const environment = useEnvironment(); const { report } = useAlertsReport(); @@ -361,6 +363,25 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
{menuOpen && (
+
+ Density +
+ {DENSITIES.map((d) => ( + + ))} +
+
- )} - -
-
+ ) : undefined + } + onExport={exportCsv} + exportDisabled={!sorted?.length} + />
diff --git a/web/src/pages/Alerts.tsx b/web/src/pages/Alerts.tsx index d5d24b7..9781835 100644 --- a/web/src/pages/Alerts.tsx +++ b/web/src/pages/Alerts.tsx @@ -9,6 +9,8 @@ import { downloadCsv } from "../utils/csv"; import { formatDateTime } from "../utils/date"; import { formatAgo } from "../utils/duration"; import { readableError } from "../utils/errors"; +import { ErrorNotice } from "../components/Notice"; +import TableToolbar from "../components/TableToolbar"; const SEVERITY: Record = { critical: { label: "Critical", badge: "bg-red-lt text-red", rank: 0 }, @@ -113,7 +115,7 @@ export default function Alerts(_props: { user: CurrentUser }) { )} - {error &&
{error}
} + {!report && !error && (
@@ -172,31 +174,35 @@ export default function Alerts(_props: { user: CurrentUser }) {
) : (
-
-
- setSearch(e.target.value)} /> - - - {(counts?.silenced ?? 0) > 0 && ( - - )} -
-
+ + + + {(counts?.silenced ?? 0) > 0 && ( + + )} + + } + />
diff --git a/web/src/pages/AuditLog.tsx b/web/src/pages/AuditLog.tsx index c911040..e1facd0 100644 --- a/web/src/pages/AuditLog.tsx +++ b/web/src/pages/AuditLog.tsx @@ -6,6 +6,9 @@ import SortableTh from "../components/SortableTh"; import { usePagination } from "../hooks/usePagination"; import Pagination from "../components/Pagination"; import { downloadCsv } from "../utils/csv"; +import { ErrorNotice } from "../components/Notice"; +import { SearchBox } from "../components/TableToolbar"; +import { useTableSearch } from "../hooks/useTableSearch"; function targetLabel(e: AuditLogEntry): string { if (!e.targetType) return "—"; @@ -50,7 +53,8 @@ export default function AuditLog() { .catch((err) => setError(String(err))); }, []); - const { sorted, sortKey, sortDir, requestSort } = useSortable(entries, "createdAt", "desc"); + const tableSearch = useTableSearch(entries); + const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "createdAt", "desc"); const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted); function exportCsv() { @@ -70,8 +74,11 @@ export default function AuditLog() { Export CSV - {error &&
{error}
} +
+
+ +
diff --git a/web/src/pages/Consistency.tsx b/web/src/pages/Consistency.tsx index 5ff61d1..27af577 100644 --- a/web/src/pages/Consistency.tsx +++ b/web/src/pages/Consistency.tsx @@ -6,6 +6,7 @@ import { formatDateTime, parseDbTimestamp } from "../utils/date"; import { formatAgo } from "../utils/duration"; import { readableError } from "../utils/errors"; import { promptDialog } from "../utils/dialogs"; +import { ErrorNotice, SuccessNotice } from "../components/Notice"; const KINDS: { kind: ConsistencyKind; title: string; blurb: string }[] = [ { kind: "ip_conflict", title: "Address conflicts", blurb: "The same address reported by more than one server." }, @@ -169,8 +170,8 @@ export default function Consistency({ user }: { user: CurrentUser }) { Where IPAM, DNS and your servers disagree about what lives at an address. It compares what's already stored — nothing is fetched from the servers or DNS providers when you open this page. - {error &&
{error}
} - {notice &&
{notice}
} + + {report && (
diff --git a/web/src/pages/Dashboard.tsx b/web/src/pages/Dashboard.tsx index 07cd6d2..af7ec39 100644 --- a/web/src/pages/Dashboard.tsx +++ b/web/src/pages/Dashboard.tsx @@ -14,6 +14,7 @@ import { } from "../api/client"; import { formatAgo } from "../utils/duration"; import StatusStrip from "../components/StatusStrip"; +import { ErrorNotice } from "../components/Notice"; const DNS_TYPE_COLORS: Record = { A: "#60a5fa", @@ -576,7 +577,7 @@ export default function Dashboard({ user }: { user: CurrentUser }) { ) } > - {dnsError &&
{dnsError}
} + {!dnsStats ? (
Fetching status…
) : dnsStats.totalProviders === 0 ? ( @@ -669,7 +670,7 @@ export default function Dashboard({ user }: { user: CurrentUser }) { ) } > - {serverError &&
{serverError}
} + {!serverSummary ? ( !serverError &&
Fetching status…
) : serverSummary.total === 0 ? ( @@ -762,7 +763,7 @@ export default function Dashboard({ user }: { user: CurrentUser }) { ) } > - {domainError &&
{domainError}
} + {!domainList ? ( !domainError &&
Fetching status…
) : domains.length === 0 ? ( diff --git a/web/src/pages/DiagLog.tsx b/web/src/pages/DiagLog.tsx index 22322eb..394799d 100644 --- a/web/src/pages/DiagLog.tsx +++ b/web/src/pages/DiagLog.tsx @@ -5,6 +5,7 @@ import { useSortable } from "../hooks/useSortable"; import SortableTh from "../components/SortableTh"; import { downloadCsv } from "../utils/csv"; import { confirmDialog } from "../utils/dialogs"; +import { ErrorNotice } from "../components/Notice"; const SOURCE_LABELS: Record = { cloudflare: "Cloudflare", @@ -103,7 +104,7 @@ export default function DiagLog() { {clearing ? "Clearing…" : "Clear log"}
- {error &&
{error}
} +
diff --git a/web/src/pages/Dns.tsx b/web/src/pages/Dns.tsx index 472d0da..26e1587 100644 --- a/web/src/pages/Dns.tsx +++ b/web/src/pages/Dns.tsx @@ -17,6 +17,8 @@ import { usePagination } from "../hooks/usePagination"; import Pagination from "../components/Pagination"; import { downloadCsv } from "../utils/csv"; import { confirmDialog } from "../utils/dialogs"; +import { ErrorNotice } from "../components/Notice"; +import { toast } from "../utils/toast"; const PROVIDER_LABELS: Record = { cloudflare: "Cloudflare", @@ -168,8 +170,10 @@ export default function Dns({ user }: { user: CurrentUser }) { try { if (editingRecordId) { await api.dns.records.update(selectedProviderId, selectedZone.id, editingRecordId, recordForm); + toast.success("Record updated."); } else { await api.dns.records.create(selectedProviderId, selectedZone.id, recordForm); + toast.success("Record added."); } setRecordForm(null); setEditingRecordId(null); @@ -187,6 +191,7 @@ export default function Dns({ user }: { user: CurrentUser }) { setError(null); try { await api.dns.records.remove(selectedProviderId, selectedZone.id, r.id); + toast.success(`Deleted ${r.type} record ${r.name}.`); loadRecords(selectedProviderId, selectedZone); } catch (err) { setError(err instanceof Error ? err.message : String(err)); @@ -270,7 +275,7 @@ export default function Dns({ user }: { user: CurrentUser }) { )}
- {error &&
{error}
} + {managingProviders ? ( <> @@ -402,7 +407,7 @@ export default function Dns({ user }: { user: CurrentUser }) {
- {zonesError &&
{zonesError}
} +
diff --git a/web/src/pages/Docker.tsx b/web/src/pages/Docker.tsx index 446bbfa..9d0aee2 100644 --- a/web/src/pages/Docker.tsx +++ b/web/src/pages/Docker.tsx @@ -14,6 +14,10 @@ import Pagination from "../components/Pagination"; import { downloadCsv } from "../utils/csv"; import { confirmDialog } from "../utils/dialogs"; import IntegrationPageTitle from "../components/IntegrationPageTitle"; +import { ErrorNotice } from "../components/Notice"; +import { toast } from "../utils/toast"; +import { SearchBox } from "../components/TableToolbar"; +import { useTableSearch } from "../hooks/useTableSearch"; function updateBadge(c: DockhandContainer) { if (c.updateAvailable === null) return —; @@ -91,7 +95,8 @@ export default function Docker({ user }: { user: CurrentUser }) { const hosts = [...new Set((data?.containers ?? []).map((c) => c.environmentName))].sort(); const filteredContainers = (data?.containers ?? []).filter((c) => !hostFilter || c.environmentName === hostFilter); - const { sorted, sortKey, sortDir, requestSort } = useSortable(filteredContainers); + const tableSearch = useTableSearch(filteredContainers); + const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered); const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted); function exportCsv() { @@ -131,6 +136,7 @@ export default function Docker({ user }: { user: CurrentUser }) { setError(null); try { await api.integrations.dockhand[action](selectedId, c.environmentId, c.id); + toast.success(`${action === "start" ? "Started" : action === "stop" ? "Stopped" : "Restarted"} ${c.name}.`); loadContainers(selectedId); } catch (err) { setError(err instanceof Error ? err.message : String(err)); @@ -142,7 +148,7 @@ export default function Docker({ user }: { user: CurrentUser }) { return ( <> - {error &&
{error}
} + {integrations?.length === 0 ? (
@@ -193,6 +199,7 @@ export default function Docker({ user }: { user: CurrentUser }) { )} +
{hosts.length > 1 && ( setTheme(e.target.value)} disabled={!themes}> diff --git a/web/src/pages/Gitea.tsx b/web/src/pages/Gitea.tsx index 453d99e..093cf9f 100644 --- a/web/src/pages/Gitea.tsx +++ b/web/src/pages/Gitea.tsx @@ -9,6 +9,9 @@ import Pagination from "../components/Pagination"; import { downloadCsv } from "../utils/csv"; import { formatDateTime } from "../utils/date"; import { formatAgo } from "../utils/duration"; +import { ErrorNotice } from "../components/Notice"; +import { SearchBox } from "../components/TableToolbar"; +import { useTableSearch } from "../hooks/useTableSearch"; function runStatusBadge(repo: GiteaRepo) { const run = repo.latestRun; @@ -93,7 +96,8 @@ export default function Gitea({ user }: { user: CurrentUser }) { } } - const { sorted, sortKey, sortDir, requestSort } = useSortable(repos); + const tableSearch = useTableSearch(repos); + const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered); const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted); function exportCsv() { @@ -115,7 +119,7 @@ export default function Gitea({ user }: { user: CurrentUser }) { return ( <> - {error &&
{error}
} + {integrations?.length === 0 ? (
@@ -153,6 +157,7 @@ export default function Gitea({ user }: { user: CurrentUser }) {

Repositories

+
)}
- {error &&
{error}
} + {editingIntegration ? (

IP Addresses

- {error &&
{error}
} + {syncResult &&
Synced from {syncResult}
}
@@ -351,38 +353,36 @@ export default function Ipam({ user }: { user: CurrentUser }) { )}
-
-
- setSearch(e.target.value)} - /> - {canEdit && !showForm && ( - - )} - {canEdit && ( - <> - - - - - )} - -
-
+ )} + {canEdit && ( + <> + + + + + )} + + } + onExport={exportCsv} + /> {canEdit && selection.count > 0 && (
{selection.count} selected diff --git a/web/src/pages/Maintenance.tsx b/web/src/pages/Maintenance.tsx index 07473b5..92fbd0e 100644 --- a/web/src/pages/Maintenance.tsx +++ b/web/src/pages/Maintenance.tsx @@ -13,6 +13,8 @@ import { import { formatDateTime } from "../utils/date"; import { formatRemaining } from "../utils/duration"; import { readableError } from "../utils/errors"; +import { ErrorNotice } from "../components/Notice"; +import { toast } from "../utils/toast"; const DURATIONS: { minutes: number; label: string }[] = [ { minutes: 30, label: "30 minutes" }, @@ -102,6 +104,7 @@ export default function Maintenance({ user }: { user: CurrentUser }) { }); setTarget(""); setReason(""); + toast.success("Maintenance started. Alerts for it are silenced until it ends."); load(); announceChange(); } catch (err) { @@ -143,6 +146,7 @@ export default function Maintenance({ user }: { user: CurrentUser }) { setError(null); try { await api.maintenance.end(w.id); + toast.success(w.startedAt > new Date().toISOString() ? "Scheduled window cancelled." : "Maintenance ended. Alerts for it are active again."); load(); announceChange(); } catch (err) { @@ -194,7 +198,7 @@ export default function Maintenance({ user }: { user: CurrentUser }) { Silence alerts about one server or integration while you work on it. Every window ends on its own — anything still wrong when it ends alerts then, so nothing stays hidden.
- {error &&
{error}
} + {canEdit && (
diff --git a/web/src/pages/OsTicket.tsx b/web/src/pages/OsTicket.tsx index 7ba065a..d4053df 100644 --- a/web/src/pages/OsTicket.tsx +++ b/web/src/pages/OsTicket.tsx @@ -6,6 +6,9 @@ import SortableTh from "../components/SortableTh"; import { downloadCsv } from "../utils/csv"; import { formatDateTime } from "../utils/date"; import { formatAgo } from "../utils/duration"; +import { ErrorNotice } from "../components/Notice"; +import { SearchBox } from "../components/TableToolbar"; +import { useTableSearch } from "../hooks/useTableSearch"; function priorityBadge(t: OsTicketTicket) { if (!t.priorityName) return —; @@ -58,7 +61,8 @@ export default function OsTicket({ user: _user }: { user: CurrentUser }) { // eslint-disable-next-line react-hooks/exhaustive-deps }, [selectedId]); - const { sorted: sortedTickets, sortKey, sortDir, requestSort } = useSortable(data?.tickets); + const tableSearch = useTableSearch(data?.tickets); + const { sorted: sortedTickets, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered); function exportCsv() { if (!sortedTickets) return; @@ -85,7 +89,7 @@ export default function OsTicket({ user: _user }: { user: CurrentUser }) { return ( <>

osTicket

- {error &&
{error}
} + {integrations?.length === 0 ? (
@@ -157,6 +161,7 @@ export default function OsTicket({ user: _user }: { user: CurrentUser }) {

Open tickets

+
- {agentError &&
{agentError}
} +
@@ -366,7 +367,7 @@ export default function Ports({ user }: { user: CurrentUser }) { - {forwardError &&
{forwardError}
} +
diff --git a/web/src/pages/Privacy.tsx b/web/src/pages/Privacy.tsx index 601f204..9045457 100644 --- a/web/src/pages/Privacy.tsx +++ b/web/src/pages/Privacy.tsx @@ -4,6 +4,7 @@ import { api, type PrivacyOverview } from "../api/client"; import { formatDateTime } from "../utils/date"; import { formatAgo } from "../utils/duration"; import { readableError } from "../utils/errors"; +import { ErrorNotice } from "../components/Notice"; const CHANNEL_LABELS = { gotify: "Gotify", ntfy: "ntfy", smtp: "email (SMTP)", webhook: "webhook" } as const; @@ -57,7 +58,7 @@ export default function Privacy() { for this installation. - {error &&
{error}
} + {data && (
diff --git a/web/src/pages/Proxmox.tsx b/web/src/pages/Proxmox.tsx index e8d1201..4584c88 100644 --- a/web/src/pages/Proxmox.tsx +++ b/web/src/pages/Proxmox.tsx @@ -17,6 +17,10 @@ import Pagination from "../components/Pagination"; import { downloadCsv } from "../utils/csv"; import { confirmDialog } from "../utils/dialogs"; import IntegrationPageTitle from "../components/IntegrationPageTitle"; +import { ErrorNotice } from "../components/Notice"; +import { toast } from "../utils/toast"; +import { SearchBox } from "../components/TableToolbar"; +import { useTableSearch } from "../hooks/useTableSearch"; function proxmoxStatusBadge(status: string) { return status === "running" ? ( @@ -181,6 +185,7 @@ export default function Proxmox({ user }: { user: CurrentUser }) { setError(null); try { await api.integrations.proxmox[action](selectedId, g.node, g.type, g.vmid); + toast.success(`${{ start: "Started", stop: "Stopped", restart: "Restarted", shutdown: "Shut down" }[action]} ${g.name}.`); loadGuests(selectedId); } catch (err) { setError(err instanceof Error ? err.message : String(err)); @@ -189,7 +194,8 @@ export default function Proxmox({ user }: { user: CurrentUser }) { } } - const { sorted: sortedGuests, sortKey: guestSortKey, sortDir: guestSortDir, requestSort: requestGuestSort } = useSortable(data?.guests); + const tableSearch = useTableSearch(data?.guests); + const { sorted: sortedGuests, sortKey: guestSortKey, sortDir: guestSortDir, requestSort: requestGuestSort } = useSortable(tableSearch.filtered); const { pageItems: guestPageItems, page: guestPage, setPage: setGuestPage, pageCount: guestPageCount, totalCount: guestTotalCount } = usePagination(sortedGuests); @@ -205,7 +211,7 @@ export default function Proxmox({ user }: { user: CurrentUser }) { return ( <> - {error &&
{error}
} + {integrations?.length === 0 ? (
@@ -241,7 +247,7 @@ export default function Proxmox({ user }: { user: CurrentUser }) {
) : ( <> - {nodeStatsError &&
{nodeStatsError}
} +
{nodeStats?.map((n) => (
@@ -355,7 +361,7 @@ export default function Proxmox({ user }: { user: CurrentUser }) {
- {backupsError &&
{backupsError}
} + {backupTasks && backupTasks.length > 0 && !backupTasks[0].ok && backupTasks[0].status !== "running" && (
Most recent backup run on {backupTasks[0].node} @@ -473,6 +479,7 @@ export default function Proxmox({ user }: { user: CurrentUser }) { )} +
-
-
+ } + shown={filtered.length} + total={secrets?.length} + onExport={exportCsv} + /> {canEdit && selection.count > 0 && (
{selection.count} selected diff --git a/web/src/pages/Semaphore.tsx b/web/src/pages/Semaphore.tsx index 4ba2d01..85a3f52 100644 --- a/web/src/pages/Semaphore.tsx +++ b/web/src/pages/Semaphore.tsx @@ -15,6 +15,9 @@ import Pagination from "../components/Pagination"; import { downloadCsv } from "../utils/csv"; import { confirmDialog } from "../utils/dialogs"; import IntegrationPageTitle from "../components/IntegrationPageTitle"; +import { ErrorNotice } from "../components/Notice"; +import { SearchBox } from "../components/TableToolbar"; +import { useTableSearch } from "../hooks/useTableSearch"; function semaphoreStatusBadge(template: SemaphoreTemplate) { const status = template.lastTask?.status; @@ -100,7 +103,8 @@ export default function Semaphore({ user }: { user: CurrentUser }) { } } - const { sorted, sortKey, sortDir, requestSort } = useSortable(data?.templates); + const tableSearch = useTableSearch(data?.templates); + const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered); const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted); function exportCsv() { @@ -120,7 +124,7 @@ export default function Semaphore({ user }: { user: CurrentUser }) { return ( <> - {error &&
{error}
} + {integrations?.length === 0 ? (
@@ -164,6 +168,7 @@ export default function Semaphore({ user }: { user: CurrentUser }) { {data.summary.failing} failing )} +
- {error &&
{error}
} +
- {adminLinkError &&
{adminLinkError}
} + {adminLinkForm && (
@@ -629,7 +630,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
)}
- {guestActionError &&
{guestActionError}
} +
CPU
diff --git a/web/src/pages/Servers.tsx b/web/src/pages/Servers.tsx index 8da1e8d..9d8ea8e 100644 --- a/web/src/pages/Servers.tsx +++ b/web/src/pages/Servers.tsx @@ -12,6 +12,10 @@ import { TagBadges } from "../components/ServerTags"; import { AGENT_RUN_HINT, agentOsOf, installCommand, uninstallCommand, type AgentOs } from "../utils/agentCommands"; import { tagBadge, useTagColors } from "../utils/tags"; import { confirmDialog } from "../utils/dialogs"; +import { ErrorNotice } from "../components/Notice"; +import { toast } from "../utils/toast"; +import { SearchBox } from "../components/TableToolbar"; +import { useTableSearch } from "../hooks/useTableSearch"; function typeBadgeStyle(colors: Record, type: string): CSSProperties { const color = colors[type]; @@ -66,6 +70,7 @@ export default function Servers({ user }: { user: CurrentUser }) { osType: serverOs, }); setNewToken(result); + toast.success(`Added ${serverName}. Its install command is shown below.`); setServerName(""); setServerHostname(""); setServerDescription(""); @@ -89,13 +94,15 @@ export default function Servers({ user }: { user: CurrentUser }) { if (!(await confirmDialog({ title: "Remove server", message: "Remove this server and all its tracked tasks?", confirmLabel: "Remove", danger: true }))) return; try { await api.servers.remove(id); + toast.success("Server removed."); await loadServers(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } } - const { sorted: sortedServers, sortKey, sortDir, requestSort } = useSortable(servers); + const tableSearch = useTableSearch(servers); + const { sorted: sortedServers, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered); const { pageItems: serverPageItems, page: serverPage, setPage: setServerPage, pageCount: serverPageCount, totalCount: serverTotalCount } = usePagination(sortedServers); @@ -136,7 +143,7 @@ export default function Servers({ user }: { user: CurrentUser }) { )}
- {error &&
{error}
} + {managingServers ? ( <> @@ -257,8 +264,9 @@ export default function Servers({ user }: { user: CurrentUser }) { )}
-
-
diff --git a/web/src/pages/Sessions.tsx b/web/src/pages/Sessions.tsx index 673530f..67e187f 100644 --- a/web/src/pages/Sessions.tsx +++ b/web/src/pages/Sessions.tsx @@ -5,6 +5,9 @@ import { useSortable } from "../hooks/useSortable"; import SortableTh from "../components/SortableTh"; import { downloadCsv } from "../utils/csv"; import { confirmDialog } from "../utils/dialogs"; +import { ErrorNotice } from "../components/Notice"; +import { SearchBox } from "../components/TableToolbar"; +import { useTableSearch } from "../hooks/useTableSearch"; function friendlyUserAgent(ua: string | null): string { if (!ua) return "—"; @@ -72,7 +75,8 @@ export default function Sessions() { } } - const { sorted, sortKey, sortDir, requestSort } = useSortable(sessions); + const tableSearch = useTableSearch(sessions); + const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered); function exportCsv() { if (!sorted) return; @@ -102,8 +106,11 @@ export default function Sessions() { Export CSV
- {error &&
{error}
} +
+
+ +
diff --git a/web/src/pages/Synology.tsx b/web/src/pages/Synology.tsx index 4a0f71c..2111635 100644 --- a/web/src/pages/Synology.tsx +++ b/web/src/pages/Synology.tsx @@ -13,6 +13,7 @@ import { useSortable } from "../hooks/useSortable"; import SortableTh from "../components/SortableTh"; import { downloadCsv } from "../utils/csv"; import IntegrationPageTitle from "../components/IntegrationPageTitle"; +import { ErrorNotice } from "../components/Notice"; function healthBadge(status: string) { return status === "normal" ? ( @@ -135,7 +136,7 @@ export default function Synology({ user: _user }: { user: CurrentUser }) { return ( <> - {error &&
{error}
} + {integrations?.length === 0 ? (
diff --git a/web/src/pages/Tailscale.tsx b/web/src/pages/Tailscale.tsx index 66fafa8..988b94e 100644 --- a/web/src/pages/Tailscale.tsx +++ b/web/src/pages/Tailscale.tsx @@ -16,6 +16,10 @@ import { downloadCsv } from "../utils/csv"; import { useSelection } from "../hooks/useSelection"; import { confirmDialog } from "../utils/dialogs"; import IntegrationPageTitle from "../components/IntegrationPageTitle"; +import { ErrorNotice } from "../components/Notice"; +import { toast } from "../utils/toast"; +import { SearchBox } from "../components/TableToolbar"; +import { useTableSearch } from "../hooks/useTableSearch"; const KEY_EXPIRY_WARN_DAYS = 30; @@ -83,6 +87,7 @@ export default function Tailscale({ user }: { user: CurrentUser }) { if (!selectedId) return; try { await api.integrations.tailscale.setAuthorized(selectedId, device.id, authorized); + toast.success(`${authorized ? "Authorized" : "Deauthorized"} ${device.label || device.hostname}.`); loadDevices(selectedId); } catch (err) { setError(err instanceof Error ? err.message : String(err)); @@ -94,6 +99,7 @@ export default function Tailscale({ user }: { user: CurrentUser }) { if (!(await confirmDialog({ title: "Remove device", message: `Remove device "${device.label || device.hostname}" from the tailnet?`, confirmLabel: "Remove", danger: true }))) return; try { await api.integrations.tailscale.remove(selectedId, device.id); + toast.success(`Removed ${device.label || device.hostname} from the tailnet.`); loadDevices(selectedId); } catch (err) { setError(err instanceof Error ? err.message : String(err)); @@ -135,7 +141,8 @@ export default function Tailscale({ user }: { user: CurrentUser }) { } } - const { sorted, sortKey, sortDir, requestSort } = useSortable(data?.devices); + const tableSearch = useTableSearch(data?.devices); + const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered); const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted); function exportCsv() { @@ -158,7 +165,7 @@ export default function Tailscale({ user }: { user: CurrentUser }) { return ( <> - {error &&
{error}
} + {integrations?.length === 0 ? (
@@ -206,6 +213,7 @@ export default function Tailscale({ user }: { user: CurrentUser }) { )} +
- {error &&
{error}
} +
+
+ +
diff --git a/web/src/pages/settings/AlertTicketSettings.tsx b/web/src/pages/settings/AlertTicketSettings.tsx index 5f00395..2fac0ed 100644 --- a/web/src/pages/settings/AlertTicketSettings.tsx +++ b/web/src/pages/settings/AlertTicketSettings.tsx @@ -4,6 +4,7 @@ import { api, type AlertTicketOverview, type AlertTicketRunSummary, type AlertTi import { formatDateTime } from "../../utils/date"; import { formatAgo } from "../../utils/duration"; import { readableError } from "../../utils/errors"; +import { ErrorNotice, SuccessNotice } from "../../components/Notice"; const SEVERITIES: { value: AlertTicketSeverity; label: string; hint: string }[] = [ { value: "critical", label: "Critical", hint: "A server down, a disk nearly full, a failed backup, something expired" }, @@ -108,8 +109,8 @@ export default function AlertTicketSettings() { return ( <> - {error &&
{error}
} - {notice &&
{notice}
} + +
diff --git a/web/src/pages/settings/BackupSettings.tsx b/web/src/pages/settings/BackupSettings.tsx index aa27093..c7e8ea4 100644 --- a/web/src/pages/settings/BackupSettings.tsx +++ b/web/src/pages/settings/BackupSettings.tsx @@ -1,6 +1,7 @@ import { useRef, useState } from "react"; import { api, type EncryptedExportFile, type ImportResult } from "../../api/client"; import { confirmDialog } from "../../utils/dialogs"; +import { ErrorNotice } from "../../components/Notice"; function downloadJson(filename: string, data: unknown) { const blob = new Blob([JSON.stringify(data)], { type: "application/json" }); @@ -103,7 +104,7 @@ export default function BackupSettings() { somewhere you trust and don't lose the passphrase — it can't be recovered.

Not included: DNS records, secrets, IPAM, servers, or the audit/diagnostic logs — this is configuration only.

- {exportError &&
{exportError}
} +
added — anything that already exists with the same name is left alone, so this is safe to run more than once.

- {importError &&
{importError}
} - {importFileError &&
{importFileError}
} + + {importResult && (
diff --git a/web/src/pages/settings/BadgeSettings.tsx b/web/src/pages/settings/BadgeSettings.tsx index 27e303f..1007019 100644 --- a/web/src/pages/settings/BadgeSettings.tsx +++ b/web/src/pages/settings/BadgeSettings.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import { api } from "../../api/client"; +import { ErrorNotice } from "../../components/Notice"; const PROVIDER_NAMES: Record = { cloudflare: "Cloudflare", @@ -106,7 +107,7 @@ export default function BadgeSettings() {
- {loadError &&
{loadError}
} +
diff --git a/web/src/pages/settings/CacheSettings.tsx b/web/src/pages/settings/CacheSettings.tsx index 0d674ea..12cb80f 100644 --- a/web/src/pages/settings/CacheSettings.tsx +++ b/web/src/pages/settings/CacheSettings.tsx @@ -1,6 +1,7 @@ import { useState } from "react"; import { api } from "../../api/client"; import { confirmDialog } from "../../utils/dialogs"; +import { ErrorNotice } from "../../components/Notice"; export default function CacheSettings() { const [clearing, setClearing] = useState(false); @@ -35,7 +36,7 @@ export default function CacheSettings() { The DNS module keeps a local copy of every synced zone and record so pages load instantly. Clear it if you see stale or incorrect data — every zone will need to be re-synced from its provider afterwards.

- {error &&
{error}
} +
- {loadError &&
{loadError}
} +
diff --git a/web/src/pages/settings/LogSettings.tsx b/web/src/pages/settings/LogSettings.tsx index 9b35536..3bcc611 100644 --- a/web/src/pages/settings/LogSettings.tsx +++ b/web/src/pages/settings/LogSettings.tsx @@ -1,6 +1,7 @@ import { useEffect, useState } from "react"; import { api, type AppSettings } from "../../api/client"; import { confirmDialog } from "../../utils/dialogs"; +import { ErrorNotice } from "../../components/Notice"; const INTERVAL_OPTIONS: { value: number; label: string }[] = [ { value: 1, label: "Every hour" }, @@ -81,7 +82,7 @@ export default function LogSettings() {
- {loadError &&
{loadError}
} +
@@ -145,7 +146,7 @@ export default function LogSettings() { Runs a purge immediately using the retention period above, regardless of whether automatic purging is enabled.

- {purgeError &&
{purgeError}
} + {purgeResult && (
Deleted {purgeResult.diagDeleted} diagnostic log and {purgeResult.auditDeleted} audit log diff --git a/web/src/pages/settings/NameSettings.tsx b/web/src/pages/settings/NameSettings.tsx index 40b50d9..5c493fd 100644 --- a/web/src/pages/settings/NameSettings.tsx +++ b/web/src/pages/settings/NameSettings.tsx @@ -4,6 +4,7 @@ import { confirmDialog } from "../../utils/dialogs"; import { formatDateTime } from "../../utils/date"; import { readableError } from "../../utils/errors"; import { parseNames } from "../../utils/nameLists"; +import { ErrorNotice, SuccessNotice } from "../../components/Notice"; /** One list as it's being edited. The names are kept as the text in the box, so typing stays natural. */ interface Draft { @@ -221,8 +222,8 @@ export default function NameSettings() { return ( <> - {error &&
{error}
} - {notice &&
{notice}
} + +
@@ -334,7 +335,7 @@ export default function NameSettings() { {fetching ? "Fetching…" : "Fetch names"}
- {importError &&
{importError}
} + {preview && (
diff --git a/web/src/pages/settings/NotificationSettings.tsx b/web/src/pages/settings/NotificationSettings.tsx index af93247..d4ce582 100644 --- a/web/src/pages/settings/NotificationSettings.tsx +++ b/web/src/pages/settings/NotificationSettings.tsx @@ -10,6 +10,7 @@ import { type QuietHoursSettings, type HealthCheckSettings, } from "../../api/client"; +import { ErrorNotice } from "../../components/Notice"; const TIMEZONES = [ "UTC", @@ -212,7 +213,7 @@ export default function NotificationSettings() {
- {loadError &&
{loadError}
} +
diff --git a/web/src/pages/settings/TagSettings.tsx b/web/src/pages/settings/TagSettings.tsx index e38a648..7c4ad3b 100644 --- a/web/src/pages/settings/TagSettings.tsx +++ b/web/src/pages/settings/TagSettings.tsx @@ -3,6 +3,7 @@ import { api, type TagEntry } from "../../api/client"; import { readableError } from "../../utils/errors"; import { normalizeTagInput, refreshTagColors, tagBadge } from "../../utils/tags"; import { confirmDialog, promptDialog } from "../../utils/dialogs"; +import { ErrorNotice, SuccessNotice } from "../../components/Notice"; const DEFAULT_PICK = "#3b82f6"; @@ -99,8 +100,8 @@ export default function TagSettings() { return ( <> - {error &&
{error}
} - {notice &&
{notice}
} + +
diff --git a/web/src/styles.css b/web/src/styles.css index 60e8d43..ce4e7d4 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -150,3 +150,135 @@ html[data-env] .navbar-vertical { padding-top: 0.3rem; padding-bottom: 0.3rem; } + +/* Toasts: short results that appear in the corner and fade away (utils/toast). */ +.toast-stack { + position: fixed; + right: 1rem; + bottom: 1rem; + z-index: 2000; + display: flex; + flex-direction: column; + gap: 0.5rem; + width: min(24rem, calc(100vw - 2rem)); +} + +.toast-item { + display: flex; + gap: 0.6rem; + padding: 0.7rem 0.8rem; + color: #fff; + background: #1f2937; + border-left: 4px solid #6b7280; + border-radius: var(--tblr-border-radius, 4px); + box-shadow: 0 6px 20px rgba(0, 0, 0, 0.35); + animation: toast-in 0.18s ease-out; +} + +.toast-success { + border-left-color: #22c55e; +} + +.toast-error { + border-left-color: #ef4444; +} + +.toast-info { + border-left-color: #3b82f6; +} + +.toast-close { + flex-shrink: 0; + align-self: flex-start; + padding: 0.1rem; + color: inherit; + opacity: 0.7; + background: none; + border: 0; +} + +.toast-close:hover { + opacity: 1; +} + +@keyframes toast-in { + from { + opacity: 0; + transform: translateY(0.5rem); + } +} + +@media (prefers-reduced-motion: reduce) { + .toast-item { + animation: none; + } +} + +/* ── Table toolbar: search and filters on the left, row count, then the table's actions and Export CSV on the right. ── */ +.table-toolbar-inner { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 0.5rem; + width: 100%; +} + +.table-toolbar-actions { + display: flex; + flex-wrap: wrap; + gap: 0.5rem; + margin-left: auto; +} + +.table-search { + width: 16rem; + max-width: 100%; +} + +/* ── Long tables scroll inside their card with the column headings kept in view (wide screens only: on a phone the page scrolls). ── */ +@media (min-width: 992px) { + .card > .table-responsive { + max-height: calc(100vh - 12rem); + overflow: auto; + } + + .card > .table-responsive > .table > thead > tr > th { + position: sticky; + top: 0; + z-index: 2; + background-color: var(--tblr-bg-surface-secondary, var(--tblr-card-bg)); + box-shadow: inset 0 -1px 0 var(--tblr-border-color); + } +} + +/* ── Density: how tightly pages are packed. Normal is Tabler's own look; the choice is in the user menu. ── */ +html[data-density="compact"] { + --tblr-body-font-size: 0.8125rem; + --tblr-card-spacer-y: 0.85rem; + --tblr-card-spacer-x: 1rem; +} + +html[data-density="compact"] .table > :not(caption) > * > * { + padding: 0.35rem 0.6rem; +} + +html[data-density="compact"] .page-body { + margin-top: 0.75rem; +} + +html[data-density="roomy"] { + --tblr-body-font-size: 0.975rem; + --tblr-card-spacer-y: 1.5rem; + --tblr-card-spacer-x: 1.5rem; +} + +html[data-density="roomy"] .table > :not(caption) > * > * { + padding: 1rem 0.9rem; +} + +.user-menu-density { + display: flex; + flex-direction: column; + gap: 0.25rem; + padding: 0.4rem 0.5rem; +} diff --git a/web/src/utils/density.ts b/web/src/utils/density.ts new file mode 100644 index 0000000..013a9f1 --- /dev/null +++ b/web/src/utils/density.ts @@ -0,0 +1,42 @@ +// How tightly the pages are packed: Compact fits more on screen, Roomy is easier to read on a big monitor or a tablet. +// Chosen per browser (the styles key off the data-density attribute on ); Normal is the original look. + +export type Density = "compact" | "normal" | "roomy"; + +export const DENSITIES: { value: Density; label: string }[] = [ + { value: "compact", label: "Compact" }, + { value: "normal", label: "Normal" }, + { value: "roomy", label: "Roomy" }, +]; + +const KEY = "hlm-density"; + +export function getDensity(): Density { + const value = document.documentElement.getAttribute("data-density"); + return value === "compact" || value === "roomy" ? value : "normal"; +} + +function apply(density: Density): void { + if (density === "normal") document.documentElement.removeAttribute("data-density"); + else document.documentElement.setAttribute("data-density", density); +} + +/** Called once at start-up, before anything is drawn, so the page never flashes in the wrong density. */ +export function applyStoredDensity(): void { + try { + const stored = localStorage.getItem(KEY); + if (stored === "compact" || stored === "roomy") apply(stored); + } catch { + // storage blocked: the normal look + } +} + +export function setDensity(density: Density): void { + apply(density); + try { + if (density === "normal") localStorage.removeItem(KEY); + else localStorage.setItem(KEY, density); + } catch { + // not remembered; it still applies for this visit + } +} diff --git a/web/src/utils/environment.ts b/web/src/utils/environment.ts index ee5e6d7..4a85a17 100644 --- a/web/src/utils/environment.ts +++ b/web/src/utils/environment.ts @@ -41,6 +41,39 @@ function applyEnvironment(look: EnvironmentLook | null): void { root.setAttribute("data-env", look.name || "custom"); document.title = look.name ? `[${look.name}] ${BASE_TITLE}` : BASE_TITLE; document.querySelector('meta[name="theme-color"]')?.setAttribute("content", look.color); + tintFavicon(look.color); +} + +/** The tab icon gets a dot in the environment's colour in its corner, so this tab stands out among several. */ +function tintFavicon(color: string): void { + const links = document.querySelectorAll('link[rel~="icon"]'); + if (links.length === 0) return; + const image = new Image(); + image.onload = () => { + try { + const size = 64; + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = size; + const ctx = canvas.getContext("2d"); + if (!ctx) return; + ctx.drawImage(image, 0, 0, size, size); + ctx.beginPath(); + ctx.arc(size - 19, size - 19, 18, 0, Math.PI * 2); + ctx.fillStyle = color; + ctx.fill(); + ctx.lineWidth = 5; + ctx.strokeStyle = "#ffffff"; + ctx.stroke(); + const href = canvas.toDataURL("image/png"); + links.forEach((link) => { + link.href = href; + link.removeAttribute("sizes"); + }); + } catch { + // The plain icon stays; this is only a nicety. + } + }; + image.src = "/icon-192.png"; } /** Whether white text on this colour would be hard to read. */ diff --git a/web/src/utils/toast.ts b/web/src/utils/toast.ts new file mode 100644 index 0000000..077620e --- /dev/null +++ b/web/src/utils/toast.ts @@ -0,0 +1,48 @@ +// Short messages that appear in a corner of the screen and go away by themselves — for the result of something you just did +// when the place you did it may no longer be in view. Anything can call toast.success() / toast.error() / toast.info(); one +// (mounted once, in App) draws them. + +export type ToastKind = "success" | "error" | "info"; + +export interface ToastItem { + id: number; + kind: ToastKind; + message: string; +} + +let nextId = 1; +let items: ToastItem[] = []; +const listeners = new Set<(items: ToastItem[]) => void>(); + +function emit() { + for (const l of listeners) l(items); +} + +export function subscribeToasts(listener: (items: ToastItem[]) => void): () => void { + listeners.add(listener); + listener(items); + return () => { + listeners.delete(listener); + }; +} + +export function dismissToast(id: number): void { + items = items.filter((t) => t.id !== id); + emit(); +} + +function show(kind: ToastKind, message: string): void { + const text = message.trim(); + if (!text) return; + // The same message twice in a row is one toast, not two. + if (items.some((t) => t.kind === kind && t.message === text)) return; + // A handful at most: the newest few are what matter. + items = [...items, { id: nextId++, kind, message: text }].slice(-4); + emit(); +} + +export const toast = { + success: (message: string) => show("success", message), + error: (message: string) => show("error", message), + info: (message: string) => show("info", message), +};