refactor(app-data): split monolithic context into focused SWR hooks (#5576)

* refactor(app-data): split monolithic context into focused SWR hooks

* refactor(swr): unify polling and consolidate proxy/config/provider data flow
This commit is contained in:
Sline
2025-11-24 16:18:31 +08:00
committed by GitHub
parent 871881c460
commit 8e8182f707
17 changed files with 432 additions and 295 deletions
+206
View File
@@ -0,0 +1,206 @@
import { useCallback, useMemo } from "react";
import useSWR, { useSWRConfig } from "swr";
import {
getBaseConfig,
getRuleProviders,
getRules,
} from "tauri-plugin-mihomo-api";
import {
calcuProxies,
calcuProxyProviders,
getAppUptime,
getSystemProxy,
} from "@/services/cmds";
import { SWR_DEFAULTS, SWR_REALTIME, SWR_SLOW_POLL } from "@/services/config";
import { useSharedSWRPoller } from "./use-shared-swr-poller";
import { useVerge } from "./use-verge";
export const useProxiesData = () => {
const { mutate: globalMutate } = useSWRConfig();
const { data, error, isLoading } = useSWR("getProxies", calcuProxies, {
...SWR_REALTIME,
refreshInterval: 0,
onError: (err) => console.warn("[AppData] Proxy fetch failed:", err),
});
const refreshProxy = useCallback(
() => globalMutate("getProxies"),
[globalMutate],
);
const pollerRefresh = useCallback(() => {
void globalMutate("getProxies");
}, [globalMutate]);
useSharedSWRPoller("getProxies", SWR_REALTIME.refreshInterval, pollerRefresh);
return {
proxies: data,
refreshProxy,
isLoading,
error,
};
};
export const useClashConfig = () => {
const { mutate: globalMutate } = useSWRConfig();
const { data, error, isLoading } = useSWR("getClashConfig", getBaseConfig, {
...SWR_SLOW_POLL,
refreshInterval: 0,
});
const refreshClashConfig = useCallback(
() => globalMutate("getClashConfig"),
[globalMutate],
);
const pollerRefresh = useCallback(() => {
void globalMutate("getClashConfig");
}, [globalMutate]);
useSharedSWRPoller(
"getClashConfig",
SWR_SLOW_POLL.refreshInterval,
pollerRefresh,
);
return {
clashConfig: data,
refreshClashConfig,
isLoading,
error,
};
};
export const useProxyProvidersData = () => {
const { data, error, isLoading, mutate } = useSWR(
"getProxyProviders",
calcuProxyProviders,
SWR_DEFAULTS,
);
const refreshProxyProviders = useCallback(() => mutate(), [mutate]);
return {
proxyProviders: data || {},
refreshProxyProviders,
isLoading,
error,
};
};
export const useRuleProvidersData = () => {
const { data, error, isLoading, mutate } = useSWR(
"getRuleProviders",
getRuleProviders,
SWR_DEFAULTS,
);
const refreshRuleProviders = useCallback(() => mutate(), [mutate]);
return {
ruleProviders: data?.providers || {},
refreshRuleProviders,
isLoading,
error,
};
};
export const useRulesData = () => {
const { data, error, isLoading, mutate } = useSWR(
"getRules",
getRules,
SWR_DEFAULTS,
);
const refreshRules = useCallback(() => mutate(), [mutate]);
return {
rules: data?.rules || [],
refreshRules,
isLoading,
error,
};
};
export const useSystemProxyData = () => {
const { data, error, isLoading, mutate } = useSWR(
"getSystemProxy",
getSystemProxy,
SWR_DEFAULTS,
);
const refreshSysproxy = useCallback(() => mutate(), [mutate]);
return {
sysproxy: data,
refreshSysproxy,
isLoading,
error,
};
};
type ClashConfig = Awaited<ReturnType<typeof getBaseConfig>>;
type SystemProxy = Awaited<ReturnType<typeof getSystemProxy>>;
interface SystemProxyAddressParams {
clashConfig?: ClashConfig | null;
sysproxy?: SystemProxy | null;
}
export const useSystemProxyAddress = ({
clashConfig,
sysproxy,
}: SystemProxyAddressParams) => {
const { verge } = useVerge();
return useMemo(() => {
if (!verge || !clashConfig) return "-";
const isPacMode = verge.proxy_auto_config ?? false;
if (isPacMode) {
const proxyHost = verge.proxy_host || "127.0.0.1";
const proxyPort = verge.verge_mixed_port || clashConfig.mixedPort || 7897;
return [proxyHost, proxyPort].join(":");
}
const systemServer = sysproxy?.server;
if (systemServer && systemServer !== "-" && !systemServer.startsWith(":")) {
return systemServer;
}
const proxyHost = verge.proxy_host || "127.0.0.1";
const proxyPort = verge.verge_mixed_port || clashConfig.mixedPort || 7897;
return [proxyHost, proxyPort].join(":");
}, [clashConfig, sysproxy, verge]);
};
export const useAppUptime = () => {
const { data, error, isLoading } = useSWR("appUptime", getAppUptime, {
...SWR_DEFAULTS,
refreshInterval: 3000,
errorRetryCount: 1,
});
return {
uptime: data || 0,
error,
isLoading,
};
};
export const useRefreshAll = () => {
const { mutate } = useSWRConfig();
return useCallback(async () => {
await Promise.all([
mutate("getProxies"),
mutate("getClashConfig"),
mutate("getRules"),
mutate("getSystemProxy"),
mutate("getProxyProviders"),
mutate("getRuleProviders"),
]);
}, [mutate]);
};
+11 -13
View File
@@ -1,17 +1,11 @@
import { useMemo } from "react";
import { useAppData } from "@/providers/app-data-context";
// 定义代理组类型
interface ProxyGroup {
name: string;
now: string;
}
import { useClashConfig, useProxiesData } from "@/hooks/app-data";
// 获取当前代理节点信息的自定义Hook
export const useCurrentProxy = () => {
// 从AppDataProvider获取数据
const { proxies, clashConfig, refreshProxy } = useAppData();
const { proxies, refreshProxy } = useProxiesData();
const { clashConfig } = useClashConfig();
// 获取当前模式
const currentMode = clashConfig?.mode?.toLowerCase() || "rule";
@@ -20,11 +14,15 @@ export const useCurrentProxy = () => {
const currentProxyInfo = useMemo(() => {
if (!proxies) return { currentProxy: null, primaryGroupName: null };
const { global, groups, records } = proxies;
const globalGroup = proxies.global as IProxyGroupItem | undefined;
const groups: IProxyGroupItem[] = Array.isArray(proxies.groups)
? (proxies.groups as IProxyGroupItem[])
: [];
const records = (proxies.records || {}) as Record<string, IProxyItem>;
// 默认信息
let primaryGroupName = "GLOBAL";
let currentName = global?.now;
let currentName = globalGroup?.now;
// 在规则模式下,寻找主要代理组(通常是第一个或者名字包含特定关键词的组)
if (currentMode === "rule" && groups.length > 0) {
@@ -37,11 +35,11 @@ export const useCurrentProxy = () => {
"自动选择",
];
const primaryGroup =
groups.find((group: ProxyGroup) =>
groups.find((group) =>
primaryKeywords.some((keyword) =>
group.name.toLowerCase().includes(keyword.toLowerCase()),
),
) || groups.filter((g: ProxyGroup) => g.name !== "GLOBAL")[0];
) || groups.filter((g) => g.name !== "GLOBAL")[0];
if (primaryGroup) {
primaryGroupName = primaryGroup.name;
+121
View File
@@ -0,0 +1,121 @@
import { useEffect } from "react";
import type { Key } from "swr";
type SharedPollerEntry = {
subscribers: number;
timer: number | null;
interval: number;
callback: (() => void) | null;
refreshWhenHidden: boolean;
refreshWhenOffline: boolean;
};
const sharedPollers = new Map<string, SharedPollerEntry>();
const isDocumentHidden = () => {
if (typeof document === "undefined") return false;
return document.visibilityState === "hidden";
};
const isOffline = () => {
if (typeof navigator === "undefined") return false;
return navigator.onLine === false;
};
const ensureTimer = (key: string, entry: SharedPollerEntry) => {
if (typeof window === "undefined") return;
if (entry.timer !== null) {
clearInterval(entry.timer);
}
entry.timer = window.setInterval(() => {
if (!entry.refreshWhenHidden && isDocumentHidden()) return;
if (!entry.refreshWhenOffline && isOffline()) return;
entry.callback?.();
}, entry.interval);
};
const registerSharedPoller = (
key: string,
interval: number,
callback: () => void,
options: { refreshWhenHidden: boolean; refreshWhenOffline: boolean },
) => {
let entry = sharedPollers.get(key);
if (!entry) {
entry = {
subscribers: 0,
timer: null,
interval,
callback,
refreshWhenHidden: options.refreshWhenHidden,
refreshWhenOffline: options.refreshWhenOffline,
};
sharedPollers.set(key, entry);
}
entry.subscribers += 1;
entry.callback = callback;
entry.interval = Math.min(entry.interval, interval);
entry.refreshWhenHidden =
entry.refreshWhenHidden || options.refreshWhenHidden;
entry.refreshWhenOffline =
entry.refreshWhenOffline || options.refreshWhenOffline;
ensureTimer(key, entry);
return () => {
const current = sharedPollers.get(key);
if (!current) return;
current.subscribers -= 1;
if (current.subscribers <= 0) {
if (current.timer !== null) {
clearInterval(current.timer);
}
sharedPollers.delete(key);
}
};
};
const normalizeKey = (key: Key): string | null => {
if (typeof key === "string") return key;
if (typeof key === "number" || typeof key === "boolean") return String(key);
if (Array.isArray(key)) {
try {
return JSON.stringify(key);
} catch {
return null;
}
}
return null;
};
export interface SharedSWRPollerOptions {
refreshWhenHidden?: boolean;
refreshWhenOffline?: boolean;
}
export const useSharedSWRPoller = (
key: Key,
interval?: number,
callback?: () => void,
options?: SharedSWRPollerOptions,
) => {
const refreshWhenHidden = options?.refreshWhenHidden ?? false;
const refreshWhenOffline = options?.refreshWhenOffline ?? false;
useEffect(() => {
if (!key || !interval || interval <= 0 || !callback) return;
const serializedKey = normalizeKey(key);
if (!serializedKey) return;
return registerSharedPoller(serializedKey, interval, callback, {
refreshWhenHidden,
refreshWhenOffline,
});
}, [key, interval, callback, refreshWhenHidden, refreshWhenOffline]);
};
+2 -2
View File
@@ -2,14 +2,14 @@ import { useLockFn } from "ahooks";
import useSWR, { mutate } from "swr";
import { closeAllConnections } from "tauri-plugin-mihomo-api";
import { useSystemProxyData } from "@/hooks/app-data";
import { useVerge } from "@/hooks/use-verge";
import { useAppData } from "@/providers/app-data-context";
import { getAutotemProxy } from "@/services/cmds";
// 系统代理状态检测统一逻辑
export const useSystemProxyState = () => {
const { verge, mutateVerge, patchVerge } = useVerge();
const { sysproxy } = useAppData();
const { sysproxy } = useSystemProxyData();
const { data: autoproxy } = useSWR("getAutotemProxy", getAutotemProxy, {
revalidateOnFocus: true,
revalidateOnReconnect: true,