refactor: use zustand store, rewrite log clearing logic

This commit is contained in:
huzibaca
2024-11-18 06:48:23 +08:00
parent 3b8147b6ad
commit 62eb070c1b
4 changed files with 87 additions and 21 deletions

View File

@@ -3,12 +3,20 @@ import { useEnableLog } from "../services/states";
import { createSockette } from "../utils/websocket";
import { useClashInfo } from "./use-clash";
import dayjs from "dayjs";
import { create } from "zustand";
const MAX_LOG_NUM = 1000;
// 添加 LogLevel 类型定义
export type LogLevel = "warning" | "info" | "debug" | "error";
// 添加 ILogItem 接口定义
interface ILogItem {
time?: string;
type: string;
payload: string;
[key: string]: any;
}
const buildWSUrl = (server: string, secret: string, logLevel: LogLevel) => {
const baseUrl = `ws://${server}/logs`;
const params = new URLSearchParams();
@@ -21,12 +29,44 @@ const buildWSUrl = (server: string, secret: string, logLevel: LogLevel) => {
return queryString ? `${baseUrl}?${queryString}` : baseUrl;
};
interface LogStore {
logs: Record<LogLevel, ILogItem[]>;
clearLogs: (level?: LogLevel) => void;
appendLog: (level: LogLevel, log: ILogItem) => void;
}
const useLogStore = create<LogStore>(
(set: (fn: (state: LogStore) => Partial<LogStore>) => void) => ({
logs: {
warning: [],
info: [],
debug: [],
error: [],
},
clearLogs: (level?: LogLevel) =>
set((state: LogStore) => ({
logs: level
? { ...state.logs, [level]: [] }
: { warning: [], info: [], debug: [], error: [] },
})),
appendLog: (level: LogLevel, log: ILogItem) =>
set((state: LogStore) => {
const currentLogs = state.logs[level];
const newLogs =
currentLogs.length >= MAX_LOG_NUM
? [...currentLogs.slice(1), log]
: [...currentLogs, log];
return { logs: { ...state.logs, [level]: newLogs } };
}),
})
);
export const useLogData = (logLevel: LogLevel) => {
const { clashInfo } = useClashInfo();
const [enableLog] = useEnableLog();
const { logs, appendLog } = useLogStore();
return useSWRSubscription<ILogItem[], any, [string, LogLevel] | null>(
useSWRSubscription<ILogItem[], any, [string, LogLevel] | null>(
enableLog && clashInfo ? ["getClashLog", logLevel] : null,
(_key, { next }) => {
const { server = "", secret = "" } = clashInfo!;
@@ -34,14 +74,8 @@ export const useLogData = (logLevel: LogLevel) => {
const s = createSockette(buildWSUrl(server, secret, logLevel), {
onmessage(event) {
const data = JSON.parse(event.data) as ILogItem;
// append new log item on socket message
next(null, (l = []) => {
const time = dayjs().format("MM-DD HH:mm:ss");
if (l.length >= MAX_LOG_NUM) l.shift();
return [...l, { ...data, time }];
});
const time = dayjs().format("MM-DD HH:mm:ss");
appendLog(logLevel, { ...data, time });
},
onerror(event) {
this.close();
@@ -52,10 +86,13 @@ export const useLogData = (logLevel: LogLevel) => {
return () => {
s.close();
};
},
{
fallbackData: [],
keepPreviousData: true,
}
);
return logs[logLevel];
};
// 导出清空日志的方法
export const clearLogs = (level?: LogLevel) => {
useLogStore.getState().clearLogs(level);
};