mirror of
https://github.com/clash-verge-rev/clash-verge-rev.git
synced 2026-12-02 11:40:04 +08:00
refactor(frontend): outfox foxact, foxts, and eslint-plugin-sukka (#8808)
* chore(eslint): remove eslint-plugin-sukka * refactor(frontend): remove foxts and inline local utilities * refactor(frontend): remove foxact and replace with local hooks * refactor(proxy): reuse local storage for group preferences
This commit is contained in:
@@ -1,5 +1,4 @@
|
||||
import { useTheme } from '@mui/material/styles'
|
||||
import { useLocalStorage } from 'foxact/use-local-storage'
|
||||
import {
|
||||
memo,
|
||||
useCallback,
|
||||
@@ -13,6 +12,8 @@ import {
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { useLocalStorage } from '@/hooks/use-local-storage'
|
||||
|
||||
import {
|
||||
ConnectionColumnManager,
|
||||
type ConnectionColumnOption,
|
||||
@@ -62,6 +63,19 @@ type ColumnField =
|
||||
type ColumnSizingState = Record<string, number>
|
||||
type VisibilityState = Record<string, boolean>
|
||||
|
||||
const EMPTY_RECORD = {}
|
||||
const EMPTY_COLUMN_ORDER: string[] = []
|
||||
|
||||
const parseColumnVisibility = (value: string): VisibilityState => {
|
||||
const parsed = JSON.parse(value)
|
||||
return parsed && typeof parsed === 'object' ? parsed : EMPTY_RECORD
|
||||
}
|
||||
|
||||
const parseColumnOrder = (value: string): string[] => {
|
||||
const parsed = JSON.parse(value)
|
||||
return Array.isArray(parsed) ? parsed : EMPTY_COLUMN_ORDER
|
||||
}
|
||||
|
||||
interface BaseColumn {
|
||||
field: ColumnField
|
||||
headerName: string
|
||||
@@ -368,42 +382,20 @@ export const ConnectionTable = (props: Props) => {
|
||||
const theme = useTheme()
|
||||
const [columnWidths, setColumnWidths] = useLocalStorage<ColumnSizingState>(
|
||||
'connection-table-widths',
|
||||
{},
|
||||
EMPTY_RECORD,
|
||||
)
|
||||
|
||||
const [columnVisibilityModel, setColumnVisibilityModel] =
|
||||
useLocalStorage<VisibilityState>(
|
||||
'connection-table-visibility',
|
||||
{},
|
||||
{
|
||||
serializer: JSON.stringify,
|
||||
deserializer: (value) => {
|
||||
try {
|
||||
const parsed = JSON.parse(value)
|
||||
if (parsed && typeof parsed === 'object') return parsed
|
||||
} catch (err) {
|
||||
console.warn('Failed to parse connection-table-visibility', err)
|
||||
}
|
||||
return {}
|
||||
},
|
||||
},
|
||||
EMPTY_RECORD,
|
||||
parseColumnVisibility,
|
||||
)
|
||||
|
||||
const [columnOrder, setColumnOrder] = useLocalStorage<string[]>(
|
||||
'connection-table-order',
|
||||
[],
|
||||
{
|
||||
serializer: JSON.stringify,
|
||||
deserializer: (value) => {
|
||||
try {
|
||||
const parsed = JSON.parse(value)
|
||||
if (Array.isArray(parsed)) return parsed
|
||||
} catch (err) {
|
||||
console.warn('Failed to parse connection-table-order', err)
|
||||
}
|
||||
return []
|
||||
},
|
||||
},
|
||||
EMPTY_COLUMN_ORDER,
|
||||
parseColumnOrder,
|
||||
)
|
||||
|
||||
const baseColumns = useMemo<BaseColumn[]>(() => {
|
||||
|
||||
@@ -14,20 +14,18 @@ import {
|
||||
Typography,
|
||||
} from '@mui/material'
|
||||
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow'
|
||||
import { useEffect } from 'foxact/use-abortable-effect'
|
||||
import { useIntersection } from 'foxact/use-intersection'
|
||||
import { useLocalStorage } from 'foxact/use-local-storage'
|
||||
import type { XOR } from 'foxts/ts-xor'
|
||||
import {
|
||||
forwardRef,
|
||||
memo,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useEffectEvent,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
|
||||
import { useLocalStorage } from '@/hooks/use-local-storage'
|
||||
import { getIpInfo } from '@/services/api'
|
||||
import { useQuery } from '@/services/query-client'
|
||||
import getSystem from '@/utils/get-system'
|
||||
@@ -72,15 +70,14 @@ const getCountryFlag = (countryCode: string | undefined) => {
|
||||
return String.fromCodePoint(...codePoints)
|
||||
}
|
||||
|
||||
type CountDownState = XOR<
|
||||
{
|
||||
type: 'countdown'
|
||||
remainingSeconds: number
|
||||
},
|
||||
{
|
||||
type: 'revalidating'
|
||||
}
|
||||
>
|
||||
type CountDownState =
|
||||
| {
|
||||
type: 'countdown'
|
||||
remainingSeconds: number
|
||||
}
|
||||
| {
|
||||
type: 'revalidating'
|
||||
}
|
||||
|
||||
const IPInfoCardContainer = forwardRef<HTMLElement, React.PropsWithChildren>(
|
||||
({ children }, ref) => {
|
||||
@@ -114,10 +111,19 @@ export const IpInfoCard = () => {
|
||||
)
|
||||
const appWindow = useMemo(() => getCurrentWebviewWindow(), [])
|
||||
|
||||
const [hasIntersected, setHasIntersected] = useState(false)
|
||||
// Once intersected, the card stays eligible for refresh until unmount.
|
||||
const [containerRef, hasIntersected, _resetIntersected] = useIntersection({
|
||||
rootMargin: '0px',
|
||||
})
|
||||
const containerRef = useCallback((element: HTMLElement | null) => {
|
||||
if (!element) return
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
if (entries.some((e) => e.isIntersecting || e.intersectionRatio > 0)) {
|
||||
setHasIntersected(true)
|
||||
observer.disconnect()
|
||||
}
|
||||
})
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
|
||||
const [countdown, setCountdown] = useState<CountDownState>({
|
||||
type: 'countdown',
|
||||
|
||||
@@ -19,10 +19,6 @@ import {
|
||||
styled,
|
||||
} from '@mui/material'
|
||||
import { useLockFn } from 'ahooks'
|
||||
import {
|
||||
cancelIdleCallback,
|
||||
requestIdleCallback,
|
||||
} from 'foxact/request-idle-callback'
|
||||
import * as yaml from 'js-yaml'
|
||||
import {
|
||||
startTransition,
|
||||
@@ -350,10 +346,12 @@ export const GroupsEditorViewer = (props: Props) => {
|
||||
}
|
||||
}
|
||||
|
||||
const handle = requestIdleCallback(serialize)
|
||||
return () => {
|
||||
cancelIdleCallback(handle)
|
||||
if (typeof window.requestIdleCallback === 'function') {
|
||||
const handle = window.requestIdleCallback(serialize)
|
||||
return () => window.cancelIdleCallback(handle)
|
||||
}
|
||||
const handle = window.setTimeout(serialize, 1)
|
||||
return () => window.clearTimeout(handle)
|
||||
}
|
||||
}, [prependSeq, appendSeq, deleteSeq])
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useReducer } from 'react'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { useLocalStorage } from '@/hooks/use-local-storage'
|
||||
import { useProfiles } from '@/hooks/use-profiles'
|
||||
|
||||
import { ProxySortType } from './use-filter-sort'
|
||||
@@ -16,9 +17,13 @@ export interface HeadState {
|
||||
testUrl: string
|
||||
}
|
||||
|
||||
type HeadStateStorage = Record<string, Record<string, HeadState>>
|
||||
type ProfileHeadState = Record<string, HeadState>
|
||||
type HeadStateStorage = Record<string, ProfileHeadState>
|
||||
|
||||
const HEAD_STATE_KEY = 'proxy-head-state'
|
||||
const EMPTY_STORAGE: HeadStateStorage = {}
|
||||
const EMPTY_PROFILE: ProfileHeadState = {}
|
||||
|
||||
export const DEFAULT_STATE: HeadState = {
|
||||
open: false,
|
||||
showType: true,
|
||||
@@ -31,77 +36,65 @@ export const DEFAULT_STATE: HeadState = {
|
||||
testUrl: '',
|
||||
}
|
||||
|
||||
type HeadStateAction =
|
||||
| { type: 'reset' }
|
||||
| { type: 'replace'; payload: Record<string, HeadState> }
|
||||
| { type: 'update'; groupName: string; patch: Partial<HeadState> }
|
||||
const parseStorage = (raw: string): HeadStateStorage => {
|
||||
const value = JSON.parse(raw) as HeadStateStorage | null
|
||||
return value && typeof value === 'object' && !Array.isArray(value)
|
||||
? value
|
||||
: EMPTY_STORAGE
|
||||
}
|
||||
|
||||
function headStateReducer(
|
||||
state: Record<string, HeadState>,
|
||||
action: HeadStateAction,
|
||||
): Record<string, HeadState> {
|
||||
switch (action.type) {
|
||||
case 'reset':
|
||||
return {}
|
||||
case 'replace':
|
||||
return action.payload
|
||||
case 'update': {
|
||||
const prev = state[action.groupName] || DEFAULT_STATE
|
||||
return { ...state, [action.groupName]: { ...prev, ...action.patch } }
|
||||
}
|
||||
default:
|
||||
return state
|
||||
}
|
||||
const getProfileState = (storage: HeadStateStorage, profile: string) => {
|
||||
const state = storage[profile]
|
||||
return state && typeof state === 'object' && !Array.isArray(state)
|
||||
? state
|
||||
: EMPTY_PROFILE
|
||||
}
|
||||
|
||||
export function useHeadStateNew() {
|
||||
const { profiles } = useProfiles()
|
||||
const current = profiles?.current || ''
|
||||
|
||||
const [state, dispatch] = useReducer(headStateReducer, {})
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
const data = JSON.parse(
|
||||
localStorage.getItem(HEAD_STATE_KEY)!,
|
||||
) as HeadStateStorage
|
||||
|
||||
const value = data[current] || {}
|
||||
|
||||
if (value && typeof value === 'object') {
|
||||
dispatch({ type: 'replace', payload: value })
|
||||
} else {
|
||||
dispatch({ type: 'reset' })
|
||||
}
|
||||
} catch {
|
||||
dispatch({ type: 'reset' })
|
||||
}
|
||||
}, [current])
|
||||
const [storage, setStorage] = useLocalStorage(
|
||||
HEAD_STATE_KEY,
|
||||
EMPTY_STORAGE,
|
||||
parseStorage,
|
||||
)
|
||||
const saved = getProfileState(storage, current)
|
||||
// The active profile owns its live state even if persistence fails.
|
||||
const [state, setState] = useState(() => ({
|
||||
profile: { id: current, initialGroups: saved },
|
||||
groups: saved,
|
||||
}))
|
||||
const { profile, groups } = state
|
||||
if (profile.id !== current) {
|
||||
setState({ profile: { id: current, initialGroups: saved }, groups: saved })
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (groups === profile.initialGroups) return
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
const item = localStorage.getItem(HEAD_STATE_KEY)
|
||||
|
||||
let data = (item ? JSON.parse(item) : {}) as HeadStateStorage
|
||||
|
||||
if (!data || typeof data !== 'object') data = {}
|
||||
|
||||
data[current] = state
|
||||
|
||||
localStorage.setItem(HEAD_STATE_KEY, JSON.stringify(data))
|
||||
} catch {}
|
||||
setStorage((previous) => ({
|
||||
...previous,
|
||||
[profile.id]: groups,
|
||||
}))
|
||||
})
|
||||
|
||||
return () => clearTimeout(timer)
|
||||
}, [state, current])
|
||||
}, [groups, profile, setStorage])
|
||||
|
||||
const setHeadState = useCallback(
|
||||
(groupName: string, obj: Partial<HeadState>) => {
|
||||
dispatch({ type: 'update', groupName, patch: obj })
|
||||
(groupName: string, patch: Partial<HeadState>) => {
|
||||
setState((previous) => {
|
||||
if (previous.profile !== profile) return previous
|
||||
const group = previous.groups[groupName] ?? DEFAULT_STATE
|
||||
return {
|
||||
profile,
|
||||
groups: { ...previous.groups, [groupName]: { ...group, ...patch } },
|
||||
}
|
||||
})
|
||||
},
|
||||
[],
|
||||
[profile],
|
||||
)
|
||||
|
||||
return [state, setHeadState] as const
|
||||
return [groups, setHeadState] as const
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useLocalStorage } from 'foxact/use-local-storage'
|
||||
import { useLocalStorage } from './use-local-storage'
|
||||
|
||||
const defaultClashLog: IClashLog = {
|
||||
enable: true,
|
||||
@@ -8,7 +8,4 @@ const defaultClashLog: IClashLog = {
|
||||
}
|
||||
|
||||
export const useClashLog = () =>
|
||||
useLocalStorage<IClashLog>('clash-log', defaultClashLog, {
|
||||
serializer: JSON.stringify,
|
||||
deserializer: JSON.parse,
|
||||
})
|
||||
useLocalStorage<IClashLog>('clash-log', defaultClashLog)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useLocalStorage } from 'foxact/use-local-storage'
|
||||
import { useLocalStorage } from './use-local-storage'
|
||||
|
||||
const defaultConnectionSetting: IConnectionSetting = { layout: 'table' }
|
||||
|
||||
@@ -6,8 +6,4 @@ export const useConnectionSetting = () =>
|
||||
useLocalStorage<IConnectionSetting>(
|
||||
'connections-setting',
|
||||
defaultConnectionSetting,
|
||||
{
|
||||
serializer: JSON.stringify,
|
||||
deserializer: JSON.parse,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
/* eslint-disable @eslint-react/set-state-in-effect */
|
||||
import { useEffect } from 'foxact/use-abortable-effect'
|
||||
import { useCallback, useState } from 'react'
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
import { showNotice } from '@/services/notice-service'
|
||||
|
||||
@@ -42,26 +41,28 @@ export const useEditorDocument = ({ open, load }: UseEditorDocumentOptions) => {
|
||||
}
|
||||
}, [applyLoadedValue, load])
|
||||
|
||||
useEffect(
|
||||
(signal) => {
|
||||
resetDocumentState()
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
resetDocumentState()
|
||||
|
||||
if (!open) return
|
||||
if (!open) return
|
||||
|
||||
load()
|
||||
.then((nextValue) => {
|
||||
if (signal.aborted) return
|
||||
applyLoadedValue(nextValue)
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!signal.aborted) showNotice.error(error)
|
||||
})
|
||||
.finally(() => {
|
||||
if (!signal.aborted) setLoading(false)
|
||||
})
|
||||
},
|
||||
[applyLoadedValue, load, open, resetDocumentState],
|
||||
)
|
||||
load()
|
||||
.then((nextValue) => {
|
||||
if (cancelled) return
|
||||
applyLoadedValue(nextValue)
|
||||
})
|
||||
.catch((error) => {
|
||||
if (!cancelled) showNotice.error(error)
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false)
|
||||
})
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [applyLoadedValue, load, open, resetDocumentState])
|
||||
|
||||
const markSaved = useCallback((nextValue: string) => {
|
||||
setSavedValue(nextValue)
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { useCallback, useMemo, useSyncExternalStore } from 'react'
|
||||
|
||||
interface StorageEntry {
|
||||
listeners: Set<() => void>
|
||||
raw: string | null
|
||||
parsedRaw: string | null
|
||||
parsed: unknown
|
||||
deserializer?: (value: string) => unknown
|
||||
}
|
||||
|
||||
const entries = new Map<string, StorageEntry>()
|
||||
|
||||
const readRaw = (key: string): string | null => {
|
||||
try {
|
||||
return window.localStorage.getItem(key)
|
||||
} catch (error) {
|
||||
console.warn(`[useLocalStorage] Failed to read "${key}"`, error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
const getRaw = (key: string): string | null => {
|
||||
const entry = entries.get(key)
|
||||
return entry ? entry.raw : readRaw(key)
|
||||
}
|
||||
|
||||
const handleStorageEvent = (event: StorageEvent) => {
|
||||
if (event.storageArea !== window.localStorage) return
|
||||
|
||||
if (event.key === null) {
|
||||
entries.forEach((entry) => {
|
||||
entry.raw = null
|
||||
entry.parsedRaw = null
|
||||
entry.parsed = undefined
|
||||
entry.listeners.forEach((listener) => listener())
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
const entry = entries.get(event.key)
|
||||
if (!entry) return
|
||||
entry.raw = event.newValue
|
||||
entry.parsedRaw = null
|
||||
entry.parsed = undefined
|
||||
entry.listeners.forEach((listener) => listener())
|
||||
}
|
||||
|
||||
const subscribeKey = (key: string, listener: () => void) => {
|
||||
if (entries.size === 0) {
|
||||
window.addEventListener('storage', handleStorageEvent)
|
||||
}
|
||||
|
||||
let entry = entries.get(key)
|
||||
if (!entry) {
|
||||
entry = {
|
||||
listeners: new Set(),
|
||||
raw: readRaw(key),
|
||||
parsedRaw: null,
|
||||
parsed: undefined,
|
||||
}
|
||||
entries.set(key, entry)
|
||||
}
|
||||
entry.listeners.add(listener)
|
||||
|
||||
return () => {
|
||||
const current = entries.get(key)
|
||||
if (current) {
|
||||
current.listeners.delete(listener)
|
||||
if (current.listeners.size === 0) entries.delete(key)
|
||||
}
|
||||
if (entries.size === 0) {
|
||||
window.removeEventListener('storage', handleStorageEvent)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parseRaw = <T>(
|
||||
key: string,
|
||||
raw: string | null,
|
||||
defaultValue: T,
|
||||
deserializer: (value: string) => T,
|
||||
): T => {
|
||||
if (raw === null) return defaultValue
|
||||
const entry = entries.get(key)
|
||||
if (entry && entry.parsedRaw === raw && entry.deserializer === deserializer) {
|
||||
return entry.parsed as T
|
||||
}
|
||||
try {
|
||||
const value = deserializer(raw)
|
||||
if (entry) {
|
||||
entry.parsedRaw = raw
|
||||
entry.parsed = value
|
||||
entry.deserializer = deserializer
|
||||
}
|
||||
return value
|
||||
} catch (error) {
|
||||
console.warn(`[useLocalStorage] Failed to deserialize "${key}"`, error)
|
||||
return defaultValue
|
||||
}
|
||||
}
|
||||
|
||||
export const useLocalStorage = <T>(
|
||||
key: string,
|
||||
defaultValue: T,
|
||||
deserializer: (value: string) => T = JSON.parse,
|
||||
): [T, (value: T | ((prev: T) => T)) => void] => {
|
||||
const subscribe = useCallback(
|
||||
(listener: () => void) => subscribeKey(key, listener),
|
||||
[key],
|
||||
)
|
||||
|
||||
const raw = useSyncExternalStore(subscribe, () => getRaw(key))
|
||||
|
||||
const value = useMemo<T>(
|
||||
() => parseRaw(key, raw, defaultValue, deserializer),
|
||||
[key, raw, defaultValue, deserializer],
|
||||
)
|
||||
|
||||
const setValue = useCallback(
|
||||
(next: T | ((prev: T) => T)) => {
|
||||
try {
|
||||
const entry = entries.get(key)
|
||||
const currentRaw = entry ? entry.raw : readRaw(key)
|
||||
const resolved =
|
||||
typeof next === 'function'
|
||||
? (next as (prev: T) => T)(
|
||||
parseRaw(key, currentRaw, defaultValue, deserializer),
|
||||
)
|
||||
: next
|
||||
|
||||
const serialized = JSON.stringify(resolved)
|
||||
if (currentRaw === serialized) return
|
||||
window.localStorage.setItem(key, serialized)
|
||||
if (entry) {
|
||||
entry.raw = serialized
|
||||
entry.parsedRaw = null
|
||||
entry.parsed = undefined
|
||||
entry.listeners.forEach((listener) => listener())
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`[useLocalStorage] Failed to write "${key}"`, error)
|
||||
}
|
||||
},
|
||||
[key, defaultValue, deserializer],
|
||||
)
|
||||
|
||||
return [value, setValue]
|
||||
}
|
||||
+15
-18
@@ -1,7 +1,6 @@
|
||||
import './assets/styles/index.scss'
|
||||
|
||||
import { ResizeObserver } from '@juggle/resize-observer'
|
||||
import { ComposeContextProvider } from 'foxact/compose-context-provider'
|
||||
import React from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { RouterProvider } from 'react-router'
|
||||
@@ -38,26 +37,24 @@ if (!container) {
|
||||
disableWebViewShortcuts()
|
||||
|
||||
const initializeApp = (initialThemeMode: 'light' | 'dark') => {
|
||||
const contexts = [
|
||||
<ThemeModeProvider key="theme" initialState={initialThemeMode} />,
|
||||
<AppStoreProvider key="app-store" />,
|
||||
<UpdateStateProvider key="update" />,
|
||||
]
|
||||
|
||||
const root = createRoot(container)
|
||||
root.render(
|
||||
<React.StrictMode>
|
||||
<ComposeContextProvider contexts={contexts}>
|
||||
<BaseErrorBoundary>
|
||||
<SWRConfig value={swrConfig}>
|
||||
<WindowProvider>
|
||||
<AppDataProvider>
|
||||
<RouterProvider router={router} />
|
||||
</AppDataProvider>
|
||||
</WindowProvider>
|
||||
</SWRConfig>
|
||||
</BaseErrorBoundary>
|
||||
</ComposeContextProvider>
|
||||
<ThemeModeProvider initialState={initialThemeMode}>
|
||||
<AppStoreProvider>
|
||||
<UpdateStateProvider>
|
||||
<BaseErrorBoundary>
|
||||
<SWRConfig value={swrConfig}>
|
||||
<WindowProvider>
|
||||
<AppDataProvider>
|
||||
<RouterProvider router={router} />
|
||||
</AppDataProvider>
|
||||
</WindowProvider>
|
||||
</SWRConfig>
|
||||
</BaseErrorBoundary>
|
||||
</UpdateStateProvider>
|
||||
</AppStoreProvider>
|
||||
</ThemeModeProvider>
|
||||
</React.StrictMode>,
|
||||
)
|
||||
}
|
||||
|
||||
+78
-62
@@ -1,8 +1,5 @@
|
||||
import { getName, getVersion } from '@tauri-apps/api/app'
|
||||
import { fetch } from '@tauri-apps/plugin-http'
|
||||
import { asyncRetry } from 'foxts/async-retry'
|
||||
import { extractErrorMessage } from 'foxts/extract-error-message'
|
||||
import { once } from 'foxts/once'
|
||||
import i18n from 'i18next'
|
||||
import { getBaseConfig } from 'tauri-plugin-mihomo-api'
|
||||
|
||||
@@ -10,15 +7,42 @@ import { debugLog } from '@/utils/debug'
|
||||
|
||||
import { getRuntimeConfig } from './cmds'
|
||||
|
||||
const getUserAgentPromise = once(async () => {
|
||||
try {
|
||||
const [name, version] = await Promise.all([getName(), getVersion()])
|
||||
return `${name}/${version}`
|
||||
} catch (error) {
|
||||
console.debug('Failed to build User-Agent, fallback to default', error)
|
||||
return 'clash-verge-rev'
|
||||
let userAgentPromise: Promise<string> | null = null
|
||||
const getUserAgentPromise = () =>
|
||||
(userAgentPromise ??= Promise.all([getName(), getVersion()])
|
||||
.then(([name, version]) => `${name}/${version}`)
|
||||
.catch((error) => {
|
||||
console.debug('Failed to build User-Agent, fallback to default', error)
|
||||
return 'clash-verge-rev'
|
||||
}))
|
||||
|
||||
const extractErrorMessage = (error: unknown): string | null =>
|
||||
error instanceof Error ? `${error.name}: ${error.message}`.trim() : null
|
||||
|
||||
const retryWithBackoff = async <T>(
|
||||
fn: (bail: (error: unknown) => never) => Promise<T>,
|
||||
retries: number,
|
||||
): Promise<T> => {
|
||||
let bailed = false
|
||||
const bail = (error: unknown): never => {
|
||||
bailed = true
|
||||
throw error
|
||||
}
|
||||
})
|
||||
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
return await fn(bail)
|
||||
} catch (error) {
|
||||
if (bailed || attempt >= retries) throw error
|
||||
|
||||
const delay = Math.min(
|
||||
Math.round((Math.random() + 1) * 1000 * 2 ** attempt),
|
||||
4000,
|
||||
)
|
||||
await new Promise((resolve) => setTimeout(resolve, delay))
|
||||
}
|
||||
}
|
||||
}
|
||||
// Get current IP and geolocation information (refactored IP detection with service-specific mappings)
|
||||
interface IpInfo {
|
||||
ip: string
|
||||
@@ -249,61 +273,53 @@ export const getIpInfo = async (): Promise<
|
||||
debugLog(`尝试IP检测服务: ${service.url}`)
|
||||
|
||||
try {
|
||||
return await asyncRetry(
|
||||
async (bail) => {
|
||||
console.debug('Fetching IP information:', service.url)
|
||||
return await retryWithBackoff(async (bail) => {
|
||||
console.debug('Fetching IP information:', service.url)
|
||||
|
||||
const timeoutController = new AbortController()
|
||||
const timeoutId = setTimeout(() => {
|
||||
timeoutController.abort()
|
||||
}, serviceTimeout)
|
||||
const timeoutController = new AbortController()
|
||||
const timeoutId = setTimeout(() => {
|
||||
timeoutController.abort()
|
||||
}, serviceTimeout)
|
||||
|
||||
try {
|
||||
const response = await fetch(service.url, {
|
||||
method: 'GET',
|
||||
proxy,
|
||||
signal: timeoutController.signal,
|
||||
connectTimeout: serviceTimeout,
|
||||
headers: {
|
||||
'User-Agent': userAgent,
|
||||
},
|
||||
})
|
||||
try {
|
||||
const response = await fetch(service.url, {
|
||||
method: 'GET',
|
||||
proxy,
|
||||
signal: timeoutController.signal,
|
||||
connectTimeout: serviceTimeout,
|
||||
headers: {
|
||||
'User-Agent': userAgent,
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
return bail(
|
||||
new Error(
|
||||
`IP 检测服务出错,状态码: ${response.status} from ${service.url}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
let data: any
|
||||
try {
|
||||
data = await response.json()
|
||||
} catch {
|
||||
return bail(new Error(`无法解析 JSON 响应 from ${service.url}`))
|
||||
}
|
||||
|
||||
if (data && data.ip) {
|
||||
debugLog(`IP检测成功,使用服务: ${service.url}`)
|
||||
return Object.assign(service.mapping(data), {
|
||||
// use last fetch success timestamp
|
||||
lastFetchTs: Date.now(),
|
||||
})
|
||||
} else {
|
||||
return bail(new Error(`无效的响应格式 from ${service.url}`))
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeoutId)
|
||||
if (!response.ok) {
|
||||
return bail(
|
||||
new Error(
|
||||
`IP 检测服务出错,状态码: ${response.status} from ${service.url}`,
|
||||
),
|
||||
)
|
||||
}
|
||||
},
|
||||
{
|
||||
retries: maxRetries,
|
||||
minTimeout: 1000,
|
||||
maxTimeout: 4000,
|
||||
randomize: true,
|
||||
},
|
||||
)
|
||||
|
||||
let data: any
|
||||
try {
|
||||
data = await response.json()
|
||||
} catch {
|
||||
return bail(new Error(`无法解析 JSON 响应 from ${service.url}`))
|
||||
}
|
||||
|
||||
if (data && data.ip) {
|
||||
debugLog(`IP检测成功,使用服务: ${service.url}`)
|
||||
return Object.assign(service.mapping(data), {
|
||||
// use last fetch success timestamp
|
||||
lastFetchTs: Date.now(),
|
||||
})
|
||||
} else {
|
||||
return bail(new Error(`无效的响应格式 from ${service.url}`))
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeoutId)
|
||||
}
|
||||
}, maxRetries)
|
||||
} catch (error) {
|
||||
debugLog(`IP检测服务失败: ${service.url}`, error)
|
||||
lastError = error
|
||||
|
||||
+47
-14
@@ -1,18 +1,51 @@
|
||||
import { createContextState } from 'foxact/create-context-state'
|
||||
import {
|
||||
createContext,
|
||||
createElement,
|
||||
use,
|
||||
useState,
|
||||
type Dispatch,
|
||||
type ReactNode,
|
||||
type SetStateAction,
|
||||
} from 'react'
|
||||
|
||||
const [ThemeModeProvider, useThemeMode, useSetThemeMode] = createContextState<
|
||||
'light' | 'dark'
|
||||
>()
|
||||
import noop from '@/utils/noop'
|
||||
|
||||
// save update state
|
||||
const [UpdateStateProvider, useUpdateState, useSetUpdateState] =
|
||||
createContextState<boolean>(false)
|
||||
type ThemeMode = 'light' | 'dark'
|
||||
|
||||
export {
|
||||
ThemeModeProvider,
|
||||
useThemeMode,
|
||||
useSetThemeMode,
|
||||
UpdateStateProvider,
|
||||
useUpdateState,
|
||||
useSetUpdateState,
|
||||
const ThemeModeContext = createContext<ThemeMode>('light')
|
||||
const SetThemeModeContext =
|
||||
createContext<Dispatch<SetStateAction<ThemeMode>>>(noop)
|
||||
|
||||
export const ThemeModeProvider = ({
|
||||
initialState,
|
||||
children,
|
||||
}: {
|
||||
initialState: ThemeMode
|
||||
children?: ReactNode
|
||||
}) => {
|
||||
const [mode, setMode] = useState<ThemeMode>(initialState)
|
||||
return createElement(
|
||||
ThemeModeContext,
|
||||
{ value: mode },
|
||||
createElement(SetThemeModeContext, { value: setMode }, children),
|
||||
)
|
||||
}
|
||||
|
||||
export const useThemeMode = () => use(ThemeModeContext)
|
||||
export const useSetThemeMode = () => use(SetThemeModeContext)
|
||||
|
||||
const UpdateStateContext = createContext<boolean>(false)
|
||||
const SetUpdateStateContext =
|
||||
createContext<Dispatch<SetStateAction<boolean>>>(noop)
|
||||
|
||||
export const UpdateStateProvider = ({ children }: { children?: ReactNode }) => {
|
||||
const [state, setState] = useState(false)
|
||||
return createElement(
|
||||
UpdateStateContext,
|
||||
{ value: state },
|
||||
createElement(SetUpdateStateContext, { value: setState }, children),
|
||||
)
|
||||
}
|
||||
|
||||
export const useUpdateState = () => use(UpdateStateContext)
|
||||
export const useSetUpdateState = () => use(SetUpdateStateContext)
|
||||
|
||||
Reference in New Issue
Block a user