NodeList.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. import { useMemo, useState } from 'react';
  2. import { useTranslation } from 'react-i18next';
  3. import {
  4. Badge,
  5. Button,
  6. Card,
  7. Dropdown,
  8. Modal,
  9. Space,
  10. Switch,
  11. Table,
  12. Tag,
  13. Tooltip,
  14. } from 'antd';
  15. import type { BadgeProps } from 'antd';
  16. import type { ColumnsType } from 'antd/es/table';
  17. import {
  18. ApartmentOutlined,
  19. ClusterOutlined,
  20. CloudDownloadOutlined,
  21. DeleteOutlined,
  22. EditOutlined,
  23. ExclamationCircleOutlined,
  24. EyeInvisibleOutlined,
  25. EyeOutlined,
  26. InfoCircleOutlined,
  27. MoreOutlined,
  28. PlusOutlined,
  29. RightOutlined,
  30. ThunderboltOutlined,
  31. } from '@ant-design/icons';
  32. import NodeHistoryPanel from './NodeHistoryPanel';
  33. import type { NodeRecord } from '@/api/queries/useNodesQuery';
  34. import { isPanelUpdateAvailable } from '@/lib/panel-version';
  35. import './NodeList.css';
  36. interface NodeListProps {
  37. nodes: NodeRecord[];
  38. loading?: boolean;
  39. isMobile?: boolean;
  40. latestVersion?: string;
  41. selectedIds: number[];
  42. onSelectionChange: (ids: number[]) => void;
  43. onAdd: () => void;
  44. onEdit: (node: NodeRecord) => void;
  45. onDelete: (node: NodeRecord) => void;
  46. onProbe: (node: NodeRecord) => void;
  47. onToggleEnable: (node: NodeRecord, next: boolean) => void;
  48. onUpdateNode: (node: NodeRecord) => void;
  49. onUpdateSelected: () => void;
  50. }
  51. function isUpdateEligible(n: NodeRecord): boolean {
  52. return !!n.enable && n.status === 'online';
  53. }
  54. interface NodeRow extends NodeRecord {
  55. url: string;
  56. key: string | number;
  57. }
  58. function badgeStatus(status?: string): BadgeProps['status'] {
  59. switch (status) {
  60. case 'online': return 'success';
  61. case 'offline': return 'error';
  62. default: return 'default';
  63. }
  64. }
  65. function StatusDot({ status }: { status?: string }) {
  66. if (status === 'online') return <span className="online-dot" />;
  67. return <Badge status={badgeStatus(status)} />;
  68. }
  69. function StatusLabel({ status }: { status?: string }) {
  70. const { t } = useTranslation();
  71. return (
  72. <span style={status === 'online' ? { color: 'var(--ant-color-success)' } : undefined}>
  73. {t(`pages.nodes.statusValues.${status || 'unknown'}`)}
  74. </span>
  75. );
  76. }
  77. function formatPct(p?: number): string {
  78. if (typeof p !== 'number' || Number.isNaN(p)) return '-';
  79. return `${p.toFixed(1)}%`;
  80. }
  81. function formatUptime(secs?: number): string {
  82. if (!secs) return '-';
  83. const days = Math.floor(secs / 86400);
  84. const hours = Math.floor((secs % 86400) / 3600);
  85. if (days > 0) return `${days}d ${hours}h`;
  86. const mins = Math.floor((secs % 3600) / 60);
  87. if (hours > 0) return `${hours}h ${mins}m`;
  88. return `${mins}m`;
  89. }
  90. function useRelativeTime() {
  91. const { t } = useTranslation();
  92. return (unixSeconds?: number) => {
  93. if (!unixSeconds) return t('pages.nodes.never');
  94. const diffSec = Math.max(0, Math.floor(Date.now() / 1000 - unixSeconds));
  95. if (diffSec < 5) return t('pages.nodes.justNow');
  96. if (diffSec < 60) return `${diffSec}s`;
  97. if (diffSec < 3600) return `${Math.floor(diffSec / 60)}m`;
  98. if (diffSec < 86400) return `${Math.floor(diffSec / 3600)}h`;
  99. return `${Math.floor(diffSec / 86400)}d`;
  100. };
  101. }
  102. export default function NodeList({
  103. nodes,
  104. loading = false,
  105. isMobile = false,
  106. latestVersion = '',
  107. selectedIds,
  108. onSelectionChange,
  109. onAdd,
  110. onEdit,
  111. onDelete,
  112. onProbe,
  113. onToggleEnable,
  114. onUpdateNode,
  115. onUpdateSelected,
  116. }: NodeListProps) {
  117. const { t } = useTranslation();
  118. const relativeTime = useRelativeTime();
  119. const [showAddress, setShowAddress] = useState(false);
  120. const [statsNode, setStatsNode] = useState<NodeRow | null>(null);
  121. const [expandedIds, setExpandedIds] = useState<Set<number>>(new Set());
  122. // Map a node GUID to its display name so a transitive sub-node can show which
  123. // parent it is reached through (#4983).
  124. const nameByGuid = useMemo(() => {
  125. const m = new Map<string, string>();
  126. for (const n of nodes) if (n.guid) m.set(n.guid, n.name || n.guid);
  127. return m;
  128. }, [nodes]);
  129. // Order direct nodes first, each immediately followed by its transitive
  130. // sub-nodes, so the table reads as a parent -> child tree without colliding
  131. // with the per-row history expander (transitive nodes carry id 0).
  132. const dataSource = useMemo<NodeRow[]>(() => {
  133. const toRow = (n: NodeRecord): NodeRow => ({
  134. ...n,
  135. url: `${n.scheme}://${n.address}:${n.port}${n.basePath || '/'}`,
  136. key: n.transitive ? `t-${n.guid || ''}` : n.id,
  137. });
  138. const childrenByParent = new Map<string, NodeRecord[]>();
  139. for (const n of nodes) {
  140. if (n.transitive && n.parentGuid) {
  141. const arr = childrenByParent.get(n.parentGuid) || [];
  142. arr.push(n);
  143. childrenByParent.set(n.parentGuid, arr);
  144. }
  145. }
  146. const ordered: NodeRow[] = [];
  147. const added = new Set<string>();
  148. const push = (n: NodeRecord) => {
  149. const row = toRow(n);
  150. ordered.push(row);
  151. added.add(String(row.key));
  152. };
  153. for (const n of nodes) {
  154. if (n.transitive) continue;
  155. push(n);
  156. if (n.guid) for (const child of childrenByParent.get(n.guid) || []) push(child);
  157. }
  158. // Transitive nodes whose parent isn't in the list still get shown.
  159. for (const n of nodes) {
  160. if (n.transitive && !added.has(`t-${n.guid || ''}`)) push(n);
  161. }
  162. return ordered;
  163. }, [nodes]);
  164. function toggleExpanded(id: number) {
  165. setExpandedIds((prev) => {
  166. const next = new Set(prev);
  167. if (next.has(id)) next.delete(id); else next.add(id);
  168. return next;
  169. });
  170. }
  171. const columns = useMemo<ColumnsType<NodeRow>>(() => [
  172. {
  173. title: t('pages.nodes.actions'),
  174. align: 'center',
  175. width: 190,
  176. render: (_value, record) => record.transitive ? (
  177. <Tooltip title={t('pages.nodes.subNodeTip', { parent: record.parentGuid ? (nameByGuid.get(record.parentGuid) || '-') : '-' })}>
  178. <Tag icon={<ApartmentOutlined />} style={{ margin: 0 }}>{t('pages.nodes.subNode')}</Tag>
  179. </Tooltip>
  180. ) : (
  181. <Space>
  182. <Tooltip title={t('pages.nodes.probe')}>
  183. <Button type="text" size="small" icon={<ThunderboltOutlined />} onClick={() => onProbe(record)} />
  184. </Tooltip>
  185. {isUpdateEligible(record) && (
  186. <Tooltip title={t('pages.nodes.updatePanel')}>
  187. <Button type="text" size="small" icon={<CloudDownloadOutlined />} onClick={() => onUpdateNode(record)} />
  188. </Tooltip>
  189. )}
  190. <Tooltip title={t('edit')}>
  191. <Button type="text" size="small" icon={<EditOutlined />} onClick={() => onEdit(record)} />
  192. </Tooltip>
  193. <Tooltip title={t('delete')}>
  194. <Button type="text" size="small" danger icon={<DeleteOutlined />} onClick={() => onDelete(record)} />
  195. </Tooltip>
  196. </Space>
  197. ),
  198. },
  199. {
  200. title: t('pages.nodes.enable'),
  201. dataIndex: 'enable',
  202. align: 'center',
  203. width: 80,
  204. render: (_value, record) => record.transitive ? (
  205. <span style={{ opacity: 0.4 }}>—</span>
  206. ) : (
  207. <Switch
  208. checked={!!record.enable}
  209. size="small"
  210. onChange={(v) => onToggleEnable(record, v)}
  211. />
  212. ),
  213. },
  214. {
  215. title: t('pages.nodes.name'),
  216. dataIndex: 'name',
  217. ellipsis: true,
  218. render: (_value, record) => (
  219. <div className="name-cell" style={record.transitive ? { paddingInlineStart: 20 } : undefined}>
  220. <span className="name">
  221. {record.transitive && <ApartmentOutlined style={{ marginInlineEnd: 6, opacity: 0.6 }} />}
  222. {record.name}
  223. </span>
  224. {record.remark && <span className="remark">{record.remark}</span>}
  225. </div>
  226. ),
  227. },
  228. {
  229. title: (
  230. <span className="address-header">
  231. {t('pages.nodes.address')}
  232. <Tooltip title={t('pages.index.toggleIpVisibility')}>
  233. {showAddress ? (
  234. <EyeOutlined className="ip-toggle-icon" onClick={() => setShowAddress(false)} />
  235. ) : (
  236. <EyeInvisibleOutlined className="ip-toggle-icon" onClick={() => setShowAddress(true)} />
  237. )}
  238. </Tooltip>
  239. </span>
  240. ),
  241. dataIndex: 'url',
  242. ellipsis: true,
  243. render: (_value, record) => (
  244. <a
  245. href={record.url}
  246. target="_blank"
  247. rel="noopener noreferrer"
  248. className={showAddress ? 'address-visible' : 'address-hidden'}
  249. >
  250. {record.url}
  251. </a>
  252. ),
  253. },
  254. {
  255. title: t('pages.nodes.status'),
  256. dataIndex: 'status',
  257. align: 'center',
  258. render: (_value, record) => (
  259. <Space size={4}>
  260. <StatusDot status={record.status} />
  261. <StatusLabel status={record.status} />
  262. {record.lastError && (
  263. <Tooltip title={record.lastError}>
  264. <ExclamationCircleOutlined style={{ color: 'var(--ant-color-warning)' }} />
  265. </Tooltip>
  266. )}
  267. </Space>
  268. ),
  269. },
  270. {
  271. title: t('pages.nodes.cpu'),
  272. dataIndex: 'cpuPct',
  273. align: 'center',
  274. width: 90,
  275. render: (_value, record) => formatPct(record.cpuPct),
  276. },
  277. {
  278. title: t('pages.nodes.mem'),
  279. dataIndex: 'memPct',
  280. align: 'center',
  281. width: 90,
  282. render: (_value, record) => formatPct(record.memPct),
  283. },
  284. {
  285. title: t('pages.nodes.xrayVersion'),
  286. dataIndex: 'xrayVersion',
  287. align: 'center',
  288. render: (_value, record) => record.xrayVersion || '-',
  289. },
  290. {
  291. title: t('pages.nodes.panelVersion') || 'Panel version',
  292. dataIndex: 'panelVersion',
  293. align: 'center',
  294. render: (_value, record) => {
  295. const canUpdate = isUpdateEligible(record)
  296. && isPanelUpdateAvailable(latestVersion, record.panelVersion || '');
  297. return (
  298. <Space size={4}>
  299. <span>{record.panelVersion || '-'}</span>
  300. {canUpdate && (
  301. <Tooltip title={`${t('pages.nodes.updateAvailable')}: ${latestVersion}`}>
  302. <Tag color="orange" style={{ margin: 0, cursor: 'pointer' }} onClick={() => onUpdateNode(record)}>
  303. {t('pages.nodes.updateAvailable')}
  304. </Tag>
  305. </Tooltip>
  306. )}
  307. </Space>
  308. );
  309. },
  310. },
  311. {
  312. title: t('pages.nodes.uptime'),
  313. dataIndex: 'uptimeSecs',
  314. align: 'center',
  315. render: (_value, record) => formatUptime(record.uptimeSecs),
  316. },
  317. {
  318. title: t('clients'),
  319. align: 'center',
  320. width: 160,
  321. render: (_value, record) => (
  322. <Space size={4}>
  323. <Tag color="green">{record.clientCount || 0}</Tag>
  324. {record.onlineCount ? (
  325. <Tag color="blue">{record.onlineCount} {t('online')}</Tag>
  326. ) : null}
  327. {record.depletedCount ? (
  328. <Tag color="red">{record.depletedCount} {t('depleted')}</Tag>
  329. ) : null}
  330. </Space>
  331. ),
  332. },
  333. {
  334. title: t('pages.nodes.latency'),
  335. dataIndex: 'latencyMs',
  336. align: 'center',
  337. width: 100,
  338. render: (_value, record) =>
  339. record.latencyMs && record.latencyMs > 0 ? `${record.latencyMs} ms` : '-',
  340. },
  341. {
  342. title: t('pages.nodes.lastHeartbeat'),
  343. dataIndex: 'lastHeartbeat',
  344. align: 'center',
  345. width: 120,
  346. render: (_value, record) => relativeTime(record.lastHeartbeat),
  347. },
  348. ], [t, showAddress, relativeTime, latestVersion, onToggleEnable, onProbe, onEdit, onDelete, onUpdateNode, nameByGuid]);
  349. return (
  350. <Card size="small" hoverable>
  351. <div className="toolbar">
  352. <Button type="primary" icon={<PlusOutlined />} onClick={onAdd}>
  353. {t('pages.nodes.addNode')}
  354. </Button>
  355. {selectedIds.length > 0 && (
  356. <Button icon={<CloudDownloadOutlined />} onClick={onUpdateSelected}>
  357. {t('pages.nodes.updateSelected', { count: selectedIds.length })}
  358. </Button>
  359. )}
  360. </div>
  361. {isMobile ? (
  362. <>
  363. <div className="node-cards">
  364. {dataSource.length === 0 ? (
  365. <div className="card-empty">
  366. <ClusterOutlined style={{ fontSize: 28, opacity: 0.5 }} />
  367. <div>{t('noData')}</div>
  368. </div>
  369. ) : (
  370. dataSource.map((record) => record.transitive ? (
  371. <div key={String(record.key)} className="node-card" style={{ paddingInlineStart: 16, opacity: 0.85 }}>
  372. <div className="card-head">
  373. <ApartmentOutlined style={{ opacity: 0.6 }} />
  374. <StatusDot status={record.status} />
  375. <span className="node-name">{record.name}</span>
  376. <div className="card-actions">
  377. <Tag icon={<ApartmentOutlined />} style={{ margin: 0 }}>{t('pages.nodes.subNode')}</Tag>
  378. </div>
  379. </div>
  380. </div>
  381. ) : (
  382. <div key={record.id} className="node-card">
  383. <div className="card-head" onClick={() => toggleExpanded(record.id)}>
  384. <RightOutlined className={`card-expand${expandedIds.has(record.id) ? ' is-expanded' : ''}`} />
  385. <StatusDot status={record.status} />
  386. <span className="node-name">{record.name}</span>
  387. <div className="card-actions" onClick={(e) => e.stopPropagation()}>
  388. <Tooltip title={t('info')}>
  389. <InfoCircleOutlined
  390. className="row-action-trigger"
  391. onClick={() => setStatsNode(record)}
  392. />
  393. </Tooltip>
  394. <Switch
  395. checked={!!record.enable}
  396. size="small"
  397. onChange={(v) => onToggleEnable(record, v)}
  398. />
  399. <Dropdown
  400. trigger={['click']}
  401. placement="bottomRight"
  402. menu={{
  403. items: [
  404. {
  405. key: 'probe',
  406. label: <><ThunderboltOutlined /> {t('pages.nodes.probe')}</>,
  407. onClick: () => onProbe(record),
  408. },
  409. ...(isUpdateEligible(record) ? [{
  410. key: 'update',
  411. label: <><CloudDownloadOutlined /> {t('pages.nodes.updatePanel')}</>,
  412. onClick: () => onUpdateNode(record),
  413. }] : []),
  414. {
  415. key: 'edit',
  416. label: <><EditOutlined /> {t('edit')}</>,
  417. onClick: () => onEdit(record),
  418. },
  419. {
  420. key: 'delete',
  421. danger: true,
  422. label: <><DeleteOutlined /> {t('delete')}</>,
  423. onClick: () => onDelete(record),
  424. },
  425. ],
  426. }}
  427. >
  428. <MoreOutlined className="row-action-trigger" />
  429. </Dropdown>
  430. </div>
  431. </div>
  432. {expandedIds.has(record.id) && (
  433. <div className="card-history">
  434. <NodeHistoryPanel node={record} />
  435. </div>
  436. )}
  437. </div>
  438. ))
  439. )}
  440. </div>
  441. <Modal
  442. open={!!statsNode}
  443. footer={null}
  444. width={360}
  445. centered
  446. title={statsNode?.name || ''}
  447. onCancel={() => setStatsNode(null)}
  448. >
  449. {statsNode && (
  450. <div className="card-stats">
  451. {statsNode.remark && (
  452. <div className="stat-row">
  453. <span className="stat-label">{t('pages.nodes.name')}</span>
  454. <span>{statsNode.remark}</span>
  455. </div>
  456. )}
  457. <div className="stat-row">
  458. <span className="stat-label">{t('pages.nodes.address')}</span>
  459. <a
  460. href={statsNode.url}
  461. target="_blank"
  462. rel="noopener noreferrer"
  463. className={showAddress ? 'address-visible' : 'address-hidden'}
  464. >
  465. {statsNode.url}
  466. </a>
  467. <Tooltip title={t('pages.index.toggleIpVisibility')}>
  468. {showAddress ? (
  469. <EyeOutlined className="ip-toggle-icon" onClick={() => setShowAddress(false)} />
  470. ) : (
  471. <EyeInvisibleOutlined className="ip-toggle-icon" onClick={() => setShowAddress(true)} />
  472. )}
  473. </Tooltip>
  474. </div>
  475. <div className="stat-row">
  476. <span className="stat-label">{t('pages.nodes.status')}</span>
  477. <StatusDot status={statsNode.status} />
  478. <StatusLabel status={statsNode.status} />
  479. {statsNode.lastError && (
  480. <Tooltip title={statsNode.lastError}>
  481. <ExclamationCircleOutlined style={{ color: 'var(--ant-color-warning)' }} />
  482. </Tooltip>
  483. )}
  484. </div>
  485. <div className="stat-row">
  486. <span className="stat-label">{t('pages.nodes.cpu')}</span>
  487. <Tag>{formatPct(statsNode.cpuPct)}</Tag>
  488. </div>
  489. <div className="stat-row">
  490. <span className="stat-label">{t('pages.nodes.mem')}</span>
  491. <Tag>{formatPct(statsNode.memPct)}</Tag>
  492. </div>
  493. <div className="stat-row">
  494. <span className="stat-label">{t('pages.nodes.xrayVersion')}</span>
  495. <Tag>{statsNode.xrayVersion || '-'}</Tag>
  496. </div>
  497. <div className="stat-row">
  498. <span className="stat-label">{t('pages.nodes.panelVersion') || 'Panel version'}</span>
  499. <Tag>{statsNode.panelVersion || '-'}</Tag>
  500. </div>
  501. <div className="stat-row">
  502. <span className="stat-label">{t('pages.nodes.uptime')}</span>
  503. <Tag>{formatUptime(statsNode.uptimeSecs)}</Tag>
  504. </div>
  505. <div className="stat-row">
  506. <span className="stat-label">{t('pages.nodes.latency')}</span>
  507. <Tag>
  508. {statsNode.latencyMs && statsNode.latencyMs > 0 ? `${statsNode.latencyMs} ms` : '-'}
  509. </Tag>
  510. </div>
  511. <div className="stat-row">
  512. <span className="stat-label">{t('clients')}</span>
  513. <Tag color="green">{statsNode.clientCount || 0}</Tag>
  514. {statsNode.onlineCount ? (
  515. <Tag color="blue">{statsNode.onlineCount} {t('online')}</Tag>
  516. ) : null}
  517. {statsNode.depletedCount ? (
  518. <Tag color="red">{statsNode.depletedCount} {t('depleted')}</Tag>
  519. ) : null}
  520. </div>
  521. <div className="stat-row">
  522. <span className="stat-label">{t('pages.nodes.lastHeartbeat')}</span>
  523. <Tag>{relativeTime(statsNode.lastHeartbeat)}</Tag>
  524. </div>
  525. </div>
  526. )}
  527. </Modal>
  528. </>
  529. ) : (
  530. <Table<NodeRow>
  531. dataSource={dataSource}
  532. columns={columns}
  533. pagination={false}
  534. loading={loading}
  535. scroll={{ x: 'max-content' }}
  536. size="middle"
  537. rowKey="id"
  538. rowSelection={dataSource.length > 1 ? {
  539. selectedRowKeys: selectedIds,
  540. onChange: (keys) => onSelectionChange(keys.filter((k) => typeof k === 'number') as number[]),
  541. getCheckboxProps: (record) => ({ disabled: !!record.transitive || !isUpdateEligible(record) }),
  542. } : undefined}
  543. locale={{
  544. emptyText: (
  545. <div className="card-empty">
  546. <ClusterOutlined style={{ fontSize: 32, marginBottom: 8 }} />
  547. <div>{t('noData')}</div>
  548. </div>
  549. ),
  550. }}
  551. expandable={{
  552. expandedRowRender: (record) => <NodeHistoryPanel node={record} />,
  553. rowExpandable: (record) => !record.transitive,
  554. }}
  555. />
  556. )}
  557. </Card>
  558. );
  559. }