mirror of
https://github.com/clash-verge-rev/clash-verge-rev
synced 2025-05-05 05:33:45 +08:00
refactor: remove useSWRSubscription and use useEffect
This commit is contained in:
parent
62a6f58705
commit
a507d7567f
@ -1,4 +1,4 @@
|
|||||||
import useSWRSubscription from "swr/subscription";
|
import { useEffect } from "react";
|
||||||
import { useEnableLog } from "../services/states";
|
import { useEnableLog } from "../services/states";
|
||||||
import { createSockette } from "../utils/websocket";
|
import { createSockette } from "../utils/websocket";
|
||||||
import { useClashInfo } from "./use-clash";
|
import { useClashInfo } from "./use-clash";
|
||||||
@ -9,7 +9,6 @@ const MAX_LOG_NUM = 1000;
|
|||||||
|
|
||||||
export type LogLevel = "warning" | "info" | "debug" | "error";
|
export type LogLevel = "warning" | "info" | "debug" | "error";
|
||||||
|
|
||||||
// 添加 ILogItem 接口定义
|
|
||||||
interface ILogItem {
|
interface ILogItem {
|
||||||
time?: string;
|
time?: string;
|
||||||
type: string;
|
type: string;
|
||||||
@ -66,28 +65,31 @@ export const useLogData = (logLevel: LogLevel) => {
|
|||||||
const [enableLog] = useEnableLog();
|
const [enableLog] = useEnableLog();
|
||||||
const { logs, appendLog } = useLogStore();
|
const { logs, appendLog } = useLogStore();
|
||||||
|
|
||||||
useSWRSubscription<ILogItem[], any, [string, LogLevel] | null>(
|
useEffect(() => {
|
||||||
enableLog && clashInfo ? ["getClashLog", logLevel] : null,
|
if (!enableLog || !clashInfo) return;
|
||||||
(_key, { next }) => {
|
|
||||||
const { server = "", secret = "" } = clashInfo!;
|
|
||||||
|
|
||||||
const s = createSockette(buildWSUrl(server, secret, logLevel), {
|
const { server = "", secret = "" } = clashInfo;
|
||||||
onmessage(event) {
|
const wsUrl = buildWSUrl(server, secret, logLevel);
|
||||||
const data = JSON.parse(event.data) as ILogItem;
|
|
||||||
const time = dayjs().format("MM-DD HH:mm:ss");
|
|
||||||
appendLog(logLevel, { ...data, time });
|
|
||||||
},
|
|
||||||
onerror(event) {
|
|
||||||
this.close();
|
|
||||||
next(event);
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => {
|
let isActive = true;
|
||||||
s.close();
|
const socket = createSockette(wsUrl, {
|
||||||
};
|
onmessage(event) {
|
||||||
}
|
if (!isActive) return;
|
||||||
);
|
const data = JSON.parse(event.data) as ILogItem;
|
||||||
|
const time = dayjs().format("MM-DD HH:mm:ss");
|
||||||
|
appendLog(logLevel, { ...data, time });
|
||||||
|
},
|
||||||
|
onerror() {
|
||||||
|
if (!isActive) return;
|
||||||
|
socket.close();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
isActive = false;
|
||||||
|
socket.close();
|
||||||
|
};
|
||||||
|
}, [clashInfo, enableLog, logLevel]);
|
||||||
|
|
||||||
return logs[logLevel];
|
return logs[logLevel];
|
||||||
};
|
};
|
||||||
|
Loading…
x
Reference in New Issue
Block a user