Files
Homelab-manager/web/src/pages/Semaphore.tsx
T
bobbanandClaude Sonnet 5 7bf9b03839 Paginate tables that can grow large
Sorting/CSV export were already app-wide; tables with a real chance of
growing into dozens or hundreds of rows (a busy tailnet, a big DNS
zone, a homelab's full IP inventory, a Gitea org with many repos, ...)
had no pagination at all, making them a long unbroken scroll.

New usePagination hook (client-side slicing over an already-sorted/
filtered array, 20 rows per page) and a matching Pagination component
(Prev/Next + "Page X of Y (N total)", hidden entirely when everything
fits on one page). The current page is clamped to the valid range on
every render rather than reset via an effect, so switching to a
smaller data set (a different selected integration, a filter that
narrows the result) can never strand the view on a now-nonexistent
page -- no per-page "reset on change" wiring needed anywhere.

Applied to Audit Log, DNS zones and records, IP Addresses, Secrets,
Servers (manage table), Docker containers, Proxmox guests, Semaphore
templates, Gitea repos, and Tailscale devices. CSV export keeps
exporting the full sorted/filtered array regardless of which page is
currently shown -- pagination only affects what's rendered on screen.
Left the already-small tables (Synology volumes/disks, Users,
Integrations, per-node Proxmox storage) unpaginated, and left the
Diagnostic Log's existing server-driven pagination as-is rather than
bolting a second, different pagination scheme onto it.

Verified the clamping logic directly: a normal page, the trailing
partial page, a requested page beyond the end (clamps to the last
valid page instead of rendering empty), and an empty result set
(clamps to page 0 with a page count of 1 instead of a negative range).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-18 23:51:14 +02:00

237 lines
8.8 KiB
TypeScript

import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import {
api,
type CurrentUser,
type IntegrationSummary,
type SemaphoreTemplate,
type SemaphoreTemplatesResponse,
} from "../api/client";
import { formatDateTime } from "../utils/date";
import { useSortable } from "../hooks/useSortable";
import SortableTh from "../components/SortableTh";
import { usePagination } from "../hooks/usePagination";
import Pagination from "../components/Pagination";
import { downloadCsv } from "../utils/csv";
function semaphoreStatusBadge(template: SemaphoreTemplate) {
const status = template.lastTask?.status;
if (!status) return <span className="badge bg-secondary-lt text-secondary">Never run</span>;
switch (status) {
case "success":
return <span className="badge bg-green-lt text-green">Success</span>;
case "error":
return <span className="badge bg-red-lt text-red">Failed</span>;
case "stopped":
return <span className="badge bg-secondary-lt text-secondary">Stopped</span>;
case "rejected":
return <span className="badge bg-secondary-lt text-secondary">Rejected</span>;
case "waiting":
case "starting":
case "waiting_confirmation":
case "confirmed":
return <span className="badge bg-yellow-lt text-yellow">Queued</span>;
case "running":
case "stopping":
return <span className="badge bg-blue-lt text-blue">Running</span>;
default:
return <span className="badge bg-secondary-lt text-secondary">{status}</span>;
}
}
export default function Semaphore({ user }: { user: CurrentUser }) {
const canEdit = user.role === "admin" || user.role === "operator";
const [integrations, setIntegrations] = useState<IntegrationSummary[] | null>(null);
const [selectedId, setSelectedId] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const [data, setData] = useState<SemaphoreTemplatesResponse | null>(null);
const [loading, setLoading] = useState(false);
const [runningTemplate, setRunningTemplate] = useState<number | null>(null);
useEffect(() => {
api.integrations
.list()
.then((res) => {
const semaphoreIntegrations = res.integrations.filter((i) => i.type === "semaphore");
setIntegrations(semaphoreIntegrations);
if (!selectedId && semaphoreIntegrations.length > 0) setSelectedId(semaphoreIntegrations[0].id);
})
.catch((err) => setError(err instanceof Error ? err.message : String(err)));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const selected = integrations?.find((i) => i.id === selectedId) ?? null;
function loadTemplates(id: number) {
setLoading(true);
setError(null);
api.integrations.semaphore
.templates(id)
.then((res) => setData(res))
.catch((err) => setError(err instanceof Error ? err.message : String(err)))
.finally(() => setLoading(false));
}
useEffect(() => {
if (selected?.enabled) {
loadTemplates(selected.id);
} else {
setData(null);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedId]);
async function runTemplate(t: SemaphoreTemplate) {
if (!selectedId) return;
if (!confirm(`Run "${t.name}" now?`)) return;
setRunningTemplate(t.id);
setError(null);
try {
await api.integrations.semaphore.run(selectedId, t.projectId, t.id);
loadTemplates(selectedId);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setRunningTemplate(null);
}
}
const { sorted, sortKey, sortDir, requestSort } = useSortable(data?.templates);
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
function exportCsv() {
if (!sorted) return;
downloadCsv(
"semaphore-templates.csv",
["Template", "Project", "Last run", "Status"],
sorted.map((t) => [
t.name,
t.projectName,
t.lastTask ? formatDateTime(new Date(t.lastTask.end ?? t.lastTask.start ?? t.lastTask.created ?? "")) : "",
t.lastTask?.status ?? "never run",
]),
);
}
return (
<>
<h2 className="page-title mb-3">Semaphore</h2>
{error && <div className="alert alert-danger">{error}</div>}
{integrations?.length === 0 ? (
<div className="card">
<div className="card-body text-secondary">
No Semaphore integration configured yet.{" "}
<Link to="/integrations">Add one under Integrations</Link>.
</div>
</div>
) : (
<>
{integrations && integrations.length > 1 && (
<div className="mb-3" style={{ maxWidth: 320 }}>
<select
className="form-select"
value={selectedId ?? ""}
onChange={(e) => setSelectedId(Number(e.target.value))}
>
{integrations.map((i) => (
<option key={i.id} value={i.id} disabled={!i.enabled}>
{i.name}
{!i.enabled ? " — disabled" : ""}
</option>
))}
</select>
</div>
)}
{selected && !selected.enabled ? (
<div className="card">
<div className="card-body text-secondary">
"{selected.name}" is disabled. Enable it under Integrations → Manage integrations to see its
templates.
</div>
</div>
) : (
<div className="card">
<div className="card-header">
<h3 className="card-title">
Templates
{data && data.summary.failing > 0 && (
<span className="text-red fw-normal ms-2">{data.summary.failing} failing</span>
)}
</h3>
<div className="card-actions">
<button className="btn btn-sm btn-outline-secondary" onClick={exportCsv} disabled={!sorted || sorted.length === 0}>
Export CSV
</button>
<button
className="btn btn-sm btn-outline-secondary"
onClick={() => selected && loadTemplates(selected.id)}
disabled={loading}
>
{loading ? "Refreshing…" : "Refresh"}
</button>
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<SortableTh<SemaphoreTemplate> label="Template" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<SemaphoreTemplate>
label="Project"
sortKeyName="projectName"
activeKey={sortKey}
direction={sortDir}
onSort={requestSort}
/>
<th>Last run</th>
<th>Status</th>
{canEdit && <th className="w-1">Actions</th>}
</tr>
</thead>
<tbody>
{pageItems?.map((t) => (
<tr key={`${t.projectId}:${t.id}`}>
<td>{t.name}</td>
<td className="text-secondary">{t.projectName}</td>
<td className="text-secondary">
{t.lastTask
? formatDateTime(new Date(t.lastTask.end ?? t.lastTask.start ?? t.lastTask.created ?? ""))
: "—"}
</td>
<td>{semaphoreStatusBadge(t)}</td>
{canEdit && (
<td>
<button
className="btn btn-sm btn-primary"
onClick={() => runTemplate(t)}
disabled={runningTemplate === t.id}
>
{runningTemplate === t.id ? "Starting…" : "Run"}
</button>
</td>
)}
</tr>
))}
{sorted?.length === 0 && (
<tr>
<td colSpan={canEdit ? 5 : 4} className="text-secondary text-center">
No templates found across any project.
</td>
</tr>
)}
</tbody>
</table>
</div>
<Pagination page={page} pageCount={pageCount} totalCount={totalCount} onPageChange={setPage} />
</div>
)}
</>
)}
</>
);
}