Compare commits

..

1 Commits

Author SHA1 Message Date
renovate[bot]
afa29c4d2a
chore(deps): update github/gh-aw-actions action to v0.67.0 2026-04-05 04:56:35 +00:00
31 changed files with 511 additions and 211 deletions

View File

@ -60,7 +60,7 @@ jobs:
title: ${{ steps.sanitized.outputs.title }}
steps:
- name: Setup Scripts
uses: github/gh-aw-actions/setup@addd8a8bc8bad66050cec907c7bf182cca4d2e69 # v0.67.1
uses: github/gh-aw-actions/setup@182c89382b76125ac25e7116e09ad0c02673b72e # v0.67.0
with:
destination: ${{ runner.temp }}/gh-aw/actions
- name: Generate agentic run info
@ -271,7 +271,7 @@ jobs:
output_types: ${{ steps.collect_output.outputs.output_types }}
steps:
- name: Setup Scripts
uses: github/gh-aw-actions/setup@addd8a8bc8bad66050cec907c7bf182cca4d2e69 # v0.67.1
uses: github/gh-aw-actions/setup@182c89382b76125ac25e7116e09ad0c02673b72e # v0.67.0
with:
destination: ${{ runner.temp }}/gh-aw/actions
- name: Set runtime paths
@ -888,7 +888,7 @@ jobs:
total_count: ${{ steps.missing_tool.outputs.total_count }}
steps:
- name: Setup Scripts
uses: github/gh-aw-actions/setup@addd8a8bc8bad66050cec907c7bf182cca4d2e69 # v0.67.1
uses: github/gh-aw-actions/setup@182c89382b76125ac25e7116e09ad0c02673b72e # v0.67.0
with:
destination: ${{ runner.temp }}/gh-aw/actions
- name: Download agent output artifact
@ -999,7 +999,7 @@ jobs:
process_safe_outputs_temporary_id_map: ${{ steps.process_safe_outputs.outputs.temporary_id_map }}
steps:
- name: Setup Scripts
uses: github/gh-aw-actions/setup@addd8a8bc8bad66050cec907c7bf182cca4d2e69 # v0.67.1
uses: github/gh-aw-actions/setup@182c89382b76125ac25e7116e09ad0c02673b72e # v0.67.0
with:
destination: ${{ runner.temp }}/gh-aw/actions
- name: Download agent output artifact

View File

@ -54,7 +54,7 @@
"@tauri-apps/plugin-http": "~2.5.7",
"@tauri-apps/plugin-process": "^2.3.1",
"@tauri-apps/plugin-shell": "2.3.5",
"@tauri-apps/plugin-updater": "2.10.1",
"@tauri-apps/plugin-updater": "2.10.0",
"ahooks": "^3.9.6",
"cidr-block": "^2.3.0",
"dayjs": "1.11.20",

10
pnpm-lock.yaml generated
View File

@ -69,8 +69,8 @@ importers:
specifier: 2.3.5
version: 2.3.5
'@tauri-apps/plugin-updater':
specifier: 2.10.1
version: 2.10.1
specifier: 2.10.0
version: 2.10.0
ahooks:
specifier: ^3.9.6
version: 3.9.7(react-dom@19.2.4(react@19.2.4))(react@19.2.4)
@ -1562,8 +1562,8 @@ packages:
'@tauri-apps/plugin-shell@2.3.5':
resolution: {integrity: sha512-jewtULhiQ7lI7+owCKAjc8tYLJr92U16bPOeAa472LHJdgaibLP83NcfAF2e+wkEcA53FxKQAZ7byDzs2eeizg==}
'@tauri-apps/plugin-updater@2.10.1':
resolution: {integrity: sha512-NFYMg+tWOZPJdzE/PpFj2qfqwAWwNS3kXrb1tm1gnBJ9mYzZ4WDRrwy8udzWoAnfGCHLuePNLY1WVCNHnh3eRA==}
'@tauri-apps/plugin-updater@2.10.0':
resolution: {integrity: sha512-ljN8jPlnT0aSn8ecYhuBib84alxfMx6Hc8vJSKMJyzGbTPFZAC44T2I1QNFZssgWKrAlofvJqCC6Rr472JWfkQ==}
'@tybys/wasm-util@0.10.1':
resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==}
@ -5059,7 +5059,7 @@ snapshots:
dependencies:
'@tauri-apps/api': 2.10.1
'@tauri-apps/plugin-updater@2.10.1':
'@tauri-apps/plugin-updater@2.10.0':
dependencies:
'@tauri-apps/api': 2.10.1

View File

@ -1,6 +1,8 @@
use super::CmdResult;
use crate::core::autostart;
use crate::core::{autostart, handle};
use crate::utils::resolve::ui::{self, UiReadyStage};
use crate::{cmd::StringifyErr as _, feat, utils::dirs};
use clash_verge_logging::{Type, logging};
use smartstring::alias::String;
use tauri::{AppHandle, Manager as _};
@ -107,3 +109,22 @@ pub async fn download_icon_cache(url: String, name: String) -> CmdResult<String>
pub async fn copy_icon_file(path: String, icon_info: feat::IconInfo) -> CmdResult<String> {
feat::copy_icon_file(path, icon_info).await
}
/// 通知UI已准备就绪
#[tauri::command]
pub async fn notify_ui_ready() {
logging!(info, Type::Cmd, "前端UI已准备就绪");
ui::mark_ui_ready();
handle::Handle::refresh_clash();
let delayed_refresh_delay = std::time::Duration::from_millis(1500);
tokio::time::sleep(delayed_refresh_delay).await;
handle::Handle::refresh_clash();
}
/// UI加载阶段
#[tauri::command]
pub fn update_ui_stage(stage: UiReadyStage) {
logging!(info, Type::Cmd, "UI加载阶段更新: {:?}", &stage);
ui::update_ui_ready_stage(stage);
}

View File

@ -3,7 +3,7 @@ use crate::{
core::{CoreManager, handle, tray},
feat::clean_async,
process::AsyncHandler,
utils,
utils::{self, resolve::reset_resolve_done},
};
use clash_verge_logging::{Type, logging};
use serde_yaml_ng::{Mapping, Value};
@ -42,6 +42,7 @@ pub async fn restart_app() {
if cleanup_result { 0 } else { 1 }
);
reset_resolve_done();
let app_handle = handle::Handle::app_handle();
app_handle.restart();
}

View File

@ -149,6 +149,8 @@ mod app_init {
cmd::start_core,
cmd::stop_core,
cmd::restart_core,
cmd::notify_ui_ready,
cmd::update_ui_stage,
cmd::get_running_mode,
cmd::get_auto_launch_status,
cmd::entry_lightweight_mode,
@ -251,6 +253,7 @@ pub fn run() {
resolve::resolve_setup_async();
resolve::resolve_setup_sync();
resolve::init_signal();
resolve::resolve_done();
logging!(info, Type::Setup, "初始化已启动");
Ok(())

View File

@ -6,7 +6,6 @@ use crate::{
config::Config,
core::{
CoreManager, Timer,
handle::Handle,
hotkey::Hotkey,
logger::Logger,
service::{SERVICE_MANAGER, ServiceManager, is_service_ipc_path_exists},
@ -23,6 +22,7 @@ use clash_verge_signal;
pub mod dns;
pub mod scheme;
pub mod ui;
pub mod window;
pub mod window_script;
@ -62,9 +62,14 @@ pub fn resolve_setup_async() {
init_system_proxy_guard().await;
});
let tray_init = async {
init_tray().await;
refresh_tray_menu().await;
};
let _ = futures::join!(
core_init,
init_tray(),
tray_init,
init_timer(),
init_hotkey(),
init_auto_lightweight_boot(),
@ -72,9 +77,7 @@ pub fn resolve_setup_async() {
init_silent_updater(),
);
Handle::refresh_clash();
refresh_tray_menu().await;
resolve_done();
});
}
@ -216,3 +219,7 @@ pub fn resolve_done() {
pub fn is_resolve_done() -> bool {
RESOLVE_DONE.load(Ordering::Acquire)
}
pub fn reset_resolve_done() {
RESOLVE_DONE.store(false, Ordering::Release);
}

View File

@ -0,0 +1,57 @@
use once_cell::sync::OnceCell;
use serde::{Deserialize, Serialize};
use std::sync::{
Arc,
atomic::{AtomicBool, AtomicU8, Ordering},
};
use tokio::sync::Notify;
use clash_verge_logging::{Type, logging};
// 获取 UI 是否准备就绪的全局状态
static UI_READY: AtomicBool = AtomicBool::new(false);
// 获取UI就绪状态细节
static UI_READY_STATE: AtomicU8 = AtomicU8::new(0);
// 添加通知机制,用于事件驱动的 UI 就绪检测
static UI_READY_NOTIFY: OnceCell<Arc<Notify>> = OnceCell::new();
// UI就绪阶段状态枚举
#[repr(u8)]
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub enum UiReadyStage {
NotStarted = 0,
Loading,
DomReady,
ResourcesLoaded,
Ready,
}
pub fn get_ui_ready() -> &'static AtomicBool {
&UI_READY
}
fn get_ui_ready_state() -> &'static AtomicU8 {
&UI_READY_STATE
}
fn get_ui_ready_notify() -> &'static Arc<Notify> {
UI_READY_NOTIFY.get_or_init(|| Arc::new(Notify::new()))
}
// 更新UI准备阶段
pub fn update_ui_ready_stage(stage: UiReadyStage) {
get_ui_ready_state().store(stage as u8, Ordering::Release);
// 如果是最终阶段标记UI完全就绪
if stage == UiReadyStage::Ready {
mark_ui_ready();
}
}
// 标记UI已准备就绪
pub fn mark_ui_ready() {
get_ui_ready().store(true, Ordering::Release);
logging!(info, Type::Window, "UI已标记为完全就绪");
// 通知所有等待的任务
get_ui_ready_notify().notify_waiters();
}

View File

@ -2,7 +2,11 @@ use dark_light::{Mode as SystemTheme, detect as detect_system_theme};
use tauri::utils::config::Color;
use tauri::{Theme, WebviewWindow};
use crate::{config::Config, core::handle, utils::resolve::window_script::build_window_initial_script};
use crate::{
config::Config,
core::handle,
utils::resolve::window_script::{INITIAL_LOADING_OVERLAY, build_window_initial_script},
};
use clash_verge_logging::{Type, logging_error};
const DARK_BACKGROUND_COLOR: Color = Color(46, 48, 61, 255); // #2E303D
@ -78,6 +82,7 @@ pub async fn build_new_window() -> Result<WebviewWindow, String> {
match builder.build() {
Ok(window) => {
logging_error!(Type::Window, window.set_background_color(Some(background_color)));
logging_error!(Type::Window, window.eval(INITIAL_LOADING_OVERLAY));
Ok(window)
}
Err(e) => Err(e.to_string()),

View File

@ -91,3 +91,11 @@ pub const WINDOW_INITIAL_SCRIPT: &str = r##"
console.log('[Tauri] ');
"##;
pub const INITIAL_LOADING_OVERLAY: &str = r"
const overlay = document.getElementById('initial-loading-overlay');
if (overlay) {
overlay.style.opacity = '0';
setTimeout(() => overlay.remove(), 300);
}
";

View File

@ -129,7 +129,7 @@ impl WindowManager {
logging!(info, Type::Window, "窗口不存在,创建新窗口");
if Self::create_window(true).await {
logging!(info, Type::Window, "窗口创建成功");
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
std::thread::sleep(std::time::Duration::from_millis(50));
WindowOperationResult::Created
} else {
logging!(warn, Type::Window, "窗口创建失败");
@ -285,31 +285,31 @@ impl WindowManager {
}
/// 创建新窗口,防抖避免重复调用
/// 窗口创建后保持隐藏,由前端 index.html 在 overlay 渲染后调用 show避免主题闪烁
pub fn create_window(should_create: bool) -> Pin<Box<dyn Future<Output = bool> + Send>> {
pub fn create_window(is_show: bool) -> Pin<Box<dyn Future<Output = bool> + Send>> {
Box::pin(async move {
logging!(info, Type::Window, "开始创建主窗口, should_create={}", should_create);
logging!(info, Type::Window, "开始创建/显示主窗口, is_show={}", is_show);
if !should_create {
if !is_show {
return false;
}
match build_new_window().await {
Ok(_) => {
logging!(info, Type::Window, "新窗口创建成功,等待前端渲染后显示");
#[cfg(target_os = "macos")]
{
handle::Handle::global().set_activation_policy_regular();
}
true
let window = match build_new_window().await {
Ok(window) => {
logging!(info, Type::Window, "新窗口创建成功");
window
}
Err(e) => {
logging!(error, Type::Window, "新窗口创建失败: {}", e);
false
return false;
}
};
// 直接激活刚创建的窗口,避免因防抖导致首次显示被跳过
if WindowOperationResult::Failed == Self::activate_window(&window) {
return false;
}
true
})
}

View File

@ -41,7 +41,7 @@ const MODE_META: Record<
export const ClashModeCard = () => {
const { t } = useTranslation()
const { verge } = useVerge()
const { clashConfig, isCoreDataPending, refreshClashConfig } = useAppData()
const { clashConfig, refreshClashConfig } = useAppData()
// 支持的模式列表
const modeList = CLASH_MODES
@ -57,11 +57,8 @@ export const ClashModeCard = () => {
if (currentModeKey) {
return t(MODE_META[currentModeKey].description)
}
if (isCoreDataPending) {
return '\u00A0'
}
return t('home.components.clashMode.errors.communication')
}, [currentModeKey, isCoreDataPending, t])
}, [currentModeKey, t])
// 模式图标映射
const modeIcons = useMemo(

View File

@ -105,8 +105,7 @@ export const CurrentProxyCard = () => {
const { t } = useTranslation()
const navigate = useNavigate()
const theme = useTheme()
const { proxies, clashConfig, isCoreDataPending, refreshProxy, rules } =
useAppData()
const { proxies, clashConfig, refreshProxy, rules } = useAppData()
const { verge } = useVerge()
const { current: currentProfile } = useProfiles()
const autoDelayEnabled = verge?.enable_auto_delay_detection ?? false
@ -445,12 +444,6 @@ export const CurrentProxyCard = () => {
[setState],
)
useEffect(() => {
return () => {
if (timeoutRef.current) clearTimeout(timeoutRef.current)
}
}, [])
// 处理代理组变更
const handleGroupChange = useCallback(
(event: SelectChangeEvent<string>) => {
@ -912,9 +905,7 @@ export const CurrentProxyCard = () => {
</Box>
}
>
{isCoreDataPending ? (
<Box sx={{ py: 4 }} />
) : currentProxy ? (
{currentProxy ? (
<Box>
{/* 代理节点信息显示 */}
<Box

View File

@ -425,7 +425,7 @@ function useIPInfo() {
queryKey: [IP_INFO_CACHE_KEY],
queryFn: getIpInfo,
staleTime: Infinity,
gcTime: 60 * 60 * 1000,
gcTime: Infinity,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: 1,

View File

@ -168,13 +168,6 @@ export const EditorViewer = ({
}
}, [open, syncMaximizedState])
useEffect(() => {
return () => {
editorRef.current?.dispose()
editorRef.current = null
}
}, [])
return (
<Dialog
open={open}

View File

@ -34,13 +34,11 @@ import {
requestIdleCallback,
} from 'foxact/request-idle-callback'
import yaml from 'js-yaml'
import type { editor } from 'monaco-editor'
import {
startTransition,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import { Controller, useForm } from 'react-hook-form'
@ -151,7 +149,6 @@ export const GroupsEditorViewer = (props: Props) => {
[t],
)
const themeMode = useThemeMode()
const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null)
const [prevData, setPrevData] = useState('')
const [currData, setCurrData] = useState('')
const [visualization, setVisualization] = useState(true)
@ -484,13 +481,6 @@ export const GroupsEditorViewer = (props: Props) => {
getInterfaceNameList()
}, [fetchContent, fetchProfile, getInterfaceNameList, open])
useEffect(() => {
return () => {
editorRef.current?.dispose()
editorRef.current = null
}
}, [])
const validateGroup = () => {
const group = formIns.getValues()
if (group.name === '') {
@ -1115,9 +1105,6 @@ export const GroupsEditorViewer = (props: Props) => {
language="yaml"
value={currData}
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
onMount={(editorInstance) => {
editorRef.current = editorInstance
}}
options={{
tabSize: 2, // 根据语言类型设置缩进大小
minimap: {

View File

@ -19,7 +19,7 @@ import {
import { open } from '@tauri-apps/plugin-shell'
import { useLockFn } from 'ahooks'
import dayjs from 'dayjs'
import { useCallback, useEffect, useReducer, useRef, useState } from 'react'
import { useCallback, useEffect, useReducer, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { ConfirmViewer } from '@/components/profile/confirm-viewer'
@ -96,11 +96,7 @@ export const ProfileItem = (props: Props) => {
// 新增状态:是否显示下次更新时间
const [showNextUpdate, setShowNextUpdate] = useState(false)
const showNextUpdateRef = useRef(false)
const [nextUpdateTime, setNextUpdateTime] = useState('')
const refreshTimeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(
undefined,
)
const { uid, name = 'Profile', extra, updated = 0, option } = itemData
@ -182,10 +178,6 @@ export const ProfileItem = (props: Props) => {
setShowNextUpdate(!showNextUpdate)
}
useEffect(() => {
showNextUpdateRef.current = showNextUpdate
}, [showNextUpdate])
// 当组件加载或更新间隔变化时更新下次更新时间
useEffect(() => {
if (showNextUpdate) {
@ -200,18 +192,19 @@ export const ProfileItem = (props: Props) => {
// 订阅定时器更新事件
useEffect(() => {
let refreshTimeout: number | undefined
// 处理定时器更新事件 - 这个事件专门用于通知定时器变更
const handleTimerUpdate = (event: Event) => {
const source = event as CustomEvent<string> & { payload?: string }
const updatedUid = source.detail ?? source.payload
// 只有当更新的是当前配置时才刷新显示
if (updatedUid === itemData.uid && showNextUpdateRef.current) {
if (updatedUid === itemData.uid && showNextUpdate) {
debugLog(`收到定时器更新事件: uid=${updatedUid}`)
if (refreshTimeoutRef.current !== undefined) {
clearTimeout(refreshTimeoutRef.current)
if (refreshTimeout !== undefined) {
clearTimeout(refreshTimeout)
}
refreshTimeoutRef.current = window.setTimeout(() => {
refreshTimeout = window.setTimeout(() => {
fetchNextUpdateTime(true)
}, 1000)
}
@ -221,13 +214,13 @@ export const ProfileItem = (props: Props) => {
window.addEventListener('verge://timer-updated', handleTimerUpdate)
return () => {
if (refreshTimeoutRef.current !== undefined) {
clearTimeout(refreshTimeoutRef.current)
if (refreshTimeout !== undefined) {
clearTimeout(refreshTimeout)
}
// 清理事件监听
window.removeEventListener('verge://timer-updated', handleTimerUpdate)
}
}, [fetchNextUpdateTime, itemData.uid])
}, [fetchNextUpdateTime, itemData.uid, showNextUpdate])
// local file mode
// remote file mode

View File

@ -27,13 +27,11 @@ import {
} from '@mui/material'
import { useLockFn } from 'ahooks'
import yaml from 'js-yaml'
import type { editor } from 'monaco-editor'
import {
startTransition,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
@ -58,7 +56,6 @@ export const ProxiesEditorViewer = (props: Props) => {
const { profileUid, property, open, onClose, onSave } = props
const { t } = useTranslation()
const themeMode = useThemeMode()
const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null)
const [prevData, setPrevData] = useState('')
const [currData, setCurrData] = useState('')
const [visualization, setVisualization] = useState(true)
@ -346,13 +343,6 @@ export const ProxiesEditorViewer = (props: Props) => {
fetchProfile()
}, [fetchContent, fetchProfile, open])
useEffect(() => {
return () => {
editorRef.current?.dispose()
editorRef.current = null
}
}, [])
const handleSave = useLockFn(async () => {
try {
await saveProfileFile(property, currData)
@ -479,9 +469,6 @@ export const ProxiesEditorViewer = (props: Props) => {
language="yaml"
value={currData}
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
onMount={(editorInstance) => {
editorRef.current = editorInstance
}}
options={{
tabSize: 2, // 根据语言类型设置缩进大小
minimap: {

View File

@ -29,13 +29,11 @@ import {
} from '@mui/material'
import { useLockFn } from 'ahooks'
import yaml from 'js-yaml'
import type { editor } from 'monaco-editor'
import {
startTransition,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react'
import { useTranslation } from 'react-i18next'
@ -253,8 +251,6 @@ export const RulesEditorViewer = (props: Props) => {
const { t } = useTranslation()
const themeMode = useThemeMode()
const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null)
const [prevData, setPrevData] = useState('')
const [currData, setCurrData] = useState('')
const [visualization, setVisualization] = useState(true)
@ -540,13 +536,6 @@ export const RulesEditorViewer = (props: Props) => {
fetchProfile()
}, [fetchContent, fetchProfile, open])
useEffect(() => {
return () => {
editorRef.current?.dispose()
editorRef.current = null
}
}, [])
const validateRule = () => {
if ((ruleType.required ?? true) && !ruleContent) {
throw new Error(
@ -781,9 +770,6 @@ export const RulesEditorViewer = (props: Props) => {
language="yaml"
value={currData}
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
onMount={(editorInstance) => {
editorRef.current = editorInstance
}}
options={{
tabSize: 2, // 根据语言类型设置缩进大小
minimap: {

View File

@ -16,7 +16,6 @@ import {
import { invoke } from '@tauri-apps/api/core'
import { useLockFn } from 'ahooks'
import yaml from 'js-yaml'
import type { editor } from 'monaco-editor'
import type { Ref } from 'react'
import {
useCallback,
@ -190,7 +189,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
const [open, setOpen] = useState(false)
const [visualization, setVisualization] = useState(true)
const skipYamlSyncRef = useRef(false)
const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null)
const [values, setValues] = useState<{
enable: boolean
listen: string
@ -455,13 +453,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
}
}, [visualization])
useEffect(() => {
return () => {
editorRef.current?.dispose()
editorRef.current = null
}
}, [])
const initDnsConfig = useCallback(async () => {
try {
const dnsConfigExists = await invoke<boolean>(
@ -1066,9 +1057,6 @@ export function DnsViewer({ ref }: { ref?: Ref<DialogRef> }) {
value={yamlContent}
theme={themeMode === 'light' ? 'light' : 'vs-dark'}
className="flex-grow"
onMount={(editorInstance) => {
editorRef.current = editorInstance
}}
options={{
tabSize: 2,
minimap: {

View File

@ -42,7 +42,7 @@ export const useIconCache = ({
refetchOnWindowFocus: false,
refetchOnReconnect: false,
staleTime: Infinity,
gcTime: 30 * 60 * 1000,
gcTime: Infinity,
retry: 2,
})

View File

@ -93,7 +93,7 @@ export const useMihomoWsSubscription = <T>(
subscriptionCacheKey ?? '$sub$__disabled__',
]) ?? fallbackData,
staleTime: Infinity,
gcTime: 30_000,
gcTime: Infinity,
enabled: subscriptionCacheKey !== null,
})
@ -243,11 +243,8 @@ export const useMihomoWsSubscription = <T>(
}, [subscriptionCacheKey])
const refresh = useCallback(() => {
if (subscriptionCacheKey) {
queryClient.removeQueries({ queryKey: [subscriptionCacheKey] })
}
setDate(Date.now())
}, [queryClient, subscriptionCacheKey, setDate])
}, [setDate])
return { response, refresh, subscriptionCacheKey, wsRef }
}

View File

@ -11,15 +11,27 @@
<title>Clash Verge</title>
<style>
:root {
--bg-color: #f5f5f5;
--text-color: #333;
--initial-bg: #f5f5f5;
--initial-text: #333;
--initial-spinner-track: #e3e3e3;
--initial-spinner-top: #3498db;
--bg-color: var(--initial-bg);
--text-color: var(--initial-text);
--spinner-track: var(--initial-spinner-track);
--spinner-top: var(--initial-spinner-top);
color-scheme: light;
}
@media (prefers-color-scheme: dark) {
:root {
--bg-color: #2e303d;
--text-color: #ffffff;
--initial-bg: #2e303d;
--initial-text: #ffffff;
--initial-spinner-track: #3a3a3a;
--initial-spinner-top: #0a84ff;
--bg-color: var(--initial-bg);
--text-color: var(--initial-text);
--spinner-track: var(--initial-spinner-track);
--spinner-top: var(--initial-spinner-top);
color-scheme: dark;
}
}
@ -41,28 +53,48 @@
position: fixed;
inset: 0;
background: var(--bg-color);
color: var(--text-color);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
z-index: 9999;
transition: opacity 0.2s ease-out;
font-family:
-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
transition: opacity 0.3s ease;
}
#initial-loading-overlay[data-hidden='true'] {
opacity: 0;
pointer-events: none;
}
.initial-spinner {
width: 40px;
height: 40px;
border: 3px solid var(--spinner-track);
border-top: 3px solid var(--spinner-top);
border-radius: 50%;
animation: initial-spin 1s linear infinite;
}
@keyframes initial-spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<div id="initial-loading-overlay"></div>
<script>
if (window.__TAURI_INTERNALS__) {
window.__TAURI_INTERNALS__
.invoke('plugin:window|show', { label: 'main' })
.catch(function () {});
window.__TAURI_INTERNALS__
.invoke('plugin:window|set_focus', { label: 'main' })
.catch(function () {});
}
</script>
<div id="initial-loading-overlay">
<div class="initial-spinner"></div>
<div style="font-size: 14px; opacity: 0.7; margin-top: 20px">
Loading Clash Verge...
</div>
</div>
<div id="root"></div>
<script type="module" src="./main.tsx"></script>
</body>

View File

@ -44,6 +44,7 @@ import { useThemeMode } from '@/services/states'
import getSystem from '@/utils/get-system'
import {
useAppInitialization,
useCustomTheme,
useLayoutEvents,
useLoadingOverlay,
@ -216,6 +217,7 @@ const Layout = () => {
)
useLoadingOverlay(themeReady)
useAppInitialization()
const handleNotice = useCallback(
(payload: [string, string]) => {

View File

@ -1,3 +1,4 @@
export { useAppInitialization } from './use-app-initialization'
export { useLayoutEvents } from './use-layout-events'
export { useLoadingOverlay } from './use-loading-overlay'
export { useNavMenuOrder } from './use-nav-menu-order'

View File

@ -0,0 +1,112 @@
import { invoke } from '@tauri-apps/api/core'
import { useEffect, useRef } from 'react'
import { hideInitialOverlay } from '../utils'
export const useAppInitialization = () => {
const initRef = useRef(false)
useEffect(() => {
if (initRef.current) return
initRef.current = true
let isInitialized = false
let isCancelled = false
const timers = new Set<number>()
const scheduleTimeout = (handler: () => void, delay: number) => {
if (isCancelled) return -1
const id = window.setTimeout(() => {
if (!isCancelled) {
handler()
}
timers.delete(id)
}, delay)
timers.add(id)
return id
}
const notifyBackend = async (stage?: string) => {
if (isCancelled) return
try {
if (stage) {
await invoke('update_ui_stage', { stage })
} else {
await invoke('notify_ui_ready')
}
} catch (err) {
console.error(`[Initialization] Failed to notify backend:`, err)
}
}
const removeLoadingOverlay = () => {
hideInitialOverlay({ schedule: scheduleTimeout })
}
const performInitialization = async () => {
if (isCancelled || isInitialized) return
isInitialized = true
try {
removeLoadingOverlay()
await notifyBackend('Loading')
await new Promise<void>((resolve) => {
const check = () => {
const root = document.getElementById('root')
if (root && root.children.length > 0) {
resolve()
} else {
scheduleTimeout(check, 50)
}
}
check()
scheduleTimeout(resolve, 2000)
})
await notifyBackend('DomReady')
await new Promise((resolve) => requestAnimationFrame(resolve))
await notifyBackend('ResourcesLoaded')
await notifyBackend()
} catch (error) {
if (!isCancelled) {
console.error('[Initialization] Failed:', error)
removeLoadingOverlay()
notifyBackend().catch(console.error)
}
}
}
const checkBackendReady = async () => {
try {
if (isCancelled) return
await invoke('update_ui_stage', { stage: 'Loading' })
performInitialization()
} catch {
scheduleTimeout(performInitialization, 1500)
}
}
scheduleTimeout(checkBackendReady, 100)
scheduleTimeout(() => {
if (!isInitialized) {
removeLoadingOverlay()
notifyBackend().catch(console.error)
}
}, 5000)
return () => {
isCancelled = true
timers.forEach((id) => {
try {
window.clearTimeout(id)
} catch (error) {
console.warn('[Initialization] Failed to clear timer:', error)
}
})
timers.clear()
}
}, [])
}

View File

@ -309,22 +309,20 @@ export const useCustomTheme = () => {
styleElement.innerHTML = effectiveInjectedCss + globalStyles
}
return muiTheme
}, [mode, theme_setting, userBackgroundImage, hasUserBackground])
useEffect(() => {
const id = setTimeout(() => {
const { palette } = muiTheme
setTimeout(() => {
const dom = document.querySelector('#Gradient2')
if (dom) {
dom.innerHTML = `
<stop offset="0%" stop-color="${theme.palette.primary.main}" />
<stop offset="80%" stop-color="${theme.palette.primary.dark}" />
<stop offset="100%" stop-color="${theme.palette.primary.dark}" />
<stop offset="0%" stop-color="${palette.primary.main}" />
<stop offset="80%" stop-color="${palette.primary.dark}" />
<stop offset="100%" stop-color="${palette.primary.dark}" />
`
}
}, 0)
return () => clearTimeout(id)
}, [theme.palette.primary.main, theme.palette.primary.dark])
return muiTheme
}, [mode, theme_setting, userBackgroundImage, hasUserBackground])
return { theme }
}

View File

@ -3,15 +3,46 @@ import { useEffect, useRef } from 'react'
import { hideInitialOverlay } from '../utils'
export const useLoadingOverlay = (themeReady: boolean) => {
const doneRef = useRef(false)
const overlayRemovedRef = useRef(false)
useEffect(() => {
if (!themeReady || doneRef.current) return
doneRef.current = true
if (!themeReady || overlayRemovedRef.current) return
let removalTimer: number | undefined
let retryTimer: number | undefined
let attempts = 0
const maxAttempts = 50
let stopped = false
const tryRemoveOverlay = () => {
if (stopped || overlayRemovedRef.current) return
const { removed, removalTimer: timerId } = hideInitialOverlay({
assumeMissingAsRemoved: true,
})
if (typeof timerId === 'number') {
removalTimer = timerId
}
if (removed) {
overlayRemovedRef.current = true
return
}
if (attempts < maxAttempts) {
attempts += 1
retryTimer = window.setTimeout(tryRemoveOverlay, 100)
} else {
console.warn('[Loading Overlay] Element not found')
}
}
tryRemoveOverlay()
const timer = hideInitialOverlay()
return () => {
if (timer !== undefined) window.clearTimeout(timer)
stopped = true
if (typeof removalTimer === 'number') window.clearTimeout(removalTimer)
if (typeof retryTimer === 'number') window.clearTimeout(retryTimer)
}
}, [themeReady])
}

View File

@ -1,17 +1,45 @@
let removed = false
const OVERLAY_ID = 'initial-loading-overlay'
const REMOVE_DELAY = 300
export const hideInitialOverlay = (): number | undefined => {
if (removed) return undefined
let overlayRemoved = false
const overlay = document.getElementById('initial-loading-overlay')
if (!overlay) {
removed = true
return undefined
type HideOverlayOptions = {
schedule?: (handler: () => void, delay: number) => number
assumeMissingAsRemoved?: boolean
}
type HideOverlayResult = {
removed: boolean
removalTimer?: number
}
export const hideInitialOverlay = (
options: HideOverlayOptions = {},
): HideOverlayResult => {
if (overlayRemoved) {
return { removed: true }
}
removed = true
const overlay = document.getElementById(OVERLAY_ID)
if (!overlay) {
if (options.assumeMissingAsRemoved) {
overlayRemoved = true
return { removed: true }
}
return { removed: false }
}
overlayRemoved = true
overlay.dataset.hidden = 'true'
const timer = window.setTimeout(() => overlay.remove(), 200)
return timer
const schedule = options.schedule ?? window.setTimeout
const removalTimer = schedule(() => {
try {
overlay.remove()
} catch (error) {
console.warn('[Loading Overlay] Removal failed:', error)
}
}, REMOVE_DELAY)
return { removed: true, removalTimer }
}

View File

@ -16,7 +16,6 @@ export interface AppDataContextType {
proxyProviders: Record<string, ProxyProvider>
ruleProviders: Record<string, RuleProvider>
systemProxyAddress: string
isCoreDataPending: boolean
refreshProxy: () => Promise<any>
refreshClashConfig: () => Promise<any>

View File

@ -1,6 +1,6 @@
import { useQuery } from '@tanstack/react-query'
import { listen } from '@tauri-apps/api/event'
import React, { useCallback, useEffect, useMemo, useRef } from 'react'
import React, { useCallback, useEffect, useMemo } from 'react'
import {
getBaseConfig,
getRuleProviders,
@ -23,7 +23,7 @@ const TQ_MIHOMO = {
refetchOnReconnect: false,
staleTime: 1500,
retry: 3,
retryDelay: (attempt: number) => Math.min(200 * 2 ** attempt, 3000),
retryDelay: 2000,
} as const
const TQ_DEFAULTS = {
@ -41,21 +41,13 @@ export const AppDataProvider = ({
}) => {
const { verge } = useVerge()
const {
data: proxiesData,
isPending: isProxiesPending,
refetch: refreshProxy,
} = useQuery({
const { data: proxiesData, refetch: refreshProxy } = useQuery({
queryKey: ['getProxies'],
queryFn: calcuProxies,
...TQ_MIHOMO,
})
const {
data: clashConfig,
isPending: isClashConfigPending,
refetch: refreshClashConfig,
} = useQuery({
const { data: clashConfig, refetch: refreshClashConfig } = useQuery({
queryKey: ['getClashConfig'],
queryFn: getBaseConfig,
...TQ_MIHOMO,
@ -79,45 +71,106 @@ export const AppDataProvider = ({
...TQ_MIHOMO,
})
const refreshProxyRef = useRef(refreshProxy)
const refreshRulesRef = useRef(refreshRules)
const refreshRuleProvidersRef = useRef(refreshRuleProviders)
useEffect(() => {
refreshProxyRef.current = refreshProxy
}, [refreshProxy])
useEffect(() => {
refreshRulesRef.current = refreshRules
}, [refreshRules])
useEffect(() => {
refreshRuleProvidersRef.current = refreshRuleProviders
}, [refreshRuleProviders])
useEffect(() => {
let lastProfileId: string | null = null
let lastUpdateTime = 0
const refreshThrottle = 800
let isUnmounted = false
const scheduledTimeouts = new Set<number>()
const cleanupFns: Array<() => void> = []
const registerCleanup = (fn: () => void) => {
if (isUnmounted) {
try {
fn()
} catch (error) {
console.error('[DataProvider] Immediate cleanup failed:', error)
}
} else {
cleanupFns.push(fn)
}
}
const addWindowListener = (eventName: string, handler: EventListener) => {
// eslint-disable-next-line @eslint-react/web-api-no-leaked-event-listener
window.addEventListener(eventName, handler)
return () => window.removeEventListener(eventName, handler)
}
const scheduleTimeout = (
callback: () => void | Promise<void>,
delay: number,
) => {
if (isUnmounted) return -1
const timeoutId = window.setTimeout(() => {
scheduledTimeouts.delete(timeoutId)
if (!isUnmounted) {
void callback()
}
}, delay)
scheduledTimeouts.add(timeoutId)
return timeoutId
}
const clearAllTimeouts = () => {
scheduledTimeouts.forEach((timeoutId) => clearTimeout(timeoutId))
scheduledTimeouts.clear()
}
const handleProfileChanged = (event: { payload: string }) => {
const newProfileId = event.payload
const now = Date.now()
if (
lastProfileId === newProfileId &&
now - lastUpdateTime < refreshThrottle
) {
return
}
lastProfileId = newProfileId
lastUpdateTime = now
refreshRulesRef.current().catch(() => {})
refreshRuleProvidersRef.current().catch(() => {})
scheduleTimeout(() => {
refreshRules().catch((error) =>
console.warn('[DataProvider] Rules refresh failed:', error),
)
refreshRuleProviders().catch((error) =>
console.warn('[DataProvider] Rule providers refresh failed:', error),
)
}, 200)
}
const handleRefreshClash = () => {
const now = Date.now()
if (now - lastUpdateTime <= refreshThrottle) return
lastUpdateTime = now
scheduleTimeout(async () => {
await Promise.all([
refreshProxy().catch((error) =>
console.error('[DataProvider] Proxy refresh failed:', error),
),
refreshClashConfig().catch((error) =>
console.error('[DataProvider] Clash config refresh failed:', error),
),
])
}, 200)
}
const handleRefreshProxy = () => {
const now = Date.now()
if (now - lastUpdateTime <= refreshThrottle) return
lastUpdateTime = now
refreshProxyRef.current().catch(() => {})
scheduleTimeout(() => {
refreshProxy().catch((error) =>
console.warn('[DataProvider] Proxy refresh failed:', error),
)
}, 200)
}
const initializeListeners = async () => {
@ -126,34 +179,62 @@ export const AppDataProvider = ({
'profile-changed',
handleProfileChanged,
)
cleanupFns.push(unlistenProfile)
registerCleanup(unlistenProfile)
} catch (error) {
console.error('[AppDataProvider] 监听 Profile 事件失败:', error)
}
try {
const unlistenClash = await listen(
'verge://refresh-clash-config',
handleRefreshClash,
)
const unlistenProxy = await listen(
'verge://refresh-proxy-config',
handleRefreshProxy,
)
cleanupFns.push(unlistenProxy)
registerCleanup(() => {
unlistenClash()
unlistenProxy()
})
} catch (error) {
console.warn('[AppDataProvider] 设置 Tauri 事件监听器失败:', error)
const fallbackHandlers: Array<[string, EventListener]> = [
['verge://refresh-clash-config', handleRefreshClash],
['verge://refresh-proxy-config', handleRefreshProxy],
]
fallbackHandlers.forEach(([eventName, handler]) => {
registerCleanup(addWindowListener(eventName, handler))
})
}
}
void initializeListeners()
return () => {
cleanupFns.forEach((fn) => {
isUnmounted = true
clearAllTimeouts()
const errors: Error[] = []
cleanupFns.splice(0).forEach((fn) => {
try {
fn()
} catch (error) {
console.error('[DataProvider] Cleanup error:', error)
errors.push(error instanceof Error ? error : new Error(String(error)))
}
})
if (errors.length > 0) {
console.error(
`[DataProvider] ${errors.length} errors during cleanup:`,
errors,
)
}
}
}, [])
}, [refreshProxy, refreshClashConfig, refreshRules, refreshRuleProviders])
const { data: sysproxy, refetch: refreshSysproxy } = useQuery({
queryKey: ['getSystemProxy'],
@ -242,9 +323,6 @@ export const AppDataProvider = ({
systemProxyAddress: calculateSystemProxyAddress(),
// core 数据加载状态
isCoreDataPending: isProxiesPending || isClashConfigPending,
// 刷新方法
refreshProxy,
refreshClashConfig,
@ -257,8 +335,6 @@ export const AppDataProvider = ({
}, [
proxiesData,
clashConfig,
isProxiesPending,
isClashConfigPending,
rulesData,
sysproxy,
runningMode,