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:
Tunglies
2026-12-02 01:34:55 +00:00
committed by GitHub
parent 87de9bd5bf
commit 186ec116fa
14 changed files with 409 additions and 318 deletions
-3
View File
@@ -7,7 +7,6 @@ import pluginImportX from 'eslint-plugin-import-x'
import pluginReactCompiler from 'eslint-plugin-react-compiler' import pluginReactCompiler from 'eslint-plugin-react-compiler'
import pluginReactHooks from 'eslint-plugin-react-hooks' import pluginReactHooks from 'eslint-plugin-react-hooks'
import pluginReactRefresh from 'eslint-plugin-react-refresh' import pluginReactRefresh from 'eslint-plugin-react-refresh'
import PluginSukka from 'eslint-plugin-sukka'
import pluginUnusedImports from 'eslint-plugin-unused-imports' import pluginUnusedImports from 'eslint-plugin-unused-imports'
import globals from 'globals' import globals from 'globals'
import tseslint from 'typescript-eslint' import tseslint from 'typescript-eslint'
@@ -112,7 +111,6 @@ export default defineConfig([
'import-x': pluginImportX, 'import-x': pluginImportX,
'react-refresh': pluginReactRefresh, 'react-refresh': pluginReactRefresh,
'unused-imports': pluginUnusedImports, 'unused-imports': pluginUnusedImports,
sukka: PluginSukka,
}, },
extends: [ extends: [
@@ -182,7 +180,6 @@ export default defineConfig([
'@eslint-react/no-unused-class-component-members': 'error', '@eslint-react/no-unused-class-component-members': 'error',
'@eslint-react/no-unused-state': 'error', '@eslint-react/no-unused-state': 'error',
'@eslint-react/jsx-no-useless-fragment': 'warn', '@eslint-react/jsx-no-useless-fragment': 'warn',
'sukka/react-prefer-destructuring-assignment': 'warn',
// TypeScript // TypeScript
'@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-explicit-any': 'off',
-3
View File
@@ -57,8 +57,6 @@
"ahooks": "^3.10.0", "ahooks": "^3.10.0",
"cidr-block": "^2.3.0", "cidr-block": "^2.3.0",
"dayjs": "1.11.23", "dayjs": "1.11.23",
"foxact": "^0.3.12",
"foxts": "^5.9.1",
"i18next": "^27.0.0", "i18next": "^27.0.0",
"js-yaml": "^5.4.2", "js-yaml": "^5.4.2",
"lodash-es": "^4.18.1", "lodash-es": "^4.18.1",
@@ -107,7 +105,6 @@
"eslint-plugin-react-compiler": "19.1.0-rc.2", "eslint-plugin-react-compiler": "19.1.0-rc.2",
"eslint-plugin-react-hooks": "^7.1.1", "eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.7", "eslint-plugin-react-refresh": "^0.5.7",
"eslint-plugin-sukka": "^10.2.0",
"eslint-plugin-unused-imports": "^4.4.1", "eslint-plugin-unused-imports": "^4.4.1",
"globals": "^17.12.0", "globals": "^17.12.0",
"https-proxy-agent": "^9.1.0", "https-proxy-agent": "^9.1.0",
-80
View File
@@ -248,12 +248,6 @@ importers:
dayjs: dayjs:
specifier: 1.11.23 specifier: 1.11.23
version: 1.11.23 version: 1.11.23
foxact:
specifier: ^0.3.12
version: 0.3.12(react-dom@19.3.1(react@19.3.1))(react@19.3.1)
foxts:
specifier: ^5.9.1
version: 5.9.1
i18next: i18next:
specifier: ^27.0.0 specifier: ^27.0.0
version: 27.0.1(typescript@6.0.3) version: 27.0.1(typescript@6.0.3)
@@ -393,9 +387,6 @@ importers:
eslint-plugin-react-refresh: eslint-plugin-react-refresh:
specifier: ^0.5.7 specifier: ^0.5.7
version: 0.5.7(eslint@10.16.0(jiti@2.7.0)) version: 0.5.7(eslint@10.16.0(jiti@2.7.0))
eslint-plugin-sukka:
specifier: ^10.2.0
version: 10.2.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)
eslint-plugin-unused-imports: eslint-plugin-unused-imports:
specifier: ^4.4.1 specifier: ^4.4.1
version: 4.4.1(@typescript-eslint/eslint-plugin@8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)) version: 4.4.1(@typescript-eslint/eslint-plugin@8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0))
@@ -2569,9 +2560,6 @@ packages:
resolution: {integrity: sha512-zlnpg0jNcibNrO7GG9IeHH7maWFeCz+Ja1wx/7tZNU5ASSSSZ+/qZciM0/LHCYxSdqv5h2sdbQ/PXYdOuetXvA==} resolution: {integrity: sha512-zlnpg0jNcibNrO7GG9IeHH7maWFeCz+Ja1wx/7tZNU5ASSSSZ+/qZciM0/LHCYxSdqv5h2sdbQ/PXYdOuetXvA==}
engines: {node: '>=0.10'} engines: {node: '>=0.10'}
client-only@0.0.1:
resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==}
clsx@2.1.1: clsx@2.1.1:
resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==}
engines: {node: '>=6'} engines: {node: '>=6'}
@@ -2850,12 +2838,6 @@ packages:
eslint: '*' eslint: '*'
typescript: '*' typescript: '*'
eslint-plugin-sukka@10.2.0:
resolution: {integrity: sha512-BbErYY/fymqL7Te5yiDeBGfSF7QMxzZrT4SQpFI2e8ecRun3oYbL5aJm4kzFfeUzNZ/hET8T7pedpaH1fuXXHg==}
peerDependencies:
eslint: '>=9.29.0'
typescript: '*'
eslint-plugin-unused-imports@4.4.1: eslint-plugin-unused-imports@4.4.1:
resolution: {integrity: sha512-oZGYUz1X3sRMGUB+0cZyK2VcvRX5lm/vB56PgNNcU+7ficUCKm66oZWKUubXWnOuPjQ8PvmXtCViXBMONPe7tQ==} resolution: {integrity: sha512-oZGYUz1X3sRMGUB+0cZyK2VcvRX5lm/vB56PgNNcU+7ficUCKm66oZWKUubXWnOuPjQ8PvmXtCViXBMONPe7tQ==}
peerDependencies: peerDependencies:
@@ -2929,9 +2911,6 @@ packages:
event-emitter@0.3.5: event-emitter@0.3.5:
resolution: {integrity: sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==} resolution: {integrity: sha512-D9rRn9y7kLPnJ+hMq7S/nhvoKwwvVJahBi2BPmx3bvbsEdK3W9ii8cBSGjP+72/LnM4n6fo3+dkCX5FeTQruXA==}
event-target-bus@1.1.0:
resolution: {integrity: sha512-24JX34nM0qRcsj7KvtLbVpMcX8ZQYmb0+0a6viaV2GJtVFg5UGyJyDLITkBipJIG0fSscNskI2PxdhTBIMeg8g==}
expect-type@1.4.0: expect-type@1.4.0:
resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==}
engines: {node: '>=12.0.0'} engines: {node: '>=12.0.0'}
@@ -2945,10 +2924,6 @@ packages:
fast-deep-equal@3.1.3: fast-deep-equal@3.1.3:
resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
fast-fnv1a@1.0.0:
resolution: {integrity: sha512-Y7iaFmz24pNJX+nqXgDuyHYFTfV9XPWJRfqp0hlG0Xuz1vKnelwLwvmKkbvVVvp5WzYWnrovBTLdk2PWkOYzCg==}
engines: {node: ^22.15.0 || ^23.8.0 || >=24.0.0}
fast-json-stable-stringify@2.1.0: fast-json-stable-stringify@2.1.0:
resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==} resolution: {integrity: sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==}
@@ -2983,10 +2958,6 @@ packages:
flatted@3.4.4: flatted@3.4.4:
resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==} resolution: {integrity: sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==}
fnv1a52@1.0.0:
resolution: {integrity: sha512-dUnV6Uok578HuGYTC/EM0LqeXewXBCHsh/kmLkdcqN1zgSy7K3gCIrshPBS5JwW20XSaRv4Vnz7z8lMjOV8jWw==}
engines: {node: '>=18.0.0'}
follow-redirects@1.16.2: follow-redirects@1.16.2:
resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}
engines: {node: '>=4.0'} engines: {node: '>=4.0'}
@@ -3005,20 +2976,6 @@ packages:
engines: {node: ^20.12.0 || >=22} engines: {node: ^20.12.0 || >=22}
hasBin: true hasBin: true
foxact@0.3.12:
resolution: {integrity: sha512-sXE1plDgAUsKWzqbAMq/+ifRI3TSOnDPmyZGoaniW9AhtZqk3cOEUSC0jC4a4srvLf4PXwtCB+zQczBdxHGSDA==}
peerDependencies:
react: '*'
react-dom: '*'
peerDependenciesMeta:
react:
optional: true
react-dom:
optional: true
foxts@5.9.1:
resolution: {integrity: sha512-NrIHGlf4LZGTjjGlVi3gmMbtvC4871SFUflu9yb8X91FYppAk+WMiYS6ZlaEgkPqAkgIGNeq+Y5YCL80GL6v8g==}
fsevents@2.3.3: fsevents@2.3.3:
resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
@@ -3833,9 +3790,6 @@ packages:
engines: {node: '>=10'} engines: {node: '>=10'}
hasBin: true hasBin: true
server-only@0.0.1:
resolution: {integrity: sha512-qepMx2JxAa5jjfzxG79yPPq+8BuFToHd1hm7kI+Z4zAq1ftQiP7HcxMhDDItrbtwVeLg/cY2JnKnrcFkmiswNA==}
shebang-command@2.0.0: shebang-command@2.0.0:
resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}
engines: {node: '>=8'} engines: {node: '>=8'}
@@ -6390,8 +6344,6 @@ snapshots:
memoizee: 0.4.17 memoizee: 0.4.17
timers-ext: 0.1.8 timers-ext: 0.1.8
client-only@0.0.1: {}
clsx@2.1.1: {} clsx@2.1.1: {}
combined-stream@1.0.8: combined-stream@1.0.8:
@@ -6728,16 +6680,6 @@ snapshots:
transitivePeerDependencies: transitivePeerDependencies:
- supports-color - supports-color
eslint-plugin-sukka@10.2.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3):
dependencies:
'@typescript-eslint/types': 8.74.0
'@typescript-eslint/utils': 8.70.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3)
eslint: 10.16.0(jiti@2.7.0)
foxts: 5.9.1
typescript: 6.0.3
transitivePeerDependencies:
- supports-color
eslint-plugin-unused-imports@4.4.1(@typescript-eslint/eslint-plugin@8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)): eslint-plugin-unused-imports@4.4.1(@typescript-eslint/eslint-plugin@8.74.0(@typescript-eslint/parser@8.74.0(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0))(typescript@6.0.3))(eslint@10.16.0(jiti@2.7.0)):
dependencies: dependencies:
eslint: 10.16.0(jiti@2.7.0) eslint: 10.16.0(jiti@2.7.0)
@@ -6835,8 +6777,6 @@ snapshots:
d: 1.0.2 d: 1.0.2
es5-ext: 0.10.64 es5-ext: 0.10.64
event-target-bus@1.1.0: {}
expect-type@1.4.0: {} expect-type@1.4.0: {}
ext@1.7.0: ext@1.7.0:
@@ -6847,8 +6787,6 @@ snapshots:
fast-deep-equal@3.1.3: {} fast-deep-equal@3.1.3: {}
fast-fnv1a@1.0.0: {}
fast-json-stable-stringify@2.1.0: {} fast-json-stable-stringify@2.1.0: {}
fast-levenshtein@2.0.6: {} fast-levenshtein@2.0.6: {}
@@ -6880,8 +6818,6 @@ snapshots:
flatted@3.4.4: {} flatted@3.4.4: {}
fnv1a52@1.0.0: {}
follow-redirects@1.16.2(debug@4.4.3): follow-redirects@1.16.2(debug@4.4.3):
optionalDependencies: optionalDependencies:
debug: 4.4.3 debug: 4.4.3
@@ -6904,20 +6840,6 @@ snapshots:
transitivePeerDependencies: transitivePeerDependencies:
- '@clack/prompts' - '@clack/prompts'
foxact@0.3.12(react-dom@19.3.1(react@19.3.1))(react@19.3.1):
dependencies:
client-only: 0.0.1
event-target-bus: 1.1.0
server-only: 0.0.1
optionalDependencies:
react: 19.3.1
react-dom: 19.3.1(react@19.3.1)
foxts@5.9.1:
dependencies:
fast-fnv1a: 1.0.0
fnv1a52: 1.0.0
fsevents@2.3.3: fsevents@2.3.3:
optional: true optional: true
@@ -7921,8 +7843,6 @@ snapshots:
semver@7.8.5: {} semver@7.8.5: {}
server-only@0.0.1: {}
shebang-command@2.0.0: shebang-command@2.0.0:
dependencies: dependencies:
shebang-regex: 3.0.0 shebang-regex: 3.0.0
+20 -28
View File
@@ -1,5 +1,4 @@
import { useTheme } from '@mui/material/styles' import { useTheme } from '@mui/material/styles'
import { useLocalStorage } from 'foxact/use-local-storage'
import { import {
memo, memo,
useCallback, useCallback,
@@ -13,6 +12,8 @@ import {
} from 'react' } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useLocalStorage } from '@/hooks/use-local-storage'
import { import {
ConnectionColumnManager, ConnectionColumnManager,
type ConnectionColumnOption, type ConnectionColumnOption,
@@ -62,6 +63,19 @@ type ColumnField =
type ColumnSizingState = Record<string, number> type ColumnSizingState = Record<string, number>
type VisibilityState = Record<string, boolean> 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 { interface BaseColumn {
field: ColumnField field: ColumnField
headerName: string headerName: string
@@ -368,42 +382,20 @@ export const ConnectionTable = (props: Props) => {
const theme = useTheme() const theme = useTheme()
const [columnWidths, setColumnWidths] = useLocalStorage<ColumnSizingState>( const [columnWidths, setColumnWidths] = useLocalStorage<ColumnSizingState>(
'connection-table-widths', 'connection-table-widths',
{}, EMPTY_RECORD,
) )
const [columnVisibilityModel, setColumnVisibilityModel] = const [columnVisibilityModel, setColumnVisibilityModel] =
useLocalStorage<VisibilityState>( useLocalStorage<VisibilityState>(
'connection-table-visibility', 'connection-table-visibility',
{}, EMPTY_RECORD,
{ parseColumnVisibility,
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 {}
},
},
) )
const [columnOrder, setColumnOrder] = useLocalStorage<string[]>( const [columnOrder, setColumnOrder] = useLocalStorage<string[]>(
'connection-table-order', 'connection-table-order',
[], EMPTY_COLUMN_ORDER,
{ parseColumnOrder,
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 []
},
},
) )
const baseColumns = useMemo<BaseColumn[]>(() => { const baseColumns = useMemo<BaseColumn[]>(() => {
+22 -16
View File
@@ -14,20 +14,18 @@ import {
Typography, Typography,
} from '@mui/material' } from '@mui/material'
import { getCurrentWebviewWindow } from '@tauri-apps/api/webviewWindow' 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 { import {
forwardRef, forwardRef,
memo, memo,
useCallback, useCallback,
useEffect,
useEffectEvent, useEffectEvent,
useMemo, useMemo,
useState, useState,
} from 'react' } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useLocalStorage } from '@/hooks/use-local-storage'
import { getIpInfo } from '@/services/api' import { getIpInfo } from '@/services/api'
import { useQuery } from '@/services/query-client' import { useQuery } from '@/services/query-client'
import getSystem from '@/utils/get-system' import getSystem from '@/utils/get-system'
@@ -72,15 +70,14 @@ const getCountryFlag = (countryCode: string | undefined) => {
return String.fromCodePoint(...codePoints) return String.fromCodePoint(...codePoints)
} }
type CountDownState = XOR< type CountDownState =
{ | {
type: 'countdown' type: 'countdown'
remainingSeconds: number remainingSeconds: number
}, }
{ | {
type: 'revalidating' type: 'revalidating'
} }
>
const IPInfoCardContainer = forwardRef<HTMLElement, React.PropsWithChildren>( const IPInfoCardContainer = forwardRef<HTMLElement, React.PropsWithChildren>(
({ children }, ref) => { ({ children }, ref) => {
@@ -114,10 +111,19 @@ export const IpInfoCard = () => {
) )
const appWindow = useMemo(() => getCurrentWebviewWindow(), []) const appWindow = useMemo(() => getCurrentWebviewWindow(), [])
const [hasIntersected, setHasIntersected] = useState(false)
// Once intersected, the card stays eligible for refresh until unmount. // Once intersected, the card stays eligible for refresh until unmount.
const [containerRef, hasIntersected, _resetIntersected] = useIntersection({ const containerRef = useCallback((element: HTMLElement | null) => {
rootMargin: '0px', 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>({ const [countdown, setCountdown] = useState<CountDownState>({
type: 'countdown', type: 'countdown',
@@ -19,10 +19,6 @@ import {
styled, styled,
} from '@mui/material' } from '@mui/material'
import { useLockFn } from 'ahooks' import { useLockFn } from 'ahooks'
import {
cancelIdleCallback,
requestIdleCallback,
} from 'foxact/request-idle-callback'
import * as yaml from 'js-yaml' import * as yaml from 'js-yaml'
import { import {
startTransition, startTransition,
@@ -350,10 +346,12 @@ export const GroupsEditorViewer = (props: Props) => {
} }
} }
const handle = requestIdleCallback(serialize) if (typeof window.requestIdleCallback === 'function') {
return () => { const handle = window.requestIdleCallback(serialize)
cancelIdleCallback(handle) return () => window.cancelIdleCallback(handle)
} }
const handle = window.setTimeout(serialize, 1)
return () => window.clearTimeout(handle)
} }
}, [prependSeq, appendSeq, deleteSeq]) }, [prependSeq, appendSeq, deleteSeq])
+50 -57
View File
@@ -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 { useProfiles } from '@/hooks/use-profiles'
import { ProxySortType } from './use-filter-sort' import { ProxySortType } from './use-filter-sort'
@@ -16,9 +17,13 @@ export interface HeadState {
testUrl: string 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 HEAD_STATE_KEY = 'proxy-head-state'
const EMPTY_STORAGE: HeadStateStorage = {}
const EMPTY_PROFILE: ProfileHeadState = {}
export const DEFAULT_STATE: HeadState = { export const DEFAULT_STATE: HeadState = {
open: false, open: false,
showType: true, showType: true,
@@ -31,77 +36,65 @@ export const DEFAULT_STATE: HeadState = {
testUrl: '', testUrl: '',
} }
type HeadStateAction = const parseStorage = (raw: string): HeadStateStorage => {
| { type: 'reset' } const value = JSON.parse(raw) as HeadStateStorage | null
| { type: 'replace'; payload: Record<string, HeadState> } return value && typeof value === 'object' && !Array.isArray(value)
| { type: 'update'; groupName: string; patch: Partial<HeadState> } ? value
: EMPTY_STORAGE
}
function headStateReducer( const getProfileState = (storage: HeadStateStorage, profile: string) => {
state: Record<string, HeadState>, const state = storage[profile]
action: HeadStateAction, return state && typeof state === 'object' && !Array.isArray(state)
): Record<string, HeadState> { ? state
switch (action.type) { : EMPTY_PROFILE
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
}
} }
export function useHeadStateNew() { export function useHeadStateNew() {
const { profiles } = useProfiles() const { profiles } = useProfiles()
const current = profiles?.current || '' const current = profiles?.current || ''
const [state, dispatch] = useReducer(headStateReducer, {}) const [storage, setStorage] = useLocalStorage(
HEAD_STATE_KEY,
useEffect(() => { EMPTY_STORAGE,
try { parseStorage,
const data = JSON.parse( )
localStorage.getItem(HEAD_STATE_KEY)!, const saved = getProfileState(storage, current)
) as HeadStateStorage // The active profile owns its live state even if persistence fails.
const [state, setState] = useState(() => ({
const value = data[current] || {} profile: { id: current, initialGroups: saved },
groups: saved,
if (value && typeof value === 'object') { }))
dispatch({ type: 'replace', payload: value }) const { profile, groups } = state
} else { if (profile.id !== current) {
dispatch({ type: 'reset' }) setState({ profile: { id: current, initialGroups: saved }, groups: saved })
} }
} catch {
dispatch({ type: 'reset' })
}
}, [current])
useEffect(() => { useEffect(() => {
if (groups === profile.initialGroups) return
const timer = setTimeout(() => { const timer = setTimeout(() => {
try { setStorage((previous) => ({
const item = localStorage.getItem(HEAD_STATE_KEY) ...previous,
[profile.id]: groups,
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 {}
}) })
return () => clearTimeout(timer) return () => clearTimeout(timer)
}, [state, current]) }, [groups, profile, setStorage])
const setHeadState = useCallback( const setHeadState = useCallback(
(groupName: string, obj: Partial<HeadState>) => { (groupName: string, patch: Partial<HeadState>) => {
dispatch({ type: 'update', groupName, patch: obj }) 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
} }
+2 -5
View File
@@ -1,4 +1,4 @@
import { useLocalStorage } from 'foxact/use-local-storage' import { useLocalStorage } from './use-local-storage'
const defaultClashLog: IClashLog = { const defaultClashLog: IClashLog = {
enable: true, enable: true,
@@ -8,7 +8,4 @@ const defaultClashLog: IClashLog = {
} }
export const useClashLog = () => export const useClashLog = () =>
useLocalStorage<IClashLog>('clash-log', defaultClashLog, { useLocalStorage<IClashLog>('clash-log', defaultClashLog)
serializer: JSON.stringify,
deserializer: JSON.parse,
})
+1 -5
View File
@@ -1,4 +1,4 @@
import { useLocalStorage } from 'foxact/use-local-storage' import { useLocalStorage } from './use-local-storage'
const defaultConnectionSetting: IConnectionSetting = { layout: 'table' } const defaultConnectionSetting: IConnectionSetting = { layout: 'table' }
@@ -6,8 +6,4 @@ export const useConnectionSetting = () =>
useLocalStorage<IConnectionSetting>( useLocalStorage<IConnectionSetting>(
'connections-setting', 'connections-setting',
defaultConnectionSetting, defaultConnectionSetting,
{
serializer: JSON.stringify,
deserializer: JSON.parse,
},
) )
+21 -20
View File
@@ -1,6 +1,5 @@
/* eslint-disable @eslint-react/set-state-in-effect */ /* eslint-disable @eslint-react/set-state-in-effect */
import { useEffect } from 'foxact/use-abortable-effect' import { useCallback, useEffect, useState } from 'react'
import { useCallback, useState } from 'react'
import { showNotice } from '@/services/notice-service' import { showNotice } from '@/services/notice-service'
@@ -42,26 +41,28 @@ export const useEditorDocument = ({ open, load }: UseEditorDocumentOptions) => {
} }
}, [applyLoadedValue, load]) }, [applyLoadedValue, load])
useEffect( useEffect(() => {
(signal) => { let cancelled = false
resetDocumentState() resetDocumentState()
if (!open) return if (!open) return
load() load()
.then((nextValue) => { .then((nextValue) => {
if (signal.aborted) return if (cancelled) return
applyLoadedValue(nextValue) applyLoadedValue(nextValue)
}) })
.catch((error) => { .catch((error) => {
if (!signal.aborted) showNotice.error(error) if (!cancelled) showNotice.error(error)
}) })
.finally(() => { .finally(() => {
if (!signal.aborted) setLoading(false) if (!cancelled) setLoading(false)
}) })
},
[applyLoadedValue, load, open, resetDocumentState], return () => {
) cancelled = true
}
}, [applyLoadedValue, load, open, resetDocumentState])
const markSaved = useCallback((nextValue: string) => { const markSaved = useCallback((nextValue: string) => {
setSavedValue(nextValue) setSavedValue(nextValue)
+148
View File
@@ -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
View File
@@ -1,7 +1,6 @@
import './assets/styles/index.scss' import './assets/styles/index.scss'
import { ResizeObserver } from '@juggle/resize-observer' import { ResizeObserver } from '@juggle/resize-observer'
import { ComposeContextProvider } from 'foxact/compose-context-provider'
import React from 'react' import React from 'react'
import { createRoot } from 'react-dom/client' import { createRoot } from 'react-dom/client'
import { RouterProvider } from 'react-router' import { RouterProvider } from 'react-router'
@@ -38,26 +37,24 @@ if (!container) {
disableWebViewShortcuts() disableWebViewShortcuts()
const initializeApp = (initialThemeMode: 'light' | 'dark') => { const initializeApp = (initialThemeMode: 'light' | 'dark') => {
const contexts = [
<ThemeModeProvider key="theme" initialState={initialThemeMode} />,
<AppStoreProvider key="app-store" />,
<UpdateStateProvider key="update" />,
]
const root = createRoot(container) const root = createRoot(container)
root.render( root.render(
<React.StrictMode> <React.StrictMode>
<ComposeContextProvider contexts={contexts}> <ThemeModeProvider initialState={initialThemeMode}>
<BaseErrorBoundary> <AppStoreProvider>
<SWRConfig value={swrConfig}> <UpdateStateProvider>
<WindowProvider> <BaseErrorBoundary>
<AppDataProvider> <SWRConfig value={swrConfig}>
<RouterProvider router={router} /> <WindowProvider>
</AppDataProvider> <AppDataProvider>
</WindowProvider> <RouterProvider router={router} />
</SWRConfig> </AppDataProvider>
</BaseErrorBoundary> </WindowProvider>
</ComposeContextProvider> </SWRConfig>
</BaseErrorBoundary>
</UpdateStateProvider>
</AppStoreProvider>
</ThemeModeProvider>
</React.StrictMode>, </React.StrictMode>,
) )
} }
+78 -62
View File
@@ -1,8 +1,5 @@
import { getName, getVersion } from '@tauri-apps/api/app' import { getName, getVersion } from '@tauri-apps/api/app'
import { fetch } from '@tauri-apps/plugin-http' 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 i18n from 'i18next'
import { getBaseConfig } from 'tauri-plugin-mihomo-api' import { getBaseConfig } from 'tauri-plugin-mihomo-api'
@@ -10,15 +7,42 @@ import { debugLog } from '@/utils/debug'
import { getRuntimeConfig } from './cmds' import { getRuntimeConfig } from './cmds'
const getUserAgentPromise = once(async () => { let userAgentPromise: Promise<string> | null = null
try { const getUserAgentPromise = () =>
const [name, version] = await Promise.all([getName(), getVersion()]) (userAgentPromise ??= Promise.all([getName(), getVersion()])
return `${name}/${version}` .then(([name, version]) => `${name}/${version}`)
} catch (error) { .catch((error) => {
console.debug('Failed to build User-Agent, fallback to default', error) console.debug('Failed to build User-Agent, fallback to default', error)
return 'clash-verge-rev' 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) // Get current IP and geolocation information (refactored IP detection with service-specific mappings)
interface IpInfo { interface IpInfo {
ip: string ip: string
@@ -249,61 +273,53 @@ export const getIpInfo = async (): Promise<
debugLog(`尝试IP检测服务: ${service.url}`) debugLog(`尝试IP检测服务: ${service.url}`)
try { try {
return await asyncRetry( return await retryWithBackoff(async (bail) => {
async (bail) => { console.debug('Fetching IP information:', service.url)
console.debug('Fetching IP information:', service.url)
const timeoutController = new AbortController() const timeoutController = new AbortController()
const timeoutId = setTimeout(() => { const timeoutId = setTimeout(() => {
timeoutController.abort() timeoutController.abort()
}, serviceTimeout) }, serviceTimeout)
try { try {
const response = await fetch(service.url, { const response = await fetch(service.url, {
method: 'GET', method: 'GET',
proxy, proxy,
signal: timeoutController.signal, signal: timeoutController.signal,
connectTimeout: serviceTimeout, connectTimeout: serviceTimeout,
headers: { headers: {
'User-Agent': userAgent, 'User-Agent': userAgent,
}, },
}) })
if (!response.ok) { if (!response.ok) {
return bail( return bail(
new Error( new Error(
`IP 检测服务出错,状态码: ${response.status} from ${service.url}`, `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)
} }
},
{ let data: any
retries: maxRetries, try {
minTimeout: 1000, data = await response.json()
maxTimeout: 4000, } catch {
randomize: true, 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) { } catch (error) {
debugLog(`IP检测服务失败: ${service.url}`, error) debugLog(`IP检测服务失败: ${service.url}`, error)
lastError = error lastError = error
+47 -14
View File
@@ -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< import noop from '@/utils/noop'
'light' | 'dark'
>()
// save update state type ThemeMode = 'light' | 'dark'
const [UpdateStateProvider, useUpdateState, useSetUpdateState] =
createContextState<boolean>(false)
export { const ThemeModeContext = createContext<ThemeMode>('light')
ThemeModeProvider, const SetThemeModeContext =
useThemeMode, createContext<Dispatch<SetStateAction<ThemeMode>>>(noop)
useSetThemeMode,
UpdateStateProvider, export const ThemeModeProvider = ({
useUpdateState, initialState,
useSetUpdateState, 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)