import { toast } from "../utils/toast"; import { removeWithUndo } from "../utils/undoable"; import { useEffect, useMemo, useState } from "react"; import { useSearchParams } from "react-router-dom"; import { api, type CurrentUser, type IpamEntry, type IpamInput } from "../api/client"; import { downloadCsv } from "../utils/csv"; import { useSortable } from "../hooks/useSortable"; import SortableTh from "../components/SortableTh"; import { usePagination } from "../hooks/usePagination"; import Pagination from "../components/Pagination"; import { useSelection } from "../hooks/useSelection"; import { confirmDialog, promptDialog } from "../utils/dialogs"; import { ErrorNotice } from "../components/Notice"; import TableToolbar from "../components/TableToolbar"; import { EmptyRow, LoadingRow } from "../components/EmptyState"; const emptyForm: IpamInput = { ipAddress: "", label: "", vendor: "", location: "", notes: "" }; function isIpv6(ip: string) { return ip.includes(":"); } export default function Ipam({ user }: { user: CurrentUser }) { const canEdit = user.role === "admin" || user.role === "operator"; const [entries, setEntries] = useState(null); const [excludedRanges, setExcludedRanges] = useState([]); const [hideExcluded, setHideExcluded] = useState(true); const [showRanges, setShowRanges] = useState(false); const [newRange, setNewRange] = useState(""); const [savingRanges, setSavingRanges] = useState(false); const [error, setError] = useState(null); const [searchParams] = useSearchParams(); const [search, setSearch] = useState(() => searchParams.get("q") ?? ""); const [editing, setEditing] = useState(null); const [adding, setAdding] = useState(false); const [form, setForm] = useState(emptyForm); const [saving, setSaving] = useState(false); const [syncing, setSyncing] = useState<"tailscale" | "proxmox" | "phpipam" | "unifi" | null>(null); const [syncResult, setSyncResult] = useState(null); const selection = useSelection(); const [bulkDeleting, setBulkDeleting] = useState(false); function load() { api.ipam .list() .then((res) => { setEntries(res.entries); setExcludedRanges(res.excludedRanges); // Deep-link from global search (?editId=) — jump straight to that entry's edit form. const editId = Number(searchParams.get("editId")); const target = res.entries.find((e) => e.id === editId); if (target && canEdit) startEdit(target); }) .catch((err) => setError(String(err))); } useEffect(load, []); /** Saves the whole list (the server validates and normalises it) and reloads — shared with the Consistency page. */ async function saveRanges(ranges: string[]): Promise { setSavingRanges(true); setError(null); try { await api.consistency.setExcludedRanges(ranges); load(); return true; } catch (err) { setError(err instanceof Error ? err.message : String(err)); return false; } finally { setSavingRanges(false); } } async function addRange(e: React.FormEvent) { e.preventDefault(); if (!newRange.trim()) return; if (await saveRanges([...excludedRanges, newRange.trim()])) setNewRange(""); } async function excludeAround(entry: IpamEntry) { const suggestion = isIpv6(entry.ipAddress) ? `${entry.ipAddress}/64` : `${entry.ipAddress.split(".").slice(0, 3).join(".")}.0/24`; const range = await promptDialog({ title: "Exclude a range", message: "Hide this range from IP Addresses and the Consistency report — every address in it, not just this one.", label: "Range (a network like 172.17.0.0/16, or a single address)", defaultValue: suggestion, confirmLabel: "Exclude", required: true, }); if (range === null || !range.trim()) return; await saveRanges([...excludedRanges, range.trim()]); } const excludedCount = useMemo(() => entries?.filter((e) => e.excluded).length ?? 0, [entries]); const filtered = useMemo(() => { if (!entries) return []; const base = hideExcluded ? entries.filter((e) => !e.excluded) : entries; const q = search.trim().toLowerCase(); if (!q) return base; return base.filter((e) => [e.ipAddress, e.label, e.vendor, e.location].some((v) => (v ?? "").toLowerCase().includes(q)), ); }, [entries, hideExcluded, search]); function startAdd() { setAdding(true); setEditing(null); setForm(emptyForm); } function startEdit(entry: IpamEntry) { setEditing(entry); setAdding(false); setForm({ ipAddress: entry.ipAddress, label: entry.label ?? "", vendor: entry.vendor ?? "", location: entry.location ?? "", notes: entry.notes ?? "", }); } function cancelForm() { setAdding(false); setEditing(null); setForm(emptyForm); } async function submit(e: React.FormEvent) { e.preventDefault(); setError(null); setSaving(true); try { if (editing) { const { ipAddress: _ip, ...rest } = form; await api.ipam.update(editing.id, rest); } else { await api.ipam.create(form); } cancelForm(); load(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setSaving(false); } } /** What is needed to make an entry again; one that a sync made would come back as a hand-made one, so those are still asked about. */ const asInput = (e: IpamEntry): IpamInput => ({ ipAddress: e.ipAddress, label: e.label ?? undefined, vendor: e.vendor ?? undefined, location: e.location ?? undefined, notes: e.notes ?? undefined }); async function remove(entry: IpamEntry) { setError(null); if (entry.source) { if (!(await confirmDialog({ title: "Delete IP address", message: `Delete IP address "${entry.ipAddress}"? A sync can bring it back.`, confirmLabel: "Delete", danger: true }))) return; try { await api.ipam.remove(entry.id); load(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } return; } await removeWithUndo({ remove: () => api.ipam.remove(entry.id), restore: () => api.ipam.create(asInput(entry)), message: `Deleted ${entry.ipAddress}.`, reload: load, onError: setError, }); } async function bulkDelete() { const ids = Array.from(selection.selected); if (ids.length === 0) return; const picked = (entries ?? []).filter((e) => ids.includes(e.id)); const plain = picked.length === ids.length && picked.every((e) => !e.source); if (!plain && !(await confirmDialog({ title: "Delete IP addresses", message: `Delete ${ids.length} IP address${ids.length !== 1 ? "es" : ""}? Those a sync made can be brought back by it.`, confirmLabel: "Delete", danger: true }))) return; setError(null); setBulkDeleting(true); try { const results = await Promise.allSettled(ids.map((id) => api.ipam.remove(id))); const failed = results.filter((r) => r.status === "rejected").length; if (failed > 0) setError(`${failed} of ${ids.length} deletions failed.`); const gone = picked.filter((_, i) => results[ids.indexOf(picked[i].id)]?.status === "fulfilled"); selection.clear(); load(); if (plain && gone.length > 0) { toast.success(`Deleted ${gone.length} IP address${gone.length !== 1 ? "es" : ""}.`, { label: "Undo", onClick: async () => { const back = await Promise.allSettled(gone.map((e) => api.ipam.create(asInput(e)))); const lost = back.filter((r) => r.status === "rejected").length; if (lost > 0) toast.error(`${lost} could not be put back.`); else toast.info("Put back."); load(); }, }); } } finally { setBulkDeleting(false); } } const SYNC_LABELS: Record<"tailscale" | "proxmox" | "phpipam" | "unifi", string> = { tailscale: "Tailscale", proxmox: "Proxmox", phpipam: "phpIPAM", unifi: "UniFi", }; async function runSync(source: "tailscale" | "proxmox" | "phpipam" | "unifi") { setError(null); setSyncResult(null); setSyncing(source); try { const res = source === "tailscale" ? await api.ipam.syncTailscale() : source === "proxmox" ? await api.ipam.syncProxmox() : source === "unifi" ? await api.ipam.syncUnifi() : await api.ipam.syncPhpIpam(); const parts = [`${res.added} added`, `${res.updated} updated`]; if (res.skipped > 0) parts.push(`${res.skipped} skipped (already tracked manually)`); setSyncResult(`${SYNC_LABELS[source]}: ${parts.join(", ")}`); if (res.errors.length > 0) setError(res.errors.join("; ")); load(); } catch (err) { setError(err instanceof Error ? err.message : String(err)); } finally { setSyncing(null); } } const { sorted, sortKey, sortDir, requestSort } = useSortable(filtered); const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted); function exportCsv() { downloadCsv( "ip-addresses.csv", ["IP Address", "Label", "Vendor", "Location", "Notes", "DNS Records"], (sorted ?? []).map((e) => [ e.ipAddress, e.label ?? "", e.vendor ?? "", e.location ?? "", e.notes ?? "", e.matchingDnsRecords.join("; "), ]), ); } const showForm = adding || editing; return ( <>

IP Addresses

{syncResult &&
Synced from {syncResult}
}
{showRanges && (
Addresses in these ranges are left out here and on the Consistency report — the same setting either page manages. Meant for networks that aren't part of your LAN, like Docker's, which repeat the same subnet on many hosts.
{excludedRanges.length === 0 && Nothing excluded.} {excludedRanges.map((r) => ( {r} {canEdit && (
{canEdit && (
setNewRange(e.target.value)} />
)}
)}
{canEdit && showForm && (

{editing ? `Edit ${editing.ipAddress}` : "Add an IP address"}

setForm({ ...form, ipAddress: e.target.value })} /> {!editing &&
Cannot be changed after creation.
}
setForm({ ...form, label: e.target.value })} />
setForm({ ...form, vendor: e.target.value })} />
setForm({ ...form, location: e.target.value })} />
setForm({ ...form, notes: e.target.value })} />
)}
{canEdit && !showForm && ( )} {canEdit && ( <> )} } onExport={exportCsv} /> {canEdit && selection.count > 0 && (
{selection.count} selected
)}
{canEdit && ( )} label="IP address" sortKeyName="ipAddress" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Label" sortKeyName="label" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Vendor" sortKeyName="vendor" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Location" sortKeyName="location" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> {canEdit && } {(pageItems ?? []).map((entry) => ( {canEdit && ( )} {canEdit && ( )} ))} {entries === null && } {entries !== null && (sorted ?? []).length === 0 && ( 0 ? { filtered: () => { setSearch(""); setHideExcluded(false); }, hint: "Every tracked address is excluded or filtered out. Show the excluded ones, or clear the search, to see them." } : { title: "No IP addresses tracked yet", hint: "Track the addresses you hand out, so you can see what is taken, what is free and what clashes.", action: canEdit ? { label: "Add an address", onClick: startAdd } : undefined })} /> )}
0 && (pageItems ?? []).every((e) => selection.isSelected(e.id))} onChange={() => selection.toggleAll((pageItems ?? []).map((e) => e.id))} /> DNS recordsActions
selection.toggle(entry.id)} /> {isIpv6(entry.ipAddress) ? "IPv6" : "IPv4"} {entry.ipAddress} {entry.excluded && excluded} {entry.label ?? "—"} {entry.vendor ?? "—"} {entry.source && synced from {entry.source}} {entry.location ?? "—"} {entry.matchingDnsRecords.length > 0 ? entry.matchingDnsRecords.join(", ") : "—"}
{!entry.excluded && ( )}
); }