mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-11-16 14:54:23 +08:00
perf(nodes): paginate node lists and fetch details directly (#54)
* perf(nodes): paginate node lists and fetch details directly * fix(nodes): preserve Unicode search and page transition state * fix(nodes): validate search using the UTF-8 byte limit
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
import { useTranslations } from 'next-intl';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Field,
|
||||
FieldError,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
} from '@/components/ui/field';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type { NodeStatus } from '@/lib/services/openflare';
|
||||
|
||||
export function NodeListControls({
|
||||
search,
|
||||
searchTooLong,
|
||||
onSearchChange,
|
||||
status,
|
||||
onStatusChange,
|
||||
page,
|
||||
pageSize,
|
||||
onPageSizeChange,
|
||||
total,
|
||||
totalPages,
|
||||
loading,
|
||||
hasData,
|
||||
onPageChange,
|
||||
}: {
|
||||
search: string;
|
||||
searchTooLong: boolean;
|
||||
onSearchChange: (value: string) => void;
|
||||
status: NodeStatus | '';
|
||||
onStatusChange: (value: NodeStatus | '') => void;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
onPageSizeChange: (value: number) => void;
|
||||
total: number;
|
||||
totalPages: number;
|
||||
loading: boolean;
|
||||
hasData: boolean;
|
||||
onPageChange: (value: number) => void;
|
||||
}) {
|
||||
const t = useTranslations('nodes');
|
||||
return (
|
||||
<div className='flex flex-col gap-4'>
|
||||
<FieldGroup className='flex flex-wrap gap-3 sm:flex-row'>
|
||||
<Field className='flex-1' data-invalid={searchTooLong || undefined}>
|
||||
<FieldLabel htmlFor='node-search'>
|
||||
{t('pagination.search')}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id='node-search'
|
||||
value={search}
|
||||
onChange={(event) => onSearchChange(event.target.value)}
|
||||
placeholder={t('pagination.searchPlaceholder')}
|
||||
maxLength={256}
|
||||
aria-invalid={searchTooLong || undefined}
|
||||
aria-describedby={searchTooLong ? 'node-search-error' : undefined}
|
||||
/>
|
||||
{searchTooLong && (
|
||||
<FieldError id='node-search-error'>
|
||||
{t('pagination.searchTooLong')}
|
||||
</FieldError>
|
||||
)}
|
||||
</Field>
|
||||
<Field className='sm:w-44'>
|
||||
<FieldLabel htmlFor='node-status'>{t('table.status')}</FieldLabel>
|
||||
<Select
|
||||
value={status || 'all'}
|
||||
onValueChange={(value) =>
|
||||
onStatusChange(value === 'all' ? '' : (value as NodeStatus))
|
||||
}
|
||||
>
|
||||
<SelectTrigger id='node-status'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem value='all'>
|
||||
{t('pagination.allStatuses')}
|
||||
</SelectItem>
|
||||
{(['pending', 'online', 'offline'] as const).map((value) => (
|
||||
<SelectItem key={value} value={value}>
|
||||
{t(`status.${value}`)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
<Field className='sm:w-32'>
|
||||
<FieldLabel htmlFor='node-page-size'>
|
||||
{t('pagination.pageSize')}
|
||||
</FieldLabel>
|
||||
<Select
|
||||
value={String(pageSize)}
|
||||
onValueChange={(value) => onPageSizeChange(Number(value))}
|
||||
>
|
||||
<SelectTrigger id='node-page-size'>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
{[20, 50, 100].map((value) => (
|
||||
<SelectItem key={value} value={String(value)}>
|
||||
{value}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<div className='flex flex-wrap items-center justify-between gap-3'>
|
||||
{hasData && (
|
||||
<p className='text-sm text-muted-foreground' aria-live='polite'>
|
||||
{t('pagination.summary', { page, totalPages, total })}
|
||||
</p>
|
||||
)}
|
||||
<nav aria-label={t('pagination.navigation')} className='flex gap-2'>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
disabled={!hasData || loading || page <= 1}
|
||||
onClick={() => onPageChange(page - 1)}
|
||||
>
|
||||
{t('pagination.previous')}
|
||||
</Button>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
disabled={!hasData || loading || page >= totalPages}
|
||||
onClick={() => onPageChange(page + 1)}
|
||||
>
|
||||
{t('pagination.next')}
|
||||
</Button>
|
||||
</nav>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -37,15 +37,20 @@ export function NodesTable({
|
||||
deletingId,
|
||||
onEdit,
|
||||
onDelete,
|
||||
actionsDisabled = false,
|
||||
}: {
|
||||
nodes: NodeItem[];
|
||||
deletingId: number | null;
|
||||
actionsDisabled?: boolean;
|
||||
onEdit: (node: NodeItem) => void;
|
||||
onDelete: (node: NodeItem) => void;
|
||||
}) {
|
||||
const t = useTranslations('nodes');
|
||||
return (
|
||||
<div className='border border-dashed rounded-lg overflow-hidden'>
|
||||
<div
|
||||
className='border border-dashed rounded-lg overflow-hidden'
|
||||
aria-busy={actionsDisabled}
|
||||
>
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow className='border-dashed hover:bg-transparent'>
|
||||
@@ -144,16 +149,22 @@ export function NodesTable({
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 text-xs'
|
||||
asChild
|
||||
asChild={!actionsDisabled}
|
||||
disabled={actionsDisabled}
|
||||
>
|
||||
<Link href={`/nodes/detail?id=${node.id}`}>
|
||||
{t('detail')}
|
||||
</Link>
|
||||
{actionsDisabled ? (
|
||||
t('detail')
|
||||
) : (
|
||||
<Link href={`/nodes/detail?id=${node.id}`}>
|
||||
{t('detail')}
|
||||
</Link>
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 text-xs'
|
||||
disabled={actionsDisabled}
|
||||
onClick={() => onEdit(node)}
|
||||
>
|
||||
<Pencil className='size-3 mr-1' />
|
||||
@@ -163,7 +174,7 @@ export function NodesTable({
|
||||
variant='outline'
|
||||
size='sm'
|
||||
className='h-7 text-xs text-destructive hover:text-destructive'
|
||||
disabled={deletingId === node.id}
|
||||
disabled={actionsDisabled || deletingId === node.id}
|
||||
onClick={() => onDelete(node)}
|
||||
>
|
||||
<Trash2 className='size-3 mr-1' />
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
'use client';
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useMemo } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { ArrowLeft, Server } from 'lucide-react';
|
||||
@@ -25,20 +24,20 @@ export function NodeDetailPageClient() {
|
||||
const searchParams = useSearchParams();
|
||||
const nodeId = searchParams.get('id')?.trim() ?? '';
|
||||
|
||||
const validNodeId =
|
||||
Number.isSafeInteger(Number(nodeId)) && Number(nodeId) > 0;
|
||||
const nodesQuery = useQuery({
|
||||
queryKey: nodesQueryKey,
|
||||
queryFn: () => NodeService.listNodes(),
|
||||
refetchInterval: 5000,
|
||||
queryKey: [...nodesQueryKey, 'detail', nodeId],
|
||||
queryFn: () => NodeService.getNode(Number(nodeId)),
|
||||
enabled: validNodeId,
|
||||
refetchInterval: (query) =>
|
||||
query.state.status === 'error' ? false : 15000,
|
||||
refetchIntervalInBackground: false,
|
||||
});
|
||||
|
||||
const node = useMemo(() => {
|
||||
if (!nodeId) return null;
|
||||
return (
|
||||
(nodesQuery.data ?? []).find((item) => String(item.id) === nodeId) ?? null
|
||||
);
|
||||
}, [nodeId, nodesQuery.data]);
|
||||
const node = nodesQuery.data;
|
||||
|
||||
if (!nodeId) {
|
||||
if (!validNodeId) {
|
||||
return (
|
||||
<div className='py-6 px-1'>
|
||||
<EmptyStateWithBorder icon={Server} description={t('missingId')} />
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import Link from 'next/link';
|
||||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useSearchParams } from 'next/navigation';
|
||||
import { Loader2, Plus, RefreshCw, Server } from 'lucide-react';
|
||||
import { useTranslations } from 'next-intl';
|
||||
@@ -29,46 +29,112 @@ import {
|
||||
import { EmptyStateWithBorder } from '@/components/layout/empty';
|
||||
import { ErrorInline } from '@/components/layout/error';
|
||||
import { LoadingStateWithBorder } from '@/components/layout/loading';
|
||||
import type { NodeItem, NodeMutationPayload } from '@/lib/services/openflare';
|
||||
import type {
|
||||
NodeItem,
|
||||
NodeListQuery,
|
||||
NodeMutationPayload,
|
||||
NodeStatus,
|
||||
NodeType,
|
||||
} from '@/lib/services/openflare';
|
||||
import { NodeService } from '@/lib/services/openflare';
|
||||
|
||||
import { NodeEditorDialog } from './components/node-editor-dialog';
|
||||
import {
|
||||
filterNodesByType,
|
||||
getFilterDescription,
|
||||
getNodeFilter,
|
||||
NodeTypeFilter,
|
||||
type NodeFilter,
|
||||
} from './components/node-type-filter';
|
||||
import { NodesTable } from './components/nodes-table';
|
||||
import { NodeListControls } from './components/node-list-controls';
|
||||
import { getErrorMessage } from './components/node-utils';
|
||||
|
||||
const nodesQueryKey = ['openflare', 'nodes'];
|
||||
|
||||
export function NodesPageClient() {
|
||||
const searchParams = useSearchParams();
|
||||
const nodeFilter = getNodeFilter(
|
||||
new URLSearchParams(searchParams.toString()),
|
||||
);
|
||||
return <NodesPage key={nodeFilter} nodeFilter={nodeFilter} />;
|
||||
}
|
||||
|
||||
function NodesPage({ nodeFilter }: { nodeFilter: NodeFilter }) {
|
||||
const t = useTranslations('nodes');
|
||||
const tc = useTranslations('common');
|
||||
const searchParams = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
const [editingNode, setEditingNode] = useState<NodeItem | null>(null);
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [deleteTarget, setDeleteTarget] = useState<NodeItem | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [search, setSearch] = useState('');
|
||||
const [debouncedSearch, setDebouncedSearch] = useState('');
|
||||
const [status, setStatus] = useState<NodeStatus | ''>('');
|
||||
const searchTooLong = new TextEncoder().encode(search.trim()).length > 256;
|
||||
|
||||
const nodeFilter = useMemo(
|
||||
() => getNodeFilter(new URLSearchParams(searchParams.toString())),
|
||||
[searchParams],
|
||||
);
|
||||
const resetNodeActions = useCallback(() => {
|
||||
setEditingNode(null);
|
||||
setEditorOpen(false);
|
||||
setDeleteTarget(null);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (searchTooLong || search.trim() === debouncedSearch) return;
|
||||
const timeout = setTimeout(() => {
|
||||
setDebouncedSearch(search.trim());
|
||||
setPage(1);
|
||||
resetNodeActions();
|
||||
}, 300);
|
||||
return () => clearTimeout(timeout);
|
||||
}, [search, searchTooLong, debouncedSearch, resetNodeActions]);
|
||||
|
||||
const nodeTypes: Record<NodeFilter, NodeType | ''> = {
|
||||
all: '',
|
||||
edge: 'edge_node',
|
||||
relay: 'tunnel_relay',
|
||||
tunnel: 'tunnel_client',
|
||||
};
|
||||
const query = {
|
||||
page,
|
||||
page_size: pageSize,
|
||||
search: debouncedSearch,
|
||||
status,
|
||||
node_type: nodeTypes[nodeFilter],
|
||||
};
|
||||
const nodesQuery = useQuery({
|
||||
queryKey: nodesQueryKey,
|
||||
queryFn: () => NodeService.listNodes(),
|
||||
refetchInterval: 5000,
|
||||
queryKey: [...nodesQueryKey, 'page', query],
|
||||
queryFn: () => NodeService.listNodePage(query),
|
||||
placeholderData: (previousData, previousQuery) => {
|
||||
const previousParams = previousQuery?.queryKey[3] as
|
||||
| NodeListQuery
|
||||
| undefined;
|
||||
return previousParams?.search === query.search &&
|
||||
previousParams?.status === query.status &&
|
||||
previousParams?.node_type === query.node_type &&
|
||||
previousParams?.page_size === query.page_size
|
||||
? previousData
|
||||
: undefined;
|
||||
},
|
||||
refetchInterval: (query) =>
|
||||
query.state.status === 'error' ? false : 15000,
|
||||
refetchIntervalInBackground: false,
|
||||
});
|
||||
|
||||
const nodes = useMemo(() => nodesQuery.data ?? [], [nodesQuery.data]);
|
||||
const filteredNodes = useMemo(
|
||||
() => filterNodesByType(nodes, nodeFilter),
|
||||
[nodeFilter, nodes],
|
||||
const nodes = useMemo(
|
||||
() => nodesQuery.data?.results ?? [],
|
||||
[nodesQuery.data],
|
||||
);
|
||||
const total = nodesQuery.data?.total ?? 0;
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
if (
|
||||
!nodesQuery.isPlaceholderData &&
|
||||
nodesQuery.data?.page === page &&
|
||||
page > totalPages
|
||||
) {
|
||||
setPage(totalPages);
|
||||
resetNodeActions();
|
||||
}
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async (payload: NodeMutationPayload) => {
|
||||
@@ -106,6 +172,7 @@ export function NodesPageClient() {
|
||||
};
|
||||
|
||||
const handleEdit = (node: NodeItem) => {
|
||||
if (nodesQuery.isPlaceholderData) return;
|
||||
setEditingNode(node);
|
||||
setEditorOpen(true);
|
||||
};
|
||||
@@ -115,7 +182,7 @@ export function NodesPageClient() {
|
||||
};
|
||||
|
||||
return (
|
||||
<div className='py-6 px-1 space-y-6'>
|
||||
<div className='flex w-full flex-col gap-6 py-6 px-1'>
|
||||
<div className='flex items-center justify-between gap-3'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<Server className='size-5 text-primary' />
|
||||
@@ -166,8 +233,34 @@ export function NodesPageClient() {
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className='space-y-4'>
|
||||
<CardContent className='flex flex-col gap-4'>
|
||||
<NodeTypeFilter />
|
||||
<NodeListControls
|
||||
search={search}
|
||||
searchTooLong={searchTooLong}
|
||||
onSearchChange={setSearch}
|
||||
status={status}
|
||||
onStatusChange={(value) => {
|
||||
setStatus(value);
|
||||
setPage(1);
|
||||
resetNodeActions();
|
||||
}}
|
||||
page={nodesQuery.data?.page ?? page}
|
||||
pageSize={pageSize}
|
||||
onPageSizeChange={(value) => {
|
||||
setPageSize(value);
|
||||
setPage(1);
|
||||
resetNodeActions();
|
||||
}}
|
||||
total={total}
|
||||
totalPages={totalPages}
|
||||
loading={nodesQuery.isFetching || nodesQuery.isPlaceholderData}
|
||||
hasData={Boolean(nodesQuery.data)}
|
||||
onPageChange={(value) => {
|
||||
setPage(value);
|
||||
resetNodeActions();
|
||||
}}
|
||||
/>
|
||||
|
||||
{nodesQuery.isLoading ? (
|
||||
<LoadingStateWithBorder
|
||||
@@ -182,21 +275,26 @@ export function NodesPageClient() {
|
||||
className='justify-center'
|
||||
/>
|
||||
</div>
|
||||
) : filteredNodes.length === 0 ? (
|
||||
) : nodes.length === 0 ? (
|
||||
<EmptyStateWithBorder
|
||||
icon={Server}
|
||||
description={
|
||||
nodes.length === 0 ? t('emptyAll') : t('emptyFilter')
|
||||
debouncedSearch || status || nodeFilter !== 'all'
|
||||
? t('emptyFilter')
|
||||
: t('emptyAll')
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<NodesTable
|
||||
nodes={filteredNodes}
|
||||
nodes={nodes}
|
||||
deletingId={
|
||||
deleteMutation.isPending ? (deleteTarget?.id ?? null) : null
|
||||
}
|
||||
onEdit={handleEdit}
|
||||
onDelete={setDeleteTarget}
|
||||
onDelete={(node) => {
|
||||
if (!nodesQuery.isPlaceholderData) setDeleteTarget(node);
|
||||
}}
|
||||
actionsDisabled={nodesQuery.isPlaceholderData}
|
||||
/>
|
||||
)}
|
||||
</CardContent>
|
||||
@@ -205,13 +303,17 @@ export function NodesPageClient() {
|
||||
<NodeEditorDialog
|
||||
open={editorOpen}
|
||||
node={editingNode}
|
||||
submitting={saveMutation.isPending}
|
||||
submitting={
|
||||
saveMutation.isPending ||
|
||||
(Boolean(editingNode) && nodesQuery.isPlaceholderData)
|
||||
}
|
||||
onClose={() => {
|
||||
setEditorOpen(false);
|
||||
setEditingNode(null);
|
||||
}}
|
||||
onSubmit={async (payload) => {
|
||||
await saveMutation.mutateAsync(payload);
|
||||
if (!editingNode || !nodesQuery.isPlaceholderData)
|
||||
await saveMutation.mutateAsync(payload);
|
||||
}}
|
||||
/>
|
||||
|
||||
@@ -227,14 +329,22 @@ export function NodesPageClient() {
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteMutation.isPending}>
|
||||
<AlertDialogCancel
|
||||
disabled={
|
||||
deleteMutation.isPending || nodesQuery.isPlaceholderData
|
||||
}
|
||||
>
|
||||
{tc('cancel')}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className='bg-destructive text-white hover:bg-destructive/90'
|
||||
disabled={deleteMutation.isPending}
|
||||
disabled={
|
||||
deleteMutation.isPending || nodesQuery.isPlaceholderData
|
||||
}
|
||||
onClick={() =>
|
||||
deleteTarget && deleteMutation.mutate(deleteTarget.id)
|
||||
deleteTarget &&
|
||||
!nodesQuery.isPlaceholderData &&
|
||||
deleteMutation.mutate(deleteTarget.id)
|
||||
}
|
||||
>
|
||||
{deleteMutation.isPending ? t('deleting') : t('confirmDelete')}
|
||||
|
||||
Reference in New Issue
Block a user