connections.tsx 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. import { useEffect, useMemo, useRef, useState } from "react";
  2. import { useLockFn } from "ahooks";
  3. import {
  4. Box,
  5. Button,
  6. IconButton,
  7. MenuItem,
  8. Paper,
  9. Select,
  10. TextField,
  11. } from "@mui/material";
  12. import { useRecoilState } from "recoil";
  13. import { Virtuoso } from "react-virtuoso";
  14. import { useTranslation } from "react-i18next";
  15. import { TableChartRounded, TableRowsRounded } from "@mui/icons-material";
  16. import { closeAllConnections } from "@/services/api";
  17. import { atomConnectionSetting } from "@/services/states";
  18. import { useClashInfo } from "@/hooks/use-clash";
  19. import { BaseEmpty, BasePage } from "@/components/base";
  20. import { useWebsocket } from "@/hooks/use-websocket";
  21. import { ConnectionItem } from "@/components/connection/connection-item";
  22. import { ConnectionTable } from "@/components/connection/connection-table";
  23. import {
  24. ConnectionDetail,
  25. ConnectionDetailRef,
  26. } from "@/components/connection/connection-detail";
  27. const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
  28. type OrderFunc = (list: IConnectionsItem[]) => IConnectionsItem[];
  29. const ConnectionsPage = () => {
  30. const { t, i18n } = useTranslation();
  31. const { clashInfo } = useClashInfo();
  32. const [filterText, setFilterText] = useState("");
  33. const [curOrderOpt, setOrderOpt] = useState("Default");
  34. const [connData, setConnData] = useState<IConnections>(initConn);
  35. const [setting, setSetting] = useRecoilState(atomConnectionSetting);
  36. const isTableLayout = setting.layout === "table";
  37. const orderOpts: Record<string, OrderFunc> = {
  38. Default: (list) => list,
  39. "Upload Speed": (list) => list.sort((a, b) => b.curUpload! - a.curUpload!),
  40. "Download Speed": (list) =>
  41. list.sort((a, b) => b.curDownload! - a.curDownload!),
  42. };
  43. const filterConn = useMemo(() => {
  44. const orderFunc = orderOpts[curOrderOpt];
  45. const connections = connData.connections.filter((conn) =>
  46. (conn.metadata.host || conn.metadata.destinationIP)?.includes(filterText)
  47. );
  48. if (orderFunc) return orderFunc(connections);
  49. return connections;
  50. }, [connData, filterText, curOrderOpt]);
  51. const { connect, disconnect } = useWebsocket(
  52. (event) => {
  53. // meta v1.15.0 出现data.connections为null的情况
  54. const data = JSON.parse(event.data) as IConnections;
  55. // 尽量与前一次connections的展示顺序保持一致
  56. setConnData((old) => {
  57. const oldConn = old.connections;
  58. const maxLen = data.connections?.length;
  59. const connections: typeof oldConn = [];
  60. const rest = (data.connections || []).filter((each) => {
  61. const index = oldConn.findIndex((o) => o.id === each.id);
  62. if (index >= 0 && index < maxLen) {
  63. const old = oldConn[index];
  64. each.curUpload = each.upload - old.upload;
  65. each.curDownload = each.download - old.download;
  66. connections[index] = each;
  67. return false;
  68. }
  69. return true;
  70. });
  71. for (let i = 0; i < maxLen; ++i) {
  72. if (!connections[i] && rest.length > 0) {
  73. connections[i] = rest.shift()!;
  74. connections[i].curUpload = 0;
  75. connections[i].curDownload = 0;
  76. }
  77. }
  78. return { ...data, connections };
  79. });
  80. },
  81. { errorCount: 3, retryInterval: 1000 }
  82. );
  83. useEffect(() => {
  84. if (!clashInfo) return;
  85. const { server = "", secret = "" } = clashInfo;
  86. connect(`ws://${server}/connections?token=${encodeURIComponent(secret)}`);
  87. return () => {
  88. disconnect();
  89. };
  90. }, [clashInfo]);
  91. const onCloseAll = useLockFn(closeAllConnections);
  92. const detailRef = useRef<ConnectionDetailRef>(null!);
  93. return (
  94. <BasePage
  95. title={t("Connections")}
  96. contentStyle={{ height: "100%" }}
  97. header={
  98. <Box sx={{ mt: 1, display: "flex", alignItems: "center", gap: 2 }}>
  99. <IconButton
  100. color="inherit"
  101. size="small"
  102. onClick={() =>
  103. setSetting((o) =>
  104. o.layout === "list"
  105. ? { ...o, layout: "table" }
  106. : { ...o, layout: "list" }
  107. )
  108. }
  109. >
  110. {isTableLayout ? (
  111. <TableChartRounded fontSize="inherit" />
  112. ) : (
  113. <TableRowsRounded fontSize="inherit" />
  114. )}
  115. </IconButton>
  116. <Button size="small" variant="contained" onClick={onCloseAll}>
  117. {t("Close All")}
  118. </Button>
  119. </Box>
  120. }
  121. >
  122. <Box sx={{ boxShadow: 0, height: "100%" }}>
  123. <Box
  124. sx={{
  125. pt: 1,
  126. mb: 0.5,
  127. mx: "12px",
  128. height: "36px",
  129. display: "flex",
  130. alignItems: "center",
  131. userSelect: "text",
  132. }}
  133. >
  134. {!isTableLayout && (
  135. <Select
  136. size="small"
  137. autoComplete="off"
  138. value={curOrderOpt}
  139. onChange={(e) => setOrderOpt(e.target.value)}
  140. sx={{
  141. mr: 1,
  142. width: i18n.language === "en" ? 190 : 120,
  143. '[role="button"]': { py: 0.65 },
  144. }}
  145. >
  146. {Object.keys(orderOpts).map((opt) => (
  147. <MenuItem key={opt} value={opt}>
  148. <span style={{ fontSize: 14 }}>{t(opt)}</span>
  149. </MenuItem>
  150. ))}
  151. </Select>
  152. )}
  153. <TextField
  154. hiddenLabel
  155. fullWidth
  156. size="small"
  157. autoComplete="off"
  158. spellCheck="false"
  159. variant="outlined"
  160. placeholder={t("Filter conditions")}
  161. value={filterText}
  162. onChange={(e) => setFilterText(e.target.value)}
  163. sx={{ input: { py: 0.65, px: 1.25 } }}
  164. />
  165. </Box>
  166. <Box height="calc(100% - 50px)" sx={{ userSelect: "text" }}>
  167. {filterConn.length === 0 ? (
  168. <BaseEmpty text="No Connections" />
  169. ) : isTableLayout ? (
  170. <ConnectionTable
  171. connections={filterConn}
  172. onShowDetail={(detail) => detailRef.current?.open(detail)}
  173. />
  174. ) : (
  175. <Virtuoso
  176. data={filterConn}
  177. itemContent={(index, item) => (
  178. <ConnectionItem
  179. value={item}
  180. onShowDetail={() => detailRef.current?.open(item)}
  181. />
  182. )}
  183. />
  184. )}
  185. </Box>
  186. <ConnectionDetail ref={detailRef} />
  187. </Box>
  188. </BasePage>
  189. );
  190. };
  191. export default ConnectionsPage;