mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-11-17 09:12:10 +08:00
* feat(contract): export wire contract from backend and generate frontend types Adds a zero-dependency `frontend-contract` bin that serializes the real NoticeStatus variants and FrontendEvent payloads, scripts/gen-contract.mjs which emits the committed src/services/contract.ts, and a CI job that regenerates it and fails on a non-empty diff. events.ts now derives its event map from the generated contract instead of hand-typed shapes. * feat(events): route all backend events through a single event bus and store Adds src/services/bus (the only listen/emit site: one handler per contract event plus the frontend-internal test-all event) and the React context/reducer app store. Migrates the five scattered subscriptions (layout events, pending failures, proxy refresh, profile update/timer, test-all), deletes the old glue (events.ts, use-listen, use-layout-events, LoadingCacheProvider), moves run state into the store, and adds an architecture gate script wired into CI. Behavior is unchanged; the run-state query's poll/focus safety net is preserved by the store provider. * refactor(notice): make the notice table exhaustive and drop dead wire entries D5 cleanup, frontend and backend in one commit: removes the six config_validate::* statuses that never receive a backend send and the set_config::ok send (enum variants, golden list 41→34, send point in restart_clash_core), their frontend handlers, and the five i18n keys only those handlers used. The notice table is now typed as a Record over the generated NoticeStatus union, so a status without a frontend entry fails to compile. The info status (sent by the silent updater for breaking change notices, previously dropped with a console warning) now shows an info toast — the one deliberate behavior delta. * feat(mutate): single funnel for user-intent commands and invoke gate Adds src/services/mutate.ts: one path for optimistic apply, services-layer invoke, Busy handling, failure rollback, and the error toast, with busy bookkeeping mirrored into the app store. The patch hooks (verge, clash, profiles) now route through it. Moves the remaining direct invokes (unlock ×3, DNS ×4) into cmds.ts and turns on the invoke-only-in-services architecture gate in CI. * refactor(settings): route settings-domain commands through the mutate funnel Ports port saving, webdav/local backup operations, core change/restart/ upgrade, service install/uninstall/repair flows, the system-proxy toggle queue, the DNS override toggle, and app lifecycle commands onto the single funnel. Bespoke flows keep their own error handling via errorNotice:false; simple flows gain the funnel's default error toast and revalidation. * refactor(profiles): route profile operations through the mutate funnel Ports profile create/import/reorder/delete/update/patch/save-file and enhance calls onto the funnel; retry and editor flows keep their own error handling with errorNotice:false. Per-uid ids keep the update worker pool concurrent under the funnel's in-flight dedupe. * refactor(proxies): route proxy/home/misc commands through the mutate funnel Ports mode switching (page and home card), chain runtime updates, node selection with tray sync, selection recording, provider updates and syncs, and lightweight-mode entry onto the funnel; every site keeps its existing optimistic/revert and error-handling behavior. * docs: add frontend architecture guardrails for src Layering rules for the contract flow: generated contract as the only wire-typing source, event bus as the only listen/emit site, pure-reducer store for event-derived state, the mutate funnel for user intent, and invoke only in the services layer — each backed by the CI gates. * fix(events): close run-state race and restore single error toasts Self-review findings: the bus now re-reads the run-state snapshot in onSubscribed so an event racing the store's initial read cannot leave a stale snapshot (the ordering the old layout listener guaranteed), and the patch hooks pass errorNotice:false so GuardState/page handlers remain the only error toast, matching the pre-migration behavior. * fix(frontend): preserve queued intents and fresh runtime snapshots * refactor(frontend): trim unused mutation and busy state APIs * docs(frontend): focus guardrails on architecture ownership
235 lines
6.1 KiB
TypeScript
235 lines
6.1 KiB
TypeScript
import React, { useCallback, useMemo, useRef } from 'react'
|
|
import {
|
|
getBaseConfig,
|
|
getRuleProviders,
|
|
getRules,
|
|
} from 'tauri-plugin-mihomo-api'
|
|
|
|
import { useClashInfo, useRuntimeConfig } from '@/hooks/use-clash'
|
|
import { useVerge } from '@/hooks/use-verge'
|
|
import { getProxyView, getSystemProxy } from '@/services/cmds'
|
|
import { useQuery } from '@/services/query-client'
|
|
import { useRunState } from '@/store/app-store-context'
|
|
import { resolveDisplayedMixedPort } from '@/utils/mixed-port'
|
|
|
|
import {
|
|
ClashConfigContext,
|
|
CoreDataStatusContext,
|
|
ProxiesContext,
|
|
RefreshersContext,
|
|
RulesContext,
|
|
SystemContext,
|
|
} from './app-data-context'
|
|
|
|
const TQ_MIHOMO = {
|
|
refetchOnWindowFocus: false,
|
|
refetchOnReconnect: false,
|
|
staleTime: 1500,
|
|
retry: 3,
|
|
retryDelay: (attempt: number) => Math.min(200 * 2 ** attempt, 3000),
|
|
} as const
|
|
|
|
const TQ_DEFAULTS = {
|
|
refetchOnWindowFocus: false,
|
|
refetchOnReconnect: false,
|
|
staleTime: 5000,
|
|
retry: 2,
|
|
} as const
|
|
|
|
function useStableFn<T extends (...args: any[]) => any>(fn: T): T {
|
|
const ref = useRef(fn)
|
|
ref.current = fn
|
|
return useCallback((...args: Parameters<T>) => ref.current(...args), []) as T
|
|
}
|
|
|
|
// 全局数据提供者组件
|
|
export const AppDataProvider = ({
|
|
children,
|
|
}: {
|
|
children: React.ReactNode
|
|
}) => {
|
|
const { verge } = useVerge()
|
|
const { data: runtimeConfig } = useRuntimeConfig()
|
|
const { clashInfo } = useClashInfo()
|
|
|
|
const {
|
|
data: proxyView,
|
|
error: proxyViewError,
|
|
isPending: isProxyViewPending,
|
|
refetch: _refetchProxyView,
|
|
} = useQuery({
|
|
queryKey: ['getProxyView'],
|
|
queryFn: getProxyView,
|
|
refetchInterval: 15000,
|
|
refetchIntervalInBackground: false,
|
|
...TQ_MIHOMO,
|
|
})
|
|
|
|
const {
|
|
data: clashConfig,
|
|
isPending: isClashConfigPending,
|
|
refetch: _refetchClashConfig,
|
|
} = useQuery({
|
|
queryKey: ['getClashConfig'],
|
|
queryFn: getBaseConfig,
|
|
...TQ_MIHOMO,
|
|
})
|
|
|
|
const { data: ruleProviders, refetch: _refetchRuleProviders } = useQuery({
|
|
queryKey: ['getRuleProviders'],
|
|
queryFn: getRuleProviders,
|
|
...TQ_MIHOMO,
|
|
revalidateOnMount: false,
|
|
})
|
|
|
|
const { data: rulesData, refetch: _refetchRules } = useQuery({
|
|
queryKey: ['getRules'],
|
|
queryFn: getRules,
|
|
...TQ_MIHOMO,
|
|
})
|
|
|
|
const { data: sysproxy, refetch: _refetchSysproxy } = useQuery({
|
|
queryKey: ['getSystemProxy'],
|
|
queryFn: getSystemProxy,
|
|
...TQ_DEFAULTS,
|
|
})
|
|
|
|
// Store-owned run state; the event bus and the store's safety net write it.
|
|
const runState = useRunState()
|
|
const isRunningModePending = runState == null
|
|
const runningMode = runState?.mode
|
|
|
|
const refreshProxy = useStableFn(_refetchProxyView)
|
|
const refreshClashConfig = useStableFn(_refetchClashConfig)
|
|
const refreshRules = useStableFn(_refetchRules)
|
|
const refreshSysproxy = useStableFn(_refetchSysproxy)
|
|
const refreshRuleProviders = useStableFn(_refetchRuleProviders)
|
|
|
|
const refreshAll = useCallback(async () => {
|
|
await Promise.all([
|
|
refreshProxy(),
|
|
refreshClashConfig(),
|
|
refreshRules(),
|
|
refreshSysproxy(),
|
|
refreshRuleProviders(),
|
|
])
|
|
}, [
|
|
refreshProxy,
|
|
refreshClashConfig,
|
|
refreshRules,
|
|
refreshSysproxy,
|
|
refreshRuleProviders,
|
|
])
|
|
|
|
const proxiesValue = useMemo(
|
|
() => ({
|
|
proxyView,
|
|
isProxyViewPending,
|
|
isProxyViewError: Boolean(proxyViewError),
|
|
}),
|
|
[proxyView, isProxyViewPending, proxyViewError],
|
|
)
|
|
|
|
const rulesValue = useMemo(
|
|
() => ({
|
|
rules: rulesData?.rules ?? [],
|
|
ruleProviders: ruleProviders?.providers || {},
|
|
}),
|
|
[rulesData, ruleProviders],
|
|
)
|
|
|
|
const clashConfigValue = useMemo(
|
|
() => ({
|
|
clashConfig,
|
|
isClashConfigPending,
|
|
}),
|
|
[clashConfig, isClashConfigPending],
|
|
)
|
|
|
|
// Resolved from local sources rather than via useDisplayedMixedPort: that hook reads the
|
|
// ClashConfig context, and this component is the one providing it.
|
|
const displayedMixedPort = resolveDisplayedMixedPort({
|
|
live: clashConfig?.mixedPort,
|
|
runtime: runtimeConfig?.['mixed-port'],
|
|
selected: verge?.verge_mixed_port,
|
|
merge: clashInfo?.mixed_port,
|
|
})
|
|
|
|
const systemValue = useMemo(() => {
|
|
const calculateSystemProxyAddress = () => {
|
|
if (!verge) return '-'
|
|
|
|
const isPacMode = verge.proxy_auto_config ?? false
|
|
|
|
if (isPacMode) {
|
|
// PAC模式:显示我们期望设置的代理地址
|
|
const proxyHost = verge.proxy_host || '127.0.0.1'
|
|
return `${proxyHost}:${displayedMixedPort}`
|
|
} else {
|
|
// HTTP代理模式:优先使用系统地址,但如果格式不正确则使用期望地址
|
|
const systemServer = sysproxy?.server
|
|
if (
|
|
systemServer &&
|
|
systemServer !== '-' &&
|
|
!systemServer.startsWith(':')
|
|
) {
|
|
return systemServer
|
|
} else {
|
|
// 系统地址无效,返回期望的代理地址
|
|
const proxyHost = verge.proxy_host || '127.0.0.1'
|
|
return `${proxyHost}:${displayedMixedPort}`
|
|
}
|
|
}
|
|
}
|
|
|
|
return {
|
|
sysproxy,
|
|
runningMode,
|
|
isRunningModePending,
|
|
systemProxyAddress: calculateSystemProxyAddress(),
|
|
}
|
|
}, [sysproxy, runningMode, isRunningModePending, verge, displayedMixedPort])
|
|
|
|
const coreDataStatusValue = useMemo(
|
|
() => ({
|
|
isCoreDataPending: isProxyViewPending || isClashConfigPending,
|
|
}),
|
|
[isProxyViewPending, isClashConfigPending],
|
|
)
|
|
|
|
const refreshersValue = useMemo(
|
|
() => ({
|
|
refreshProxy,
|
|
refreshClashConfig,
|
|
refreshRules,
|
|
refreshSysproxy,
|
|
refreshRuleProviders,
|
|
refreshAll,
|
|
}),
|
|
[
|
|
refreshProxy,
|
|
refreshClashConfig,
|
|
refreshRules,
|
|
refreshSysproxy,
|
|
refreshRuleProviders,
|
|
refreshAll,
|
|
],
|
|
)
|
|
|
|
return (
|
|
<ProxiesContext value={proxiesValue}>
|
|
<RulesContext value={rulesValue}>
|
|
<ClashConfigContext value={clashConfigValue}>
|
|
<SystemContext value={systemValue}>
|
|
<CoreDataStatusContext value={coreDataStatusValue}>
|
|
<RefreshersContext value={refreshersValue}>
|
|
{children}
|
|
</RefreshersContext>
|
|
</CoreDataStatusContext>
|
|
</SystemContext>
|
|
</ClashConfigContext>
|
|
</RulesContext>
|
|
</ProxiesContext>
|
|
)
|
|
}
|