import { createContext, use, useCallback, useMemo, useState } from 'react'; import { Link, useNavigate } from '@tanstack/react-router'; import { getCoreRowModel, useReactTable, type ColumnDef, type Table } from '@tanstack/react-table'; import { useAppForm, Form } from '@/components/form'; import { Network, Trash2 } from 'lucide-react'; import { type AdminAllocation, bulkDeleteAdminNodeAllocationsInput, type CreateAllocationValues, createAdminNodeAllocationsInput, deleteAdminNodeAllocationInput, deleteAdminNodeIpBlockAllocationsInput, updateAdminNodeAllocationAliasInput, useAdminNodeAllocations, useBulkDeleteAdminNodeAllocations, useCreateAdminNodeAllocations, useDeleteAdminNodeAllocation, useDeleteAdminNodeIpBlockAllocations, useUpdateAdminNodeAllocationAlias, } from '@/api/admin/nodes/queries'; import { useNodeDetail } from '@/components/admin/nodes/useNodeDetail'; import TitledGreyBox from '@/components/elements/TitledGreyBox'; import Icon from '@/components/elements/Icon'; import { TextInput } from '@/components/form/controls'; import Checkbox from '@/components/ui/Checkbox'; import Button from '@/components/elements/Button'; import Spinner from '@/components/elements/Spinner'; import DataTable from '@/components/elements/table/DataTable'; import DataTablePagination from '@/components/elements/table/DataTablePagination'; import { actionsColumn, DeleteAction, RowActions } from '@/components/elements/table/RowActions'; import { Dialog } from '@/components/elements/dialog'; import { Alert } from '@/components/elements/alert'; import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty'; import { cardTitleClass } from '@/components/ui/typography'; import { httpErrorToHuman } from '@/api/http'; import { cn } from '@/lib/cn'; import { getPageSearch, usePageSearch } from '@/router/search'; const countLabel = (count: number, noun: string) => `${count} ${noun}${count === 1 ? '' : 's'}`; const ghostDangerClass = 'rounded-sm text-muted-foreground transition-colors hover:bg-popover hover:text-destructive'; const unassignedAllocationIds = (items: AdminAllocation[]) => { const ids: number[] = []; for (const allocation of items) { if (!allocation.attributes.assigned) { ids.push(allocation.attributes.id); } } return ids; }; const groupAllocationsByIp = (items: AdminAllocation[]) => { const map = new Map(); for (const allocation of items) { const list = map.get(allocation.attributes.ip) ?? []; list.push(allocation); map.set(allocation.attributes.ip, list); } return [...map.entries()]; }; const paginationColumns = [ { id: 'allocation', header: 'Allocation', cell: () => null }, ] as ColumnDef[]; interface AllocationTableContextValue { nodeId: number; selected: ReadonlySet; toggle: (id: number) => void; toggleGroup: (items: AdminAllocation[]) => void; deleteAllocation: (allocation: AdminAllocation) => void; } const AllocationTableContext = createContext(null); const useAllocationTable = (): AllocationTableContextValue => { const context = use(AllocationTableContext); if (!context) { throw new Error('An allocation table cell was rendered outside of its allocation tab.'); } return context; }; const AllocationGroupCheckbox = ({ allocations }: { allocations: AdminAllocation[] }) => { const { selected, toggleGroup } = useAllocationTable(); const unassignedIds = unassignedAllocationIds(allocations); const allSelected = unassignedIds.length > 0 && unassignedIds.every((id) => selected.has(id)); const ip = allocations[0]?.attributes.ip; return ( selected.has(id))} disabled={unassignedIds.length === 0} onChange={() => toggleGroup(allocations)} /> ); }; const AllocationCheckbox = ({ allocation }: { allocation: AdminAllocation }) => { const { selected, toggle } = useAllocationTable(); return ( toggle(allocation.attributes.id)} /> ); }; const AllocationAliasCell = ({ allocation }: { allocation: AdminAllocation }) => { const { nodeId } = useAllocationTable(); const savedAlias = allocation.attributes.alias ?? ''; const [draft, setDraft] = useState(null); const updateAlias = useUpdateAdminNodeAllocationAlias(); const saveAlias = () => { if (draft === null) { return; } if (draft === savedAlias) { setDraft(null); return; } const alias = draft; updateAlias.mutate(updateAdminNodeAllocationAliasInput(nodeId, allocation.attributes.id, alias), { onSuccess: () => setDraft((current) => (current === alias ? null : current)), }); }; return ( setDraft(e.currentTarget.value)} onBlur={saveAlias} className='h-8 border border-transparent bg-transparent px-2 py-1 placeholder:text-muted-foreground focus:bg-input' /> ); }; const AllocationServerCell = ({ allocation }: { allocation: AdminAllocation }) => { const { assigned, server_id: serverId, server_name: serverName } = allocation.attributes; if (!assigned) { return ( Unassigned ); } if (serverId === null) { return Assigned; } return ( {serverName ?? 'Assigned'} ); }; const AllocationDeleteCell = ({ allocation }: { allocation: AdminAllocation }) => { const { deleteAllocation } = useAllocationTable(); if (allocation.attributes.assigned) { return null; } const address = `${allocation.attributes.ip}:${allocation.attributes.port}`; return ( ( )} onConfirmed={(_event, close) => { close(); deleteAllocation(allocation); }} > This will permanently delete the {address} allocation. This action cannot be undone. ); }; const allocationColumns = [ { id: 'selected', header: ({ table }) => , cell: ({ row }) => , meta: { headerClassName: 'w-10', cellClassName: 'w-10' }, }, { id: 'port', header: 'Port', cell: ({ row }) => ( {row.original.attributes.port} ), meta: { headerClassName: 'w-24', cellClassName: 'w-24' }, }, { id: 'alias', header: 'Alias', cell: ({ row }) => , meta: { cellClassName: 'py-2 pl-1' }, }, { id: 'server', header: 'Server', cell: ({ row }) => , meta: { headerClassName: 'hidden w-44 sm:table-cell', cellClassName: 'hidden sm:table-cell' }, }, actionsColumn(1, (allocation) => ), ] satisfies ColumnDef[]; interface AllocationGroupTableProps { ip: string; allocations: AdminAllocation[]; isFetching: boolean; onDeleteBlock: (ip: string) => void; } const AllocationGroupTable = ({ ip, allocations, isFetching, onDeleteBlock }: AllocationGroupTableProps) => { const table = useReactTable({ data: allocations, columns: allocationColumns, getCoreRowModel: getCoreRowModel(), getRowId: (allocation) => String(allocation.attributes.id), }); const unassignedCount = unassignedAllocationIds(allocations).length; return (

{ip}

{countLabel(allocations.length, 'allocation')} ยท {unassignedCount} unassigned

( )} onConfirmed={(_event, close) => { close(); onDeleteBlock(ip); }} > This will permanently delete every unassigned allocation for {ip}. This action cannot be undone.
); }; interface ExistingAllocationsSummaryProps { selectedCount: number; total: number | undefined; onBulkDelete: () => void; } const ExistingAllocationsSummary = ({ selectedCount, total, onBulkDelete }: ExistingAllocationsSummaryProps) => { if (selectedCount > 0) { return (
{selectedCount} selected ( )} onConfirmed={(_event, close) => { close(); onBulkDelete(); }} > This will permanently delete the {selectedCount} selected allocation(s). This action cannot be undone.
); } if (total === undefined) { return null; } return {countLabel(total, 'allocation')}; }; type NodeAllocationsQuery = ReturnType; interface AllocationListProps { query: NodeAllocationsQuery; paginationTable: Table; showPagination: boolean; onBlockDelete: (ip: string) => void; } const AllocationList = ({ query, paginationTable, showPagination, onBlockDelete }: AllocationListProps) => { const { data: allocations, error, isFetching: loading, refetch } = query; const grouped = useMemo(() => groupAllocationsByIp(allocations?.data ?? []), [allocations?.data]); if (error && !loading) { return (
{httpErrorToHuman(error)} refetch()}> Retry
); } if (!allocations) { return ; } return ( <> {grouped.length === 0 ? ( No allocations yet Assign IP addresses and ports with the form to make them available to servers. ) : (
{grouped.map(([ip, items]) => ( ))}
)} {showPagination && ( )} ); }; export default function NodeAllocationTab() { const { node } = useNodeDetail(); const { attributes } = node; const navigate = useNavigate(); const page = usePageSearch(); const [selected, setSelected] = useState([]); const createAllocations = useCreateAdminNodeAllocations(); const { mutate: deleteAllocation } = useDeleteAdminNodeAllocation(); const { mutate: bulkDeleteAllocations } = useBulkDeleteAdminNodeAllocations(); const { mutate: ipBlockDeleteAllocations } = useDeleteAdminNodeIpBlockAllocations(); const query = useAdminNodeAllocations(attributes.id, page); const allocations = query.data; const pagination = { pageIndex: Math.max(page - 1, 0), pageSize: allocations?.meta.pagination.per_page ?? 50 }; const paginationData = useMemo(() => allocations?.data ?? [], [allocations?.data]); const paginationTable = useReactTable({ data: paginationData, columns: paginationColumns, getCoreRowModel: getCoreRowModel(), getRowId: (allocation) => String(allocation.attributes.id), manualPagination: true, rowCount: allocations?.meta.pagination.total ?? 0, state: { pagination }, onPaginationChange: (updater) => { const next = updater instanceof Function ? updater(pagination) : updater; if (next.pageIndex !== pagination.pageIndex) { void navigate({ to: '/panel/nodes/$id/allocation', params: { id: attributes.id }, search: getPageSearch(next.pageIndex + 1), replace: true, viewTransition: false, }); } }, }); const createForm = useAppForm({ defaultValues: { ip: '', alias: '', ports: '' }, onSubmit: async ({ value }) => { const ports = value.ports .split(/[\s,]+/) .map((entry) => entry.trim()) .filter((entry) => entry.length > 0); const payload: CreateAllocationValues = { ip: value.ip, alias: value.alias, ports }; try { await createAllocations.mutateAsync(createAdminNodeAllocationsInput(attributes.id, payload)); createForm.reset(); void navigate({ to: '/panel/nodes/$id/allocation', params: { id: attributes.id }, search: {}, replace: true, viewTransition: false, }); } catch { // Error toast is handled by the mutation. } }, }); const toggle = useCallback( (id: number) => setSelected((current) => (current.includes(id) ? current.filter((v) => v !== id) : [...current, id])), [] ); const toggleGroup = useCallback((items: AdminAllocation[]) => { const unassignedIds = unassignedAllocationIds(items); if (unassignedIds.length === 0) { return; } setSelected((current) => { const currentSet = new Set(current); const allSelected = unassignedIds.every((id) => currentSet.has(id)); if (allSelected) { const unassignedSet = new Set(unassignedIds); return current.filter((id) => !unassignedSet.has(id)); } return [...current, ...unassignedIds.filter((id) => !currentSet.has(id))]; }); }, []); const onDeleteSingle = useCallback( (allocation: AdminAllocation) => { deleteAllocation(deleteAdminNodeAllocationInput(attributes.id, allocation.attributes.id), { onSuccess: () => { setSelected((current) => current.filter((v) => v !== allocation.attributes.id)); }, }); }, [attributes.id, deleteAllocation] ); const onBulkDelete = () => { bulkDeleteAllocations(bulkDeleteAdminNodeAllocationsInput(attributes.id, selected), { onSuccess: () => { setSelected([]); }, }); }; const onBlockDelete = useCallback( (ip: string) => { ipBlockDeleteAllocations(deleteAdminNodeIpBlockAllocationsInput(attributes.id, ip), { onSuccess: () => { setSelected([]); }, }); }, [attributes.id, ipBlockDeleteAllocations] ); const tableContext = useMemo( () => ({ nodeId: attributes.id, selected: new Set(selected), toggle, toggleGroup, deleteAllocation: onDeleteSingle, }), [attributes.id, onDeleteSingle, selected, toggle, toggleGroup] ); const showPagination = allocations !== undefined && (allocations.meta.pagination.total_pages > 1 || page > 1); return (

Existing Allocations

} >
value.length >= 1 ? undefined : 'An IP address must be provided.', }} > {(field) => ( )} {(field) => ( )} value.length >= 1 ? undefined : 'At least one port must be provided.', }} > {(field) => ( )}
Create Allocations
); }