3x-ui/frontend/src/pages/nodes/NodesPage.tsx

184 lines
6.1 KiB
TypeScript
Raw Normal View History

refactor(frontend): port nodes to react+ts Step 4 of the planned vue->react migration. The nodes entry brings in the largest shared-infrastructure batch so far — every authenticated react page from here on can lean on these. New shared pieces (live alongside their .vue counterparts during coexistence): * hooks/useMediaQuery.ts — useState + resize listener * hooks/useWebSocket.ts — wraps WebSocketClient, subscribes on mount and unsubscribes on unmount. The underlying client is a single module-level instance so multiple components on the same page share one socket. * hooks/useNodes.ts — node list state + CRUD + probe/test, including the totals memo (online/offline/avgLatency) used by the summary card. applyNodesEvent is the entry point for the heartbeat-pushed list. * components/CustomStatistic.tsx — thin Statistic wrapper, prefix + suffix slots become props. * components/Sparkline.tsx — the SVG line chart with measured-width axis scaling, gradient fill, tooltip overlay, and per-instance gradient id from React.useId. ResizeObserver lifecycle is in useEffect; the math is unchanged. Pages: * NodesPage — wires hooks + WebSocket together, renders summary card + NodeList, hosts the form modal. Uses Modal.useModal() for the delete confirm so the dialog inherits ConfigProvider theming. * NodeList — desktop renders a Table with expandable history rows; mobile flips to a vertical card list whose actions live in a bottom-right Dropdown. The IP-blur eye toggle persists across both. * NodeFormModal — controlled form (useState object, single setForm per change). The reset-on-open effect computes the next state once and applies it with eslint-disable to satisfy the new react-hooks/set-state-in-effect rule on a legitimate pattern. * NodeHistoryPanel — polls /panel/api/nodes/history/{id}/{metric}/ {bucket} every 15s, renders cpu+mem sparklines side-by-side.
2026-05-21 19:34:46 +00:00
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Card, Col, ConfigProvider, Layout, Modal, Row, Spin, message } from 'antd';
import {
CheckCircleOutlined,
CloseCircleOutlined,
CloudServerOutlined,
ThunderboltOutlined,
} from '@ant-design/icons';
import { useTheme } from '@/hooks/useTheme';
import { useMediaQuery } from '@/hooks/useMediaQuery';
import { useNodes } from '@/hooks/useNodes';
import type { NodeRecord } from '@/hooks/useNodes';
import { useWebSocket } from '@/hooks/useWebSocket';
import AppSidebar from '@/components/AppSidebar';
import CustomStatistic from '@/components/CustomStatistic';
import NodeList from './NodeList';
import NodeFormModal from './NodeFormModal';
import './NodesPage.css';
const basePath = window.X_UI_BASE_PATH || '';
const requestUri = window.location.pathname;
export default function NodesPage() {
const { t } = useTranslation();
const { isDark, isUltra, antdThemeConfig } = useTheme();
const { isMobile } = useMediaQuery();
const [modal, modalContextHolder] = Modal.useModal();
const {
nodes,
loading,
fetched,
totals,
applyNodesEvent,
create,
update,
remove,
setEnable,
testConnection,
probe,
} = useNodes();
useWebSocket({ nodes: applyNodesEvent });
const [formOpen, setFormOpen] = useState(false);
const [formMode, setFormMode] = useState<'add' | 'edit'>('add');
const [formNode, setFormNode] = useState<NodeRecord | null>(null);
const onAdd = useCallback(() => {
setFormMode('add');
setFormNode(null);
setFormOpen(true);
}, []);
const onEdit = useCallback((node: NodeRecord) => {
setFormMode('edit');
setFormNode({ ...node });
setFormOpen(true);
}, []);
const onSave = useCallback(async (payload: Partial<NodeRecord>) => {
if (formMode === 'edit' && formNode?.id) {
return update(formNode.id, payload);
}
return create(payload);
}, [formMode, formNode, update, create]);
const onDelete = useCallback((node: NodeRecord) => {
modal.confirm({
title: t('pages.nodes.deleteConfirmTitle', { name: node.name }),
content: t('pages.nodes.deleteConfirmContent'),
okText: t('delete'),
okType: 'danger',
cancelText: t('cancel'),
onOk: async () => {
const msg = await remove(node.id);
if (msg?.success) message.success(t('pages.nodes.toasts.deleted'));
},
});
}, [modal, t, remove]);
const onProbe = useCallback(async (node: NodeRecord) => {
const msg = await probe(node.id);
if (msg?.success && msg.obj) {
if (msg.obj.status === 'online') {
message.success(t('pages.nodes.connectionOk', { ms: msg.obj.latencyMs }));
} else {
message.error(msg.obj.error || t('pages.nodes.toasts.probeFailed'));
}
}
}, [probe, t]);
const onToggleEnable = useCallback(async (node: NodeRecord, next: boolean) => {
await setEnable(node.id, next);
}, [setEnable]);
const pageClass = useMemo(() => {
const classes = ['nodes-page'];
if (isDark) classes.push('is-dark');
if (isUltra) classes.push('is-ultra');
return classes.join(' ');
}, [isDark, isUltra]);
return (
<ConfigProvider theme={antdThemeConfig}>
{modalContextHolder}
<Layout className={pageClass}>
<AppSidebar basePath={basePath} requestUri={requestUri} />
<Layout className="content-shell">
<Layout.Content id="content-layout" className="content-area">
<Spin spinning={!fetched} delay={200} tip="Loading…" size="large">
{!fetched ? (
<div className="loading-spacer" />
) : (
<Row gutter={[isMobile ? 8 : 16, isMobile ? 8 : 12]}>
<Col span={24}>
<Card size="small" hoverable className="summary-card">
<Row gutter={[16, isMobile ? 16 : 12]}>
<Col xs={12} sm={12} md={6}>
<CustomStatistic
title={t('pages.nodes.totalNodes')}
value={String(totals.total)}
prefix={<CloudServerOutlined />}
/>
</Col>
<Col xs={12} sm={12} md={6}>
<CustomStatistic
title={t('pages.nodes.onlineNodes')}
value={String(totals.online)}
prefix={<CheckCircleOutlined style={{ color: '#52c41a' }} />}
/>
</Col>
<Col xs={12} sm={12} md={6}>
<CustomStatistic
title={t('pages.nodes.offlineNodes')}
value={String(totals.offline)}
prefix={<CloseCircleOutlined style={{ color: '#ff4d4f' }} />}
/>
</Col>
<Col xs={12} sm={12} md={6}>
<CustomStatistic
title={t('pages.nodes.avgLatency')}
value={totals.avgLatency > 0 ? `${totals.avgLatency} ms` : '-'}
prefix={<ThunderboltOutlined />}
/>
</Col>
</Row>
</Card>
</Col>
<Col span={24}>
<NodeList
nodes={nodes}
loading={loading}
isMobile={isMobile}
onAdd={onAdd}
onEdit={onEdit}
onDelete={onDelete}
onProbe={onProbe}
onToggleEnable={onToggleEnable}
/>
</Col>
</Row>
)}
</Spin>
</Layout.Content>
</Layout>
<NodeFormModal
open={formOpen}
mode={formMode}
node={formNode}
testConnection={testConnection}
save={onSave}
onOpenChange={setFormOpen}
/>
</Layout>
</ConfigProvider>
);
}