6
.github/FUNDING.yml
vendored
6
.github/FUNDING.yml
vendored
@@ -1 +1,5 @@
|
||||
custom: ['https://t.me/tribute/app?startapp=dtfk','https://t.me/tribute/app?startapp=dtLE']
|
||||
custom:
|
||||
[
|
||||
"https://t.me/tribute/app?startapp=dtfk",
|
||||
"https://t.me/tribute/app?startapp=dtLE",
|
||||
]
|
||||
|
||||
3
.github/workflows/autobuild.yml
vendored
3
.github/workflows/autobuild.yml
vendored
@@ -193,6 +193,9 @@ jobs:
|
||||
- os: ubuntu-22.04
|
||||
target: x86_64-unknown-linux-gnu
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
CARGO_NET_RETRY: "5"
|
||||
CARGO_HTTP_CHECK_REVOKE: "false"
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
3
.github/workflows/clippy.yml
vendored
3
.github/workflows/clippy.yml
vendored
@@ -17,6 +17,9 @@ jobs:
|
||||
target: x86_64-unknown-linux-gnu
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
CARGO_NET_RETRY: "5"
|
||||
CARGO_HTTP_CHECK_REVOKE: "false"
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
3
.github/workflows/dev.yml
vendored
3
.github/workflows/dev.yml
vendored
@@ -28,6 +28,9 @@ jobs:
|
||||
bundle: dmg
|
||||
|
||||
runs-on: ${{ matrix.os }}
|
||||
env:
|
||||
CARGO_NET_RETRY: "5"
|
||||
CARGO_HTTP_CHECK_REVOKE: "false"
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
3
.github/workflows/fmt.yml
vendored
3
.github/workflows/fmt.yml
vendored
@@ -10,6 +10,9 @@ on:
|
||||
jobs:
|
||||
rustfmt:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
CARGO_NET_RETRY: "5"
|
||||
CARGO_HTTP_CHECK_REVOKE: "false"
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
1
.github/workflows/release.yml
vendored
1
.github/workflows/release.yml
vendored
@@ -603,4 +603,3 @@ jobs:
|
||||
token: ${{ secrets.TELEGRAM_TOKEN }}
|
||||
message_file: release.txt
|
||||
format: markdown
|
||||
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -10,3 +10,4 @@ scripts/_env.sh
|
||||
.tool-versions
|
||||
.idea
|
||||
.old
|
||||
bun.lock
|
||||
@@ -27,7 +27,6 @@
|
||||
- corrected side menu in compressed window
|
||||
- added check at the main toggle switch, now it cannot be enabled if there are no profiles.
|
||||
|
||||
|
||||
## v0.2.1
|
||||
|
||||
- added headers "announce-url", "update-always"
|
||||
|
||||
@@ -1,19 +1,21 @@
|
||||
import * as React from "react"
|
||||
import * as React from "react";
|
||||
|
||||
const MOBILE_BREAKPOINT = 768
|
||||
const MOBILE_BREAKPOINT = 768;
|
||||
|
||||
export function useIsMobile() {
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
|
||||
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
|
||||
undefined,
|
||||
);
|
||||
|
||||
React.useEffect(() => {
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
|
||||
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
|
||||
const onChange = () => {
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
}
|
||||
mql.addEventListener("change", onChange)
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
|
||||
return () => mql.removeEventListener("change", onChange)
|
||||
}, [])
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
};
|
||||
mql.addEventListener("change", onChange);
|
||||
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
|
||||
return () => mql.removeEventListener("change", onChange);
|
||||
}, []);
|
||||
|
||||
return !!isMobile
|
||||
return !!isMobile;
|
||||
}
|
||||
|
||||
17
src-tauri/Cargo.lock
generated
17
src-tauri/Cargo.lock
generated
@@ -256,6 +256,22 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-compression"
|
||||
version = "0.4.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddb939d66e4ae03cee6091612804ba446b12878410cfa17f785f4dd67d4014e8"
|
||||
dependencies = [
|
||||
"brotli",
|
||||
"flate2",
|
||||
"futures-core",
|
||||
"memchr",
|
||||
"pin-project-lite",
|
||||
"tokio",
|
||||
"zstd",
|
||||
"zstd-safe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-executor"
|
||||
version = "1.13.2"
|
||||
@@ -5853,6 +5869,7 @@ version = "0.12.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eabf4c97d9130e2bf606614eb937e86edac8292eaa6f422f995d7e8de1eb1813"
|
||||
dependencies = [
|
||||
"async-compression",
|
||||
"base64 0.22.1",
|
||||
"bytes",
|
||||
"cookie",
|
||||
|
||||
@@ -45,7 +45,7 @@ tokio = { version = "1.45.1", features = [
|
||||
"sync",
|
||||
] }
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
reqwest = { version = "0.12.20", features = ["json", "rustls-tls", "cookies"] }
|
||||
reqwest = { version = "0.12.20", features = ["json", "rustls-tls", "cookies", "brotli", "gzip", "zstd"] }
|
||||
regex = "1.11.1"
|
||||
sysproxy = { git = "https://github.com/clash-verge-rev/sysproxy-rs" }
|
||||
image = "0.25.6"
|
||||
|
||||
@@ -147,7 +147,7 @@ pub async fn download_icon_cache(url: String, name: String) -> CmdResult<String>
|
||||
Ok(icon_path.to_string_lossy().to_string())
|
||||
} else {
|
||||
let _ = std::fs::remove_file(&temp_path);
|
||||
Err(format!("下载的内容不是有效图片: {url}"))
|
||||
Err(format!("Downloaded content is not a valid image: {url}"))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -209,7 +209,7 @@ pub fn copy_icon_file(path: String, icon_info: IconInfo) -> CmdResult<String> {
|
||||
/// 通知UI已准备就绪
|
||||
#[tauri::command]
|
||||
pub fn notify_ui_ready() -> CmdResult<()> {
|
||||
log::info!(target: "app", "前端UI已准备就绪");
|
||||
log::info!(target: "app", "Frontend UI is ready");
|
||||
crate::utils::resolve::mark_ui_ready();
|
||||
Ok(())
|
||||
}
|
||||
@@ -217,7 +217,7 @@ pub fn notify_ui_ready() -> CmdResult<()> {
|
||||
/// UI加载阶段
|
||||
#[tauri::command]
|
||||
pub fn update_ui_stage(stage: String) -> CmdResult<()> {
|
||||
log::info!(target: "app", "UI加载阶段更新: {stage}");
|
||||
log::info!(target: "app", "UI loading stage updated: {stage}");
|
||||
|
||||
use crate::utils::resolve::UiReadyStage;
|
||||
|
||||
@@ -228,8 +228,8 @@ pub fn update_ui_stage(stage: String) -> CmdResult<()> {
|
||||
"ResourcesLoaded" => UiReadyStage::ResourcesLoaded,
|
||||
"Ready" => UiReadyStage::Ready,
|
||||
_ => {
|
||||
log::warn!(target: "app", "未知的UI加载阶段: {stage}");
|
||||
return Err(format!("未知的UI加载阶段: {stage}"));
|
||||
log::warn!(target: "app", "Unknown UI loading stage: {stage}");
|
||||
return Err(format!("Unknown UI loading stage: {stage}"));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -240,7 +240,7 @@ pub fn update_ui_stage(stage: String) -> CmdResult<()> {
|
||||
/// 重置UI就绪状态
|
||||
#[tauri::command]
|
||||
pub fn reset_ui_ready_state() -> CmdResult<()> {
|
||||
log::info!(target: "app", "重置UI就绪状态");
|
||||
log::info!(target: "app", "Reset UI ready state");
|
||||
crate::utils::resolve::reset_ui_ready();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use serde_yaml::Mapping;
|
||||
/// get the system proxy
|
||||
#[tauri::command]
|
||||
pub async fn get_sys_proxy() -> CmdResult<Mapping> {
|
||||
log::debug!(target: "app", "异步获取系统代理配置");
|
||||
log::debug!(target: "app", "Asynchronously getting system proxy configuration");
|
||||
|
||||
let current = AsyncProxyQuery::get_system_proxy().await;
|
||||
|
||||
@@ -19,14 +19,14 @@ pub async fn get_sys_proxy() -> CmdResult<Mapping> {
|
||||
);
|
||||
map.insert("bypass".into(), current.bypass.into());
|
||||
|
||||
log::debug!(target: "app", "返回系统代理配置: enable={}, {}:{}", current.enable, current.host, current.port);
|
||||
log::debug!(target: "app", "Return system proxy configuration: enable={}, {}:{}", current.enable, current.host, current.port);
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
/// 获取自动代理配置
|
||||
#[tauri::command]
|
||||
pub async fn get_auto_proxy() -> CmdResult<Mapping> {
|
||||
log::debug!(target: "app", "开始获取自动代理配置(事件驱动)");
|
||||
log::debug!(target: "app", "Start retrieving auto proxy configuration (event-driven)");
|
||||
|
||||
let proxy_manager = EventDrivenProxyManager::global();
|
||||
|
||||
@@ -40,7 +40,7 @@ pub async fn get_auto_proxy() -> CmdResult<Mapping> {
|
||||
map.insert("enable".into(), current.enable.into());
|
||||
map.insert("url".into(), current.url.clone().into());
|
||||
|
||||
log::debug!(target: "app", "返回自动代理配置(缓存): enable={}, url={}", current.enable, current.url);
|
||||
log::debug!(target: "app", "Return auto proxy configuration (cached): enable={}, url={}", current.enable, current.url);
|
||||
Ok(map)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,14 +6,14 @@ use crate::{
|
||||
utils::{dirs, help, logging::Type},
|
||||
wrap_err,
|
||||
};
|
||||
use base64::{engine::general_purpose::STANDARD, Engine as _};
|
||||
use percent_encoding::percent_decode_str;
|
||||
use serde_yaml::Value;
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{Mutex, RwLock};
|
||||
use std::collections::BTreeMap;
|
||||
use url::Url;
|
||||
use serde_yaml::Value;
|
||||
use base64::{engine::general_purpose::STANDARD, Engine as _};
|
||||
use percent_encoding::percent_decode_str;
|
||||
|
||||
// 全局互斥锁防止并发配置更新
|
||||
static PROFILE_UPDATE_MUTEX: Mutex<()> = Mutex::const_new(());
|
||||
@@ -138,20 +138,34 @@ pub async fn import_profile(url: String, option: Option<PrfOption>) -> CmdResult
|
||||
let profiles = Config::profiles();
|
||||
let profiles = profiles.latest();
|
||||
|
||||
profiles.items.as_ref()
|
||||
profiles
|
||||
.items
|
||||
.as_ref()
|
||||
.and_then(|items| items.iter().find(|item| item.url.as_deref() == Some(&url)))
|
||||
.and_then(|item| item.uid.clone())
|
||||
};
|
||||
|
||||
if let Some(uid) = existing_uid {
|
||||
logging!(info, Type::Cmd, true, "The profile with URL {} already exists (UID: {}). Running the update...", url, uid);
|
||||
logging!(
|
||||
info,
|
||||
Type::Cmd,
|
||||
true,
|
||||
"The profile with URL {} already exists (UID: {}). Running the update...",
|
||||
url,
|
||||
uid
|
||||
);
|
||||
update_profile(uid, option).await
|
||||
} else {
|
||||
logging!(info, Type::Cmd, true, "Profile with URL {} not found. Create a new one...", url);
|
||||
logging!(
|
||||
info,
|
||||
Type::Cmd,
|
||||
true,
|
||||
"Profile with URL {} not found. Create a new one...",
|
||||
url
|
||||
);
|
||||
let item = wrap_err!(PrfItem::from_url(&url, None, None, option).await)?;
|
||||
wrap_err!(Config::profiles().data().append_item(item))
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/// 重新排序配置文件
|
||||
@@ -181,20 +195,29 @@ pub async fn delete_profile(index: String) -> CmdResult {
|
||||
{
|
||||
let profiles_config = Config::profiles();
|
||||
let mut profiles_data = profiles_config.data();
|
||||
should_update = profiles_data.delete_item(index.clone()).map_err(|e| e.to_string())?;
|
||||
should_update = profiles_data
|
||||
.delete_item(index.clone())
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
let was_last_profile = profiles_data.items.as_ref().map_or(true, |items| {
|
||||
!items.iter().any(|item|
|
||||
item.itype == Some("remote".to_string()) || item.itype == Some("local".to_string())
|
||||
)
|
||||
let was_last_profile = profiles_data.items.as_ref().is_none_or(|items| {
|
||||
!items
|
||||
.iter()
|
||||
.any(|item| matches!(item.itype.as_deref(), Some("remote") | Some("local")))
|
||||
});
|
||||
|
||||
if was_last_profile {
|
||||
logging!(info, Type::Cmd, true, "The last profile has been deleted. Disabling proxy modes...");
|
||||
logging!(
|
||||
info,
|
||||
Type::Cmd,
|
||||
true,
|
||||
"The last profile has been deleted. Disabling proxy modes..."
|
||||
);
|
||||
let verge_config = Config::verge();
|
||||
let mut verge_data = verge_config.data();
|
||||
|
||||
if verge_data.enable_tun_mode == Some(true) || verge_data.enable_system_proxy == Some(true) {
|
||||
if verge_data.enable_tun_mode == Some(true)
|
||||
|| verge_data.enable_system_proxy == Some(true)
|
||||
{
|
||||
verge_data.enable_tun_mode = Some(false);
|
||||
verge_data.enable_system_proxy = Some(false);
|
||||
verge_data.save_file().map_err(|e| e.to_string())?;
|
||||
@@ -696,23 +719,30 @@ pub fn get_next_update_time(uid: String) -> CmdResult<Option<i64>> {
|
||||
Ok(next_time)
|
||||
}
|
||||
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn update_profiles_on_startup() -> CmdResult {
|
||||
logging!(info, Type::Cmd, true, "Checking profiles for updates at startup...");
|
||||
logging!(
|
||||
info,
|
||||
Type::Cmd,
|
||||
true,
|
||||
"Checking profiles for updates at startup..."
|
||||
);
|
||||
|
||||
let profiles_to_update = {
|
||||
let profiles = Config::profiles();
|
||||
let profiles = profiles.latest();
|
||||
|
||||
profiles.items.as_ref()
|
||||
.map_or_else(
|
||||
Vec::new,
|
||||
|items| items.iter()
|
||||
.filter(|item| item.option.as_ref().is_some_and(|opt| opt.update_always == Some(true)))
|
||||
.filter_map(|item| item.uid.clone())
|
||||
.collect()
|
||||
)
|
||||
profiles.items.as_ref().map_or_else(Vec::new, |items| {
|
||||
items
|
||||
.iter()
|
||||
.filter(|item| {
|
||||
item.option
|
||||
.as_ref()
|
||||
.is_some_and(|opt| opt.update_always == Some(true))
|
||||
})
|
||||
.filter_map(|item| item.uid.clone())
|
||||
.collect()
|
||||
})
|
||||
};
|
||||
|
||||
if profiles_to_update.is_empty() {
|
||||
@@ -720,7 +750,13 @@ pub async fn update_profiles_on_startup() -> CmdResult {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
logging!(info, Type::Cmd, true, "Found profiles to update: {:?}", profiles_to_update);
|
||||
logging!(
|
||||
info,
|
||||
Type::Cmd,
|
||||
true,
|
||||
"Found profiles to update: {:?}",
|
||||
profiles_to_update
|
||||
);
|
||||
|
||||
let mut update_futures = Vec::new();
|
||||
for uid in profiles_to_update {
|
||||
@@ -729,13 +765,25 @@ pub async fn update_profiles_on_startup() -> CmdResult {
|
||||
|
||||
let results = futures::future::join_all(update_futures).await;
|
||||
|
||||
|
||||
if results.iter().any(|res| res.is_ok()) {
|
||||
logging!(info, Type::Cmd, true, "The startup update is complete, restart the kernel...");
|
||||
CoreManager::global().update_config().await.map_err(|e| e.to_string())?;
|
||||
logging!(
|
||||
info,
|
||||
Type::Cmd,
|
||||
true,
|
||||
"The startup update is complete, restart the kernel..."
|
||||
);
|
||||
CoreManager::global()
|
||||
.update_config()
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
handle::Handle::refresh_clash();
|
||||
} else {
|
||||
logging!(warn, Type::Cmd, true, "All updates completed with errors on startup.");
|
||||
logging!(
|
||||
warn,
|
||||
Type::Cmd,
|
||||
true,
|
||||
"All updates completed with errors on startup."
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -743,7 +791,6 @@ pub async fn update_profiles_on_startup() -> CmdResult {
|
||||
|
||||
#[tauri::command]
|
||||
pub async fn create_profile_from_share_link(link: String, template_name: String) -> CmdResult {
|
||||
|
||||
const DEFAULT_TEMPLATE: &str = r#"
|
||||
mixed-port: 2080
|
||||
allow-lan: true
|
||||
@@ -1107,14 +1154,18 @@ pub async fn create_profile_from_share_link(link: String, template_name: String)
|
||||
|
||||
let parsed_url = Url::parse(&link).map_err(|e| e.to_string())?;
|
||||
let scheme = parsed_url.scheme();
|
||||
let proxy_name = parsed_url.fragment()
|
||||
let proxy_name = parsed_url
|
||||
.fragment()
|
||||
.map(|f| percent_decode_str(f).decode_utf8_lossy().to_string())
|
||||
.unwrap_or_else(|| "Proxy from Link".to_string());
|
||||
|
||||
let mut proxy_map: BTreeMap<String, Value> = BTreeMap::new();
|
||||
proxy_map.insert("name".into(), proxy_name.clone().into());
|
||||
proxy_map.insert("type".into(), scheme.into());
|
||||
proxy_map.insert("server".into(), parsed_url.host_str().unwrap_or_default().into());
|
||||
proxy_map.insert(
|
||||
"server".into(),
|
||||
parsed_url.host_str().unwrap_or_default().into(),
|
||||
);
|
||||
proxy_map.insert("port".into(), parsed_url.port().unwrap_or(443).into());
|
||||
proxy_map.insert("udp".into(), true.into());
|
||||
|
||||
@@ -1130,16 +1181,29 @@ pub async fn create_profile_from_share_link(link: String, template_name: String)
|
||||
"security" if value == "tls" => {
|
||||
proxy_map.insert("tls".into(), true.into());
|
||||
}
|
||||
"flow" => { proxy_map.insert("flow".into(), value.to_string().into()); }
|
||||
"sni" => { proxy_map.insert("servername".into(), value.to_string().into()); }
|
||||
"fp" => { proxy_map.insert("client-fingerprint".into(), value.to_string().into()); }
|
||||
"pbk" => { reality_opts.insert("public-key".into(), value.to_string().into()); }
|
||||
"sid" => { reality_opts.insert("short-id".into(), value.to_string().into()); }
|
||||
"flow" => {
|
||||
proxy_map.insert("flow".into(), value.to_string().into());
|
||||
}
|
||||
"sni" => {
|
||||
proxy_map.insert("servername".into(), value.to_string().into());
|
||||
}
|
||||
"fp" => {
|
||||
proxy_map.insert("client-fingerprint".into(), value.to_string().into());
|
||||
}
|
||||
"pbk" => {
|
||||
reality_opts.insert("public-key".into(), value.to_string().into());
|
||||
}
|
||||
"sid" => {
|
||||
reality_opts.insert("short-id".into(), value.to_string().into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !reality_opts.is_empty() {
|
||||
proxy_map.insert("reality-opts".into(), serde_yaml::to_value(reality_opts).map_err(|e| e.to_string())?);
|
||||
proxy_map.insert(
|
||||
"reality-opts".into(),
|
||||
serde_yaml::to_value(reality_opts).map_err(|e| e.to_string())?,
|
||||
);
|
||||
}
|
||||
}
|
||||
"ss" => {
|
||||
@@ -1155,19 +1219,32 @@ pub async fn create_profile_from_share_link(link: String, template_name: String)
|
||||
"vmess" => {
|
||||
if let Ok(decoded_bytes) = STANDARD.decode(parsed_url.host_str().unwrap_or_default()) {
|
||||
if let Ok(json_str) = String::from_utf8(decoded_bytes) {
|
||||
if let Ok(vmess_params) = serde_json::from_str::<BTreeMap<String, Value>>(&json_str) {
|
||||
if let Some(add) = vmess_params.get("add") { proxy_map.insert("server".into(), add.clone()); }
|
||||
if let Some(port) = vmess_params.get("port") { proxy_map.insert("port".into(), port.clone()); }
|
||||
if let Some(id) = vmess_params.get("id") { proxy_map.insert("uuid".into(), id.clone()); }
|
||||
if let Some(aid) = vmess_params.get("aid") { proxy_map.insert("alterId".into(), aid.clone()); }
|
||||
if let Some(net) = vmess_params.get("net") { proxy_map.insert("network".into(), net.clone()); }
|
||||
if let Some(ps) = vmess_params.get("ps") { proxy_map.insert("name".into(), ps.clone()); }
|
||||
if let Ok(vmess_params) =
|
||||
serde_json::from_str::<BTreeMap<String, Value>>(&json_str)
|
||||
{
|
||||
if let Some(add) = vmess_params.get("add") {
|
||||
proxy_map.insert("server".into(), add.clone());
|
||||
}
|
||||
if let Some(port) = vmess_params.get("port") {
|
||||
proxy_map.insert("port".into(), port.clone());
|
||||
}
|
||||
if let Some(id) = vmess_params.get("id") {
|
||||
proxy_map.insert("uuid".into(), id.clone());
|
||||
}
|
||||
if let Some(aid) = vmess_params.get("aid") {
|
||||
proxy_map.insert("alterId".into(), aid.clone());
|
||||
}
|
||||
if let Some(net) = vmess_params.get("net") {
|
||||
proxy_map.insert("network".into(), net.clone());
|
||||
}
|
||||
if let Some(ps) = vmess_params.get("ps") {
|
||||
proxy_map.insert("name".into(), ps.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let mut config: Value = serde_yaml::from_str(template_yaml).map_err(|e| e.to_string())?;
|
||||
@@ -1177,10 +1254,15 @@ pub async fn create_profile_from_share_link(link: String, template_name: String)
|
||||
proxies.push(serde_yaml::to_value(proxy_map).map_err(|e| e.to_string())?);
|
||||
}
|
||||
|
||||
if let Some(groups) = config.get_mut("proxy-groups").and_then(|v| v.as_sequence_mut()) {
|
||||
if let Some(groups) = config
|
||||
.get_mut("proxy-groups")
|
||||
.and_then(|v| v.as_sequence_mut())
|
||||
{
|
||||
for group in groups.iter_mut() {
|
||||
if let Some(mapping) = group.as_mapping_mut() {
|
||||
if let Some(proxies_list) = mapping.get_mut("proxies").and_then(|p| p.as_sequence_mut()) {
|
||||
if let Some(proxies_list) =
|
||||
mapping.get_mut("proxies").and_then(|p| p.as_sequence_mut())
|
||||
{
|
||||
let new_proxies_list: Vec<Value> = proxies_list
|
||||
.iter()
|
||||
.map(|p| {
|
||||
@@ -1199,8 +1281,13 @@ pub async fn create_profile_from_share_link(link: String, template_name: String)
|
||||
|
||||
let new_yaml_content = serde_yaml::to_string(&config).map_err(|e| e.to_string())?;
|
||||
|
||||
let item = PrfItem::from_local(proxy_name, "Created from share link".into(), Some(new_yaml_content), None)
|
||||
.map_err(|e| e.to_string())?;
|
||||
let item = PrfItem::from_local(
|
||||
proxy_name,
|
||||
"Created from share link".into(),
|
||||
Some(new_yaml_content),
|
||||
None,
|
||||
)
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
wrap_err!(Config::profiles().data().append_item(item))
|
||||
}
|
||||
@@ -33,7 +33,7 @@ pub async fn get_proxies() -> CmdResult<serde_json::Value> {
|
||||
state.proxies = Box::new(proxies);
|
||||
state.need_refresh = false;
|
||||
}
|
||||
log::debug!(target: "app", "proxies刷新成功");
|
||||
log::debug!(target: "app", "Proxies refreshed successfully");
|
||||
}
|
||||
|
||||
let proxies = {
|
||||
@@ -50,7 +50,7 @@ pub async fn force_refresh_proxies() -> CmdResult<serde_json::Value> {
|
||||
let app_handle = handle::Handle::global().app_handle().unwrap();
|
||||
let cmd_proxy_state = app_handle.state::<Mutex<CmdProxyState>>();
|
||||
|
||||
log::debug!(target: "app", "强制刷新代理缓存");
|
||||
log::debug!(target: "app", "Force refresh proxy cache");
|
||||
|
||||
let proxies = manager.get_refresh_proxies().await?;
|
||||
|
||||
@@ -61,7 +61,7 @@ pub async fn force_refresh_proxies() -> CmdResult<serde_json::Value> {
|
||||
state.last_refresh_time = Instant::now();
|
||||
}
|
||||
|
||||
log::debug!(target: "app", "强制刷新代理缓存完成");
|
||||
log::debug!(target: "app", "Force refresh proxy cache completed");
|
||||
Ok(proxies)
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ pub async fn get_providers_proxies() -> CmdResult<serde_json::Value> {
|
||||
state.providers_proxies = Box::new(providers);
|
||||
state.need_refresh = false;
|
||||
}
|
||||
log::debug!(target: "app", "providers_proxies刷新成功");
|
||||
log::debug!(target: "app", "providers_proxies refreshed successfully");
|
||||
}
|
||||
|
||||
let providers_proxies = {
|
||||
|
||||
@@ -133,17 +133,17 @@ pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdR
|
||||
|| (!file_path_str.ends_with(".js") && !is_script_error)
|
||||
{
|
||||
// 普通YAML错误使用YAML通知处理
|
||||
log::info!(target: "app", "[cmd配置save] YAML配置文件验证失败,发送通知");
|
||||
log::info!(target: "app", "[cmd config save] YAML config file validation failed, sending notification");
|
||||
let result = (false, error_msg.clone());
|
||||
crate::cmd::validate::handle_yaml_validation_notice(&result, "YAML配置文件");
|
||||
} else if is_script_error {
|
||||
// 脚本错误使用专门的通知处理
|
||||
log::info!(target: "app", "[cmd配置save] 脚本文件验证失败,发送通知");
|
||||
log::info!(target: "app", "[cmd config save] Script file validation failed, sending notification");
|
||||
let result = (false, error_msg.clone());
|
||||
crate::cmd::validate::handle_script_validation_notice(&result, "脚本文件");
|
||||
} else {
|
||||
// 普通配置错误使用一般通知
|
||||
log::info!(target: "app", "[cmd配置save] 其他类型验证失败,发送一般通知");
|
||||
log::info!(target: "app", "[cmd config save] Other validation failure type, sending general notification");
|
||||
handle::Handle::notice_message("config_validate::error", &error_msg);
|
||||
}
|
||||
|
||||
@@ -154,7 +154,7 @@ pub async fn save_profile_file(index: String, file_data: Option<String>) -> CmdR
|
||||
error,
|
||||
Type::Config,
|
||||
true,
|
||||
"[cmd配置save] 验证过程发生错误: {}",
|
||||
"[cmd config save] Error occurred during validation: {}",
|
||||
e
|
||||
);
|
||||
// 恢复原始配置文件
|
||||
|
||||
@@ -19,11 +19,11 @@ macro_rules! draft_define {
|
||||
|
||||
impl Draft<Box<$id>> {
|
||||
#[allow(unused)]
|
||||
pub fn data(&self) -> MappedMutexGuard<Box<$id>> {
|
||||
pub fn data(&self) -> MappedMutexGuard<'_, Box<$id>> {
|
||||
MutexGuard::map(self.inner.lock(), |guard| &mut guard.0)
|
||||
}
|
||||
|
||||
pub fn latest(&self) -> MappedMutexGuard<Box<$id>> {
|
||||
pub fn latest(&self) -> MappedMutexGuard<'_, Box<$id>> {
|
||||
MutexGuard::map(self.inner.lock(), |inner| {
|
||||
if inner.1.is_none() {
|
||||
&mut inner.0
|
||||
@@ -33,7 +33,7 @@ macro_rules! draft_define {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn draft(&self) -> MappedMutexGuard<Box<$id>> {
|
||||
pub fn draft(&self) -> MappedMutexGuard<'_, Box<$id>> {
|
||||
MutexGuard::map(self.inner.lock(), |inner| {
|
||||
if inner.1.is_none() {
|
||||
inner.1 = Some(inner.0.clone());
|
||||
|
||||
@@ -326,7 +326,7 @@ impl PrfItem {
|
||||
if let Ok(mut parsed_url) = Url::parse(url) {
|
||||
if parsed_url.set_host(Some(new_domain)).is_ok() {
|
||||
final_url = parsed_url.to_string();
|
||||
log::info!(target: "app", "URL host updated to -> {}", final_url);
|
||||
log::info!(target: "app", "URL host updated to -> {final_url}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -536,7 +536,7 @@ impl IProfiles {
|
||||
if Self::is_profile_file(file_name) {
|
||||
// 检查是否为全局扩展文件
|
||||
if protected_files.contains(file_name) {
|
||||
log::debug!(target: "app", "保护全局扩展配置文件: {file_name}");
|
||||
log::debug!(target: "app", "Protect global extension config file: {file_name}");
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -545,11 +545,11 @@ impl IProfiles {
|
||||
match std::fs::remove_file(&path) {
|
||||
Ok(_) => {
|
||||
deleted_files.push(file_name.to_string());
|
||||
log::info!(target: "app", "已清理冗余文件: {file_name}");
|
||||
log::info!(target: "app", "Cleaned up redundant file: {file_name}");
|
||||
}
|
||||
Err(e) => {
|
||||
failed_deletions.push(format!("{file_name}: {e}"));
|
||||
log::warn!(target: "app", "清理文件失败: {file_name} - {e}");
|
||||
log::warn!(target: "app", "Failed to clean file: {file_name} - {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -679,14 +679,14 @@ impl IProfiles {
|
||||
if !result.deleted_files.is_empty() {
|
||||
log::info!(
|
||||
target: "app",
|
||||
"自动清理完成,删除了 {} 个冗余文件",
|
||||
"Auto cleanup completed, deleted {} redundant files",
|
||||
result.deleted_files.len()
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!(target: "app", "自动清理失败: {e}");
|
||||
log::warn!(target: "app", "Auto cleanup failed: {e}");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,10 +340,12 @@ impl IVerge {
|
||||
}
|
||||
|
||||
pub fn new() -> Self {
|
||||
dirs::verge_path().and_then(|path| help::read_yaml::<IVerge>(&path)).unwrap_or_else(|err| {
|
||||
log::error!(target: "app", "{err}");
|
||||
Self::template()
|
||||
})
|
||||
dirs::verge_path()
|
||||
.and_then(|path| help::read_yaml::<IVerge>(&path))
|
||||
.unwrap_or_else(|err| {
|
||||
log::error!(target: "app", "{err}");
|
||||
Self::template()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn template() -> Self {
|
||||
|
||||
@@ -39,15 +39,15 @@ impl AsyncProxyQuery {
|
||||
pub async fn get_auto_proxy() -> AsyncAutoproxy {
|
||||
match timeout(Duration::from_secs(3), Self::get_auto_proxy_impl()).await {
|
||||
Ok(Ok(proxy)) => {
|
||||
log::debug!(target: "app", "异步获取自动代理成功: enable={}, url={}", proxy.enable, proxy.url);
|
||||
log::debug!(target: "app", "Async auto proxy fetch succeeded: enable={}, url={}", proxy.enable, proxy.url);
|
||||
proxy
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
log::warn!(target: "app", "异步获取自动代理失败: {e}");
|
||||
log::warn!(target: "app", "Async auto proxy fetch failed: {e}");
|
||||
AsyncAutoproxy::default()
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!(target: "app", "异步获取自动代理超时");
|
||||
log::warn!(target: "app", "Async auto proxy fetch timed out");
|
||||
AsyncAutoproxy::default()
|
||||
}
|
||||
}
|
||||
@@ -57,15 +57,15 @@ impl AsyncProxyQuery {
|
||||
pub async fn get_system_proxy() -> AsyncSysproxy {
|
||||
match timeout(Duration::from_secs(3), Self::get_system_proxy_impl()).await {
|
||||
Ok(Ok(proxy)) => {
|
||||
log::debug!(target: "app", "异步获取系统代理成功: enable={}, {}:{}", proxy.enable, proxy.host, proxy.port);
|
||||
log::debug!(target: "app", "Async system proxy fetch succeeded: enable={}, {}:{}", proxy.enable, proxy.host, proxy.port);
|
||||
proxy
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
log::warn!(target: "app", "异步获取系统代理失败: {e}");
|
||||
log::warn!(target: "app", "Async system proxy fetch failed: {e}");
|
||||
AsyncSysproxy::default()
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!(target: "app", "异步获取系统代理超时");
|
||||
log::warn!(target: "app", "Async system proxy fetch timed out");
|
||||
AsyncSysproxy::default()
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ impl AsyncProxyQuery {
|
||||
RegOpenKeyExW(HKEY_CURRENT_USER, key_path.as_ptr(), 0, KEY_READ, &mut hkey);
|
||||
|
||||
if result != 0 {
|
||||
log::debug!(target: "app", "无法打开注册表项");
|
||||
log::debug!(target: "app", "Unable to open registry key");
|
||||
return Ok(AsyncAutoproxy::default());
|
||||
}
|
||||
|
||||
@@ -123,7 +123,7 @@ impl AsyncProxyQuery {
|
||||
.position(|&x| x == 0)
|
||||
.unwrap_or(url_buffer.len());
|
||||
pac_url = String::from_utf16_lossy(&url_buffer[..end_pos]);
|
||||
log::debug!(target: "app", "从注册表读取到PAC URL: {}", pac_url);
|
||||
log::debug!(target: "app", "Read PAC URL from registry: {}", pac_url);
|
||||
}
|
||||
|
||||
// 2. 检查自动检测设置是否启用
|
||||
@@ -148,7 +148,7 @@ impl AsyncProxyQuery {
|
||||
|| (detect_query_result == 0 && detect_value_type == REG_DWORD && auto_detect != 0);
|
||||
|
||||
if pac_enabled {
|
||||
log::debug!(target: "app", "PAC配置启用: URL={}, AutoDetect={}", pac_url, auto_detect);
|
||||
log::debug!(target: "app", "PAC configuration enabled: URL={}, AutoDetect={}", pac_url, auto_detect);
|
||||
|
||||
if pac_url.is_empty() && auto_detect != 0 {
|
||||
pac_url = "auto-detect".to_string();
|
||||
@@ -159,7 +159,7 @@ impl AsyncProxyQuery {
|
||||
url: pac_url,
|
||||
})
|
||||
} else {
|
||||
log::debug!(target: "app", "PAC配置未启用");
|
||||
log::debug!(target: "app", "PAC configuration not enabled");
|
||||
Ok(AsyncAutoproxy::default())
|
||||
}
|
||||
}
|
||||
@@ -194,7 +194,7 @@ impl AsyncProxyQuery {
|
||||
}
|
||||
}
|
||||
|
||||
log::debug!(target: "app", "解析结果: pac_enabled={pac_enabled}, pac_url={pac_url}");
|
||||
log::debug!(target: "app", "Parse result: pac_enabled={pac_enabled}, pac_url={pac_url}");
|
||||
|
||||
Ok(AsyncAutoproxy {
|
||||
enable: pac_enabled && !pac_url.is_empty(),
|
||||
@@ -361,7 +361,7 @@ impl AsyncProxyQuery {
|
||||
(proxy_server, 8080)
|
||||
};
|
||||
|
||||
log::debug!(target: "app", "从注册表读取到代理设置: {}:{}, bypass: {}", host, port, bypass_list);
|
||||
log::debug!(target: "app", "Read proxy settings from registry: {}:{}, bypass: {}", host, port, bypass_list);
|
||||
|
||||
Ok(AsyncSysproxy {
|
||||
enable: true,
|
||||
@@ -518,7 +518,7 @@ impl AsyncProxyQuery {
|
||||
};
|
||||
|
||||
if host.is_empty() {
|
||||
return Err(anyhow!("无效的代理URL"));
|
||||
return Err(anyhow!("Invalid proxy URL"));
|
||||
}
|
||||
|
||||
Ok(AsyncSysproxy {
|
||||
|
||||
@@ -112,7 +112,7 @@ impl WebDavClient {
|
||||
.redirect(reqwest::redirect::Policy::custom(|attempt| {
|
||||
// 允许所有请求类型的重定向,包括PUT
|
||||
if attempt.previous().len() >= 5 {
|
||||
attempt.error("重定向次数过多")
|
||||
attempt.error("Too many redirects")
|
||||
} else {
|
||||
attempt.follow()
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ impl CoreManager {
|
||||
warn,
|
||||
Type::Config,
|
||||
true,
|
||||
"无法读取文件以检测类型: {}, 错误: {}",
|
||||
"Failed to read file to detect type: {}, error: {}",
|
||||
path,
|
||||
err
|
||||
);
|
||||
@@ -130,7 +130,7 @@ impl CoreManager {
|
||||
debug,
|
||||
Type::Config,
|
||||
true,
|
||||
"无法确定文件类型,默认当作YAML处理: {}",
|
||||
"Unable to determine file type, defaulting to YAML handling: {}",
|
||||
path
|
||||
);
|
||||
Ok(false)
|
||||
@@ -153,7 +153,12 @@ impl CoreManager {
|
||||
}
|
||||
/// 验证运行时配置
|
||||
pub async fn validate_config(&self) -> Result<(bool, String)> {
|
||||
logging!(info, Type::Config, true, "生成临时配置文件用于验证");
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"Generate temporary config file for validation"
|
||||
);
|
||||
let config_path = Config::generate_file(ConfigType::Check)?;
|
||||
let config_path = dirs::path_to_str(&config_path)?;
|
||||
self.validate_config_internal(config_path).await
|
||||
@@ -166,7 +171,12 @@ impl CoreManager {
|
||||
) -> Result<(bool, String)> {
|
||||
// 检查程序是否正在退出,如果是则跳过验证
|
||||
if handle::Handle::global().is_exiting() {
|
||||
logging!(info, Type::Core, true, "应用正在退出,跳过验证");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"App is exiting, skipping validation"
|
||||
);
|
||||
return Ok((true, String::new()));
|
||||
}
|
||||
|
||||
@@ -183,7 +193,7 @@ impl CoreManager {
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"检测到Merge文件,仅进行语法检查: {}",
|
||||
"Detected merge file, performing syntax check only: {}",
|
||||
config_path
|
||||
);
|
||||
return self.validate_file_syntax(config_path).await;
|
||||
@@ -201,7 +211,7 @@ impl CoreManager {
|
||||
warn,
|
||||
Type::Config,
|
||||
true,
|
||||
"无法确定文件类型: {}, 错误: {}",
|
||||
"Unable to determine file type: {}, error: {}",
|
||||
config_path,
|
||||
err
|
||||
);
|
||||
@@ -215,7 +225,7 @@ impl CoreManager {
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"检测到脚本文件,使用JavaScript验证: {}",
|
||||
"Detected script file, validating with JavaScript: {}",
|
||||
config_path
|
||||
);
|
||||
return self.validate_script_file(config_path).await;
|
||||
@@ -226,7 +236,7 @@ impl CoreManager {
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"使用Clash内核验证配置文件: {}",
|
||||
"Validating config file with Clash core: {}",
|
||||
config_path
|
||||
);
|
||||
self.validate_config_internal(config_path).await
|
||||
@@ -235,7 +245,12 @@ impl CoreManager {
|
||||
async fn validate_config_internal(&self, config_path: &str) -> Result<(bool, String)> {
|
||||
// 检查程序是否正在退出,如果是则跳过验证
|
||||
if handle::Handle::global().is_exiting() {
|
||||
logging!(info, Type::Core, true, "应用正在退出,跳过验证");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"App is exiting, skipping validation"
|
||||
);
|
||||
return Ok((true, String::new()));
|
||||
}
|
||||
|
||||
@@ -243,17 +258,23 @@ impl CoreManager {
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"开始验证配置文件: {}",
|
||||
"Starting validation for config file: {}",
|
||||
config_path
|
||||
);
|
||||
|
||||
let clash_core = Config::verge().latest().get_valid_clash_core();
|
||||
logging!(info, Type::Config, true, "使用内核: {}", clash_core);
|
||||
logging!(info, Type::Config, true, "Using core: {}", clash_core);
|
||||
|
||||
let app_handle = handle::Handle::global().app_handle().unwrap();
|
||||
let app_dir = dirs::app_home_dir()?;
|
||||
let app_dir_str = dirs::path_to_str(&app_dir)?;
|
||||
logging!(info, Type::Config, true, "验证目录: {}", app_dir_str);
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"Validation directory: {}",
|
||||
app_dir_str
|
||||
);
|
||||
|
||||
// 使用子进程运行clash验证配置
|
||||
let output = app_handle
|
||||
@@ -271,56 +292,84 @@ impl CoreManager {
|
||||
let has_error =
|
||||
!output.status.success() || error_keywords.iter().any(|&kw| stderr.contains(kw));
|
||||
|
||||
logging!(info, Type::Config, true, "-------- 验证结果 --------");
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"-------- Validation Result --------"
|
||||
);
|
||||
|
||||
if !stderr.is_empty() {
|
||||
logging!(info, Type::Config, true, "stderr输出:\n{}", stderr);
|
||||
logging!(info, Type::Config, true, "stderr output:\n{}", stderr);
|
||||
}
|
||||
|
||||
if has_error {
|
||||
logging!(info, Type::Config, true, "发现错误,开始处理错误信息");
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"Errors found, processing error details"
|
||||
);
|
||||
let error_msg = if !stdout.is_empty() {
|
||||
stdout.to_string()
|
||||
} else if !stderr.is_empty() {
|
||||
stderr.to_string()
|
||||
} else if let Some(code) = output.status.code() {
|
||||
format!("验证进程异常退出,退出码: {code}")
|
||||
format!("Validation process exited abnormally, exit code: {code}")
|
||||
} else {
|
||||
"验证进程被终止".to_string()
|
||||
"Validation process was terminated".to_string()
|
||||
};
|
||||
|
||||
logging!(info, Type::Config, true, "-------- 验证结束 --------");
|
||||
logging!(info, Type::Config, true, "-------- Validation End --------");
|
||||
Ok((false, error_msg)) // 返回错误消息给调用者处理
|
||||
} else {
|
||||
logging!(info, Type::Config, true, "验证成功");
|
||||
logging!(info, Type::Config, true, "-------- 验证结束 --------");
|
||||
logging!(info, Type::Config, true, "Validation succeeded");
|
||||
logging!(info, Type::Config, true, "-------- Validation End --------");
|
||||
Ok((true, String::new()))
|
||||
}
|
||||
}
|
||||
/// 只进行文件语法检查,不进行完整验证
|
||||
async fn validate_file_syntax(&self, config_path: &str) -> Result<(bool, String)> {
|
||||
logging!(info, Type::Config, true, "开始检查文件: {}", config_path);
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"Starting file check: {}",
|
||||
config_path
|
||||
);
|
||||
|
||||
// 读取文件内容
|
||||
let content = match std::fs::read_to_string(config_path) {
|
||||
Ok(content) => content,
|
||||
Err(err) => {
|
||||
let error_msg = format!("Failed to read file: {err}");
|
||||
logging!(error, Type::Config, true, "无法读取文件: {}", error_msg);
|
||||
logging!(
|
||||
error,
|
||||
Type::Config,
|
||||
true,
|
||||
"Failed to read file: {}",
|
||||
error_msg
|
||||
);
|
||||
return Ok((false, error_msg));
|
||||
}
|
||||
};
|
||||
// 对YAML文件尝试解析,只检查语法正确性
|
||||
logging!(info, Type::Config, true, "进行YAML语法检查");
|
||||
logging!(info, Type::Config, true, "Performing YAML syntax check");
|
||||
match serde_yaml::from_str::<serde_yaml::Value>(&content) {
|
||||
Ok(_) => {
|
||||
logging!(info, Type::Config, true, "YAML语法检查通过");
|
||||
logging!(info, Type::Config, true, "YAML syntax check passed");
|
||||
Ok((true, String::new()))
|
||||
}
|
||||
Err(err) => {
|
||||
// 使用标准化的前缀,以便错误处理函数能正确识别
|
||||
let error_msg = format!("YAML syntax error: {err}");
|
||||
logging!(error, Type::Config, true, "YAML语法错误: {}", error_msg);
|
||||
logging!(
|
||||
error,
|
||||
Type::Config,
|
||||
true,
|
||||
"YAML syntax error: {}",
|
||||
error_msg
|
||||
);
|
||||
Ok((false, error_msg))
|
||||
}
|
||||
}
|
||||
@@ -332,13 +381,19 @@ impl CoreManager {
|
||||
Ok(content) => content,
|
||||
Err(err) => {
|
||||
let error_msg = format!("Failed to read script file: {err}");
|
||||
logging!(warn, Type::Config, true, "脚本语法错误: {}", err);
|
||||
logging!(warn, Type::Config, true, "Script syntax error: {}", err);
|
||||
//handle::Handle::notice_message("config_validate::script_syntax_error", &error_msg);
|
||||
return Ok((false, error_msg));
|
||||
}
|
||||
};
|
||||
|
||||
logging!(debug, Type::Config, true, "验证脚本文件: {}", path);
|
||||
logging!(
|
||||
debug,
|
||||
Type::Config,
|
||||
true,
|
||||
"Validating script file: {}",
|
||||
path
|
||||
);
|
||||
|
||||
// 使用boa引擎进行基本语法检查
|
||||
use boa_engine::{Context, Source};
|
||||
@@ -348,7 +403,13 @@ impl CoreManager {
|
||||
|
||||
match result {
|
||||
Ok(_) => {
|
||||
logging!(debug, Type::Config, true, "脚本语法验证通过: {}", path);
|
||||
logging!(
|
||||
debug,
|
||||
Type::Config,
|
||||
true,
|
||||
"Script syntax validation passed: {}",
|
||||
path
|
||||
);
|
||||
|
||||
// 检查脚本是否包含main函数
|
||||
if !content.contains("function main")
|
||||
@@ -356,7 +417,13 @@ impl CoreManager {
|
||||
&& !content.contains("let main")
|
||||
{
|
||||
let error_msg = "Script must contain a main function";
|
||||
logging!(warn, Type::Config, true, "脚本缺少main函数: {}", path);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Config,
|
||||
true,
|
||||
"Script missing main function: {}",
|
||||
path
|
||||
);
|
||||
//handle::Handle::notice_message("config_validate::script_missing_main", error_msg);
|
||||
return Ok((false, error_msg.to_string()));
|
||||
}
|
||||
@@ -365,7 +432,7 @@ impl CoreManager {
|
||||
}
|
||||
Err(err) => {
|
||||
let error_msg = format!("Script syntax error: {err}");
|
||||
logging!(warn, Type::Config, true, "脚本语法错误: {}", err);
|
||||
logging!(warn, Type::Config, true, "Script syntax error: {}", err);
|
||||
//handle::Handle::notice_message("config_validate::script_syntax_error", &error_msg);
|
||||
Ok((false, error_msg))
|
||||
}
|
||||
@@ -375,33 +442,55 @@ impl CoreManager {
|
||||
pub async fn update_config(&self) -> Result<(bool, String)> {
|
||||
// 检查程序是否正在退出,如果是则跳过完整验证流程
|
||||
if handle::Handle::global().is_exiting() {
|
||||
logging!(info, Type::Config, true, "应用正在退出,跳过验证");
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"App is exiting, skipping validation"
|
||||
);
|
||||
return Ok((true, String::new()));
|
||||
}
|
||||
|
||||
logging!(info, Type::Config, true, "开始更新配置");
|
||||
logging!(info, Type::Config, true, "Starting config update");
|
||||
|
||||
// 1. 先生成新的配置内容
|
||||
logging!(info, Type::Config, true, "生成新的配置内容");
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"Generating new configuration content"
|
||||
);
|
||||
Config::generate().await?;
|
||||
|
||||
// 2. 验证配置
|
||||
match self.validate_config().await {
|
||||
Ok((true, _)) => {
|
||||
logging!(info, Type::Config, true, "配置验证通过");
|
||||
logging!(info, Type::Config, true, "Configuration validation passed");
|
||||
// 4. 验证通过后,生成正式的运行时配置
|
||||
logging!(info, Type::Config, true, "生成运行时配置");
|
||||
logging!(info, Type::Config, true, "Generating runtime configuration");
|
||||
let run_path = Config::generate_file(ConfigType::Run)?;
|
||||
logging_error!(Type::Config, true, self.put_configs_force(run_path).await);
|
||||
Ok((true, "something".into()))
|
||||
}
|
||||
Ok((false, error_msg)) => {
|
||||
logging!(warn, Type::Config, true, "配置验证失败: {}", error_msg);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Config,
|
||||
true,
|
||||
"Configuration validation failed: {}",
|
||||
error_msg
|
||||
);
|
||||
Config::runtime().discard();
|
||||
Ok((false, error_msg))
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(warn, Type::Config, true, "验证过程发生错误: {}", e);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Config,
|
||||
true,
|
||||
"Error occurred during validation: {}",
|
||||
e
|
||||
);
|
||||
Config::runtime().discard();
|
||||
Err(e)
|
||||
}
|
||||
@@ -435,7 +524,12 @@ impl CoreManager {
|
||||
impl CoreManager {
|
||||
/// 清理多余的 mihomo 进程
|
||||
async fn cleanup_orphaned_mihomo_processes(&self) -> Result<()> {
|
||||
logging!(info, Type::Core, true, "开始清理多余的 mihomo 进程");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"Starting cleanup of orphaned mihomo processes"
|
||||
);
|
||||
|
||||
// 获取当前管理的进程 PID
|
||||
let current_pid = {
|
||||
@@ -471,7 +565,7 @@ impl CoreManager {
|
||||
debug,
|
||||
Type::Core,
|
||||
true,
|
||||
"跳过当前管理的进程: {} (PID: {})",
|
||||
"Skipping currently managed process: {} (PID: {})",
|
||||
process_name,
|
||||
pid
|
||||
);
|
||||
@@ -482,13 +576,24 @@ impl CoreManager {
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(debug, Type::Core, true, "查找进程时发生错误: {}", e);
|
||||
logging!(
|
||||
debug,
|
||||
Type::Core,
|
||||
true,
|
||||
"Error occurred while finding processes: {}",
|
||||
e
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if pids_to_kill.is_empty() {
|
||||
logging!(debug, Type::Core, true, "未发现多余的 mihomo 进程");
|
||||
logging!(
|
||||
debug,
|
||||
Type::Core,
|
||||
true,
|
||||
"No orphaned mihomo processes found"
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -837,7 +942,12 @@ impl CoreManager {
|
||||
// 当服务安装失败时的回退逻辑
|
||||
async fn attempt_service_init(&self) -> Result<()> {
|
||||
if service::check_service_needs_reinstall().await {
|
||||
logging!(info, Type::Core, true, "服务版本不匹配或状态异常,执行重装");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"Service version mismatch or abnormal status, performing reinstallation"
|
||||
);
|
||||
if let Err(e) = service::reinstall_service().await {
|
||||
logging!(
|
||||
warn,
|
||||
@@ -849,7 +959,12 @@ impl CoreManager {
|
||||
return Err(e);
|
||||
}
|
||||
// 如果重装成功,还需要尝试启动服务
|
||||
logging!(info, Type::Core, true, "服务重装成功,尝试启动服务");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"Service reinstalled successfully, attempting to start"
|
||||
);
|
||||
}
|
||||
|
||||
if let Err(e) = self.start_core_by_service().await {
|
||||
@@ -857,14 +972,14 @@ impl CoreManager {
|
||||
warn,
|
||||
Type::Core,
|
||||
true,
|
||||
"通过服务启动核心失败 during attempt_service_init: {}",
|
||||
"Failed to start core via service during attempt_service_init: {}",
|
||||
e
|
||||
);
|
||||
// 确保 prefer_sidecar 在 start_core_by_service 失败时也被设置
|
||||
let mut state = service::ServiceState::get();
|
||||
if !state.prefer_sidecar {
|
||||
state.prefer_sidecar = true;
|
||||
state.last_error = Some(format!("通过服务启动核心失败: {e}"));
|
||||
state.last_error = Some(format!("Failed to start core via service: {e}"));
|
||||
if let Err(save_err) = state.save() {
|
||||
logging!(
|
||||
error,
|
||||
@@ -901,11 +1016,16 @@ impl CoreManager {
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"服务当前可用或看似可用,尝试通过服务模式启动/重装"
|
||||
"Service currently available or appears available; attempting to start/reinstall via service mode"
|
||||
);
|
||||
match self.attempt_service_init().await {
|
||||
Ok(_) => {
|
||||
logging!(info, Type::Core, true, "服务模式成功启动核心");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"Service mode successfully started core"
|
||||
);
|
||||
core_started_successfully = true;
|
||||
}
|
||||
Err(_err) => {
|
||||
@@ -913,7 +1033,7 @@ impl CoreManager {
|
||||
warn,
|
||||
Type::Core,
|
||||
true,
|
||||
"服务模式启动或重装失败。将尝试Sidecar模式回退。"
|
||||
"Service mode start or reinstall failed. Will attempt Sidecar fallback."
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -922,7 +1042,7 @@ impl CoreManager {
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"服务初始不可用 (is_service_available 调用失败)"
|
||||
"Service initially unavailable (is_service_available call failed)"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -931,7 +1051,7 @@ impl CoreManager {
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"核心未通过服务模式启动,执行Sidecar回退或首次安装逻辑"
|
||||
"Core not started via service mode; performing Sidecar fallback or first-time install logic"
|
||||
);
|
||||
|
||||
let service_state = service::ServiceState::get();
|
||||
@@ -941,7 +1061,7 @@ impl CoreManager {
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"用户偏好Sidecar模式或先前服务启动失败,使用Sidecar模式启动"
|
||||
"User prefers Sidecar mode or previous service start failed; starting with Sidecar mode"
|
||||
);
|
||||
self.start_core_by_sidecar().await?;
|
||||
// 如果 sidecar 启动成功,我们可以认为核心初始化流程到此结束
|
||||
@@ -953,26 +1073,41 @@ impl CoreManager {
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"无服务安装记录 (首次运行或状态重置),尝试安装服务"
|
||||
"No service installation record (first run or state reset); attempting to install service"
|
||||
);
|
||||
match service::install_service().await {
|
||||
Ok(_) => {
|
||||
logging!(info, Type::Core, true, "服务安装成功(首次尝试)");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"Service installed successfully (first attempt)"
|
||||
);
|
||||
let mut new_state = service::ServiceState::default();
|
||||
new_state.record_install();
|
||||
new_state.prefer_sidecar = false;
|
||||
new_state.save()?;
|
||||
|
||||
if service::is_service_available().await.is_ok() {
|
||||
logging!(info, Type::Core, true, "新安装的服务可用,尝试启动");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"Newly installed service available; attempting to start"
|
||||
);
|
||||
if self.start_core_by_service().await.is_ok() {
|
||||
logging!(info, Type::Core, true, "新安装的服务启动成功");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"Newly installed service started successfully"
|
||||
);
|
||||
} else {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
true,
|
||||
"新安装的服务启动失败,回退到Sidecar模式"
|
||||
"Newly installed service failed to start; falling back to Sidecar mode"
|
||||
);
|
||||
let mut final_state = service::ServiceState::get();
|
||||
final_state.prefer_sidecar = true;
|
||||
@@ -986,7 +1121,7 @@ impl CoreManager {
|
||||
warn,
|
||||
Type::Core,
|
||||
true,
|
||||
"服务安装成功但未能连接/立即可用,回退到Sidecar模式"
|
||||
"Service installed successfully but not connectable/immediately available; falling back to Sidecar mode"
|
||||
);
|
||||
let mut final_state = service::ServiceState::get();
|
||||
final_state.prefer_sidecar = true;
|
||||
@@ -999,7 +1134,13 @@ impl CoreManager {
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
logging!(warn, Type::Core, true, "服务首次安装失败: {}", err);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Core,
|
||||
true,
|
||||
"Service first-time installation failed: {}",
|
||||
err
|
||||
);
|
||||
let new_state = service::ServiceState {
|
||||
last_error: Some(err.to_string()),
|
||||
prefer_sidecar: true,
|
||||
@@ -1062,7 +1203,12 @@ impl CoreManager {
|
||||
if service::check_service_needs_reinstall().await {
|
||||
service::reinstall_service().await?;
|
||||
}
|
||||
logging!(info, Type::Core, true, "服务可用,使用服务模式启动");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"Service available; starting in service mode"
|
||||
);
|
||||
self.start_core_by_service().await?;
|
||||
} else {
|
||||
// 服务不可用,检查用户偏好
|
||||
@@ -1072,11 +1218,16 @@ impl CoreManager {
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"服务不可用,根据用户偏好使用Sidecar模式"
|
||||
"Service unavailable; starting in Sidecar mode per user preference"
|
||||
);
|
||||
self.start_core_by_sidecar().await?;
|
||||
} else {
|
||||
logging!(info, Type::Core, true, "服务不可用,使用Sidecar模式");
|
||||
logging!(
|
||||
info,
|
||||
Type::Core,
|
||||
true,
|
||||
"Service unavailable; starting in Sidecar mode"
|
||||
);
|
||||
self.start_core_by_sidecar().await?;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ struct QueryRequest {
|
||||
response_tx: oneshot::Sender<Autoproxy>,
|
||||
}
|
||||
|
||||
// 配置结构体移到外部
|
||||
// Configuration structure moved to external
|
||||
struct ProxyConfig {
|
||||
sys_enabled: bool,
|
||||
pac_enabled: bool,
|
||||
@@ -106,59 +106,59 @@ impl EventDrivenProxyManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取自动代理配置(缓存)
|
||||
/// Get automatic proxy configuration (cached)
|
||||
pub fn get_auto_proxy_cached(&self) -> Autoproxy {
|
||||
self.state.read().auto_proxy.clone()
|
||||
}
|
||||
|
||||
/// 异步获取最新的自动代理配置
|
||||
/// Asynchronously get the latest automatic proxy configuration
|
||||
pub async fn get_auto_proxy_async(&self) -> Autoproxy {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let query = QueryRequest { response_tx: tx };
|
||||
|
||||
if self.query_sender.send(query).is_err() {
|
||||
log::error!(target: "app", "发送查询请求失败,返回缓存数据");
|
||||
log::error!(target: "app", "Failed to send query request, returning cached data");
|
||||
return self.get_auto_proxy_cached();
|
||||
}
|
||||
|
||||
match timeout(Duration::from_secs(5), rx).await {
|
||||
Ok(Ok(result)) => result,
|
||||
_ => {
|
||||
log::warn!(target: "app", "查询超时,返回缓存数据");
|
||||
log::warn!(target: "app", "Query timed out, returning cached data");
|
||||
self.get_auto_proxy_cached()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 通知配置变更
|
||||
/// Notify configuration changed
|
||||
pub fn notify_config_changed(&self) {
|
||||
self.send_event(ProxyEvent::ConfigChanged);
|
||||
}
|
||||
|
||||
/// 通知应用启动
|
||||
/// Notify application started
|
||||
pub fn notify_app_started(&self) {
|
||||
self.send_event(ProxyEvent::AppStarted);
|
||||
}
|
||||
|
||||
/// 通知应用即将关闭
|
||||
/// Notify application stopping
|
||||
#[allow(dead_code)]
|
||||
pub fn notify_app_stopping(&self) {
|
||||
self.send_event(ProxyEvent::AppStopping);
|
||||
}
|
||||
|
||||
/// 启用系统代理
|
||||
/// Enable system proxy
|
||||
#[allow(dead_code)]
|
||||
pub fn enable_proxy(&self) {
|
||||
self.send_event(ProxyEvent::EnableProxy);
|
||||
}
|
||||
|
||||
/// 禁用系统代理
|
||||
/// Disable system proxy
|
||||
#[allow(dead_code)]
|
||||
pub fn disable_proxy(&self) {
|
||||
self.send_event(ProxyEvent::DisableProxy);
|
||||
}
|
||||
|
||||
/// 强制检查代理状态
|
||||
/// Force check proxy status
|
||||
#[allow(dead_code)]
|
||||
pub fn force_check(&self) {
|
||||
self.send_event(ProxyEvent::ForceCheck);
|
||||
@@ -166,7 +166,7 @@ impl EventDrivenProxyManager {
|
||||
|
||||
fn send_event(&self, event: ProxyEvent) {
|
||||
if let Err(e) = self.event_sender.send(event) {
|
||||
log::error!(target: "app", "发送代理事件失败: {e}");
|
||||
log::error!(target: "app", "Failed to send proxy event: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -176,18 +176,18 @@ impl EventDrivenProxyManager {
|
||||
mut query_rx: mpsc::UnboundedReceiver<QueryRequest>,
|
||||
) {
|
||||
tokio::spawn(async move {
|
||||
log::info!(target: "app", "事件驱动代理管理器启动");
|
||||
log::info!(target: "app", "Event-driven proxy manager started");
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
event = event_rx.recv() => {
|
||||
match event {
|
||||
Some(event) => {
|
||||
log::debug!(target: "app", "处理代理事件: {event:?}");
|
||||
log::debug!(target: "app", "Handling proxy event: {event:?}");
|
||||
Self::handle_event(&state, event).await;
|
||||
}
|
||||
None => {
|
||||
log::info!(target: "app", "事件通道关闭,代理管理器停止");
|
||||
log::info!(target: "app", "Event channel closed, proxy manager stopped");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -199,7 +199,7 @@ impl EventDrivenProxyManager {
|
||||
let _ = query.response_tx.send(result);
|
||||
}
|
||||
None => {
|
||||
log::info!(target: "app", "查询通道关闭");
|
||||
log::info!(target: "app", "Query channel closed");
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -230,7 +230,7 @@ impl EventDrivenProxyManager {
|
||||
Self::initialize_proxy_state(state).await;
|
||||
}
|
||||
ProxyEvent::AppStopping => {
|
||||
log::info!(target: "app", "清理代理状态");
|
||||
log::info!(target: "app", "Cleaning up proxy state");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -246,7 +246,7 @@ impl EventDrivenProxyManager {
|
||||
}
|
||||
|
||||
async fn initialize_proxy_state(state: &Arc<RwLock<ProxyState>>) {
|
||||
log::info!(target: "app", "初始化代理状态");
|
||||
log::info!(target: "app", "Initializing proxy state");
|
||||
|
||||
let config = Self::get_proxy_config();
|
||||
let auto_proxy = Self::get_auto_proxy_with_timeout().await;
|
||||
@@ -260,11 +260,11 @@ impl EventDrivenProxyManager {
|
||||
s.is_healthy = true;
|
||||
});
|
||||
|
||||
log::info!(target: "app", "代理状态初始化完成: sys={}, pac={}", config.sys_enabled, config.pac_enabled);
|
||||
log::info!(target: "app", "Proxy state initialized: sys={}, pac={}", config.sys_enabled, config.pac_enabled);
|
||||
}
|
||||
|
||||
async fn update_proxy_config(state: &Arc<RwLock<ProxyState>>) {
|
||||
log::debug!(target: "app", "更新代理配置");
|
||||
log::debug!(target: "app", "Updating proxy configuration");
|
||||
|
||||
let config = Self::get_proxy_config();
|
||||
|
||||
@@ -288,7 +288,7 @@ impl EventDrivenProxyManager {
|
||||
return;
|
||||
}
|
||||
|
||||
log::debug!(target: "app", "检查代理状态");
|
||||
log::debug!(target: "app", "Checking proxy status");
|
||||
|
||||
if pac_enabled {
|
||||
Self::check_and_restore_pac_proxy(state).await;
|
||||
@@ -306,7 +306,7 @@ impl EventDrivenProxyManager {
|
||||
});
|
||||
|
||||
if !current.enable || current.url != expected.url {
|
||||
log::info!(target: "app", "PAC代理设置异常,正在恢复...");
|
||||
log::info!(target: "app", "PAC proxy setting abnormal, recovering...");
|
||||
Self::restore_pac_proxy(&expected.url).await;
|
||||
|
||||
sleep(Duration::from_millis(500)).await;
|
||||
@@ -328,7 +328,7 @@ impl EventDrivenProxyManager {
|
||||
});
|
||||
|
||||
if !current.enable || current.host != expected.host || current.port != expected.port {
|
||||
log::info!(target: "app", "系统代理设置异常,正在恢复...");
|
||||
log::info!(target: "app", "System proxy setting abnormal, recovering...");
|
||||
Self::restore_sys_proxy(&expected).await;
|
||||
|
||||
sleep(Duration::from_millis(500)).await;
|
||||
@@ -344,7 +344,7 @@ impl EventDrivenProxyManager {
|
||||
}
|
||||
|
||||
async fn enable_system_proxy(state: &Arc<RwLock<ProxyState>>) {
|
||||
log::info!(target: "app", "启用系统代理");
|
||||
log::info!(target: "app", "Enabling system proxy");
|
||||
|
||||
let pac_enabled = state.read().pac_enabled;
|
||||
|
||||
@@ -360,7 +360,7 @@ impl EventDrivenProxyManager {
|
||||
}
|
||||
|
||||
async fn disable_system_proxy(_state: &Arc<RwLock<ProxyState>>) {
|
||||
log::info!(target: "app", "禁用系统代理");
|
||||
log::info!(target: "app", "Disabling system proxy");
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
{
|
||||
@@ -373,7 +373,7 @@ impl EventDrivenProxyManager {
|
||||
}
|
||||
|
||||
async fn switch_proxy_mode(state: &Arc<RwLock<ProxyState>>, to_pac: bool) {
|
||||
log::info!(target: "app", "切换到{}模式", if to_pac { "PAC" } else { "HTTP代理" });
|
||||
log::info!(target: "app", "Switching to {} mode", if to_pac { "PAC" } else { "HTTP Proxy" });
|
||||
|
||||
if to_pac {
|
||||
let disabled_sys = Sysproxy::default();
|
||||
@@ -396,7 +396,7 @@ impl EventDrivenProxyManager {
|
||||
async fn get_auto_proxy_with_timeout() -> Autoproxy {
|
||||
let async_proxy = AsyncProxyQuery::get_auto_proxy().await;
|
||||
|
||||
// 转换为兼容的结构
|
||||
// Convert to compatible structure
|
||||
Autoproxy {
|
||||
enable: async_proxy.enable,
|
||||
url: async_proxy.url,
|
||||
@@ -406,7 +406,7 @@ impl EventDrivenProxyManager {
|
||||
async fn get_sys_proxy_with_timeout() -> Sysproxy {
|
||||
let async_proxy = AsyncProxyQuery::get_system_proxy().await;
|
||||
|
||||
// 转换为兼容的结构
|
||||
// Convert to compatible structure
|
||||
Sysproxy {
|
||||
enable: async_proxy.enable,
|
||||
host: async_proxy.host,
|
||||
@@ -415,7 +415,7 @@ impl EventDrivenProxyManager {
|
||||
}
|
||||
}
|
||||
|
||||
// 统一的状态更新方法
|
||||
// Unified state update method
|
||||
fn update_state_timestamp<F>(state: &Arc<RwLock<ProxyState>>, update_fn: F)
|
||||
where
|
||||
F: FnOnce(&mut ProxyState),
|
||||
@@ -534,14 +534,14 @@ impl EventDrivenProxyManager {
|
||||
let binary_path = match dirs::service_path() {
|
||||
Ok(path) => path,
|
||||
Err(e) => {
|
||||
log::error!(target: "app", "获取服务路径失败: {}", e);
|
||||
log::error!(target: "app", "Failed to get service path: {}", e);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let sysproxy_exe = binary_path.with_file_name("sysproxy.exe");
|
||||
if !sysproxy_exe.exists() {
|
||||
log::error!(target: "app", "sysproxy.exe 不存在");
|
||||
log::error!(target: "app", "sysproxy.exe does not exist");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -554,17 +554,17 @@ impl EventDrivenProxyManager {
|
||||
match output {
|
||||
Ok(output) => {
|
||||
if !output.status.success() {
|
||||
log::error!(target: "app", "执行sysproxy命令失败: {:?}", args);
|
||||
log::error!(target: "app", "Failed to execute sysproxy command: {:?}", args);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
if !stderr.is_empty() {
|
||||
log::error!(target: "app", "sysproxy错误输出: {}", stderr);
|
||||
log::error!(target: "app", "sysproxy stderr: {}", stderr);
|
||||
}
|
||||
} else {
|
||||
log::debug!(target: "app", "成功执行sysproxy命令: {:?}", args);
|
||||
log::debug!(target: "app", "Successfully executed sysproxy command: {:?}", args);
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!(target: "app", "执行sysproxy命令出错: {}", e);
|
||||
log::error!(target: "app", "Error executing sysproxy command: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,7 +416,7 @@ impl Handle {
|
||||
info,
|
||||
Type::Frontend,
|
||||
true,
|
||||
"启动过程中发现错误,加入消息队列: {} - {}",
|
||||
"Error found during startup; queued: {} - {}",
|
||||
status_str,
|
||||
msg_str
|
||||
);
|
||||
@@ -466,7 +466,7 @@ impl Handle {
|
||||
info,
|
||||
Type::Frontend,
|
||||
true,
|
||||
"发送{}条启动时累积的错误消息",
|
||||
"Sending {} accumulated startup error messages",
|
||||
errors.len()
|
||||
);
|
||||
|
||||
|
||||
@@ -346,7 +346,7 @@ pub async fn reinstall_service() -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => {
|
||||
let error = format!("failed to install service: {}", err);
|
||||
let error = format!("failed to install service: {err}");
|
||||
service_state.last_error = Some(error.clone());
|
||||
service_state.prefer_sidecar = true;
|
||||
service_state.save()?;
|
||||
@@ -477,7 +477,12 @@ pub async fn reinstall_service() -> Result<()> {
|
||||
|
||||
/// 检查服务状态 - 使用IPC通信
|
||||
pub async fn check_ipc_service_status() -> Result<JsonResponse> {
|
||||
logging!(info, Type::Service, true, "开始检查服务状态 (IPC)");
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"Starting service status check (IPC)"
|
||||
);
|
||||
|
||||
// 使用IPC通信
|
||||
let payload = serde_json::json!({});
|
||||
@@ -495,8 +500,16 @@ pub async fn check_ipc_service_status() -> Result<JsonResponse> {
|
||||
); */
|
||||
|
||||
if !response.success {
|
||||
let err_msg = response.error.unwrap_or_else(|| "未知服务错误".to_string());
|
||||
logging!(error, Type::Service, true, "服务响应错误: {}", err_msg);
|
||||
let err_msg = response
|
||||
.error
|
||||
.unwrap_or_else(|| "Unknown service error".to_string());
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Service response error: {}",
|
||||
err_msg
|
||||
);
|
||||
bail!(err_msg);
|
||||
}
|
||||
|
||||
@@ -516,7 +529,7 @@ pub async fn check_ipc_service_status() -> Result<JsonResponse> {
|
||||
warn,
|
||||
Type::Service,
|
||||
true,
|
||||
"解析嵌套的ResponseBody失败: {}; 尝试其他方式",
|
||||
"Failed to parse nested ResponseBody: {}; trying alternative",
|
||||
e
|
||||
);
|
||||
None
|
||||
@@ -536,7 +549,7 @@ pub async fn check_ipc_service_status() -> Result<JsonResponse> {
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"服务检测成功: code={}, msg={}, data存在={}",
|
||||
"Service check succeeded: code={}, msg={}, data_present={}",
|
||||
json_response.code,
|
||||
json_response.msg,
|
||||
json_response.data.is_some()
|
||||
@@ -550,7 +563,7 @@ pub async fn check_ipc_service_status() -> Result<JsonResponse> {
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"服务检测成功: code={}, msg={}",
|
||||
"Service check succeeded: code={}, msg={}",
|
||||
json_response.code,
|
||||
json_response.msg
|
||||
);
|
||||
@@ -561,31 +574,42 @@ pub async fn check_ipc_service_status() -> Result<JsonResponse> {
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"解析服务响应失败: {}; 原始数据: {:?}",
|
||||
"Failed to parse service response: {}; raw data: {:?}",
|
||||
e,
|
||||
data
|
||||
);
|
||||
bail!("无法解析服务响应数据: {}", e)
|
||||
bail!("Unable to parse service response data: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
logging!(error, Type::Service, true, "服务响应中没有数据");
|
||||
bail!("服务响应中没有数据")
|
||||
logging!(error, Type::Service, true, "No data in service response");
|
||||
bail!("No data in service response")
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, true, "IPC通信失败: {}", e);
|
||||
bail!("无法连接到Koala Clash Service: {}", e)
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"IPC communication failed: {}",
|
||||
e
|
||||
);
|
||||
bail!("Unable to connect to Koala Clash Service: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查服务版本 - 使用IPC通信
|
||||
pub async fn check_service_version() -> Result<String> {
|
||||
logging!(info, Type::Service, true, "开始检查服务版本 (IPC)");
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"Starting service version check (IPC)"
|
||||
);
|
||||
|
||||
let payload = serde_json::json!({});
|
||||
// logging!(debug, Type::Service, true, "发送GetVersion请求");
|
||||
@@ -604,8 +628,14 @@ pub async fn check_service_version() -> Result<String> {
|
||||
if !response.success {
|
||||
let err_msg = response
|
||||
.error
|
||||
.unwrap_or_else(|| "获取服务版本失败".to_string());
|
||||
logging!(error, Type::Service, true, "获取版本错误: {}", err_msg);
|
||||
.unwrap_or_else(|| "Failed to get service version".to_string());
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to get service version: {}",
|
||||
err_msg
|
||||
);
|
||||
bail!(err_msg);
|
||||
}
|
||||
|
||||
@@ -618,7 +648,7 @@ pub async fn check_service_version() -> Result<String> {
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"获取到服务版本: {}",
|
||||
"Service version: {}",
|
||||
version_str
|
||||
);
|
||||
return Ok(version_str.to_string());
|
||||
@@ -628,7 +658,7 @@ pub async fn check_service_version() -> Result<String> {
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"嵌套数据中没有version字段: {:?}",
|
||||
"Nested data does not contain version field: {:?}",
|
||||
nested_data
|
||||
);
|
||||
} else {
|
||||
@@ -639,7 +669,7 @@ pub async fn check_service_version() -> Result<String> {
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"获取到服务版本: {}",
|
||||
"Received service version: {}",
|
||||
version_response.version
|
||||
);
|
||||
return Ok(version_response.version);
|
||||
@@ -649,44 +679,55 @@ pub async fn check_service_version() -> Result<String> {
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"解析版本响应失败: {}; 原始数据: {:?}",
|
||||
"Failed to parse version response: {}; raw data: {:?}",
|
||||
e,
|
||||
data
|
||||
);
|
||||
bail!("无法解析服务版本数据: {}", e)
|
||||
bail!("Unable to parse service version data: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
bail!("响应中未找到有效的版本信息")
|
||||
bail!("No valid version information found in response")
|
||||
}
|
||||
None => {
|
||||
logging!(error, Type::Service, true, "版本响应中没有数据");
|
||||
bail!("服务版本响应中没有数据")
|
||||
logging!(error, Type::Service, true, "No data in version response");
|
||||
bail!("No data in service version response")
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, true, "IPC通信失败: {}", e);
|
||||
bail!("无法连接到Koala Clash Service: {}", e)
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"IPC communication failed: {}",
|
||||
e
|
||||
);
|
||||
bail!("Unable to connect to Koala Clash Service: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 检查服务是否需要重装
|
||||
pub async fn check_service_needs_reinstall() -> bool {
|
||||
logging!(info, Type::Service, true, "开始检查服务是否需要重装");
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"Checking whether service needs reinstallation"
|
||||
);
|
||||
|
||||
let service_state = ServiceState::get();
|
||||
|
||||
if !service_state.can_reinstall() {
|
||||
log::info!(target: "app", "服务重装检查: 处于冷却期或已达最大尝试次数");
|
||||
log::info!(target: "app", "Service reinstall check: in cooldown period or max attempts reached");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查版本和可用性
|
||||
match check_service_version().await {
|
||||
Ok(version) => {
|
||||
log::info!(target: "app", "服务版本检测:当前={version}, 要求={REQUIRED_SERVICE_VERSION}");
|
||||
log::info!(target: "app", "Service version check: current={version}, required={REQUIRED_SERVICE_VERSION}");
|
||||
/* logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
@@ -698,25 +739,36 @@ pub async fn check_service_needs_reinstall() -> bool {
|
||||
|
||||
let needs_reinstall = version != REQUIRED_SERVICE_VERSION;
|
||||
if needs_reinstall {
|
||||
log::warn!(target: "app", "发现服务版本不匹配,需要重装! 当前={version}, 要求={REQUIRED_SERVICE_VERSION}");
|
||||
logging!(warn, Type::Service, true, "服务版本不匹配,需要重装");
|
||||
log::warn!(target: "app", "Service version mismatch detected, reinstallation required! current={version}, required={REQUIRED_SERVICE_VERSION}");
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
true,
|
||||
"Service version mismatch, reinstallation required"
|
||||
);
|
||||
|
||||
// log::debug!(target: "app", "当前版本字节: {:?}", version.as_bytes());
|
||||
// log::debug!(target: "app", "要求版本字节: {:?}", REQUIRED_SERVICE_VERSION.as_bytes());
|
||||
} else {
|
||||
log::info!(target: "app", "服务版本匹配,无需重装");
|
||||
log::info!(target: "app", "Service version matches, no reinstallation needed");
|
||||
// logging!(info, Type::Service, true, "服务版本匹配,无需重装");
|
||||
}
|
||||
|
||||
needs_reinstall
|
||||
}
|
||||
Err(err) => {
|
||||
logging!(error, Type::Service, true, "检查服务版本失败: {}", err);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to check service version: {}",
|
||||
err
|
||||
);
|
||||
|
||||
// 检查服务是否可用
|
||||
match is_service_available().await {
|
||||
Ok(()) => {
|
||||
log::info!(target: "app", "服务正在运行但版本检查失败: {err}");
|
||||
log::info!(target: "app", "Service is running but version check failed: {err}");
|
||||
/* logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
@@ -727,7 +779,7 @@ pub async fn check_service_needs_reinstall() -> bool {
|
||||
false
|
||||
}
|
||||
_ => {
|
||||
log::info!(target: "app", "服务不可用或未运行,需要重装");
|
||||
log::info!(target: "app", "Service unavailable or not running, reinstallation needed");
|
||||
// logging!(info, Type::Service, true, "服务不可用或未运行,需要重装");
|
||||
true
|
||||
}
|
||||
@@ -738,7 +790,7 @@ pub async fn check_service_needs_reinstall() -> bool {
|
||||
|
||||
/// 尝试使用服务启动core
|
||||
pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result<()> {
|
||||
log::info!(target:"app", "尝试使用现有服务启动核心 (IPC)");
|
||||
log::info!(target:"app", "Attempting to start core with existing service (IPC)");
|
||||
// logging!(info, Type::Service, true, "尝试使用现有服务启动核心");
|
||||
|
||||
let clash_core = Config::verge().latest().get_valid_clash_core();
|
||||
@@ -781,8 +833,16 @@ pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result
|
||||
); */
|
||||
|
||||
if !response.success {
|
||||
let err_msg = response.error.unwrap_or_else(|| "启动核心失败".to_string());
|
||||
logging!(error, Type::Service, true, "启动核心失败: {}", err_msg);
|
||||
let err_msg = response
|
||||
.error
|
||||
.unwrap_or_else(|| "Failed to start core".to_string());
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to start core: {}",
|
||||
err_msg
|
||||
);
|
||||
bail!(err_msg);
|
||||
}
|
||||
|
||||
@@ -793,127 +853,140 @@ pub(super) async fn start_with_existing_service(config_file: &PathBuf) -> Result
|
||||
let msg = data
|
||||
.get("msg")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("未知错误");
|
||||
.unwrap_or("Unknown error");
|
||||
|
||||
if code_value != 0 {
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"启动核心返回错误: code={}, msg={}",
|
||||
"Start core returned error: code={}, msg={}",
|
||||
code_value,
|
||||
msg
|
||||
);
|
||||
bail!("启动核心失败: {}", msg);
|
||||
bail!("Failed to start core: {}", msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logging!(info, Type::Service, true, "服务成功启动核心");
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"Service successfully started core"
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, true, "启动核心IPC通信失败: {}", e);
|
||||
bail!("无法连接到Koala Clash Service: {}", e)
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to start core via IPC: {}",
|
||||
e
|
||||
);
|
||||
bail!("Unable to connect to Koala Clash Service: {}", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 以服务启动core
|
||||
pub(super) async fn run_core_by_service(config_file: &PathBuf) -> Result<()> {
|
||||
log::info!(target: "app", "正在尝试通过服务启动核心");
|
||||
log::info!(target: "app", "Attempting to start core via service");
|
||||
|
||||
// 先检查服务版本,不受冷却期限制
|
||||
let version_check = match check_service_version().await {
|
||||
Ok(version) => {
|
||||
log::info!(target: "app", "检测到服务版本: {version}, 要求版本: {REQUIRED_SERVICE_VERSION}");
|
||||
log::info!(target: "app", "Detected service version: {version}, required: {REQUIRED_SERVICE_VERSION}");
|
||||
|
||||
if version.as_bytes() != REQUIRED_SERVICE_VERSION.as_bytes() {
|
||||
log::warn!(target: "app", "服务版本不匹配,需要重装");
|
||||
log::warn!(target: "app", "Service version mismatch, reinstallation required");
|
||||
false
|
||||
} else {
|
||||
log::info!(target: "app", "服务版本匹配");
|
||||
log::info!(target: "app", "Service version matches");
|
||||
true
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!(target: "app", "无法获取服务版本: {err}");
|
||||
log::warn!(target: "app", "Failed to get service version: {err}");
|
||||
false
|
||||
}
|
||||
};
|
||||
|
||||
if version_check && is_service_available().await.is_ok() {
|
||||
log::info!(target: "app", "服务已在运行且版本匹配,尝试使用");
|
||||
log::info!(target: "app", "Service is running and version matches, attempting to use it");
|
||||
return start_with_existing_service(config_file).await;
|
||||
}
|
||||
|
||||
if !version_check {
|
||||
log::info!(target: "app", "服务版本不匹配,尝试重装");
|
||||
log::info!(target: "app", "Service version mismatch, attempting reinstallation");
|
||||
|
||||
let service_state = ServiceState::get();
|
||||
if !service_state.can_reinstall() {
|
||||
log::warn!(target: "app", "由于限制无法重装服务");
|
||||
log::warn!(target: "app", "Cannot reinstall service due to limitations");
|
||||
if let Ok(()) = start_with_existing_service(config_file).await {
|
||||
log::info!(target: "app", "尽管版本不匹配,但成功启动了服务");
|
||||
log::info!(target: "app", "Service started successfully despite version mismatch");
|
||||
return Ok(());
|
||||
} else {
|
||||
bail!("服务版本不匹配且无法重装,启动失败");
|
||||
bail!("Service version mismatch and cannot reinstall; startup failed");
|
||||
}
|
||||
}
|
||||
|
||||
log::info!(target: "app", "开始重装服务");
|
||||
log::info!(target: "app", "Starting service reinstallation");
|
||||
if let Err(err) = reinstall_service().await {
|
||||
log::warn!(target: "app", "服务重装失败: {err}");
|
||||
log::warn!(target: "app", "Service reinstallation failed: {err}");
|
||||
|
||||
log::info!(target: "app", "尝试使用现有服务");
|
||||
log::info!(target: "app", "Attempting to use existing service");
|
||||
return start_with_existing_service(config_file).await;
|
||||
}
|
||||
|
||||
log::info!(target: "app", "服务重装成功,尝试启动");
|
||||
log::info!(target: "app", "Service reinstalled successfully, attempting to start");
|
||||
return start_with_existing_service(config_file).await;
|
||||
}
|
||||
|
||||
// 检查服务状态
|
||||
// Check service status
|
||||
match check_ipc_service_status().await {
|
||||
Ok(_) => {
|
||||
log::info!(target: "app", "服务可用但未运行核心,尝试启动");
|
||||
log::info!(target: "app", "Service available but core not running, attempting to start");
|
||||
if let Ok(()) = start_with_existing_service(config_file).await {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!(target: "app", "服务检查失败: {err}");
|
||||
log::warn!(target: "app", "Service check failed: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
// 服务不可用或启动失败,检查是否需要重装
|
||||
// Service unavailable or startup failed, check if reinstallation is needed
|
||||
if check_service_needs_reinstall().await {
|
||||
log::info!(target: "app", "服务需要重装");
|
||||
log::info!(target: "app", "Service needs reinstallation");
|
||||
|
||||
if let Err(err) = reinstall_service().await {
|
||||
log::warn!(target: "app", "服务重装失败: {err}");
|
||||
log::warn!(target: "app", "Service reinstallation failed: {err}");
|
||||
bail!("Failed to reinstall service: {}", err);
|
||||
}
|
||||
|
||||
log::info!(target: "app", "服务重装完成,尝试启动核心");
|
||||
log::info!(target: "app", "Service reinstallation completed, attempting to start core");
|
||||
start_with_existing_service(config_file).await
|
||||
} else {
|
||||
log::warn!(target: "app", "服务不可用且无法重装");
|
||||
log::warn!(target: "app", "Service unavailable and cannot be reinstalled");
|
||||
bail!("Service is not available and cannot be reinstalled at this time")
|
||||
}
|
||||
}
|
||||
|
||||
/// 通过服务停止core
|
||||
pub(super) async fn stop_core_by_service() -> Result<()> {
|
||||
logging!(info, Type::Service, true, "通过服务停止核心 (IPC)");
|
||||
logging!(info, Type::Service, true, "Stopping core via service (IPC)");
|
||||
|
||||
let payload = serde_json::json!({});
|
||||
let response = send_ipc_request(IpcCommand::StopClash, payload)
|
||||
.await
|
||||
.context("无法连接到Koala Clash Service")?;
|
||||
.context("Unable to connect to Koala Clash Service")?;
|
||||
|
||||
if !response.success {
|
||||
bail!(response.error.unwrap_or_else(|| "停止核心失败".to_string()));
|
||||
bail!(response
|
||||
.error
|
||||
.unwrap_or_else(|| "Failed to stop core".to_string()));
|
||||
}
|
||||
|
||||
if let Some(data) = &response.data {
|
||||
@@ -922,18 +995,18 @@ pub(super) async fn stop_core_by_service() -> Result<()> {
|
||||
let msg = data
|
||||
.get("msg")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("未知错误");
|
||||
.unwrap_or("Unknown error");
|
||||
|
||||
if code_value != 0 {
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"停止核心返回错误: code={}, msg={}",
|
||||
"Stop core returned error: code={}, msg={}",
|
||||
code_value,
|
||||
msg
|
||||
);
|
||||
bail!("停止核心失败: {}", msg);
|
||||
bail!("Failed to stop core: {}", msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -943,19 +1016,24 @@ pub(super) async fn stop_core_by_service() -> Result<()> {
|
||||
|
||||
/// 检查服务是否正在运行
|
||||
pub async fn is_service_available() -> Result<()> {
|
||||
logging!(info, Type::Service, true, "开始检查服务是否正在运行");
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"Checking whether service is running"
|
||||
);
|
||||
|
||||
match check_ipc_service_status().await {
|
||||
Ok(resp) => {
|
||||
if resp.code == 0 && resp.msg == "ok" && resp.data.is_some() {
|
||||
logging!(info, Type::Service, true, "服务正在运行");
|
||||
logging!(info, Type::Service, true, "Service is running");
|
||||
Ok(())
|
||||
} else {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Service,
|
||||
true,
|
||||
"服务未正常运行: code={}, msg={}",
|
||||
"Service not running normally: code={}, msg={}",
|
||||
resp.code,
|
||||
resp.msg
|
||||
);
|
||||
@@ -963,7 +1041,13 @@ pub async fn is_service_available() -> Result<()> {
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
logging!(error, Type::Service, true, "检查服务运行状态失败: {}", err);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to check service running status: {}",
|
||||
err
|
||||
);
|
||||
Err(err)
|
||||
}
|
||||
}
|
||||
@@ -971,21 +1055,21 @@ pub async fn is_service_available() -> Result<()> {
|
||||
|
||||
/// 强制重装服务(UI修复按钮)
|
||||
pub async fn force_reinstall_service() -> Result<()> {
|
||||
log::info!(target: "app", "用户请求强制重装服务");
|
||||
log::info!(target: "app", "User requested forced service reinstallation");
|
||||
|
||||
let service_state = ServiceState::default();
|
||||
service_state.save()?;
|
||||
|
||||
log::info!(target: "app", "已重置服务状态,开始执行重装");
|
||||
log::info!(target: "app", "Service state reset, starting reinstallation");
|
||||
|
||||
match reinstall_service().await {
|
||||
Ok(()) => {
|
||||
log::info!(target: "app", "服务重装成功");
|
||||
log::info!(target: "app", "Service reinstalled successfully");
|
||||
Ok(())
|
||||
}
|
||||
Err(err) => {
|
||||
log::error!(target: "app", "强制重装服务失败: {err}");
|
||||
bail!("强制重装服务失败: {}", err)
|
||||
log::error!(target: "app", "Forced service reinstallation failed: {err}");
|
||||
bail!("Forced service reinstallation failed: {}", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,14 +129,25 @@ pub async fn send_ipc_request(
|
||||
winnt::{FILE_SHARE_READ, FILE_SHARE_WRITE, GENERIC_READ, GENERIC_WRITE},
|
||||
};
|
||||
|
||||
logging!(info, Type::Service, true, "正在连接服务 (Windows)...");
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"Connecting to service (Windows)..."
|
||||
);
|
||||
|
||||
let command_type = format!("{:?}", command);
|
||||
|
||||
let request = match create_signed_request(command, payload) {
|
||||
Ok(req) => req,
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, true, "创建签名请求失败: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to create signed request: {}",
|
||||
e
|
||||
);
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
@@ -147,8 +158,14 @@ pub async fn send_ipc_request(
|
||||
let c_pipe_name = match CString::new(IPC_SOCKET_NAME) {
|
||||
Ok(name) => name,
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, true, "创建CString失败: {}", e);
|
||||
return Err(anyhow::anyhow!("创建CString失败: {}", e));
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to create CString: {}",
|
||||
e
|
||||
);
|
||||
return Err(anyhow::anyhow!("Failed to create CString: {}", e));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -177,29 +194,52 @@ pub async fn send_ipc_request(
|
||||
}
|
||||
|
||||
let mut pipe = unsafe { File::from_raw_handle(handle as RawHandle) };
|
||||
logging!(info, Type::Service, true, "服务连接成功 (Windows)");
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"Service connection successful (Windows)"
|
||||
);
|
||||
|
||||
let request_bytes = request_json.as_bytes();
|
||||
let len_bytes = (request_bytes.len() as u32).to_be_bytes();
|
||||
|
||||
if let Err(e) = pipe.write_all(&len_bytes) {
|
||||
logging!(error, Type::Service, true, "写入请求长度失败: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to write request length: {}",
|
||||
e
|
||||
);
|
||||
return Err(anyhow::anyhow!("写入请求长度失败: {}", e));
|
||||
}
|
||||
|
||||
if let Err(e) = pipe.write_all(request_bytes) {
|
||||
logging!(error, Type::Service, true, "写入请求内容失败: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to write request body: {}",
|
||||
e
|
||||
);
|
||||
return Err(anyhow::anyhow!("写入请求内容失败: {}", e));
|
||||
}
|
||||
|
||||
if let Err(e) = pipe.flush() {
|
||||
logging!(error, Type::Service, true, "刷新管道失败: {}", e);
|
||||
logging!(error, Type::Service, true, "Failed to flush pipe: {}", e);
|
||||
return Err(anyhow::anyhow!("刷新管道失败: {}", e));
|
||||
}
|
||||
|
||||
let mut response_len_bytes = [0u8; 4];
|
||||
if let Err(e) = pipe.read_exact(&mut response_len_bytes) {
|
||||
logging!(error, Type::Service, true, "读取响应长度失败: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to read response length: {}",
|
||||
e
|
||||
);
|
||||
return Err(anyhow::anyhow!("读取响应长度失败: {}", e));
|
||||
}
|
||||
|
||||
@@ -207,14 +247,26 @@ pub async fn send_ipc_request(
|
||||
|
||||
let mut response_bytes = vec![0u8; response_len];
|
||||
if let Err(e) = pipe.read_exact(&mut response_bytes) {
|
||||
logging!(error, Type::Service, true, "读取响应内容失败: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to read response body: {}",
|
||||
e
|
||||
);
|
||||
return Err(anyhow::anyhow!("读取响应内容失败: {}", e));
|
||||
}
|
||||
|
||||
let response: IpcResponse = match serde_json::from_slice::<IpcResponse>(&response_bytes) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, true, "服务响应解析失败: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to parse service response: {}",
|
||||
e
|
||||
);
|
||||
return Err(anyhow::anyhow!("解析响应失败: {}", e));
|
||||
}
|
||||
};
|
||||
@@ -222,12 +274,23 @@ pub async fn send_ipc_request(
|
||||
match verify_response_signature(&response) {
|
||||
Ok(valid) => {
|
||||
if !valid {
|
||||
logging!(error, Type::Service, true, "服务响应签名验证失败");
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Service response signature verification failed"
|
||||
);
|
||||
bail!("服务响应签名验证失败");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, true, "验证响应签名时出错: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Error verifying response signature: {}",
|
||||
e
|
||||
);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
@@ -236,7 +299,7 @@ pub async fn send_ipc_request(
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"IPC请求完成: 命令={}, 成功={}",
|
||||
"IPC request completed: command={}, success={}",
|
||||
command_type,
|
||||
response.success
|
||||
);
|
||||
@@ -255,7 +318,7 @@ pub async fn send_ipc_request(
|
||||
) -> Result<IpcResponse> {
|
||||
use std::os::unix::net::UnixStream;
|
||||
|
||||
logging!(info, Type::Service, true, "正在连接服务 (Unix)...");
|
||||
logging!(info, Type::Service, true, "Connecting to service (Unix)...");
|
||||
|
||||
let command_type = format!("{command:?}");
|
||||
|
||||
@@ -271,11 +334,22 @@ pub async fn send_ipc_request(
|
||||
|
||||
let mut stream = match UnixStream::connect(IPC_SOCKET_NAME) {
|
||||
Ok(s) => {
|
||||
logging!(info, Type::Service, true, "服务连接成功 (Unix)");
|
||||
logging!(
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"Service connection successful (Unix)"
|
||||
);
|
||||
s
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, true, "连接到Unix套接字失败: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to connect to Unix socket: {}",
|
||||
e
|
||||
);
|
||||
return Err(anyhow::anyhow!("无法连接到服务Unix套接字: {}", e));
|
||||
}
|
||||
};
|
||||
@@ -310,7 +384,13 @@ pub async fn send_ipc_request(
|
||||
let response: IpcResponse = match serde_json::from_slice::<IpcResponse>(&response_bytes) {
|
||||
Ok(r) => r,
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, true, "服务响应解析失败: {}", e,);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Failed to parse service response: {}",
|
||||
e,
|
||||
);
|
||||
return Err(anyhow::anyhow!("解析响应失败: {}", e));
|
||||
}
|
||||
};
|
||||
@@ -323,7 +403,13 @@ pub async fn send_ipc_request(
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
logging!(error, Type::Service, true, "验证响应签名时出错: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Service,
|
||||
true,
|
||||
"Error verifying response signature: {}",
|
||||
e
|
||||
);
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
@@ -332,7 +418,7 @@ pub async fn send_ipc_request(
|
||||
info,
|
||||
Type::Service,
|
||||
true,
|
||||
"IPC请求完成: 命令={}, 成功={}",
|
||||
"IPC request completed: command={}, success={}",
|
||||
command_type,
|
||||
response.success
|
||||
);
|
||||
|
||||
@@ -63,7 +63,7 @@ impl Sysopt {
|
||||
let proxy_manager = EventDrivenProxyManager::global();
|
||||
proxy_manager.notify_app_started();
|
||||
|
||||
log::info!(target: "app", "已启用事件驱动代理守卫");
|
||||
log::info!(target: "app", "Event-driven proxy guard enabled");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -193,7 +193,7 @@ impl Sysopt {
|
||||
let mut autoproxy = match Autoproxy::get_auto_proxy() {
|
||||
Ok(ap) => ap,
|
||||
Err(e) => {
|
||||
log::warn!(target: "app", "重置代理时获取自动代理配置失败: {e}, 使用默认配置");
|
||||
log::warn!(target: "app", "Failed to get auto proxy config while resetting: {e}, using default config");
|
||||
Autoproxy {
|
||||
enable: false,
|
||||
url: "".to_string(),
|
||||
@@ -248,14 +248,14 @@ impl Sysopt {
|
||||
{
|
||||
if is_enable {
|
||||
if let Err(e) = startup_shortcut::create_shortcut() {
|
||||
log::error!(target: "app", "创建启动快捷方式失败: {}", e);
|
||||
log::error!(target: "app", "Failed to create startup shortcut: {}", e);
|
||||
// 如果快捷方式创建失败,回退到原来的方法
|
||||
self.try_original_autostart_method(is_enable);
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
} else if let Err(e) = startup_shortcut::remove_shortcut() {
|
||||
log::error!(target: "app", "删除启动快捷方式失败: {}", e);
|
||||
log::error!(target: "app", "Failed to remove startup shortcut: {}", e);
|
||||
self.try_original_autostart_method(is_enable);
|
||||
} else {
|
||||
return Ok(());
|
||||
@@ -290,11 +290,11 @@ impl Sysopt {
|
||||
{
|
||||
match startup_shortcut::is_shortcut_enabled() {
|
||||
Ok(enabled) => {
|
||||
log::info!(target: "app", "快捷方式自启动状态: {}", enabled);
|
||||
log::info!(target: "app", "Shortcut auto-launch state: {}", enabled);
|
||||
return Ok(enabled);
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!(target: "app", "检查快捷方式失败,尝试原来的方法: {}", e);
|
||||
log::error!(target: "app", "Failed to check shortcut, falling back to original method: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,7 +73,7 @@ impl Timer {
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"已注册的定时任务数量: {}",
|
||||
"Registered timer task count: {}",
|
||||
timer_map.len()
|
||||
);
|
||||
|
||||
@@ -81,7 +81,7 @@ impl Timer {
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"注册了定时任务 - uid={}, interval={}min, task_id={}",
|
||||
"Registered timer task - uid={}, interval={}min, task_id={}",
|
||||
uid,
|
||||
task.interval_minutes,
|
||||
task.task_id
|
||||
@@ -100,7 +100,12 @@ impl Timer {
|
||||
let uid = item.uid.as_ref()?;
|
||||
|
||||
if interval > 0 && cur_timestamp - updated >= interval * 60 {
|
||||
logging!(info, Type::Timer, "需要立即更新的配置: uid={}", uid);
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"Profile requires immediate update: uid={}",
|
||||
uid
|
||||
);
|
||||
Some(uid.clone())
|
||||
} else {
|
||||
None
|
||||
@@ -116,7 +121,7 @@ impl Timer {
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"需要立即更新的配置数量: {}",
|
||||
"Number of profiles requiring immediate update: {}",
|
||||
profiles_to_update.len()
|
||||
);
|
||||
let timer_map = self.timer_map.read();
|
||||
@@ -124,7 +129,7 @@ impl Timer {
|
||||
|
||||
for uid in profiles_to_update {
|
||||
if let Some(task) = timer_map.get(&uid) {
|
||||
logging!(info, Type::Timer, "立即执行任务: uid={}", uid);
|
||||
logging!(info, Type::Timer, "Executing task immediately: uid={}", uid);
|
||||
if let Err(e) = delay_timer.advance_task(task.task_id) {
|
||||
logging!(warn, Type::Timer, "Failed to advance task {}: {}", uid, e);
|
||||
}
|
||||
@@ -237,7 +242,7 @@ impl Timer {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"找到定时更新配置: uid={}, interval={}min",
|
||||
"Found scheduled update config: uid={}, interval={}min",
|
||||
uid,
|
||||
interval
|
||||
);
|
||||
@@ -251,7 +256,7 @@ impl Timer {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"生成的定时更新配置数量: {}",
|
||||
"Generated scheduled update config count: {}",
|
||||
new_map.len()
|
||||
);
|
||||
new_map
|
||||
@@ -267,7 +272,7 @@ impl Timer {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"当前 timer_map 大小: {}",
|
||||
"Current timer_map size: {}",
|
||||
timer_map.len()
|
||||
);
|
||||
|
||||
@@ -279,7 +284,7 @@ impl Timer {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"定时任务间隔变更: uid={}, 旧={}, 新={}",
|
||||
"Timer task interval changed: uid={}, old={}, new={}",
|
||||
uid,
|
||||
task.interval_minutes,
|
||||
interval
|
||||
@@ -288,12 +293,12 @@ impl Timer {
|
||||
}
|
||||
None => {
|
||||
// Task no longer needed
|
||||
logging!(debug, Type::Timer, "定时任务已删除: uid={}", uid);
|
||||
logging!(debug, Type::Timer, "Timer task removed: uid={}", uid);
|
||||
diff_map.insert(uid.clone(), DiffFlag::Del(task.task_id));
|
||||
}
|
||||
_ => {
|
||||
// Task exists with same interval, no change needed
|
||||
logging!(debug, Type::Timer, "定时任务保持不变: uid={}", uid);
|
||||
logging!(debug, Type::Timer, "Timer task unchanged: uid={}", uid);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -306,7 +311,7 @@ impl Timer {
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"新增定时任务: uid={}, interval={}min",
|
||||
"Added timer task: uid={}, interval={}min",
|
||||
uid,
|
||||
interval
|
||||
);
|
||||
@@ -321,6 +326,12 @@ impl Timer {
|
||||
}
|
||||
|
||||
logging!(debug, Type::Timer, "定时任务变更数量: {}", diff_map.len());
|
||||
logging!(
|
||||
debug,
|
||||
Type::Timer,
|
||||
"Number of timer task changes: {}",
|
||||
diff_map.len()
|
||||
);
|
||||
diff_map
|
||||
}
|
||||
|
||||
@@ -363,13 +374,18 @@ impl Timer {
|
||||
|
||||
/// Get next update time for a profile
|
||||
pub fn get_next_update_time(&self, uid: &str) -> Option<i64> {
|
||||
logging!(info, Type::Timer, "获取下次更新时间,uid={}", uid);
|
||||
logging!(info, Type::Timer, "Getting next update time, uid={}", uid);
|
||||
|
||||
let timer_map = self.timer_map.read();
|
||||
let task = match timer_map.get(uid) {
|
||||
Some(t) => t,
|
||||
None => {
|
||||
logging!(warn, Type::Timer, "找不到对应的定时任务,uid={}", uid);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Timer,
|
||||
"Corresponding timer task not found, uid={}",
|
||||
uid
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
@@ -380,7 +396,7 @@ impl Timer {
|
||||
let items = match profiles.get_items() {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
logging!(warn, Type::Timer, "获取配置列表失败");
|
||||
logging!(warn, Type::Timer, "Failed to get profile list");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
@@ -388,7 +404,12 @@ impl Timer {
|
||||
let profile = match items.iter().find(|item| item.uid.as_deref() == Some(uid)) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
logging!(warn, Type::Timer, "找不到对应的配置,uid={}", uid);
|
||||
logging!(
|
||||
warn,
|
||||
Type::Timer,
|
||||
"Corresponding profile not found, uid={}",
|
||||
uid
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
@@ -401,7 +422,7 @@ impl Timer {
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"计算得到下次更新时间: {}, uid={}",
|
||||
"Calculated next update time: {}, uid={}",
|
||||
next_time,
|
||||
uid
|
||||
);
|
||||
@@ -410,7 +431,7 @@ impl Timer {
|
||||
logging!(
|
||||
warn,
|
||||
Type::Timer,
|
||||
"更新时间或间隔无效,updated={}, interval={}",
|
||||
"Invalid update time or interval, updated={}, interval={}",
|
||||
updated,
|
||||
task.interval_minutes
|
||||
);
|
||||
@@ -442,7 +463,7 @@ impl Timer {
|
||||
logging!(
|
||||
info,
|
||||
Type::Timer,
|
||||
"配置 {} 是否为当前激活配置: {}",
|
||||
"Is profile {} currently active: {}",
|
||||
uid,
|
||||
is_current
|
||||
);
|
||||
|
||||
@@ -3,7 +3,6 @@ use tauri::tray::TrayIconBuilder;
|
||||
#[cfg(target_os = "macos")]
|
||||
pub mod speed_rate;
|
||||
use crate::{
|
||||
cmd,
|
||||
config::Config,
|
||||
feat, logging,
|
||||
module::{lightweight::is_in_lightweight_mode, mihomo::Rate},
|
||||
@@ -46,7 +45,7 @@ fn should_handle_tray_click() -> bool {
|
||||
*last_click = now;
|
||||
true
|
||||
} else {
|
||||
log::debug!(target: "app", "托盘点击被防抖机制忽略,距离上次点击 {:?}ms",
|
||||
log::debug!(target: "app", "Tray click ignored by debounce; time since last click: {:?}ms",
|
||||
now.duration_since(*last_click).as_millis());
|
||||
false
|
||||
}
|
||||
@@ -231,7 +230,7 @@ impl Tray {
|
||||
let app_handle = match handle::Handle::global().app_handle() {
|
||||
Some(handle) => handle,
|
||||
None => {
|
||||
log::warn!(target: "app", "更新托盘菜单失败: app_handle不存在");
|
||||
log::warn!(target: "app", "Failed to update tray menu: app_handle not found");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -279,11 +278,11 @@ impl Tray {
|
||||
profile_uid_and_name,
|
||||
is_lightweight_mode,
|
||||
)?));
|
||||
log::debug!(target: "app", "托盘菜单更新成功");
|
||||
log::debug!(target: "app", "Tray menu updated successfully");
|
||||
Ok(())
|
||||
}
|
||||
None => {
|
||||
log::warn!(target: "app", "更新托盘菜单失败: 托盘不存在");
|
||||
log::warn!(target: "app", "Failed to update tray menu: tray not found");
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -295,7 +294,7 @@ impl Tray {
|
||||
let app_handle = match handle::Handle::global().app_handle() {
|
||||
Some(handle) => handle,
|
||||
None => {
|
||||
log::warn!(target: "app", "更新托盘图标失败: app_handle不存在");
|
||||
log::warn!(target: "app", "Failed to update tray icon: app_handle not found");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -303,7 +302,7 @@ impl Tray {
|
||||
let tray = match app_handle.tray_by_id("main") {
|
||||
Some(tray) => tray,
|
||||
None => {
|
||||
log::warn!(target: "app", "更新托盘图标失败: 托盘不存在");
|
||||
log::warn!(target: "app", "Failed to update tray icon: tray not found");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -332,7 +331,7 @@ impl Tray {
|
||||
let app_handle = match handle::Handle::global().app_handle() {
|
||||
Some(handle) => handle,
|
||||
None => {
|
||||
log::warn!(target: "app", "更新托盘图标失败: app_handle不存在");
|
||||
log::warn!(target: "app", "Failed to update tray icon: app_handle not found");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -340,7 +339,7 @@ impl Tray {
|
||||
let tray = match app_handle.tray_by_id("main") {
|
||||
Some(tray) => tray,
|
||||
None => {
|
||||
log::warn!(target: "app", "更新托盘图标失败: 托盘不存在");
|
||||
log::warn!(target: "app", "Failed to update tray icon: tray not found");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -376,7 +375,7 @@ impl Tray {
|
||||
let app_handle = match handle::Handle::global().app_handle() {
|
||||
Some(handle) => handle,
|
||||
None => {
|
||||
log::warn!(target: "app", "更新托盘提示失败: app_handle不存在");
|
||||
log::warn!(target: "app", "Failed to update tray tooltip: app_handle not found");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -384,7 +383,7 @@ impl Tray {
|
||||
let version = match VERSION.get() {
|
||||
Some(v) => v,
|
||||
None => {
|
||||
log::warn!(target: "app", "更新托盘提示失败: 版本信息不存在");
|
||||
log::warn!(target: "app", "Failed to update tray tooltip: version info not found");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
@@ -423,7 +422,7 @@ impl Tray {
|
||||
current_profile_name
|
||||
)));
|
||||
} else {
|
||||
log::warn!(target: "app", "更新托盘提示失败: 托盘不存在");
|
||||
log::warn!(target: "app", "Failed to update tray tooltip: tray not found");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
@@ -443,7 +442,7 @@ impl Tray {
|
||||
pub fn unsubscribe_traffic(&self) {}
|
||||
|
||||
pub fn create_tray_from_handle(&self, app_handle: &AppHandle) -> Result<()> {
|
||||
log::info!(target: "app", "正在从AppHandle创建系统托盘");
|
||||
log::info!(target: "app", "Creating system tray from AppHandle");
|
||||
|
||||
// 获取图标
|
||||
let icon_bytes = TrayState::get_common_tray_icon().1;
|
||||
@@ -491,20 +490,20 @@ impl Tray {
|
||||
"tun_mode" => feat::toggle_tun_mode(None),
|
||||
"main_window" => {
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
log::info!(target: "app", "Tray点击事件: 显示主窗口");
|
||||
log::info!(target: "app", "Tray click: show main window");
|
||||
if crate::module::lightweight::is_in_lightweight_mode() {
|
||||
log::info!(target: "app", "当前在轻量模式,正在退出轻量模式");
|
||||
log::info!(target: "app", "Currently in lightweight mode, exiting lightweight mode");
|
||||
crate::module::lightweight::exit_lightweight_mode();
|
||||
}
|
||||
let result = WindowManager::show_main_window();
|
||||
log::info!(target: "app", "窗口显示结果: {result:?}");
|
||||
log::info!(target: "app", "Window show result: {result:?}");
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
tray.on_menu_event(on_menu_event);
|
||||
log::info!(target: "app", "系统托盘创建成功");
|
||||
log::info!(target: "app", "System tray created successfully");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -718,18 +717,18 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) {
|
||||
}
|
||||
"open_window" => {
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
log::info!(target: "app", "托盘菜单点击: 打开窗口");
|
||||
log::info!(target: "app", "Tray menu click: open window");
|
||||
|
||||
if !should_handle_tray_click() {
|
||||
return;
|
||||
}
|
||||
|
||||
if crate::module::lightweight::is_in_lightweight_mode() {
|
||||
log::info!(target: "app", "当前在轻量模式,正在退出");
|
||||
log::info!(target: "app", "Currently in lightweight mode, exiting");
|
||||
crate::module::lightweight::exit_lightweight_mode();
|
||||
}
|
||||
let result = WindowManager::show_main_window();
|
||||
log::info!(target: "app", "窗口显示结果: {result:?}");
|
||||
log::info!(target: "app", "Window show result: {result:?}");
|
||||
}
|
||||
"system_proxy" => {
|
||||
feat::toggle_system_proxy();
|
||||
@@ -754,7 +753,7 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) {
|
||||
if was_lightweight {
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
let result = WindowManager::show_main_window();
|
||||
log::info!(target: "app", "退出轻量模式后显示主窗口: {result:?}");
|
||||
log::info!(target: "app", "Show main window after exiting lightweight mode: {result:?}");
|
||||
}
|
||||
}
|
||||
"quit" => {
|
||||
@@ -768,6 +767,6 @@ fn on_menu_event(_: &AppHandle, event: MenuEvent) {
|
||||
}
|
||||
|
||||
if let Err(e) = Tray::global().update_all_states() {
|
||||
log::warn!(target: "app", "更新托盘状态失败: {e}");
|
||||
log::warn!(target: "app", "Failed to update tray state: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -202,7 +202,9 @@ pub async fn enhance() -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
||||
});
|
||||
let patch_tun = value.as_mapping().cloned().unwrap_or(Mapping::new());
|
||||
for (key, value) in patch_tun.into_iter() {
|
||||
tun.insert(key, value);
|
||||
if !tun.contains_key(&key) {
|
||||
tun.insert(key, value);
|
||||
}
|
||||
}
|
||||
config.insert("tun".into(), tun.into());
|
||||
} else {
|
||||
@@ -239,7 +241,7 @@ pub async fn enhance() -> (Mapping, Vec<String>, HashMap<String, ResultLog>) {
|
||||
.filter(|(s, _)| s.is_support(clash_core.as_ref()))
|
||||
.map(|(_, c)| c)
|
||||
.for_each(|item| {
|
||||
log::debug!(target: "app", "run builtin script {}", item.uid);
|
||||
log::debug!(target: "app", "run builtin script {0}", item.uid);
|
||||
if let ChainType::Script(script) = item.data {
|
||||
match use_script(script, config.to_owned(), "".to_string()) {
|
||||
Ok((res_config, _)) => {
|
||||
|
||||
@@ -141,8 +141,8 @@ fn test_script() {
|
||||
fn test_escape_unescape() {
|
||||
let test_string = r#"Hello "World"!\nThis is a test with \u00A9 copyright symbol."#;
|
||||
let escaped = escape_js_string_for_single_quote(test_string);
|
||||
println!("Original: {}", test_string);
|
||||
println!("Escaped: {}", escaped);
|
||||
println!("Original: {test_string}");
|
||||
println!("Escaped: {escaped}");
|
||||
|
||||
let json_str = r#"{"key":"value","nested":{"key":"value"}}"#;
|
||||
let parsed = parse_json_safely(json_str).unwrap();
|
||||
|
||||
@@ -31,7 +31,13 @@ pub async fn update_profile(
|
||||
option: Option<PrfOption>,
|
||||
auto_refresh: Option<bool>,
|
||||
) -> Result<()> {
|
||||
logging!(info, Type::Config, true, "[订阅更新] 开始更新订阅 {}", uid);
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"[Subscription Update] Start updating subscription {}",
|
||||
uid
|
||||
);
|
||||
let auto_refresh = auto_refresh.unwrap_or(true); // 默认为true,保持兼容性
|
||||
|
||||
let url_opt = {
|
||||
@@ -41,14 +47,14 @@ pub async fn update_profile(
|
||||
let is_remote = item.itype.as_ref().is_some_and(|s| s == "remote");
|
||||
|
||||
if !is_remote {
|
||||
log::info!(target: "app", "[订阅更新] {uid} 不是远程订阅,跳过更新");
|
||||
log::info!(target: "app", "[Subscription Update] {uid} is not a remote subscription, skipping update");
|
||||
None // 非远程订阅直接更新
|
||||
} else if item.url.is_none() {
|
||||
log::warn!(target: "app", "[订阅更新] {uid} 缺少URL,无法更新");
|
||||
log::warn!(target: "app", "[Subscription Update] {uid} is missing URL, cannot update");
|
||||
bail!("failed to get the profile item url");
|
||||
} else {
|
||||
log::info!(target: "app",
|
||||
"[订阅更新] {} 是远程订阅,URL: {}",
|
||||
"[Subscription Update] {} is a remote subscription, URL: {}",
|
||||
uid,
|
||||
item.url.clone().unwrap()
|
||||
);
|
||||
@@ -58,24 +64,24 @@ pub async fn update_profile(
|
||||
|
||||
let should_update = match url_opt {
|
||||
Some((url, opt)) => {
|
||||
log::info!(target: "app", "[订阅更新] 开始下载新的订阅内容");
|
||||
log::info!(target: "app", "[Subscription Update] Start downloading new subscription content");
|
||||
let merged_opt = PrfOption::merge(opt.clone(), option.clone());
|
||||
|
||||
// 尝试使用正常设置更新
|
||||
match PrfItem::from_url(&url, None, None, merged_opt.clone()).await {
|
||||
Ok(item) => {
|
||||
log::info!(target: "app", "[订阅更新] 更新订阅配置成功");
|
||||
log::info!(target: "app", "[Subscription Update] Subscription config updated successfully");
|
||||
let profiles = Config::profiles();
|
||||
let mut profiles = profiles.latest();
|
||||
profiles.update_item(uid.clone(), item)?;
|
||||
|
||||
let is_current = Some(uid.clone()) == profiles.get_current();
|
||||
log::info!(target: "app", "[订阅更新] 是否为当前使用的订阅: {is_current}");
|
||||
log::info!(target: "app", "[Subscription Update] Is current active subscription: {is_current}");
|
||||
is_current && auto_refresh
|
||||
}
|
||||
Err(err) => {
|
||||
// 首次更新失败,尝试使用Clash代理
|
||||
log::warn!(target: "app", "[订阅更新] 正常更新失败: {err},尝试使用Clash代理更新");
|
||||
log::warn!(target: "app", "[Subscription Update] Normal update failed: {err}, trying to update via Clash proxy");
|
||||
|
||||
// 发送通知
|
||||
handle::Handle::notice_message("update_retry_with_clash", uid.clone());
|
||||
@@ -92,7 +98,7 @@ pub async fn update_profile(
|
||||
// 使用Clash代理重试
|
||||
match PrfItem::from_url(&url, None, None, Some(fallback_opt)).await {
|
||||
Ok(mut item) => {
|
||||
log::info!(target: "app", "[订阅更新] 使用Clash代理更新成功");
|
||||
log::info!(target: "app", "[Subscription Update] Update via Clash proxy succeeded");
|
||||
|
||||
// 恢复原始代理设置到item
|
||||
if let Some(option) = item.option.as_mut() {
|
||||
@@ -112,11 +118,11 @@ pub async fn update_profile(
|
||||
handle::Handle::notice_message("update_with_clash_proxy", profile_name);
|
||||
|
||||
let is_current = Some(uid.clone()) == profiles.get_current();
|
||||
log::info!(target: "app", "[订阅更新] 是否为当前使用的订阅: {is_current}");
|
||||
log::info!(target: "app", "[Subscription Update] Is current active subscription: {is_current}");
|
||||
is_current && auto_refresh
|
||||
}
|
||||
Err(retry_err) => {
|
||||
log::error!(target: "app", "[订阅更新] 使用Clash代理更新仍然失败: {retry_err}");
|
||||
log::error!(target: "app", "[Subscription Update] Update via Clash proxy still failed: {retry_err}");
|
||||
handle::Handle::notice_message(
|
||||
"update_failed_even_with_clash",
|
||||
format!("{retry_err}"),
|
||||
@@ -131,14 +137,30 @@ pub async fn update_profile(
|
||||
};
|
||||
|
||||
if should_update {
|
||||
logging!(info, Type::Config, true, "[订阅更新] 更新内核配置");
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"[Subscription Update] Update core configuration"
|
||||
);
|
||||
match CoreManager::global().update_config().await {
|
||||
Ok(_) => {
|
||||
logging!(info, Type::Config, true, "[订阅更新] 更新成功");
|
||||
logging!(
|
||||
info,
|
||||
Type::Config,
|
||||
true,
|
||||
"[Subscription Update] Update succeeded"
|
||||
);
|
||||
handle::Handle::refresh_clash();
|
||||
}
|
||||
Err(err) => {
|
||||
logging!(error, Type::Config, true, "[订阅更新] 更新失败: {}", err);
|
||||
logging!(
|
||||
error,
|
||||
Type::Config,
|
||||
true,
|
||||
"[Subscription Update] Update failed: {}",
|
||||
err
|
||||
);
|
||||
handle::Handle::notice_message("update_failed", format!("{err}"));
|
||||
log::error!(target: "app", "{err}");
|
||||
}
|
||||
|
||||
@@ -25,14 +25,14 @@ fn open_or_close_dashboard_internal(bypass_debounce: bool) {
|
||||
use crate::process::AsyncHandler;
|
||||
use crate::utils::window_manager::WindowManager;
|
||||
|
||||
log::info!(target: "app", "Attempting to open/close dashboard (绕过防抖: {bypass_debounce})");
|
||||
log::info!(target: "app", "Attempting to open/close dashboard (bypass debounce: {bypass_debounce})");
|
||||
|
||||
// 热键调用调度到主线程执行,避免 WebView 创建死锁
|
||||
if bypass_debounce {
|
||||
log::info!(target: "app", "热键调用,调度到主线程执行窗口操作");
|
||||
log::info!(target: "app", "Hotkey invoked, dispatching window operation to main thread");
|
||||
|
||||
AsyncHandler::spawn(move || async move {
|
||||
log::info!(target: "app", "主线程中执行热键窗口操作");
|
||||
log::info!(target: "app", "Executing hotkey window operation on main thread");
|
||||
|
||||
if crate::module::lightweight::is_in_lightweight_mode() {
|
||||
log::info!(target: "app", "Currently in lightweight mode, exiting lightweight mode");
|
||||
@@ -64,7 +64,7 @@ fn open_or_close_dashboard_internal(bypass_debounce: bool) {
|
||||
/// 异步优化的应用退出函数
|
||||
pub fn quit() {
|
||||
use crate::process::AsyncHandler;
|
||||
logging!(debug, Type::System, true, "启动退出流程");
|
||||
logging!(debug, Type::System, true, "Start exit process");
|
||||
|
||||
// 获取应用句柄并设置退出标志
|
||||
let app_handle = handle::Handle::global().app_handle().unwrap();
|
||||
@@ -73,19 +73,24 @@ pub fn quit() {
|
||||
// 优先关闭窗口,提供立即反馈
|
||||
if let Some(window) = handle::Handle::global().get_window() {
|
||||
let _ = window.hide();
|
||||
log::info!(target: "app", "窗口已隐藏");
|
||||
log::info!(target: "app", "Window hidden");
|
||||
}
|
||||
|
||||
// 使用异步任务处理资源清理,避免阻塞
|
||||
AsyncHandler::spawn(move || async move {
|
||||
logging!(info, Type::System, true, "开始异步清理资源");
|
||||
logging!(
|
||||
info,
|
||||
Type::System,
|
||||
true,
|
||||
"Start asynchronous resource cleanup"
|
||||
);
|
||||
let cleanup_result = clean_async().await;
|
||||
|
||||
logging!(
|
||||
info,
|
||||
Type::System,
|
||||
true,
|
||||
"资源清理完成,退出代码: {}",
|
||||
"Resource cleanup completed, exit code: {}",
|
||||
if cleanup_result { 0 } else { 1 }
|
||||
);
|
||||
app_handle.exit(if cleanup_result { 0 } else { 1 });
|
||||
@@ -95,7 +100,12 @@ pub fn quit() {
|
||||
async fn clean_async() -> bool {
|
||||
use tokio::time::{timeout, Duration};
|
||||
|
||||
logging!(info, Type::System, true, "开始执行异步清理操作...");
|
||||
logging!(
|
||||
info,
|
||||
Type::System,
|
||||
true,
|
||||
"Start executing asynchronous cleanup..."
|
||||
);
|
||||
|
||||
// 1. 处理TUN模式
|
||||
let tun_task = async {
|
||||
@@ -112,11 +122,11 @@ async fn clean_async() -> bool {
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
log::info!(target: "app", "TUN模式已禁用");
|
||||
log::info!(target: "app", "TUN mode disabled");
|
||||
true
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!(target: "app", "禁用TUN模式超时");
|
||||
log::warn!(target: "app", "Timeout disabling TUN mode");
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -134,11 +144,11 @@ async fn clean_async() -> bool {
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
log::info!(target: "app", "系统代理已重置");
|
||||
log::info!(target: "app", "System proxy reset");
|
||||
true
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!(target: "app", "重置系统代理超时");
|
||||
log::warn!(target: "app", "Timeout resetting system proxy");
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -148,11 +158,11 @@ async fn clean_async() -> bool {
|
||||
let core_task = async {
|
||||
match timeout(Duration::from_secs(3), CoreManager::global().stop_core()).await {
|
||||
Ok(_) => {
|
||||
log::info!(target: "app", "核心服务已停止");
|
||||
log::info!(target: "app", "Core service stopped");
|
||||
true
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!(target: "app", "停止核心服务超时");
|
||||
log::warn!(target: "app", "Timeout stopping core service");
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -168,11 +178,11 @@ async fn clean_async() -> bool {
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
log::info!(target: "app", "DNS设置已恢复");
|
||||
log::info!(target: "app", "DNS settings restored");
|
||||
true
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!(target: "app", "恢复DNS设置超时");
|
||||
log::warn!(target: "app", "Timeout restoring DNS settings");
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -192,7 +202,7 @@ async fn clean_async() -> bool {
|
||||
info,
|
||||
Type::System,
|
||||
true,
|
||||
"异步清理操作完成 - TUN: {}, 代理: {}, 核心: {}, DNS: {}, 总体: {}",
|
||||
"Asynchronous cleanup completed - TUN: {}, Proxy: {}, Core: {}, DNS: {}, Overall: {}",
|
||||
tun_success,
|
||||
proxy_success,
|
||||
core_success,
|
||||
@@ -209,7 +219,7 @@ pub fn clean() -> bool {
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
|
||||
AsyncHandler::spawn(move || async move {
|
||||
logging!(info, Type::System, true, "开始执行清理操作...");
|
||||
logging!(info, Type::System, true, "Start executing cleanup...");
|
||||
|
||||
// 使用已有的异步清理函数
|
||||
let cleanup_result = clean_async().await;
|
||||
@@ -220,7 +230,13 @@ pub fn clean() -> bool {
|
||||
|
||||
match rx.recv_timeout(std::time::Duration::from_secs(8)) {
|
||||
Ok(result) => {
|
||||
logging!(info, Type::System, true, "清理操作完成,结果: {}", result);
|
||||
logging!(
|
||||
info,
|
||||
Type::System,
|
||||
true,
|
||||
"Cleanup completed, result: {}",
|
||||
result
|
||||
);
|
||||
result
|
||||
}
|
||||
Err(_) => {
|
||||
@@ -228,7 +244,7 @@ pub fn clean() -> bool {
|
||||
warn,
|
||||
Type::System,
|
||||
true,
|
||||
"清理操作超时,返回成功状态避免阻塞"
|
||||
"Cleanup timed out, returning success to avoid blocking"
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
@@ -115,7 +115,7 @@ pub fn run() {
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.plugin(tauri_plugin_deep_link::init())
|
||||
.setup(|app| {
|
||||
logging!(info, Type::Setup, true, "开始应用初始化...");
|
||||
logging!(info, Type::Setup, true, "Starting app initialization...");
|
||||
let mut auto_start_plugin_builder = tauri_plugin_autostart::Builder::new();
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
@@ -128,7 +128,7 @@ pub fn run() {
|
||||
#[cfg(any(target_os = "linux", all(debug_assertions, windows)))]
|
||||
{
|
||||
use tauri_plugin_deep_link::DeepLinkExt;
|
||||
logging!(info, Type::Setup, true, "注册深层链接...");
|
||||
logging!(info, Type::Setup, true, "Registering deep links...");
|
||||
logging_error!(Type::System, true, app.deep_link().register_all());
|
||||
}
|
||||
|
||||
@@ -144,7 +144,12 @@ pub fn run() {
|
||||
});
|
||||
|
||||
// 窗口管理
|
||||
logging!(info, Type::Setup, true, "初始化窗口状态管理...");
|
||||
logging!(
|
||||
info,
|
||||
Type::Setup,
|
||||
true,
|
||||
"Initializing window state management..."
|
||||
);
|
||||
let window_state_plugin = tauri_plugin_window_state::Builder::new()
|
||||
.with_filename("window_state.json")
|
||||
.with_state_flags(tauri_plugin_window_state::StateFlags::default())
|
||||
@@ -154,7 +159,12 @@ pub fn run() {
|
||||
// 异步处理
|
||||
let app_handle = app.handle().clone();
|
||||
AsyncHandler::spawn(move || async move {
|
||||
logging!(info, Type::Setup, true, "异步执行应用设置...");
|
||||
logging!(
|
||||
info,
|
||||
Type::Setup,
|
||||
true,
|
||||
"Executing app setup asynchronously..."
|
||||
);
|
||||
match timeout(
|
||||
Duration::from_secs(30),
|
||||
resolve::resolve_setup_async(&app_handle),
|
||||
@@ -162,35 +172,52 @@ pub fn run() {
|
||||
.await
|
||||
{
|
||||
Ok(_) => {
|
||||
logging!(info, Type::Setup, true, "应用设置成功完成");
|
||||
logging!(info, Type::Setup, true, "App setup completed successfully");
|
||||
}
|
||||
Err(_) => {
|
||||
logging!(
|
||||
error,
|
||||
Type::Setup,
|
||||
true,
|
||||
"应用设置超时(30秒),继续执行后续流程"
|
||||
"App setup timed out (30s), continuing with subsequent steps"
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
logging!(info, Type::Setup, true, "执行主要设置操作...");
|
||||
logging!(
|
||||
info,
|
||||
Type::Setup,
|
||||
true,
|
||||
"Executing main setup operations..."
|
||||
);
|
||||
|
||||
logging!(info, Type::Setup, true, "初始化AppHandleManager...");
|
||||
logging!(info, Type::Setup, true, "Initializing AppHandleManager...");
|
||||
AppHandleManager::global().init(app.handle().clone());
|
||||
|
||||
logging!(info, Type::Setup, true, "初始化核心句柄...");
|
||||
logging!(info, Type::Setup, true, "Initializing core handle...");
|
||||
core::handle::Handle::global().init(app.handle());
|
||||
|
||||
logging!(info, Type::Setup, true, "初始化配置...");
|
||||
logging!(info, Type::Setup, true, "Initializing config...");
|
||||
if let Err(e) = utils::init::init_config() {
|
||||
logging!(error, Type::Setup, true, "初始化配置失败: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Setup,
|
||||
true,
|
||||
"Failed to initialize config: {}",
|
||||
e
|
||||
);
|
||||
}
|
||||
|
||||
logging!(info, Type::Setup, true, "初始化资源...");
|
||||
logging!(info, Type::Setup, true, "Initializing resources...");
|
||||
if let Err(e) = utils::init::init_resources() {
|
||||
logging!(error, Type::Setup, true, "初始化资源失败: {}", e);
|
||||
logging!(
|
||||
error,
|
||||
Type::Setup,
|
||||
true,
|
||||
"Failed to initialize resources: {}",
|
||||
e
|
||||
);
|
||||
}
|
||||
|
||||
app.manage(Mutex::new(state::proxy::CmdProxyState::default()));
|
||||
@@ -198,13 +225,23 @@ pub fn run() {
|
||||
|
||||
tauri::async_runtime::spawn(async {
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
logging!(info, Type::Cmd, true, "Running profile updates at startup...");
|
||||
logging!(
|
||||
info,
|
||||
Type::Cmd,
|
||||
true,
|
||||
"Running profile updates at startup..."
|
||||
);
|
||||
if let Err(e) = crate::cmd::update_profiles_on_startup().await {
|
||||
log::error!("Failed to update profiles on startup: {}", e);
|
||||
log::error!("Failed to update profiles on startup: {e}");
|
||||
}
|
||||
});
|
||||
|
||||
logging!(info, Type::Setup, true, "初始化完成,继续执行");
|
||||
logging!(
|
||||
info,
|
||||
Type::Setup,
|
||||
true,
|
||||
"Initialization completed, continuing"
|
||||
);
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
@@ -324,7 +361,7 @@ pub fn run() {
|
||||
|
||||
app.run(|app_handle, e| match e {
|
||||
tauri::RunEvent::Ready | tauri::RunEvent::Resumed => {
|
||||
logging!(info, Type::System, true, "应用就绪或恢复");
|
||||
logging!(info, Type::System, true, "App ready or resumed");
|
||||
AppHandleManager::global().init(app_handle.clone());
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
@@ -332,7 +369,7 @@ pub fn run() {
|
||||
.get_handle()
|
||||
.get_webview_window("main")
|
||||
{
|
||||
logging!(info, Type::Window, true, "设置macOS窗口标题");
|
||||
logging!(info, Type::Window, true, "Setting macOS window title");
|
||||
let _ = window.set_title("Koala Clash");
|
||||
}
|
||||
}
|
||||
@@ -376,7 +413,12 @@ pub fn run() {
|
||||
if let Some(window) = core::handle::Handle::global().get_window() {
|
||||
let _ = window.hide();
|
||||
} else {
|
||||
logging!(warn, Type::Window, true, "尝试隐藏窗口但窗口不存在");
|
||||
logging!(
|
||||
warn,
|
||||
Type::Window,
|
||||
true,
|
||||
"Tried to hide window but it does not exist"
|
||||
);
|
||||
}
|
||||
}
|
||||
tauri::WindowEvent::Focused(true) => {
|
||||
|
||||
@@ -28,9 +28,9 @@ impl LightWeightState {
|
||||
pub fn set_lightweight_mode(&mut self, value: bool) -> &Self {
|
||||
self.is_lightweight = value;
|
||||
if value {
|
||||
logging!(info, Type::Lightweight, true, "轻量模式已开启");
|
||||
logging!(info, Type::Lightweight, true, "Lightweight mode enabled");
|
||||
} else {
|
||||
logging!(info, Type::Lightweight, true, "轻量模式已关闭");
|
||||
logging!(info, Type::Lightweight, true, "Lightweight mode disabled");
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
@@ -41,9 +41,9 @@ pub fn create_shortcut() -> Result<()> {
|
||||
let startup_dir = get_startup_dir()?;
|
||||
let shortcut_path = startup_dir.join("Koala-Clash.lnk");
|
||||
|
||||
// 如果快捷方式已存在,直接返回成功
|
||||
// If the shortcut already exists, return success directly
|
||||
if shortcut_path.exists() {
|
||||
info!(target: "app", "启动快捷方式已存在");
|
||||
info!(target: "app", "Startup shortcut already exists");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
@@ -59,36 +59,36 @@ pub fn create_shortcut() -> Result<()> {
|
||||
|
||||
let output = std::process::Command::new("powershell")
|
||||
.args(["-Command", &powershell_command])
|
||||
// 隐藏 PowerShell 窗口
|
||||
// Hide the PowerShell window
|
||||
.creation_flags(0x08000000) // CREATE_NO_WINDOW
|
||||
.output()
|
||||
.map_err(|e| anyhow!("执行 PowerShell 命令失败: {}", e))?;
|
||||
.map_err(|e| anyhow!("Failed to execute PowerShell command: {}", e))?;
|
||||
|
||||
if !output.status.success() {
|
||||
let error_msg = String::from_utf8_lossy(&output.stderr);
|
||||
return Err(anyhow!("创建快捷方式失败: {}", error_msg));
|
||||
return Err(anyhow!("Failed to create shortcut: {}", error_msg));
|
||||
}
|
||||
|
||||
info!(target: "app", "成功创建启动快捷方式");
|
||||
info!(target: "app", "Successfully created startup shortcut");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 删除快捷方式
|
||||
/// Remove the shortcut
|
||||
#[cfg(target_os = "windows")]
|
||||
pub fn remove_shortcut() -> Result<()> {
|
||||
let startup_dir = get_startup_dir()?;
|
||||
let shortcut_path = startup_dir.join("Koala-Clash.lnk");
|
||||
|
||||
// 如果快捷方式不存在,直接返回成功
|
||||
// If the shortcut does not exist, return success directly
|
||||
if !shortcut_path.exists() {
|
||||
info!(target: "app", "启动快捷方式不存在,无需删除");
|
||||
info!(target: "app", "Startup shortcut does not exist, nothing to remove");
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// 删除快捷方式
|
||||
fs::remove_file(&shortcut_path).map_err(|e| anyhow!("删除快捷方式失败: {}", e))?;
|
||||
// Delete the shortcut
|
||||
fs::remove_file(&shortcut_path).map_err(|e| anyhow!("Failed to delete shortcut: {}", e))?;
|
||||
|
||||
info!(target: "app", "成功删除启动快捷方式");
|
||||
info!(target: "app", "Successfully removed startup shortcut");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -23,7 +23,6 @@ use tauri::{AppHandle, Manager};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
use tauri::Url;
|
||||
use crate::config::PrfOption;
|
||||
//#[cfg(not(target_os = "linux"))]
|
||||
// use window_shadows::set_shadow;
|
||||
|
||||
@@ -556,7 +555,9 @@ pub async fn resolve_scheme(param: String) -> Result<()> {
|
||||
for (key, value) in link_parsed.query_pairs() {
|
||||
match key.as_ref() {
|
||||
"name" => name = Some(value.into_owned()),
|
||||
"url" => url_param = Some(percent_decode_str(&value).decode_utf8_lossy().to_string()),
|
||||
"url" => {
|
||||
url_param = Some(percent_decode_str(&value).decode_utf8_lossy().to_string())
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ fn get_window_operation_debounce() -> &'static Mutex<Instant> {
|
||||
|
||||
fn should_handle_window_operation() -> bool {
|
||||
if WINDOW_OPERATION_IN_PROGRESS.load(Ordering::Acquire) {
|
||||
log::warn!(target: "app", "[防抖] 窗口操作已在进行中,跳过重复调用");
|
||||
log::warn!(target: "app", "[debounce] Window operation already in progress, skipping duplicate call");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -62,16 +62,16 @@ fn should_handle_window_operation() -> bool {
|
||||
let now = Instant::now();
|
||||
let elapsed = now.duration_since(*last_operation);
|
||||
|
||||
log::debug!(target: "app", "[防抖] 检查窗口操作间隔: {}ms (需要>={}ms)",
|
||||
log::debug!(target: "app", "[debounce] Checking window operation interval: {}ms (need >={}ms)",
|
||||
elapsed.as_millis(), WINDOW_OPERATION_DEBOUNCE_MS);
|
||||
|
||||
if elapsed >= Duration::from_millis(WINDOW_OPERATION_DEBOUNCE_MS) {
|
||||
*last_operation = now;
|
||||
WINDOW_OPERATION_IN_PROGRESS.store(true, Ordering::Release);
|
||||
log::info!(target: "app", "[防抖] 窗口操作被允许执行");
|
||||
log::info!(target: "app", "[debounce] Window operation allowed to execute");
|
||||
true
|
||||
} else {
|
||||
log::warn!(target: "app", "[防抖] 窗口操作被防抖机制忽略,距离上次操作 {}ms < {}ms",
|
||||
log::warn!(target: "app", "[debounce] Window operation ignored by debounce: {}ms since last < {}ms",
|
||||
elapsed.as_millis(), WINDOW_OPERATION_DEBOUNCE_MS);
|
||||
false
|
||||
}
|
||||
|
||||
@@ -31,4 +31,3 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,9 +3,9 @@ import Layout from "./pages/_layout";
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<AppDataProvider>
|
||||
<Layout />
|
||||
</AppDataProvider>
|
||||
<AppDataProvider>
|
||||
<Layout />
|
||||
</AppDataProvider>
|
||||
);
|
||||
}
|
||||
export default App;
|
||||
|
||||
@@ -73,21 +73,25 @@ interface Props {
|
||||
scrollerRef: (element: HTMLElement | Window | null) => void;
|
||||
}
|
||||
|
||||
const ColumnResizer = ({ header }: { header: Header<ConnectionRow, unknown> }) => {
|
||||
const ColumnResizer = ({
|
||||
header,
|
||||
}: {
|
||||
header: Header<ConnectionRow, unknown>;
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
onMouseDown={header.getResizeHandler()}
|
||||
onTouchStart={header.getResizeHandler()}
|
||||
className={cn(
|
||||
"absolute right-0 top-0 h-full w-1 cursor-col-resize select-none touch-none",
|
||||
"bg-transparent hover:bg-primary/50 active:bg-primary",
|
||||
"transition-colors duration-150",
|
||||
header.column.getIsResizing() && "bg-primary"
|
||||
)}
|
||||
style={{
|
||||
transform: header.column.getIsResizing() ? `translateX(0px)` : "",
|
||||
}}
|
||||
/>
|
||||
<div
|
||||
onMouseDown={header.getResizeHandler()}
|
||||
onTouchStart={header.getResizeHandler()}
|
||||
className={cn(
|
||||
"absolute right-0 top-0 h-full w-1 cursor-col-resize select-none touch-none",
|
||||
"bg-transparent hover:bg-primary/50 active:bg-primary",
|
||||
"transition-colors duration-150",
|
||||
header.column.getIsResizing() && "bg-primary",
|
||||
)}
|
||||
style={{
|
||||
transform: header.column.getIsResizing() ? `translateX(0px)` : "",
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -105,8 +109,8 @@ export const ConnectionTable = (props: Props) => {
|
||||
try {
|
||||
const saved = localStorage.getItem("connection-table-widths");
|
||||
return saved
|
||||
? JSON.parse(saved)
|
||||
: {
|
||||
? JSON.parse(saved)
|
||||
: {
|
||||
host: 220,
|
||||
download: 88,
|
||||
upload: 88,
|
||||
@@ -140,8 +144,8 @@ export const ConnectionTable = (props: Props) => {
|
||||
|
||||
useEffect(() => {
|
||||
localStorage.setItem(
|
||||
"connection-table-widths",
|
||||
JSON.stringify(columnSizing)
|
||||
"connection-table-widths",
|
||||
JSON.stringify(columnSizing),
|
||||
);
|
||||
}, [columnSizing]);
|
||||
|
||||
@@ -151,13 +155,13 @@ export const ConnectionTable = (props: Props) => {
|
||||
const chains = [...each.chains].reverse().join(" / ");
|
||||
const rule = rulePayload ? `${each.rule}(${rulePayload})` : each.rule;
|
||||
const Destination = metadata.destinationIP
|
||||
? `${metadata.destinationIP}:${metadata.destinationPort}`
|
||||
: `${metadata.remoteDestination}:${metadata.destinationPort}`;
|
||||
? `${metadata.destinationIP}:${metadata.destinationPort}`
|
||||
: `${metadata.remoteDestination}:${metadata.destinationPort}`;
|
||||
return {
|
||||
id: each.id,
|
||||
host: metadata.host
|
||||
? `${metadata.host}:${metadata.destinationPort}`
|
||||
: `${metadata.remoteDestination}:${metadata.destinationPort}`,
|
||||
? `${metadata.host}:${metadata.destinationPort}`
|
||||
: `${metadata.remoteDestination}:${metadata.destinationPort}`,
|
||||
download: each.download,
|
||||
upload: each.upload,
|
||||
dlSpeed: each.curDownload ?? 0,
|
||||
@@ -175,118 +179,118 @@ export const ConnectionTable = (props: Props) => {
|
||||
}, [connections]);
|
||||
|
||||
const columns = useMemo<ColumnDef<ConnectionRow>[]>(
|
||||
() => [
|
||||
{
|
||||
accessorKey: "host",
|
||||
header: () => t("Host"),
|
||||
size: columnSizing?.host || 220,
|
||||
minSize: 180,
|
||||
maxSize: 400,
|
||||
},
|
||||
{
|
||||
accessorKey: "download",
|
||||
header: () => t("Downloaded"),
|
||||
size: columnSizing?.download || 88,
|
||||
minSize: 80,
|
||||
maxSize: 150,
|
||||
cell: ({ getValue }) => (
|
||||
<div className="text-right font-mono text-sm">
|
||||
{parseTraffic(getValue<number>()).join(" ")}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "upload",
|
||||
header: () => t("Uploaded"),
|
||||
size: columnSizing?.upload || 88,
|
||||
minSize: 80,
|
||||
maxSize: 150,
|
||||
cell: ({ getValue }) => (
|
||||
<div className="text-right font-mono text-sm">
|
||||
{parseTraffic(getValue<number>()).join(" ")}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "dlSpeed",
|
||||
header: () => t("DL Speed"),
|
||||
size: columnSizing?.dlSpeed || 88,
|
||||
minSize: 80,
|
||||
maxSize: 150,
|
||||
cell: ({ getValue }) => (
|
||||
<div className="text-right font-mono text-sm">
|
||||
{parseTraffic(getValue<number>()).join(" ")}/s
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "ulSpeed",
|
||||
header: () => t("UL Speed"),
|
||||
size: columnSizing?.ulSpeed || 88,
|
||||
minSize: 80,
|
||||
maxSize: 150,
|
||||
cell: ({ getValue }) => (
|
||||
<div className="text-right font-mono text-sm">
|
||||
{parseTraffic(getValue<number>()).join(" ")}/s
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "chains",
|
||||
header: () => t("Chains"),
|
||||
size: columnSizing?.chains || 340,
|
||||
minSize: 180,
|
||||
maxSize: 500,
|
||||
},
|
||||
{
|
||||
accessorKey: "rule",
|
||||
header: () => t("Rule"),
|
||||
size: columnSizing?.rule || 280,
|
||||
minSize: 180,
|
||||
maxSize: 400,
|
||||
},
|
||||
{
|
||||
accessorKey: "process",
|
||||
header: () => t("Process"),
|
||||
size: columnSizing?.process || 220,
|
||||
minSize: 180,
|
||||
maxSize: 350,
|
||||
},
|
||||
{
|
||||
accessorKey: "time",
|
||||
header: () => t("Time"),
|
||||
size: columnSizing?.time || 120,
|
||||
minSize: 100,
|
||||
maxSize: 180,
|
||||
cell: ({ getValue }) => (
|
||||
<div className="text-right font-mono text-sm">
|
||||
{dayjs(getValue<string>()).fromNow()}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "source",
|
||||
header: () => t("Source"),
|
||||
size: columnSizing?.source || 200,
|
||||
minSize: 130,
|
||||
maxSize: 300,
|
||||
},
|
||||
{
|
||||
accessorKey: "remoteDestination",
|
||||
header: () => t("Destination"),
|
||||
size: columnSizing?.remoteDestination || 200,
|
||||
minSize: 130,
|
||||
maxSize: 300,
|
||||
},
|
||||
{
|
||||
accessorKey: "type",
|
||||
header: () => t("Type"),
|
||||
size: columnSizing?.type || 160,
|
||||
minSize: 100,
|
||||
maxSize: 220,
|
||||
},
|
||||
],
|
||||
[columnSizing]
|
||||
() => [
|
||||
{
|
||||
accessorKey: "host",
|
||||
header: () => t("Host"),
|
||||
size: columnSizing?.host || 220,
|
||||
minSize: 180,
|
||||
maxSize: 400,
|
||||
},
|
||||
{
|
||||
accessorKey: "download",
|
||||
header: () => t("Downloaded"),
|
||||
size: columnSizing?.download || 88,
|
||||
minSize: 80,
|
||||
maxSize: 150,
|
||||
cell: ({ getValue }) => (
|
||||
<div className="text-right font-mono text-sm">
|
||||
{parseTraffic(getValue<number>()).join(" ")}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "upload",
|
||||
header: () => t("Uploaded"),
|
||||
size: columnSizing?.upload || 88,
|
||||
minSize: 80,
|
||||
maxSize: 150,
|
||||
cell: ({ getValue }) => (
|
||||
<div className="text-right font-mono text-sm">
|
||||
{parseTraffic(getValue<number>()).join(" ")}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "dlSpeed",
|
||||
header: () => t("DL Speed"),
|
||||
size: columnSizing?.dlSpeed || 88,
|
||||
minSize: 80,
|
||||
maxSize: 150,
|
||||
cell: ({ getValue }) => (
|
||||
<div className="text-right font-mono text-sm">
|
||||
{parseTraffic(getValue<number>()).join(" ")}/s
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "ulSpeed",
|
||||
header: () => t("UL Speed"),
|
||||
size: columnSizing?.ulSpeed || 88,
|
||||
minSize: 80,
|
||||
maxSize: 150,
|
||||
cell: ({ getValue }) => (
|
||||
<div className="text-right font-mono text-sm">
|
||||
{parseTraffic(getValue<number>()).join(" ")}/s
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "chains",
|
||||
header: () => t("Chains"),
|
||||
size: columnSizing?.chains || 340,
|
||||
minSize: 180,
|
||||
maxSize: 500,
|
||||
},
|
||||
{
|
||||
accessorKey: "rule",
|
||||
header: () => t("Rule"),
|
||||
size: columnSizing?.rule || 280,
|
||||
minSize: 180,
|
||||
maxSize: 400,
|
||||
},
|
||||
{
|
||||
accessorKey: "process",
|
||||
header: () => t("Process"),
|
||||
size: columnSizing?.process || 220,
|
||||
minSize: 180,
|
||||
maxSize: 350,
|
||||
},
|
||||
{
|
||||
accessorKey: "time",
|
||||
header: () => t("Time"),
|
||||
size: columnSizing?.time || 120,
|
||||
minSize: 100,
|
||||
maxSize: 180,
|
||||
cell: ({ getValue }) => (
|
||||
<div className="text-right font-mono text-sm">
|
||||
{dayjs(getValue<string>()).fromNow()}
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
accessorKey: "source",
|
||||
header: () => t("Source"),
|
||||
size: columnSizing?.source || 200,
|
||||
minSize: 130,
|
||||
maxSize: 300,
|
||||
},
|
||||
{
|
||||
accessorKey: "remoteDestination",
|
||||
header: () => t("Destination"),
|
||||
size: columnSizing?.remoteDestination || 200,
|
||||
minSize: 130,
|
||||
maxSize: 300,
|
||||
},
|
||||
{
|
||||
accessorKey: "type",
|
||||
header: () => t("Type"),
|
||||
size: columnSizing?.type || 160,
|
||||
minSize: 100,
|
||||
maxSize: 220,
|
||||
},
|
||||
],
|
||||
[columnSizing],
|
||||
);
|
||||
|
||||
const table = useReactTable({
|
||||
@@ -305,82 +309,82 @@ export const ConnectionTable = (props: Props) => {
|
||||
|
||||
if (connRows.length === 0) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-muted-foreground">{t("No connections")}</p>
|
||||
</div>
|
||||
<div className="flex h-full items-center justify-center">
|
||||
<p className="text-muted-foreground">{t("No connections")}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-md border relative bg-background">
|
||||
<Table
|
||||
className="w-full border-collapse table-fixed"
|
||||
style={{
|
||||
width: totalTableWidth,
|
||||
minWidth: "100%",
|
||||
}}
|
||||
>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow
|
||||
key={headerGroup.id}
|
||||
className="hover:bg-transparent border-b-0 h-10"
|
||||
<div className="rounded-md border relative bg-background">
|
||||
<Table
|
||||
className="w-full border-collapse table-fixed"
|
||||
style={{
|
||||
width: totalTableWidth,
|
||||
minWidth: "100%",
|
||||
}}
|
||||
>
|
||||
<TableHeader>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
<TableRow
|
||||
key={headerGroup.id}
|
||||
className="hover:bg-transparent border-b-0 h-10"
|
||||
>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
className={cn(
|
||||
"sticky top-0 z-10",
|
||||
"p-2 text-xs font-semibold select-none border-r last:border-r-0 bg-background h-10",
|
||||
)}
|
||||
style={{
|
||||
width: header.getSize(),
|
||||
minWidth: header.column.columnDef.minSize,
|
||||
maxWidth: header.column.columnDef.maxSize,
|
||||
}}
|
||||
>
|
||||
{headerGroup.headers.map((header) => (
|
||||
<TableHead
|
||||
key={header.id}
|
||||
className={cn(
|
||||
"sticky top-0 z-10",
|
||||
"p-2 text-xs font-semibold select-none border-r last:border-r-0 bg-background h-10"
|
||||
)}
|
||||
style={{
|
||||
width: header.getSize(),
|
||||
minWidth: header.column.columnDef.minSize,
|
||||
maxWidth: header.column.columnDef.maxSize,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center justify-between h-full">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext()
|
||||
)}
|
||||
</div>
|
||||
{header.column.getCanResize() && (
|
||||
<ColumnResizer header={header} />
|
||||
<div className="flex items-center justify-between h-full">
|
||||
{header.isPlaceholder
|
||||
? null
|
||||
: flexRender(
|
||||
header.column.columnDef.header,
|
||||
header.getContext(),
|
||||
)}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
</div>
|
||||
{header.column.getCanResize() && (
|
||||
<ColumnResizer header={header} />
|
||||
)}
|
||||
</TableHead>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableHeader>
|
||||
|
||||
<TableBody>
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
className="cursor-pointer hover:bg-muted/50 transition-colors"
|
||||
onClick={() => onShowDetail(row.original.connectionData)}
|
||||
<TableBody>
|
||||
{table.getRowModel().rows.map((row) => (
|
||||
<TableRow
|
||||
key={row.id}
|
||||
data-state={row.getIsSelected() && "selected"}
|
||||
className="cursor-pointer hover:bg-muted/50 transition-colors"
|
||||
onClick={() => onShowDetail(row.original.connectionData)}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell
|
||||
key={cell.id}
|
||||
className="p-2 whitespace-nowrap overflow-hidden text-ellipsis text-sm border-r last:border-r-0"
|
||||
style={{
|
||||
width: cell.column.getSize(),
|
||||
minWidth: cell.column.columnDef.minSize,
|
||||
maxWidth: cell.column.columnDef.maxSize,
|
||||
}}
|
||||
>
|
||||
{row.getVisibleCells().map((cell) => (
|
||||
<TableCell
|
||||
key={cell.id}
|
||||
className="p-2 whitespace-nowrap overflow-hidden text-ellipsis text-sm border-r last:border-r-0"
|
||||
style={{
|
||||
width: cell.column.getSize(),
|
||||
minWidth: cell.column.columnDef.minSize,
|
||||
maxWidth: cell.column.columnDef.maxSize,
|
||||
}}
|
||||
>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
{flexRender(cell.column.columnDef.cell, cell.getContext())}
|
||||
</TableCell>
|
||||
))}
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -1,64 +1,72 @@
|
||||
import React from 'react';
|
||||
import { cn } from '@root/lib/utils';
|
||||
import { Power } from 'lucide-react';
|
||||
import React from "react";
|
||||
import { cn } from "@root/lib/utils";
|
||||
import { Power } from "lucide-react";
|
||||
|
||||
export interface PowerButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
checked?: boolean;
|
||||
loading?: boolean;
|
||||
export interface PowerButtonProps
|
||||
extends React.ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
checked?: boolean;
|
||||
loading?: boolean;
|
||||
}
|
||||
|
||||
export const PowerButton = React.forwardRef<HTMLButtonElement, PowerButtonProps>(
|
||||
({ className, checked = false, loading = false, ...props }, ref) => {
|
||||
const state = checked ? 'on' : 'off';
|
||||
export const PowerButton = React.forwardRef<
|
||||
HTMLButtonElement,
|
||||
PowerButtonProps
|
||||
>(({ className, checked = false, loading = false, ...props }, ref) => {
|
||||
const state = checked ? "on" : "off";
|
||||
|
||||
return (
|
||||
<div className="relative flex items-center justify-center h-44 w-44">
|
||||
return (
|
||||
<div className="relative flex items-center justify-center h-44 w-44">
|
||||
<div
|
||||
className={cn(
|
||||
"absolute h-28 w-28 rounded-full blur-3xl transition-all duration-500",
|
||||
state === "on" ? "bg-green-400/60" : "bg-red-500/40",
|
||||
props.disabled && "opacity-0",
|
||||
)}
|
||||
/>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'absolute h-28 w-28 rounded-full blur-3xl transition-all duration-500',
|
||||
state === 'on' ? 'bg-green-400/60' : 'bg-red-500/40',
|
||||
props.disabled && 'opacity-0'
|
||||
)}
|
||||
/>
|
||||
<button
|
||||
ref={ref}
|
||||
type="button"
|
||||
disabled={loading || props.disabled}
|
||||
data-state={state}
|
||||
className={cn(
|
||||
"relative z-10 flex items-center justify-center h-36 w-36 rounded-full border-2",
|
||||
"backdrop-blur-sm bg-white/10 border-white/20",
|
||||
"text-red-500 shadow-[0_0_30px_rgba(239,68,68,0.6)]",
|
||||
"data-[state=on]:text-green-500 dark:data-[state=on]:text-white",
|
||||
"data-[state=on]:shadow-[0_0_50px_rgba(34,197,94,1)]",
|
||||
"transition-all duration-300 hover:scale-105 active:scale-95 focus:outline-none",
|
||||
"disabled:cursor-not-allowed disabled:scale-100",
|
||||
|
||||
<button
|
||||
ref={ref}
|
||||
type="button"
|
||||
disabled={loading || props.disabled}
|
||||
data-state={state}
|
||||
className={cn(
|
||||
'relative z-10 flex items-center justify-center h-36 w-36 rounded-full border-2',
|
||||
'backdrop-blur-sm bg-white/10 border-white/20',
|
||||
'text-red-500 shadow-[0_0_30px_rgba(239,68,68,0.6)]',
|
||||
'data-[state=on]:text-green-500 dark:data-[state=on]:text-white',
|
||||
'data-[state=on]:shadow-[0_0_50px_rgba(34,197,94,1)]',
|
||||
'transition-all duration-300 hover:scale-105 active:scale-95 focus:outline-none',
|
||||
'disabled:cursor-not-allowed disabled:scale-100',
|
||||
// Стили ТОЛЬКО для отключенного состояния (но не для загрузки)
|
||||
props.disabled &&
|
||||
!loading &&
|
||||
"grayscale opacity-50 shadow-none bg-slate-100/70 border-slate-300/80",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<Power
|
||||
className={cn(
|
||||
"h-20 w-20",
|
||||
!props.disabled &&
|
||||
"active:scale-90 transition-transform duration-300",
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
|
||||
// Стили ТОЛЬКО для отключенного состояния (но не для загрузки)
|
||||
(props.disabled && !loading) && 'grayscale opacity-50 shadow-none bg-slate-100/70 border-slate-300/80',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<Power className={cn(
|
||||
"h-20 w-20",
|
||||
!props.disabled && "active:scale-90 transition-transform duration-300"
|
||||
)} />
|
||||
</button>
|
||||
|
||||
{loading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center z-20">
|
||||
<div className={cn(
|
||||
'h-full w-full animate-spin rounded-full border-4',
|
||||
'border-transparent',
|
||||
checked ? 'border-t-green-500' : 'border-t-red-500',
|
||||
'blur-xs'
|
||||
)} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
{loading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center z-20">
|
||||
<div
|
||||
className={cn(
|
||||
"h-full w-full animate-spin rounded-full border-4",
|
||||
"border-transparent",
|
||||
checked ? "border-t-green-500" : "border-t-red-500",
|
||||
"blur-xs",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,16 +1,18 @@
|
||||
import { Link } from 'react-router-dom';
|
||||
import { Link } from "react-router-dom";
|
||||
import {
|
||||
Sidebar,
|
||||
SidebarContent, SidebarFooter,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarHeader,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem, useSidebar,
|
||||
} from "@/components/ui/sidebar"
|
||||
import { t } from 'i18next';
|
||||
import { cn } from '@root/lib/utils';
|
||||
SidebarMenuItem,
|
||||
useSidebar,
|
||||
} from "@/components/ui/sidebar";
|
||||
import { t } from "i18next";
|
||||
import { cn } from "@root/lib/utils";
|
||||
|
||||
import {
|
||||
Home,
|
||||
@@ -19,21 +21,22 @@ import {
|
||||
Cable,
|
||||
ListChecks,
|
||||
FileText,
|
||||
Settings, EarthLock,
|
||||
} from 'lucide-react';
|
||||
Settings,
|
||||
EarthLock,
|
||||
} from "lucide-react";
|
||||
import { UpdateButton } from "@/components/layout/update-button";
|
||||
import React from "react";
|
||||
import { SheetClose } from '@/components/ui/sheet';
|
||||
import logo from "@/assets/image/logo.png"
|
||||
import { SheetClose } from "@/components/ui/sheet";
|
||||
import logo from "@/assets/image/logo.png";
|
||||
|
||||
const menuItems = [
|
||||
{ title: 'Home', url: '/home', icon: Home },
|
||||
{ title: 'Profiles', url: '/profile', icon: Users },
|
||||
{ title: 'Proxies', url: '/proxies', icon: Server },
|
||||
{ title: 'Connections', url: '/connections', icon: Cable },
|
||||
{ title: 'Rules', url: '/rules', icon: ListChecks },
|
||||
{ title: 'Logs', url: '/logs', icon: FileText },
|
||||
{ title: 'Settings', url: '/settings', icon: Settings },
|
||||
{ title: "Home", url: "/home", icon: Home },
|
||||
{ title: "Profiles", url: "/profile", icon: Users },
|
||||
{ title: "Proxies", url: "/proxies", icon: Server },
|
||||
{ title: "Connections", url: "/connections", icon: Cable },
|
||||
{ title: "Rules", url: "/rules", icon: ListChecks },
|
||||
{ title: "Logs", url: "/logs", icon: FileText },
|
||||
{ title: "Settings", url: "/settings", icon: Settings },
|
||||
];
|
||||
|
||||
export function AppSidebar() {
|
||||
@@ -41,18 +44,15 @@ export function AppSidebar() {
|
||||
return (
|
||||
<Sidebar variant="floating" collapsible="icon">
|
||||
<SidebarHeader>
|
||||
<SidebarMenuButton size="lg"
|
||||
<SidebarMenuButton
|
||||
size="lg"
|
||||
className={cn(
|
||||
"flex h-12 items-center transition-all duration-200",
|
||||
"group-data-[state=expanded]:w-full group-data-[state=expanded]:gap-2 group-data-[state=expanded]:px-3",
|
||||
"group-data-[state=collapsed]:w-full group-data-[state=collapsed]:justify-center"
|
||||
"group-data-[state=collapsed]:w-full group-data-[state=collapsed]:justify-center",
|
||||
)}
|
||||
>
|
||||
<img
|
||||
src={logo}
|
||||
alt="logo"
|
||||
className="h-6 w-6 flex-shrink-0"
|
||||
/>
|
||||
<img src={logo} alt="logo" className="h-6 w-6 flex-shrink-0" />
|
||||
<span className="font-semibold whitespace-nowrap group-data-[state=collapsed]:hidden">
|
||||
Koala Clash
|
||||
</span>
|
||||
@@ -69,30 +69,29 @@ export function AppSidebar() {
|
||||
key={item.title}
|
||||
to={item.url}
|
||||
className={cn(
|
||||
'flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary',
|
||||
'data-[active=true]:font-semibold data-[active=true]:border'
|
||||
"flex items-center gap-3 rounded-lg px-3 py-2 text-muted-foreground transition-all hover:text-primary",
|
||||
"data-[active=true]:font-semibold data-[active=true]:border",
|
||||
)}
|
||||
>
|
||||
<item.icon className="h-4 w-4 drop-shadow-md" />
|
||||
{t(item.title)}
|
||||
</Link>
|
||||
)
|
||||
);
|
||||
return (
|
||||
<SidebarMenuItem key={item.title} className="my-1">
|
||||
<SidebarMenuButton
|
||||
asChild
|
||||
isActive={isActive}
|
||||
tooltip={t(item.title)}>
|
||||
{isMobile ? (
|
||||
<SheetClose asChild>
|
||||
{linkElement}
|
||||
</SheetClose>
|
||||
<SidebarMenuItem key={item.title} className="my-1">
|
||||
<SidebarMenuButton
|
||||
asChild
|
||||
isActive={isActive}
|
||||
tooltip={t(item.title)}
|
||||
>
|
||||
{isMobile ? (
|
||||
<SheetClose asChild>{linkElement}</SheetClose>
|
||||
) : (
|
||||
linkElement
|
||||
)}
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
)
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
})}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
@@ -104,5 +103,5 @@ export function AppSidebar() {
|
||||
</div>
|
||||
</SidebarFooter>
|
||||
</Sidebar>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import { DialogRef } from "../base";
|
||||
import { useVerge } from "@/hooks/use-verge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { t } from "i18next";
|
||||
import {Download, RefreshCw} from "lucide-react";
|
||||
import { Download, RefreshCw } from "lucide-react";
|
||||
import { useSidebar } from "../ui/sidebar";
|
||||
|
||||
interface Props {
|
||||
@@ -17,7 +17,7 @@ export const UpdateButton = (props: Props) => {
|
||||
const { className } = props;
|
||||
const { verge } = useVerge();
|
||||
const { auto_check_update } = verge || {};
|
||||
const { state: sidebarState } = useSidebar();
|
||||
const { state: sidebarState } = useSidebar();
|
||||
|
||||
const viewerRef = useRef<DialogRef>(null);
|
||||
|
||||
@@ -36,7 +36,7 @@ export const UpdateButton = (props: Props) => {
|
||||
return (
|
||||
<>
|
||||
<UpdateViewer ref={viewerRef} />
|
||||
{sidebarState === 'collapsed' ? (
|
||||
{sidebarState === "collapsed" ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useSetThemeMode, useThemeMode } from "@/services/states";
|
||||
import { useVerge } from "@/hooks/use-verge";
|
||||
import { getCurrentWebviewWindow, WebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
import {
|
||||
getCurrentWebviewWindow,
|
||||
WebviewWindow,
|
||||
} from "@tauri-apps/api/webviewWindow";
|
||||
import { Theme } from "@tauri-apps/api/window";
|
||||
|
||||
export const useCustomTheme = () => {
|
||||
@@ -12,26 +15,28 @@ export const useCustomTheme = () => {
|
||||
const mode = useThemeMode();
|
||||
const setMode = useSetThemeMode();
|
||||
|
||||
const [systemTheme, setSystemTheme] = useState(
|
||||
() => window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"
|
||||
const [systemTheme, setSystemTheme] = useState(() =>
|
||||
window.matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "dark"
|
||||
: "light",
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setMode(
|
||||
theme_mode === "light" || theme_mode === "dark" ? theme_mode : "system",
|
||||
theme_mode === "light" || theme_mode === "dark" ? theme_mode : "system",
|
||||
);
|
||||
}, [theme_mode, setMode]);
|
||||
|
||||
useEffect(() => {
|
||||
if (mode !== 'system') return;
|
||||
if (mode !== "system") return;
|
||||
|
||||
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const handleChange = (e: MediaQueryListEvent) => {
|
||||
setSystemTheme(e.matches ? "dark" : "light");
|
||||
};
|
||||
|
||||
mediaQuery.addEventListener('change', handleChange);
|
||||
return () => mediaQuery.removeEventListener('change', handleChange);
|
||||
mediaQuery.addEventListener("change", handleChange);
|
||||
return () => mediaQuery.removeEventListener("change", handleChange);
|
||||
}, [mode]);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -45,7 +50,6 @@ export const useCustomTheme = () => {
|
||||
} else {
|
||||
appWindow.setTheme(activeTheme as Theme).catch(console.error);
|
||||
}
|
||||
|
||||
}, [mode, systemTheme, appWindow, theme_mode]);
|
||||
|
||||
return {};
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogDescription,
|
||||
DialogFooter
|
||||
DialogFooter,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { AlertTriangle } from "lucide-react";
|
||||
@@ -21,10 +21,10 @@ export const HwidErrorDialog = () => {
|
||||
setErrorMessage(customEvent.detail);
|
||||
};
|
||||
|
||||
window.addEventListener('show-hwid-error', handleShowHwidError);
|
||||
window.addEventListener("show-hwid-error", handleShowHwidError);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('show-hwid-error', handleShowHwidError);
|
||||
window.removeEventListener("show-hwid-error", handleShowHwidError);
|
||||
};
|
||||
}, []);
|
||||
|
||||
|
||||
@@ -65,7 +65,8 @@ import {
|
||||
ListTree,
|
||||
CheckCircle,
|
||||
Infinity,
|
||||
RefreshCw, Network,
|
||||
RefreshCw,
|
||||
Network,
|
||||
} from "lucide-react";
|
||||
import { t } from "i18next";
|
||||
|
||||
@@ -299,7 +300,8 @@ export const ProfileItem = (props: Props) => {
|
||||
};
|
||||
|
||||
const MAX_NAME_LENGTH = 25;
|
||||
const truncatedName = name.length > MAX_NAME_LENGTH
|
||||
const truncatedName =
|
||||
name.length > MAX_NAME_LENGTH
|
||||
? `${name.slice(0, MAX_NAME_LENGTH)}...`
|
||||
: name;
|
||||
|
||||
@@ -344,10 +346,7 @@ export const ProfileItem = (props: Props) => {
|
||||
) : null}
|
||||
</div>
|
||||
<div className="flex items-center flex-shrink-0">
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-xs shadow-sm"
|
||||
>
|
||||
<Badge variant="outline" className="text-xs shadow-sm">
|
||||
{type}
|
||||
</Badge>
|
||||
</div>
|
||||
@@ -389,14 +388,13 @@ export const ProfileItem = (props: Props) => {
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center">
|
||||
<Download className="h-3 w-3 inline mr-1.5" />
|
||||
<span className="pr-5">
|
||||
{parseTraffic(download)}
|
||||
</span>
|
||||
<span className="pr-5">{parseTraffic(download)}</span>
|
||||
<Network className="h-3 w-3 inline mr-1.5" />
|
||||
{total > 0 ? (
|
||||
<span>{parseTraffic(total)}</span>
|
||||
) : <Infinity className="h-3 w-3 inline mr-1.5" />}
|
||||
|
||||
<span>{parseTraffic(total)}</span>
|
||||
) : (
|
||||
<Infinity className="h-3 w-3 inline mr-1.5" />
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -510,11 +508,11 @@ export const ProfileItem = (props: Props) => {
|
||||
)}
|
||||
|
||||
<ConfirmViewer
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
onConfirm={onDelete}
|
||||
title={t("Delete Profile", { name: truncatedName })}
|
||||
description={t("This action cannot be undone.")}
|
||||
open={confirmOpen}
|
||||
onOpenChange={setConfirmOpen}
|
||||
onConfirm={onDelete}
|
||||
title={t("Delete Profile", { name: truncatedName })}
|
||||
description={t("This action cannot be undone.")}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -12,7 +12,8 @@ import {
|
||||
createProfile,
|
||||
patchProfile,
|
||||
importProfile,
|
||||
enhanceProfiles, createProfileFromShareLink,
|
||||
enhanceProfiles,
|
||||
createProfileFromShareLink,
|
||||
} from "@/services/cmds";
|
||||
import { useProfiles } from "@/hooks/use-profiles";
|
||||
import { showNotice } from "@/services/noticeService";
|
||||
@@ -138,7 +139,9 @@ export const ProfileViewer = forwardRef<ProfileViewerRef, Props>(
|
||||
setIsCheckingUrl(true);
|
||||
|
||||
const handler = setTimeout(() => {
|
||||
const isValid = /^(https?|vmess|vless|ss|socks|trojan):\/\//.test(importUrl);
|
||||
const isValid = /^(https?|vmess|vless|ss|socks|trojan):\/\//.test(
|
||||
importUrl,
|
||||
);
|
||||
setIsUrlValid(isValid);
|
||||
setIsCheckingUrl(false);
|
||||
}, 500);
|
||||
@@ -165,23 +168,35 @@ export const ProfileViewer = forwardRef<ProfileViewerRef, Props>(
|
||||
await enhanceProfiles();
|
||||
setOpen(false);
|
||||
} catch (err: any) {
|
||||
const errorMessage = typeof err === 'string' ? err : (err.message || String(err));
|
||||
const errorMessage =
|
||||
typeof err === "string" ? err : err.message || String(err);
|
||||
const lowerErrorMessage = errorMessage.toLowerCase();
|
||||
if (lowerErrorMessage.includes('device') || lowerErrorMessage.includes('устройств')) {
|
||||
window.dispatchEvent(new CustomEvent('show-hwid-error', { detail: errorMessage }));
|
||||
if (
|
||||
lowerErrorMessage.includes("device") ||
|
||||
lowerErrorMessage.includes("устройств")
|
||||
) {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("show-hwid-error", { detail: errorMessage }),
|
||||
);
|
||||
} else if (!isShareLink && errorMessage.includes("failed to fetch")) {
|
||||
showNotice("info", t("Import failed, retrying with Clash proxy..."));
|
||||
try {
|
||||
await importProfile(importUrl, { with_proxy: false, self_proxy: true });
|
||||
showNotice("success", t("Profile Imported with Clash proxy"));
|
||||
props.onChange();
|
||||
await enhanceProfiles();
|
||||
setOpen(false);
|
||||
} catch (retryErr: any) {
|
||||
showNotice("error", `${t("Import failed even with Clash proxy")}: ${retryErr?.message || retryErr.toString()}`);
|
||||
}
|
||||
showNotice("info", t("Import failed, retrying with Clash proxy..."));
|
||||
try {
|
||||
await importProfile(importUrl, {
|
||||
with_proxy: false,
|
||||
self_proxy: true,
|
||||
});
|
||||
showNotice("success", t("Profile Imported with Clash proxy"));
|
||||
props.onChange();
|
||||
await enhanceProfiles();
|
||||
setOpen(false);
|
||||
} catch (retryErr: any) {
|
||||
showNotice(
|
||||
"error",
|
||||
`${t("Import failed even with Clash proxy")}: ${retryErr?.message || retryErr.toString()}`,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
showNotice("error", errorMessage);
|
||||
showNotice("error", errorMessage);
|
||||
}
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
@@ -302,19 +317,26 @@ export const ProfileViewer = forwardRef<ProfileViewerRef, Props>(
|
||||
</div>
|
||||
|
||||
{/^(vmess|vless|ss|socks|trojan):\/\//.test(importUrl) && (
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-2">
|
||||
<Label>{t("Template")}</Label>
|
||||
<Select value={selectedTemplate} onValueChange={setSelectedTemplate}>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a template..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="default">{t("Default Template")}</SelectItem>
|
||||
<SelectItem value="without_ru">{t("Template without RU Rules")}</SelectItem>
|
||||
</SelectContent>
|
||||
<Select
|
||||
value={selectedTemplate}
|
||||
onValueChange={setSelectedTemplate}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="Select a template..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="default">
|
||||
{t("Default Template")}
|
||||
</SelectItem>
|
||||
<SelectItem value="without_ru">
|
||||
{t("Template without RU Rules")}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
@@ -473,15 +495,15 @@ export const ProfileViewer = forwardRef<ProfileViewerRef, Props>(
|
||||
control={control}
|
||||
name="option.update_always"
|
||||
render={({ field }) => (
|
||||
<FormItem className="flex flex-row items-center justify-between">
|
||||
<FormLabel>{t("Update on Startup")}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
<FormItem className="flex flex-row items-center justify-between">
|
||||
<FormLabel>{t("Update on Startup")}</FormLabel>
|
||||
<FormControl>
|
||||
<Switch
|
||||
checked={field.value}
|
||||
onCheckedChange={field.onChange}
|
||||
/>
|
||||
</FormControl>
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
<FormField
|
||||
|
||||
@@ -24,7 +24,6 @@ import delayManager from "@/services/delay";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ScrollTopButton } from "../layout/scroll-top-button";
|
||||
|
||||
|
||||
function throttle<T extends (...args: any[]) => any>(
|
||||
func: T,
|
||||
wait: number,
|
||||
@@ -53,7 +52,6 @@ function throttle<T extends (...args: any[]) => any>(
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
interface Props {
|
||||
mode: string;
|
||||
}
|
||||
@@ -72,7 +70,6 @@ export const ProxyGroups = memo((props: Props) => {
|
||||
const scrollerRef = useRef<Element | null>(null);
|
||||
const [showScrollTop, setShowScrollTop] = useState(false);
|
||||
|
||||
|
||||
// Обработчик скролла для показа/скрытия кнопки "Наверх"
|
||||
const handleScroll = useCallback(
|
||||
throttle((e: any) => {
|
||||
|
||||
@@ -112,7 +112,7 @@ export const LayoutViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
}));
|
||||
|
||||
const handleConfigChange = (patch: Partial<IVergeConfig>) => {
|
||||
setLocalConfig(prev => ({ ...prev, ...patch }));
|
||||
setLocalConfig((prev) => ({ ...prev, ...patch }));
|
||||
};
|
||||
|
||||
const handleIconChange = useLockFn(
|
||||
@@ -133,7 +133,8 @@ export const LayoutViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
handleConfigChange({ [key]: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
const handleSave = useLockFn(async () => {
|
||||
setLoading(true);
|
||||
@@ -149,75 +150,112 @@ export const LayoutViewer = forwardRef<DialogRef>((props, ref) => {
|
||||
});
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("Layout Setting")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t("Layout Setting")}</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="py-4 space-y-1">
|
||||
{OS === "macos" && (
|
||||
<>
|
||||
<SettingRow label={t("Tray Icon")}>
|
||||
<Select
|
||||
onValueChange={(value) => handleConfigChange({ tray_icon: value as any })}
|
||||
value={localConfig.tray_icon ?? "monochrome"}
|
||||
>
|
||||
<SelectTrigger className="w-40 h-8"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="monochrome">{t("Monochrome")}</SelectItem>
|
||||
<SelectItem value="colorful">{t("Colorful")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
<div className="py-4 space-y-1">
|
||||
{OS === "macos" && (
|
||||
<>
|
||||
<SettingRow label={t("Tray Icon")}>
|
||||
<Select
|
||||
onValueChange={(value) =>
|
||||
handleConfigChange({ tray_icon: value as any })
|
||||
}
|
||||
value={localConfig.tray_icon ?? "monochrome"}
|
||||
>
|
||||
<SelectTrigger className="w-40 h-8">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="monochrome">
|
||||
{t("Monochrome")}
|
||||
</SelectItem>
|
||||
<SelectItem value="colorful">{t("Colorful")}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label={t("Enable Tray Icon")}>
|
||||
<Switch
|
||||
checked={localConfig.enable_tray_icon ?? true}
|
||||
onCheckedChange={(checked) => handleConfigChange({ enable_tray_icon: checked })}
|
||||
/>
|
||||
</SettingRow>
|
||||
</>
|
||||
)}
|
||||
<SettingRow label={t("Enable Tray Icon")}>
|
||||
<Switch
|
||||
checked={localConfig.enable_tray_icon ?? true}
|
||||
onCheckedChange={(checked) =>
|
||||
handleConfigChange({ enable_tray_icon: checked })
|
||||
}
|
||||
/>
|
||||
</SettingRow>
|
||||
</>
|
||||
)}
|
||||
|
||||
<SettingRow label={t("Common Tray Icon")}>
|
||||
<Button variant="outline" size="sm" className="h-8" onClick={() => handleIconChange("common")}>
|
||||
{localConfig.common_tray_icon && commonIcon && (
|
||||
<img src={convertFileSrc(commonIcon)} className="h-5 mr-2" alt="common tray icon" />
|
||||
)}
|
||||
{localConfig.common_tray_icon ? t("Clear") : t("Browse")}
|
||||
</Button>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label={t("System Proxy Tray Icon")}>
|
||||
<Button variant="outline" size="sm" className="h-8" onClick={() => handleIconChange("sysproxy")}>
|
||||
{localConfig.sysproxy_tray_icon && sysproxyIcon && (
|
||||
<img src={convertFileSrc(sysproxyIcon)} className="h-5 mr-2" alt="system proxy tray icon" />
|
||||
)}
|
||||
{localConfig.sysproxy_tray_icon ? t("Clear") : t("Browse")}
|
||||
</Button>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label={t("Tun Tray Icon")}>
|
||||
<Button variant="outline" size="sm" className="h-8" onClick={() => handleIconChange("tun")}>
|
||||
{localConfig.tun_tray_icon && tunIcon && (
|
||||
<img src={convertFileSrc(tunIcon)} className="h-5 mr-2" alt="tun mode tray icon" />
|
||||
)}
|
||||
{localConfig.tun_tray_icon ? t("Clear") : t("Browse")}
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">{t("Cancel")}</Button>
|
||||
</DialogClose>
|
||||
<Button type="button" onClick={handleSave} disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t("Save")}
|
||||
<SettingRow label={t("Common Tray Icon")}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8"
|
||||
onClick={() => handleIconChange("common")}
|
||||
>
|
||||
{localConfig.common_tray_icon && commonIcon && (
|
||||
<img
|
||||
src={convertFileSrc(commonIcon)}
|
||||
className="h-5 mr-2"
|
||||
alt="common tray icon"
|
||||
/>
|
||||
)}
|
||||
{localConfig.common_tray_icon ? t("Clear") : t("Browse")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label={t("System Proxy Tray Icon")}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8"
|
||||
onClick={() => handleIconChange("sysproxy")}
|
||||
>
|
||||
{localConfig.sysproxy_tray_icon && sysproxyIcon && (
|
||||
<img
|
||||
src={convertFileSrc(sysproxyIcon)}
|
||||
className="h-5 mr-2"
|
||||
alt="system proxy tray icon"
|
||||
/>
|
||||
)}
|
||||
{localConfig.sysproxy_tray_icon ? t("Clear") : t("Browse")}
|
||||
</Button>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow label={t("Tun Tray Icon")}>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-8"
|
||||
onClick={() => handleIconChange("tun")}
|
||||
>
|
||||
{localConfig.tun_tray_icon && tunIcon && (
|
||||
<img
|
||||
src={convertFileSrc(tunIcon)}
|
||||
className="h-5 mr-2"
|
||||
alt="tun mode tray icon"
|
||||
/>
|
||||
)}
|
||||
{localConfig.tun_tray_icon ? t("Clear") : t("Browse")}
|
||||
</Button>
|
||||
</SettingRow>
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose asChild>
|
||||
<Button type="button" variant="outline">
|
||||
{t("Cancel")}
|
||||
</Button>
|
||||
</DialogClose>
|
||||
<Button type="button" onClick={handleSave} disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{t("Save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import {useMemo, useRef, useState} from "react";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { mutate } from "swr";
|
||||
@@ -43,7 +43,7 @@ import {
|
||||
Power,
|
||||
BellOff,
|
||||
Repeat,
|
||||
Fingerprint
|
||||
Fingerprint,
|
||||
} from "lucide-react";
|
||||
|
||||
// Модальные окна
|
||||
@@ -56,7 +56,7 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {useProfiles} from "@/hooks/use-profiles";
|
||||
import { useProfiles } from "@/hooks/use-profiles";
|
||||
|
||||
const isWIN = getSystem() === "windows";
|
||||
interface Props {
|
||||
@@ -110,7 +110,7 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
const { profiles } = useProfiles();
|
||||
const hasProfiles = useMemo(() => {
|
||||
const items = profiles?.items ?? [];
|
||||
return items.some(p => p.type === 'local' || p.type === 'remote');
|
||||
return items.some((p) => p.type === "local" || p.type === "remote");
|
||||
}, [profiles]);
|
||||
|
||||
const {
|
||||
@@ -261,7 +261,10 @@ const SettingSystem = ({ onError }: Props) => {
|
||||
);
|
||||
}
|
||||
if (e) {
|
||||
return patchVerge({ enable_tun_mode: true, enable_system_proxy: false });
|
||||
return patchVerge({
|
||||
enable_tun_mode: true,
|
||||
enable_system_proxy: false,
|
||||
});
|
||||
} else {
|
||||
return patchVerge({ enable_tun_mode: false });
|
||||
}
|
||||
|
||||
@@ -188,20 +188,20 @@ const SettingVergeBasic = ({ onError }: Props) => {
|
||||
|
||||
{OS !== "linux" && (
|
||||
<SettingRow
|
||||
label={
|
||||
<LabelWithIcon
|
||||
icon={MousePointerClick}
|
||||
text={t("Tray Click Event")}
|
||||
/>
|
||||
}
|
||||
label={
|
||||
<LabelWithIcon
|
||||
icon={MousePointerClick}
|
||||
text={t("Tray Click Event")}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<GuardState
|
||||
value={tray_event ?? "main_window"}
|
||||
onCatch={onError}
|
||||
onFormat={(v) => v}
|
||||
onChange={(e) => onChangeData({ tray_event: e })}
|
||||
onGuard={(e) => patchVerge({ tray_event: e })}
|
||||
onChangeProps="onValueChange"
|
||||
value={tray_event ?? "main_window"}
|
||||
onCatch={onError}
|
||||
onFormat={(v) => v}
|
||||
onChange={(e) => onChangeData({ tray_event: e })}
|
||||
onGuard={(e) => patchVerge({ tray_event: e })}
|
||||
onChangeProps="onValueChange"
|
||||
>
|
||||
<Select>
|
||||
<SelectTrigger className="w-40 h-8">
|
||||
|
||||
@@ -5,263 +5,263 @@ import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
|
||||
import { cn } from "@root/lib/utils";
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md p-1",
|
||||
"backdrop-blur-sm bg-white/70 border border-white/40",
|
||||
"dark:bg-white/10 dark:border-white/20",
|
||||
"shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]",
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md p-1",
|
||||
"backdrop-blur-sm bg-white/70 border border-white/40",
|
||||
"dark:bg-white/10 dark:border-white/20",
|
||||
"shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]",
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
);
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean;
|
||||
variant?: "default" | "destructive";
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8",
|
||||
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
|
||||
"dark:hover:bg-white/20 dark:focus:bg-white/20",
|
||||
"data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-red-200/80 data-[variant=destructive]:focus:bg-red-200/80",
|
||||
"dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20",
|
||||
"data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive",
|
||||
"[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8",
|
||||
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
|
||||
"dark:hover:bg-white/20 dark:focus:bg-white/20",
|
||||
"data-[variant=destructive]:text-destructive data-[variant=destructive]:hover:bg-red-200/80 data-[variant=destructive]:focus:bg-red-200/80",
|
||||
"dark:data-[variant=destructive]:hover:bg-destructive/20 dark:data-[variant=destructive]:focus:bg-destructive/20",
|
||||
"data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive",
|
||||
"[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
|
||||
"dark:hover:bg-white/20 dark:focus:bg-white/20",
|
||||
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
|
||||
"dark:hover:bg-white/20 dark:focus:bg-white/20",
|
||||
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
|
||||
"dark:hover:bg-white/20 dark:focus:bg-white/20",
|
||||
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
|
||||
"dark:hover:bg-white/20 dark:focus:bg-white/20",
|
||||
"[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
"text-foreground/80",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
"text-foreground/80",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn(
|
||||
"-mx-1 my-1 h-px",
|
||||
"bg-gray-400/50 dark:bg-white/20",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn(
|
||||
"-mx-1 my-1 h-px",
|
||||
"bg-gray-400/50 dark:bg-white/20",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest",
|
||||
"text-foreground/60",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"ml-auto text-xs tracking-widest",
|
||||
"text-foreground/60",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean;
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
||||
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
|
||||
"data-[state=open]:backdrop-blur-sm data-[state=open]:bg-gray-200/80",
|
||||
"dark:hover:bg-white/20 dark:focus:bg-white/20 dark:data-[state=open]:bg-white/20",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8",
|
||||
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
|
||||
"data-[state=open]:backdrop-blur-sm data-[state=open]:bg-gray-200/80",
|
||||
"dark:hover:bg-white/20 dark:focus:bg-white/20 dark:data-[state=open]:bg-white/20",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
);
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md p-1",
|
||||
"backdrop-blur-sm bg-white/70 border border-white/40",
|
||||
"dark:bg-white/10 dark:border-white/20",
|
||||
"shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]",
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
"z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md p-1",
|
||||
"backdrop-blur-sm bg-white/70 border border-white/40",
|
||||
"dark:bg-white/10 dark:border-white/20",
|
||||
"shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]",
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,191 +5,191 @@ import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react";
|
||||
import { cn } from "@root/lib/utils";
|
||||
|
||||
function Select({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
|
||||
return <SelectPrimitive.Root data-slot="select" {...props} />;
|
||||
}
|
||||
|
||||
function SelectGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
|
||||
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
|
||||
}
|
||||
|
||||
function SelectValue({
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
|
||||
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
|
||||
}
|
||||
|
||||
function SelectTrigger({
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default";
|
||||
className,
|
||||
size = "default",
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
|
||||
size?: "sm" | "default";
|
||||
}) {
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow,background-color] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"backdrop-blur-sm bg-white/80 border-gray-300/60",
|
||||
"dark:bg-white/5 dark:border-white/15",
|
||||
"hover:bg-white/90 hover:border-gray-400/70",
|
||||
"dark:hover:bg-white/10 dark:hover:border-white/20",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
return (
|
||||
<SelectPrimitive.Trigger
|
||||
data-slot="select-trigger"
|
||||
data-size={size}
|
||||
className={cn(
|
||||
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive flex w-fit items-center justify-between gap-2 rounded-md border px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow,background-color] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
"backdrop-blur-sm bg-white/80 border-gray-300/60",
|
||||
"dark:bg-white/5 dark:border-white/15",
|
||||
"hover:bg-white/90 hover:border-gray-400/70",
|
||||
"dark:hover:bg-white/10 dark:hover:border-white/20",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<SelectPrimitive.Icon asChild>
|
||||
<ChevronDownIcon className="size-4 opacity-50" />
|
||||
</SelectPrimitive.Icon>
|
||||
</SelectPrimitive.Trigger>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectContent({
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md",
|
||||
"backdrop-blur-sm bg-white/70 border border-white/40",
|
||||
"dark:bg-white/10 dark:border-white/20",
|
||||
"shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]",
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
);
|
||||
className,
|
||||
children,
|
||||
position = "popper",
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
|
||||
return (
|
||||
<SelectPrimitive.Portal>
|
||||
<SelectPrimitive.Content
|
||||
data-slot="select-content"
|
||||
className={cn(
|
||||
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md",
|
||||
"backdrop-blur-sm bg-white/70 border border-white/40",
|
||||
"dark:bg-white/10 dark:border-white/20",
|
||||
"shadow-[0_8px_32px_rgba(0,0,0,0.12)] dark:shadow-[0_8px_32px_rgba(255,255,255,0.05)]",
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
|
||||
position === "popper" &&
|
||||
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
|
||||
className,
|
||||
)}
|
||||
position={position}
|
||||
{...props}
|
||||
>
|
||||
<SelectScrollUpButton />
|
||||
<SelectPrimitive.Viewport
|
||||
className={cn(
|
||||
"p-1",
|
||||
position === "popper" &&
|
||||
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1",
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</SelectPrimitive.Viewport>
|
||||
<SelectScrollDownButton />
|
||||
</SelectPrimitive.Content>
|
||||
</SelectPrimitive.Portal>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectLabel({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
|
||||
return (
|
||||
<SelectPrimitive.Label
|
||||
data-slot="select-label"
|
||||
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
|
||||
"dark:hover:bg-white/20 dark:focus:bg-white/20",
|
||||
"transition-all duration-200",
|
||||
"[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
|
||||
return (
|
||||
<SelectPrimitive.Item
|
||||
data-slot="select-item"
|
||||
className={cn(
|
||||
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
|
||||
"hover:backdrop-blur-sm hover:bg-gray-200/80 focus:backdrop-blur-sm focus:bg-gray-200/80",
|
||||
"dark:hover:bg-white/20 dark:focus:bg-white/20",
|
||||
"transition-all duration-200",
|
||||
"[&_svg:not([class*='text-'])]:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="absolute right-2 flex size-3.5 items-center justify-center">
|
||||
<SelectPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</SelectPrimitive.ItemIndicator>
|
||||
</span>
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
);
|
||||
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
|
||||
</SelectPrimitive.Item>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
|
||||
return (
|
||||
<SelectPrimitive.Separator
|
||||
data-slot="select-separator"
|
||||
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollUpButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
);
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollUpButton
|
||||
data-slot="select-scroll-up-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronUpIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollUpButton>
|
||||
);
|
||||
}
|
||||
|
||||
function SelectScrollDownButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
|
||||
return (
|
||||
<SelectPrimitive.ScrollDownButton
|
||||
data-slot="select-scroll-down-button"
|
||||
className={cn(
|
||||
"flex cursor-default items-center justify-center py-1",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
);
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<ChevronDownIcon className="size-4" />
|
||||
</SelectPrimitive.ScrollDownButton>
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectGroup,
|
||||
SelectItem,
|
||||
SelectLabel,
|
||||
SelectScrollDownButton,
|
||||
SelectScrollUpButton,
|
||||
SelectSeparator,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
};
|
||||
@@ -1,54 +1,54 @@
|
||||
import * as React from "react"
|
||||
import { Slot } from "@radix-ui/react-slot"
|
||||
import { cva, VariantProps } from "class-variance-authority"
|
||||
import { PanelLeftIcon } from "lucide-react"
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, VariantProps } from "class-variance-authority";
|
||||
import { PanelLeftIcon } from "lucide-react";
|
||||
|
||||
import { useIsMobile } from "@root/hooks/use-mobile"
|
||||
import { cn } from "@root/lib/utils"
|
||||
import { Button } from "@root/src/components/ui/button"
|
||||
import { Input } from "@root/src/components/ui/input"
|
||||
import { Separator } from "@root/src/components/ui/separator"
|
||||
import { useIsMobile } from "@root/hooks/use-mobile";
|
||||
import { cn } from "@root/lib/utils";
|
||||
import { Button } from "@root/src/components/ui/button";
|
||||
import { Input } from "@root/src/components/ui/input";
|
||||
import { Separator } from "@root/src/components/ui/separator";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@root/src/components/ui/sheet"
|
||||
import { Skeleton } from "@root/src/components/ui/skeleton"
|
||||
} from "@root/src/components/ui/sheet";
|
||||
import { Skeleton } from "@root/src/components/ui/skeleton";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@root/src/components/ui/tooltip"
|
||||
} from "@root/src/components/ui/tooltip";
|
||||
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state"
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
|
||||
const SIDEBAR_WIDTH = "16rem"
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem"
|
||||
const SIDEBAR_WIDTH_ICON = "3rem"
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
|
||||
const SIDEBAR_COOKIE_NAME = "sidebar_state";
|
||||
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
|
||||
const SIDEBAR_WIDTH = "16rem";
|
||||
const SIDEBAR_WIDTH_MOBILE = "18rem";
|
||||
const SIDEBAR_WIDTH_ICON = "3rem";
|
||||
const SIDEBAR_KEYBOARD_SHORTCUT = "b";
|
||||
|
||||
type SidebarContextProps = {
|
||||
state: "expanded" | "collapsed"
|
||||
open: boolean
|
||||
setOpen: (open: boolean) => void
|
||||
openMobile: boolean
|
||||
setOpenMobile: (open: boolean) => void
|
||||
isMobile: boolean
|
||||
toggleSidebar: () => void
|
||||
}
|
||||
state: "expanded" | "collapsed";
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
openMobile: boolean;
|
||||
setOpenMobile: (open: boolean) => void;
|
||||
isMobile: boolean;
|
||||
toggleSidebar: () => void;
|
||||
};
|
||||
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
|
||||
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
|
||||
|
||||
function useSidebar() {
|
||||
const context = React.useContext(SidebarContext)
|
||||
const context = React.useContext(SidebarContext);
|
||||
if (!context) {
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.")
|
||||
throw new Error("useSidebar must be used within a SidebarProvider.");
|
||||
}
|
||||
|
||||
return context
|
||||
return context;
|
||||
}
|
||||
|
||||
function SidebarProvider({
|
||||
@@ -60,36 +60,36 @@ function SidebarProvider({
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
defaultOpen?: boolean
|
||||
open?: boolean
|
||||
onOpenChange?: (open: boolean) => void
|
||||
defaultOpen?: boolean;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}) {
|
||||
const isMobile = useIsMobile()
|
||||
const [openMobile, setOpenMobile] = React.useState(false)
|
||||
const isMobile = useIsMobile();
|
||||
const [openMobile, setOpenMobile] = React.useState(false);
|
||||
|
||||
// This is the internal state of the sidebar.
|
||||
// We use openProp and setOpenProp for control from outside the component.
|
||||
const [_open, _setOpen] = React.useState(defaultOpen)
|
||||
const open = openProp ?? _open
|
||||
const [_open, _setOpen] = React.useState(defaultOpen);
|
||||
const open = openProp ?? _open;
|
||||
const setOpen = React.useCallback(
|
||||
(value: boolean | ((value: boolean) => boolean)) => {
|
||||
const openState = typeof value === "function" ? value(open) : value
|
||||
const openState = typeof value === "function" ? value(open) : value;
|
||||
if (setOpenProp) {
|
||||
setOpenProp(openState)
|
||||
setOpenProp(openState);
|
||||
} else {
|
||||
_setOpen(openState)
|
||||
_setOpen(openState);
|
||||
}
|
||||
|
||||
// This sets the cookie to keep the sidebar state.
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
|
||||
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
|
||||
},
|
||||
[setOpenProp, open]
|
||||
)
|
||||
[setOpenProp, open],
|
||||
);
|
||||
|
||||
// Helper to toggle the sidebar.
|
||||
const toggleSidebar = React.useCallback(() => {
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
|
||||
}, [isMobile, setOpen, setOpenMobile])
|
||||
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
|
||||
}, [isMobile, setOpen, setOpenMobile]);
|
||||
|
||||
// Adds a keyboard shortcut to toggle the sidebar.
|
||||
React.useEffect(() => {
|
||||
@@ -98,18 +98,18 @@ function SidebarProvider({
|
||||
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
|
||||
(event.metaKey || event.ctrlKey)
|
||||
) {
|
||||
event.preventDefault()
|
||||
toggleSidebar()
|
||||
event.preventDefault();
|
||||
toggleSidebar();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown)
|
||||
return () => window.removeEventListener("keydown", handleKeyDown)
|
||||
}, [toggleSidebar])
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [toggleSidebar]);
|
||||
|
||||
// We add a state so that we can do data-state="expanded" or "collapsed".
|
||||
// This makes it easier to style the sidebar with Tailwind classes.
|
||||
const state = open ? "expanded" : "collapsed"
|
||||
const state = open ? "expanded" : "collapsed";
|
||||
|
||||
const contextValue = React.useMemo<SidebarContextProps>(
|
||||
() => ({
|
||||
@@ -121,8 +121,8 @@ function SidebarProvider({
|
||||
setOpenMobile,
|
||||
toggleSidebar,
|
||||
}),
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
|
||||
)
|
||||
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
|
||||
);
|
||||
|
||||
return (
|
||||
<SidebarContext.Provider value={contextValue}>
|
||||
@@ -138,7 +138,7 @@ function SidebarProvider({
|
||||
}
|
||||
className={cn(
|
||||
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -146,7 +146,7 @@ function SidebarProvider({
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</SidebarContext.Provider>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function Sidebar({
|
||||
@@ -157,11 +157,11 @@ function Sidebar({
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
side?: "left" | "right"
|
||||
variant?: "sidebar" | "floating" | "inset"
|
||||
collapsible?: "offcanvas" | "icon" | "none"
|
||||
side?: "left" | "right";
|
||||
variant?: "sidebar" | "floating" | "inset";
|
||||
collapsible?: "offcanvas" | "icon" | "none";
|
||||
}) {
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
|
||||
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
|
||||
|
||||
if (collapsible === "none") {
|
||||
return (
|
||||
@@ -169,13 +169,13 @@ function Sidebar({
|
||||
data-slot="sidebar"
|
||||
className={cn(
|
||||
"bg-sidebar text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (isMobile) {
|
||||
@@ -200,7 +200,7 @@ function Sidebar({
|
||||
<div className="flex h-full w-full flex-col">{children}</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -221,7 +221,7 @@ function Sidebar({
|
||||
"group-data-[side=right]:rotate-180",
|
||||
variant === "floating" || variant === "inset"
|
||||
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)",
|
||||
)}
|
||||
/>
|
||||
<div
|
||||
@@ -235,7 +235,7 @@ function Sidebar({
|
||||
variant === "floating" || variant === "inset"
|
||||
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
|
||||
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
@@ -248,7 +248,7 @@ function Sidebar({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarTrigger({
|
||||
@@ -256,7 +256,7 @@ function SidebarTrigger({
|
||||
onClick,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
const { toggleSidebar } = useSidebar();
|
||||
|
||||
return (
|
||||
<Button
|
||||
@@ -266,19 +266,19 @@ function SidebarTrigger({
|
||||
size="icon"
|
||||
className={cn("size-7", className)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event)
|
||||
toggleSidebar()
|
||||
onClick?.(event);
|
||||
toggleSidebar();
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
const { toggleSidebar } = useSidebar()
|
||||
const { toggleSidebar } = useSidebar();
|
||||
|
||||
return (
|
||||
<button
|
||||
@@ -295,11 +295,11 @@ function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
|
||||
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
|
||||
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
|
||||
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
@@ -309,11 +309,11 @@ function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
|
||||
className={cn(
|
||||
"bg-background relative flex w-full flex-1 flex-col",
|
||||
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarInput({
|
||||
@@ -327,7 +327,7 @@ function SidebarInput({
|
||||
className={cn("bg-background h-8 w-full shadow-none", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -338,7 +338,7 @@ function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -349,7 +349,7 @@ function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
className={cn("flex flex-col gap-2 p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarSeparator({
|
||||
@@ -363,7 +363,7 @@ function SidebarSeparator({
|
||||
className={cn("bg-sidebar-border mx-2 w-auto", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -373,11 +373,11 @@ function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
data-sidebar="content"
|
||||
className={cn(
|
||||
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
@@ -388,7 +388,7 @@ function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
|
||||
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroupLabel({
|
||||
@@ -396,7 +396,7 @@ function SidebarGroupLabel({
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "div"
|
||||
const Comp = asChild ? Slot : "div";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
@@ -405,11 +405,11 @@ function SidebarGroupLabel({
|
||||
className={cn(
|
||||
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
|
||||
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroupAction({
|
||||
@@ -417,7 +417,7 @@ function SidebarGroupAction({
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const Comp = asChild ? Slot : "button";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
@@ -428,11 +428,11 @@ function SidebarGroupAction({
|
||||
// Increases the hit area of the button on mobile.
|
||||
"after:absolute after:-inset-2 md:after:hidden",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarGroupContent({
|
||||
@@ -446,7 +446,7 @@ function SidebarGroupContent({
|
||||
className={cn("w-full text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
@@ -457,7 +457,7 @@ function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
@@ -468,7 +468,7 @@ function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
className={cn("group/menu-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const sidebarMenuButtonVariants = cva(
|
||||
@@ -490,8 +490,8 @@ const sidebarMenuButtonVariants = cva(
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
},
|
||||
);
|
||||
|
||||
function SidebarMenuButton({
|
||||
asChild = false,
|
||||
@@ -502,12 +502,12 @@ function SidebarMenuButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
isActive?: boolean
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>
|
||||
asChild?: boolean;
|
||||
isActive?: boolean;
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
|
||||
} & VariantProps<typeof sidebarMenuButtonVariants>) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const { isMobile, state } = useSidebar()
|
||||
const Comp = asChild ? Slot : "button";
|
||||
const { isMobile, state } = useSidebar();
|
||||
|
||||
const button = (
|
||||
<Comp
|
||||
@@ -518,16 +518,16 @@ function SidebarMenuButton({
|
||||
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
|
||||
if (!tooltip) {
|
||||
return button
|
||||
return button;
|
||||
}
|
||||
|
||||
if (typeof tooltip === "string") {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -540,7 +540,7 @@ function SidebarMenuButton({
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuAction({
|
||||
@@ -549,10 +549,10 @@ function SidebarMenuAction({
|
||||
showOnHover = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & {
|
||||
asChild?: boolean
|
||||
showOnHover?: boolean
|
||||
asChild?: boolean;
|
||||
showOnHover?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
const Comp = asChild ? Slot : "button";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
@@ -568,11 +568,11 @@ function SidebarMenuAction({
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
showOnHover &&
|
||||
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuBadge({
|
||||
@@ -590,11 +590,11 @@ function SidebarMenuBadge({
|
||||
"peer-data-[size=default]/menu-button:top-1.5",
|
||||
"peer-data-[size=lg]/menu-button:top-2.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSkeleton({
|
||||
@@ -602,12 +602,12 @@ function SidebarMenuSkeleton({
|
||||
showIcon = false,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & {
|
||||
showIcon?: boolean
|
||||
showIcon?: boolean;
|
||||
}) {
|
||||
// Random width between 50 to 90%.
|
||||
const width = React.useMemo(() => {
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`
|
||||
}, [])
|
||||
return `${Math.floor(Math.random() * 40) + 50}%`;
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
@@ -632,7 +632,7 @@ function SidebarMenuSkeleton({
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
@@ -643,11 +643,11 @@ function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
|
||||
className={cn(
|
||||
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSubItem({
|
||||
@@ -661,7 +661,7 @@ function SidebarMenuSubItem({
|
||||
className={cn("group/menu-sub-item relative", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarMenuSubButton({
|
||||
@@ -671,11 +671,11 @@ function SidebarMenuSubButton({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean
|
||||
size?: "sm" | "md"
|
||||
isActive?: boolean
|
||||
asChild?: boolean;
|
||||
size?: "sm" | "md";
|
||||
isActive?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a"
|
||||
const Comp = asChild ? Slot : "a";
|
||||
|
||||
return (
|
||||
<Comp
|
||||
@@ -689,11 +689,11 @@ function SidebarMenuSubButton({
|
||||
size === "sm" && "text-xs",
|
||||
size === "md" && "text-sm",
|
||||
"group-data-[collapsible=icon]:hidden",
|
||||
className
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
@@ -721,4 +721,4 @@ export {
|
||||
SidebarSeparator,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { cn } from "@root/lib/utils"
|
||||
import { cn } from "@root/lib/utils";
|
||||
|
||||
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
@@ -7,7 +7,7 @@ function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
|
||||
className={cn("bg-accent animate-pulse rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export { Skeleton }
|
||||
export { Skeleton };
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useEffect, useState, useCallback } from 'react';
|
||||
import { WebviewWindow } from '@tauri-apps/api/webviewWindow';
|
||||
import { useEffect, useState, useCallback } from "react";
|
||||
import { WebviewWindow } from "@tauri-apps/api/webviewWindow";
|
||||
|
||||
// Константы для управления масштабом
|
||||
const ZOOM_STEP = 0.1;
|
||||
@@ -22,7 +22,9 @@ export const useZoomControls = () => {
|
||||
|
||||
let initialZoom = 1.0;
|
||||
|
||||
console.log(`Physical width: ${size.width}, Scale Factor: ${scaleFactor}, Logical width: ${logicalWidth}`);
|
||||
console.log(
|
||||
`Physical width: ${size.width}, Scale Factor: ${scaleFactor}, Logical width: ${logicalWidth}`,
|
||||
);
|
||||
|
||||
// 3. Используем логическую ширину для принятия решения
|
||||
if (logicalWidth < 1300) {
|
||||
@@ -38,18 +40,24 @@ export const useZoomControls = () => {
|
||||
setInitialZoom();
|
||||
}, []);
|
||||
|
||||
const handleZoom = useCallback((delta: number, isReset = false) => {
|
||||
setZoomLevel(currentZoom => {
|
||||
const newZoom = isReset ? 1.0 : currentZoom + delta;
|
||||
const clampedZoom = Math.max(MIN_ZOOM, Math.min(newZoom, MAX_ZOOM));
|
||||
const roundedZoom = Math.round(clampedZoom * 100) / 100;
|
||||
const handleZoom = useCallback(
|
||||
(delta: number, isReset = false) => {
|
||||
setZoomLevel((currentZoom) => {
|
||||
const newZoom = isReset ? 1.0 : currentZoom + delta;
|
||||
const clampedZoom = Math.max(MIN_ZOOM, Math.min(newZoom, MAX_ZOOM));
|
||||
const roundedZoom = Math.round(clampedZoom * 100) / 100;
|
||||
|
||||
appWindow.setZoom(roundedZoom);
|
||||
const newStrokeWidth = 2 / roundedZoom;
|
||||
document.documentElement.style.setProperty('--icon-stroke-width', newStrokeWidth.toString());
|
||||
return roundedZoom;
|
||||
});
|
||||
}, [appWindow]);
|
||||
appWindow.setZoom(roundedZoom);
|
||||
const newStrokeWidth = 2 / roundedZoom;
|
||||
document.documentElement.style.setProperty(
|
||||
"--icon-stroke-width",
|
||||
newStrokeWidth.toString(),
|
||||
);
|
||||
return roundedZoom;
|
||||
});
|
||||
},
|
||||
[appWindow],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleWheel = (event: WheelEvent) => {
|
||||
@@ -63,18 +71,18 @@ export const useZoomControls = () => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.ctrlKey || event.metaKey) {
|
||||
switch (event.code) {
|
||||
case 'Equal':
|
||||
case 'NumpadAdd':
|
||||
case "Equal":
|
||||
case "NumpadAdd":
|
||||
event.preventDefault();
|
||||
handleZoom(ZOOM_STEP);
|
||||
break;
|
||||
case 'Minus':
|
||||
case 'NumpadSubtract':
|
||||
case "Minus":
|
||||
case "NumpadSubtract":
|
||||
event.preventDefault();
|
||||
handleZoom(-ZOOM_STEP);
|
||||
break;
|
||||
case 'Digit0':
|
||||
case 'Numpad0':
|
||||
case "Digit0":
|
||||
case "Numpad0":
|
||||
event.preventDefault();
|
||||
handleZoom(0, true);
|
||||
break;
|
||||
@@ -82,12 +90,12 @@ export const useZoomControls = () => {
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('wheel', handleWheel, { passive: false });
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
window.addEventListener("wheel", handleWheel, { passive: false });
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('wheel', handleWheel);
|
||||
window.removeEventListener('keydown', handleKeyDown);
|
||||
window.removeEventListener("wheel", handleWheel);
|
||||
window.removeEventListener("keydown", handleKeyDown);
|
||||
};
|
||||
}, [handleZoom]);
|
||||
};
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
@import "tw-animate-css";
|
||||
|
||||
@theme {
|
||||
--tailwind-darkMode: 'class';
|
||||
--tailwind-darkMode: "class";
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
@@ -132,7 +132,6 @@ svg {
|
||||
stroke-width: var(--icon-stroke-width, 2);
|
||||
}
|
||||
|
||||
|
||||
@keyframes gradient-wave {
|
||||
0% {
|
||||
background-position: -200% center;
|
||||
|
||||
@@ -27,7 +27,6 @@ import { AppSidebar } from "@/components/layout/sidebar";
|
||||
import { useZoomControls } from "@/hooks/useZoomControls";
|
||||
import { HwidErrorDialog } from "@/components/profile/hwid-error-dialog";
|
||||
|
||||
|
||||
const appWindow = getCurrentWebviewWindow();
|
||||
export let portableFlag = false;
|
||||
|
||||
@@ -49,16 +48,21 @@ const handleNoticeMessage = (
|
||||
mutate("getProfiles");
|
||||
navigate("/");
|
||||
showNotice("success", t("Import Subscription Successful"));
|
||||
sessionStorage.setItem('activateProfile', msg);
|
||||
sessionStorage.setItem("activateProfile", msg);
|
||||
break;
|
||||
case "import_sub_url::error":
|
||||
console.log(msg);
|
||||
if (msg.toLowerCase().includes('device') || msg.toLowerCase().includes('устройств')) {
|
||||
window.dispatchEvent(new CustomEvent('show-hwid-error', { detail: msg }));
|
||||
} else {
|
||||
showNotice("error", msg);
|
||||
}
|
||||
break;
|
||||
console.log(msg);
|
||||
if (
|
||||
msg.toLowerCase().includes("device") ||
|
||||
msg.toLowerCase().includes("устройств")
|
||||
) {
|
||||
window.dispatchEvent(
|
||||
new CustomEvent("show-hwid-error", { detail: msg }),
|
||||
);
|
||||
} else {
|
||||
showNotice("error", msg);
|
||||
}
|
||||
break;
|
||||
case "set_config::error":
|
||||
showNotice("error", msg);
|
||||
break;
|
||||
@@ -172,7 +176,10 @@ const Layout = () => {
|
||||
try {
|
||||
handleNoticeMessage(status, msg, t, navigate);
|
||||
} catch (error) {
|
||||
console.error("[Layout] Failure to process a notification message:", error);
|
||||
console.error(
|
||||
"[Layout] Failure to process a notification message:",
|
||||
error,
|
||||
);
|
||||
}
|
||||
}, 0);
|
||||
},
|
||||
@@ -233,11 +240,17 @@ const Layout = () => {
|
||||
try {
|
||||
unlisten();
|
||||
} catch (error) {
|
||||
console.error("[Layout] Failed to clear event listener:", error);
|
||||
console.error(
|
||||
"[Layout] Failed to clear event listener:",
|
||||
error,
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.error("[Layout] Failed to get unlisten function:", error);
|
||||
console.error(
|
||||
"[Layout] Failed to get unlisten function:",
|
||||
error,
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -259,7 +272,9 @@ const Layout = () => {
|
||||
|
||||
useEffect(() => {
|
||||
if (initRef.current) {
|
||||
console.log("[Layout] Initialization code has already been executed, skip");
|
||||
console.log(
|
||||
"[Layout] Initialization code has already been executed, skip",
|
||||
);
|
||||
return;
|
||||
}
|
||||
console.log("[Layout] Begin executing initialization code");
|
||||
@@ -305,7 +320,9 @@ const Layout = () => {
|
||||
}
|
||||
|
||||
initializationAttempts++;
|
||||
console.log(`[Layout] Start ${initializationAttempts} for the first time`);
|
||||
console.log(
|
||||
`[Layout] Start ${initializationAttempts} for the first time`,
|
||||
);
|
||||
|
||||
try {
|
||||
removeLoadingOverlay();
|
||||
@@ -326,7 +343,9 @@ const Layout = () => {
|
||||
checkReactMount();
|
||||
|
||||
setTimeout(() => {
|
||||
console.log("[Layout] React components mount check timeout, continue execution");
|
||||
console.log(
|
||||
"[Layout] React components mount check timeout, continue execution",
|
||||
);
|
||||
resolve();
|
||||
}, 2000);
|
||||
});
|
||||
@@ -342,7 +361,9 @@ const Layout = () => {
|
||||
await notifyBackend("UI ready");
|
||||
|
||||
isInitialized = true;
|
||||
console.log(`[Layout] The ${initializationAttempts} initialization is complete`);
|
||||
console.log(
|
||||
`[Layout] The ${initializationAttempts} initialization is complete`,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
`[Layout] Initialization failure at ${initializationAttempts}:`,
|
||||
@@ -355,7 +376,9 @@ const Layout = () => {
|
||||
);
|
||||
setTimeout(performInitialization, 500);
|
||||
} else {
|
||||
console.error("[Layout] All initialization attempts fail, perform emergency initialization");
|
||||
console.error(
|
||||
"[Layout] All initialization attempts fail, perform emergency initialization",
|
||||
);
|
||||
|
||||
removeLoadingOverlay();
|
||||
try {
|
||||
@@ -375,14 +398,19 @@ const Layout = () => {
|
||||
console.log("[Layout] Start listening for startup completion events");
|
||||
const unlisten = await listen("verge://startup-completed", () => {
|
||||
if (!hasEventTriggered) {
|
||||
console.log("[Layout] Receive startup completion event, start initialization");
|
||||
console.log(
|
||||
"[Layout] Receive startup completion event, start initialization",
|
||||
);
|
||||
hasEventTriggered = true;
|
||||
performInitialization();
|
||||
}
|
||||
});
|
||||
return unlisten;
|
||||
} catch (err) {
|
||||
console.error("[Layout] Failed to listen for startup completion event:", err);
|
||||
console.error(
|
||||
"[Layout] Failed to listen for startup completion event:",
|
||||
err,
|
||||
);
|
||||
return () => {};
|
||||
}
|
||||
};
|
||||
@@ -393,18 +421,24 @@ const Layout = () => {
|
||||
await invoke("update_ui_stage", { stage: "Loading" });
|
||||
|
||||
if (!hasEventTriggered && !isInitialized) {
|
||||
console.log("[Layout] Backend is ready, start initialization immediately");
|
||||
console.log(
|
||||
"[Layout] Backend is ready, start initialization immediately",
|
||||
);
|
||||
hasEventTriggered = true;
|
||||
performInitialization();
|
||||
}
|
||||
} catch (err) {
|
||||
console.log("[Layout] Backend not yet ready, waiting for startup completion event");
|
||||
console.log(
|
||||
"[Layout] Backend not yet ready, waiting for startup completion event",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const backupInitialization = setTimeout(() => {
|
||||
if (!hasEventTriggered && !isInitialized) {
|
||||
console.warn("[Layout] Standby initialization trigger: initialization not started within 1.5 seconds");
|
||||
console.warn(
|
||||
"[Layout] Standby initialization trigger: initialization not started within 1.5 seconds",
|
||||
);
|
||||
hasEventTriggered = true;
|
||||
performInitialization();
|
||||
}
|
||||
@@ -412,7 +446,9 @@ const Layout = () => {
|
||||
|
||||
const emergencyInitialization = setTimeout(() => {
|
||||
if (!isInitialized) {
|
||||
console.error("[Layout] Emergency initialization trigger: initialization not completed within 5 seconds");
|
||||
console.error(
|
||||
"[Layout] Emergency initialization trigger: initialization not completed within 5 seconds",
|
||||
);
|
||||
removeLoadingOverlay();
|
||||
notifyBackend("UI ready").catch(() => {});
|
||||
isInitialized = true;
|
||||
@@ -445,7 +481,7 @@ const Layout = () => {
|
||||
}, [start_page]);
|
||||
|
||||
if (!routersEles) {
|
||||
return <div className="h-screen w-screen bg-background" />;
|
||||
return <div className="h-screen w-screen bg-background" />;
|
||||
}
|
||||
|
||||
const AppLayout = () => {
|
||||
@@ -454,21 +490,18 @@ const Layout = () => {
|
||||
const routersEles = useRoutes(routers);
|
||||
|
||||
return (
|
||||
<>
|
||||
<AppSidebar />
|
||||
<main
|
||||
className="h-screen w-full overflow-y-auto transition-[margin] duration-200 ease-linear"
|
||||
>
|
||||
<div className="h-full w-full relative">
|
||||
{routersEles && React.cloneElement(routersEles, { key: location.pathname })}
|
||||
</div>
|
||||
</main>
|
||||
<HwidErrorDialog />
|
||||
</>
|
||||
<>
|
||||
<AppSidebar />
|
||||
<main className="h-screen w-full overflow-y-auto transition-[margin] duration-200 ease-linear">
|
||||
<div className="h-full w-full relative">
|
||||
{routersEles &&
|
||||
React.cloneElement(routersEles, { key: location.pathname })}
|
||||
</div>
|
||||
</main>
|
||||
<HwidErrorDialog />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
};
|
||||
|
||||
return (
|
||||
<SWRConfig value={{ errorRetryCount: 3 }}>
|
||||
|
||||
@@ -22,9 +22,7 @@ import {
|
||||
ConnectionDetail,
|
||||
ConnectionDetailRef,
|
||||
} from "@/components/connection/connection-detail";
|
||||
import {
|
||||
BaseSearchBox,
|
||||
} from "@/components/base/base-search-box";
|
||||
import { BaseSearchBox } from "@/components/base/base-search-box";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
Select,
|
||||
@@ -50,7 +48,7 @@ import {
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
} from "lucide-react";
|
||||
import {SidebarTrigger} from "@/components/ui/sidebar";
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar";
|
||||
|
||||
interface IConnectionsItem {
|
||||
id: string;
|
||||
@@ -91,14 +89,15 @@ const ConnectionsPage = () => {
|
||||
|
||||
const orderOpts: Record<string, OrderFunc> = {
|
||||
Default: (list) =>
|
||||
list.sort(
|
||||
(a, b) =>
|
||||
new Date(b.start || "0").getTime()! -
|
||||
new Date(a.start || "0").getTime()!,
|
||||
),
|
||||
"Upload Speed": (list) => list.sort((a, b) => (b.curUpload ?? 0) - (a.curUpload ?? 0)),
|
||||
list.sort(
|
||||
(a, b) =>
|
||||
new Date(b.start || "0").getTime()! -
|
||||
new Date(a.start || "0").getTime()!,
|
||||
),
|
||||
"Upload Speed": (list) =>
|
||||
list.sort((a, b) => (b.curUpload ?? 0) - (a.curUpload ?? 0)),
|
||||
"Download Speed": (list) =>
|
||||
list.sort((a, b) => (b.curDownload ?? 0) - (a.curDownload ?? 0)),
|
||||
list.sort((a, b) => (b.curDownload ?? 0) - (a.curDownload ?? 0)),
|
||||
};
|
||||
|
||||
const [isPaused, setIsPaused] = useState(false);
|
||||
@@ -121,7 +120,7 @@ const ConnectionsPage = () => {
|
||||
let conns = displayData.connections.filter((conn) => {
|
||||
const { host, destinationIP, process } = conn.metadata;
|
||||
return (
|
||||
match(host || "") || match(destinationIP || "") || match(process || "")
|
||||
match(host || "") || match(destinationIP || "") || match(process || "")
|
||||
);
|
||||
});
|
||||
if (orderFunc) conns = orderFunc(conns);
|
||||
@@ -129,24 +128,24 @@ const ConnectionsPage = () => {
|
||||
}, [displayData, match, curOrderOpt]);
|
||||
|
||||
const [scrollingElement, setScrollingElement] = useState<
|
||||
HTMLElement | Window | null
|
||||
HTMLElement | Window | null
|
||||
>(null);
|
||||
const [isScrolled, setIsScrolled] = useState(false);
|
||||
|
||||
const scrollerRefCallback = useCallback(
|
||||
(node: HTMLElement | Window | null) => {
|
||||
setScrollingElement(node);
|
||||
},
|
||||
[],
|
||||
(node: HTMLElement | Window | null) => {
|
||||
setScrollingElement(node);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!scrollingElement) return;
|
||||
const handleScroll = () => {
|
||||
const scrollTop =
|
||||
scrollingElement instanceof Window
|
||||
? scrollingElement.scrollY
|
||||
: scrollingElement.scrollTop;
|
||||
scrollingElement instanceof Window
|
||||
? scrollingElement.scrollY
|
||||
: scrollingElement.scrollTop;
|
||||
setIsScrolled(scrollTop > 5);
|
||||
};
|
||||
|
||||
@@ -157,8 +156,8 @@ const ConnectionsPage = () => {
|
||||
const onCloseAll = useLockFn(closeAllConnections);
|
||||
const detailRef = useRef<ConnectionDetailRef>(null!);
|
||||
const handleSearch = useCallback(
|
||||
(m: (content: string) => boolean) => setMatch(() => m),
|
||||
[],
|
||||
(m: (content: string) => boolean) => setMatch(() => m),
|
||||
[],
|
||||
);
|
||||
const handlePauseToggle = useCallback(() => {
|
||||
setIsPaused((prev) => {
|
||||
@@ -179,134 +178,134 @@ const ConnectionsPage = () => {
|
||||
const headerHeight = "7rem";
|
||||
|
||||
return (
|
||||
<div className="relative h-full w-full">
|
||||
<div
|
||||
className="absolute top-0 left-0 right-0 z-20 p-4 bg-background/80 backdrop-blur-sm"
|
||||
style={{ height: headerHeight }}
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="w-10">
|
||||
<SidebarTrigger />
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold tracking-tight">
|
||||
{t("Connections")}
|
||||
</h2>
|
||||
<TooltipProvider delayDuration={100}>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-4 text-sm text-muted-foreground">
|
||||
<div className="flex items-center gap-1">
|
||||
<ArrowDown className="h-4 w-4 text-green-500" />
|
||||
{parseTraffic(displayData.downloadTotal)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<ArrowUp className="h-4 w-4 text-sky-500" />
|
||||
{parseTraffic(displayData.uploadTotal)}
|
||||
</div>
|
||||
<div className="relative h-full w-full">
|
||||
<div
|
||||
className="absolute top-0 left-0 right-0 z-20 p-4 bg-background/80 backdrop-blur-sm"
|
||||
style={{ height: headerHeight }}
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="w-10">
|
||||
<SidebarTrigger />
|
||||
</div>
|
||||
<h2 className="text-2xl font-semibold tracking-tight">
|
||||
{t("Connections")}
|
||||
</h2>
|
||||
<TooltipProvider delayDuration={100}>
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex items-center gap-4 text-sm text-muted-foreground">
|
||||
<div className="flex items-center gap-1">
|
||||
<ArrowDown className="h-4 w-4 text-green-500" />
|
||||
{parseTraffic(displayData.downloadTotal)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<ArrowUp className="h-4 w-4 text-sky-500" />
|
||||
{parseTraffic(displayData.uploadTotal)}
|
||||
</div>
|
||||
<Separator orientation="vertical" className="h-6 mx-2" />
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() =>
|
||||
setSetting((o) =>
|
||||
o?.layout !== "table"
|
||||
? { ...o, layout: "table" }
|
||||
: { ...o, layout: "list" },
|
||||
)
|
||||
}
|
||||
>
|
||||
{isTableLayout ? (
|
||||
<List className="h-5 w-5" />
|
||||
) : (
|
||||
<Table2 className="h-5 w-5" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{isTableLayout ? t("List View") : t("Table View")}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handlePauseToggle}
|
||||
>
|
||||
{isPaused ? (
|
||||
<PlayCircle className="h-5 w-5" />
|
||||
) : (
|
||||
<PauseCircle className="h-5 w-5" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{isPaused ? t("Resume") : t("Pause")}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Button size="sm" variant="destructive" onClick={onCloseAll}>
|
||||
{t("Close All")}
|
||||
</Button>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
{!isTableLayout && (
|
||||
<Select
|
||||
value={curOrderOpt}
|
||||
onValueChange={(value) => setOrderOpt(value)}
|
||||
>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder={t("Sort by")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.keys(orderOpts).map((opt) => (
|
||||
<SelectItem key={opt} value={opt}>
|
||||
{t(opt)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
<div className="flex-1">
|
||||
<BaseSearchBox onSearch={handleSearch} />
|
||||
<Separator orientation="vertical" className="h-6 mx-2" />
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() =>
|
||||
setSetting((o) =>
|
||||
o?.layout !== "table"
|
||||
? { ...o, layout: "table" }
|
||||
: { ...o, layout: "list" },
|
||||
)
|
||||
}
|
||||
>
|
||||
{isTableLayout ? (
|
||||
<List className="h-5 w-5" />
|
||||
) : (
|
||||
<Table2 className="h-5 w-5" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{isTableLayout ? t("List View") : t("Table View")}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handlePauseToggle}
|
||||
>
|
||||
{isPaused ? (
|
||||
<PlayCircle className="h-5 w-5" />
|
||||
) : (
|
||||
<PauseCircle className="h-5 w-5" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{isPaused ? t("Resume") : t("Pause")}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Button size="sm" variant="destructive" onClick={onCloseAll}>
|
||||
{t("Close All")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={scrollerRefCallback}
|
||||
className="absolute left-0 right-0 bottom-0 overflow-y-auto"
|
||||
style={{ top: headerHeight }}
|
||||
>
|
||||
{filterConn.length === 0 ? (
|
||||
<BaseEmpty />
|
||||
) : isTableLayout ? (
|
||||
<div className="p-4 pt-0">
|
||||
<ConnectionTable
|
||||
connections={filterConn}
|
||||
onShowDetail={(detail) => detailRef.current?.open(detail)}
|
||||
scrollerRef={scrollerRefCallback}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<Virtuoso
|
||||
scrollerRef={scrollerRefCallback}
|
||||
data={filterConn}
|
||||
className="h-full w-full"
|
||||
itemContent={(_, item) => (
|
||||
<ConnectionItem
|
||||
value={item}
|
||||
onShowDetail={() => detailRef.current?.open(item)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<div className="flex items-center gap-2 mt-2">
|
||||
{!isTableLayout && (
|
||||
<Select
|
||||
value={curOrderOpt}
|
||||
onValueChange={(value) => setOrderOpt(value)}
|
||||
>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder={t("Sort by")} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{Object.keys(orderOpts).map((opt) => (
|
||||
<SelectItem key={opt} value={opt}>
|
||||
{t(opt)}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
)}
|
||||
<ConnectionDetail ref={detailRef} />
|
||||
<div className="flex-1">
|
||||
<BaseSearchBox onSearch={handleSearch} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
ref={scrollerRefCallback}
|
||||
className="absolute left-0 right-0 bottom-0 overflow-y-auto"
|
||||
style={{ top: headerHeight }}
|
||||
>
|
||||
{filterConn.length === 0 ? (
|
||||
<BaseEmpty />
|
||||
) : isTableLayout ? (
|
||||
<div className="p-4 pt-0">
|
||||
<ConnectionTable
|
||||
connections={filterConn}
|
||||
onShowDetail={(detail) => detailRef.current?.open(detail)}
|
||||
scrollerRef={scrollerRefCallback}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<Virtuoso
|
||||
scrollerRef={scrollerRefCallback}
|
||||
data={filterConn}
|
||||
className="h-full w-full"
|
||||
itemContent={(_, item) => (
|
||||
<ConnectionItem
|
||||
value={item}
|
||||
onShowDetail={() => detailRef.current?.open(item)}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<ConnectionDetail ref={detailRef} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import React, {useRef, useMemo, useCallback, useState, useEffect} from "react";
|
||||
import React, {
|
||||
useRef,
|
||||
useMemo,
|
||||
useCallback,
|
||||
useState,
|
||||
useEffect,
|
||||
} from "react";
|
||||
import { useLockFn } from "ahooks";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { toast } from "sonner";
|
||||
@@ -25,7 +31,11 @@ import {
|
||||
AlertTriangle,
|
||||
Loader2,
|
||||
Globe,
|
||||
Send, ExternalLink, RefreshCw, ArrowDown, ArrowUp,
|
||||
Send,
|
||||
ExternalLink,
|
||||
RefreshCw,
|
||||
ArrowDown,
|
||||
ArrowUp,
|
||||
} from "lucide-react";
|
||||
import { useVerge } from "@/hooks/use-verge";
|
||||
import { useSystemState } from "@/hooks/use-system-state";
|
||||
@@ -34,7 +44,12 @@ import { Switch } from "@/components/ui/switch";
|
||||
import { ProxySelectors } from "@/components/home/proxy-selectors";
|
||||
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
|
||||
import { closeAllConnections } from "@/services/api";
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
import { updateProfile } from "@/services/cmds";
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar";
|
||||
import parseTraffic from "@/utils/parse-traffic";
|
||||
@@ -48,45 +63,45 @@ const MinimalHomePage: React.FC = () => {
|
||||
const [isToggling, setIsToggling] = useState(false);
|
||||
const [isUpdating, setIsUpdating] = useState(false);
|
||||
const { profiles, patchProfiles, activateSelected, mutateProfiles } =
|
||||
useProfiles();
|
||||
useProfiles();
|
||||
const viewerRef = useRef<ProfileViewerRef>(null);
|
||||
const [uidToActivate, setUidToActivate] = useState<string | null>(null);
|
||||
const { connections } = useAppData();
|
||||
|
||||
const profileItems = useMemo(() => {
|
||||
const items =
|
||||
profiles && Array.isArray(profiles.items) ? profiles.items : [];
|
||||
profiles && Array.isArray(profiles.items) ? profiles.items : [];
|
||||
const allowedTypes = ["local", "remote"];
|
||||
return items.filter((i: any) => i && allowedTypes.includes(i.type!));
|
||||
}, [profiles]);
|
||||
|
||||
const currentProfile = useMemo(() => {
|
||||
return profileItems.find(p => p.uid === profiles?.current);
|
||||
return profileItems.find((p) => p.uid === profiles?.current);
|
||||
}, [profileItems, profiles?.current]);
|
||||
const currentProfileName = currentProfile?.name || profiles?.current;
|
||||
|
||||
const activateProfile = useCallback(
|
||||
async (uid: string, notifySuccess: boolean) => {
|
||||
try {
|
||||
await patchProfiles({ current: uid });
|
||||
await closeAllConnections();
|
||||
await activateSelected();
|
||||
if (notifySuccess) {
|
||||
toast.success(t("Profile Switched"));
|
||||
}
|
||||
} catch (err: any) {
|
||||
toast.error(err.message || err.toString());
|
||||
mutateProfiles();
|
||||
async (uid: string, notifySuccess: boolean) => {
|
||||
try {
|
||||
await patchProfiles({ current: uid });
|
||||
await closeAllConnections();
|
||||
await activateSelected();
|
||||
if (notifySuccess) {
|
||||
toast.success(t("Profile Switched"));
|
||||
}
|
||||
},
|
||||
[patchProfiles, activateSelected, mutateProfiles, t],
|
||||
} catch (err: any) {
|
||||
toast.error(err.message || err.toString());
|
||||
mutateProfiles();
|
||||
}
|
||||
},
|
||||
[patchProfiles, activateSelected, mutateProfiles, t],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const uidToActivate = sessionStorage.getItem('activateProfile');
|
||||
if (uidToActivate && profileItems.some(p => p.uid === uidToActivate)) {
|
||||
const uidToActivate = sessionStorage.getItem("activateProfile");
|
||||
if (uidToActivate && profileItems.some((p) => p.uid === uidToActivate)) {
|
||||
activateProfile(uidToActivate, false);
|
||||
sessionStorage.removeItem('activateProfile');
|
||||
sessionStorage.removeItem("activateProfile");
|
||||
}
|
||||
}, [profileItems, activateProfile]);
|
||||
|
||||
@@ -101,7 +116,7 @@ const MinimalHomePage: React.FC = () => {
|
||||
const isTunAvailable = isServiceMode || isAdminMode;
|
||||
const isProxyEnabled = verge?.enable_system_proxy || verge?.enable_tun_mode;
|
||||
const showTunAlert =
|
||||
(verge?.primary_action ?? "tun-mode") === "tun-mode" && !isTunAvailable;
|
||||
(verge?.primary_action ?? "tun-mode") === "tun-mode" && !isTunAvailable;
|
||||
|
||||
const handleToggleProxy = useLockFn(async () => {
|
||||
const turningOn = !isProxyEnabled;
|
||||
@@ -143,7 +158,7 @@ const MinimalHomePage: React.FC = () => {
|
||||
});
|
||||
|
||||
const handleUpdateProfile = useLockFn(async () => {
|
||||
if (!currentProfile?.uid || currentProfile.type !== 'remote') return;
|
||||
if (!currentProfile?.uid || currentProfile.type !== "remote") return;
|
||||
setIsUpdating(true);
|
||||
try {
|
||||
await updateProfile(currentProfile.uid);
|
||||
@@ -159,315 +174,324 @@ const MinimalHomePage: React.FC = () => {
|
||||
const statusInfo = useMemo(() => {
|
||||
if (isToggling) {
|
||||
return {
|
||||
text: isProxyEnabled ? t('Disconnecting...') : t('Connecting...'),
|
||||
color: isProxyEnabled ? '#f59e0b' : '#84cc16',
|
||||
text: isProxyEnabled ? t("Disconnecting...") : t("Connecting..."),
|
||||
color: isProxyEnabled ? "#f59e0b" : "#84cc16",
|
||||
isAnimating: true,
|
||||
};
|
||||
}
|
||||
if (isProxyEnabled) {
|
||||
return {
|
||||
text: t('Connected'),
|
||||
color: '#22c55e',
|
||||
text: t("Connected"),
|
||||
color: "#22c55e",
|
||||
isAnimating: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
text: t('Disconnected'),
|
||||
color: '#ef4444',
|
||||
text: t("Disconnected"),
|
||||
color: "#ef4444",
|
||||
isAnimating: false,
|
||||
};
|
||||
}, [isToggling, isProxyEnabled, t]);
|
||||
|
||||
return (
|
||||
<div className="h-full w-full flex flex-col">
|
||||
<div className="absolute inset-0 opacity-20 pointer-events-none z-0 [transform:translateZ(0)]">
|
||||
<img
|
||||
src={map}
|
||||
alt="World map"
|
||||
className="w-full h-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{isProxyEnabled && (
|
||||
<div
|
||||
className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-[500px] w-[500px] rounded-full pointer-events-none z-0 transition-opacity duration-500"
|
||||
style={{
|
||||
background: 'radial-gradient(circle, rgba(34,197,94,0.3) 0%, transparent 70%)',
|
||||
filter: 'blur(100px)',
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<header className="flex-shrink-0 p-5 grid grid-cols-3 items-center z-10">
|
||||
<div className="flex justify-start">
|
||||
<SidebarTrigger />
|
||||
</div>
|
||||
<div className="justify-self-center flex flex-col items-center gap-2">
|
||||
<div className="relative flex items-center justify-center">
|
||||
{profileItems.length > 0 ? (
|
||||
<>
|
||||
<div className="absolute right-full mr-2">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => viewerRef.current?.create()}
|
||||
className={cn(
|
||||
"backdrop-blur-sm bg-white/80 border-gray-300/60",
|
||||
"dark:bg-white/5 dark:border-white/15",
|
||||
"hover:bg-white/90 hover:border-gray-400/70",
|
||||
"dark:hover:bg-white/10 dark:hover:border-white/20",
|
||||
"transition-all duration-200"
|
||||
)}
|
||||
>
|
||||
<PlusCircle className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t("Add Profile")}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
"w-full max-w-[250px] sm:max-w-xs",
|
||||
"backdrop-blur-sm bg-white/80 border-gray-300/60",
|
||||
"dark:bg-white/5 dark:border-white/15",
|
||||
"hover:bg-white/90 hover:border-gray-400/70",
|
||||
"dark:hover:bg-white/10 dark:hover:border-white/20",
|
||||
"transition-all duration-200"
|
||||
)}
|
||||
>
|
||||
<span className="truncate">{currentProfileName}</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-[--radix-dropdown-menu-trigger-width]">
|
||||
<DropdownMenuLabel>{t("Profiles")}</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{profileItems.map((p) => (
|
||||
<DropdownMenuItem
|
||||
key={p.uid}
|
||||
onSelect={() => handleProfileChange(p.uid)}
|
||||
>
|
||||
<span className="flex-1 truncate">{p.name}</span>
|
||||
{profiles?.current === p.uid && (
|
||||
<Check className="ml-4 h-4 w-4" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{currentProfile?.type === 'remote' && (
|
||||
<div className="absolute left-full ml-2">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleUpdateProfile}
|
||||
disabled={isUpdating}
|
||||
className={cn(
|
||||
"flex-shrink-0",
|
||||
"backdrop-blur-sm bg-white/70 border border-gray-300/50",
|
||||
"dark:bg-white/5 dark:border-white/10",
|
||||
"hover:bg-white/85 hover:border-gray-400/60",
|
||||
"dark:hover:bg-white/10 dark:hover:border-white/15",
|
||||
"transition-all duration-200"
|
||||
)}
|
||||
>
|
||||
{isUpdating ? <Loader2 className="h-5 w-5 animate-spin" /> : <RefreshCw className="h-5 w-5" />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent><p>{t("Update Profile")}</p></TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="absolute right-full mr-2">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => viewerRef.current?.create()}
|
||||
className={cn(
|
||||
"backdrop-blur-sm bg-white/80 border-gray-300/60",
|
||||
"dark:bg-white/5 dark:border-white/15",
|
||||
"hover:bg-white/90 hover:border-gray-400/70",
|
||||
"dark:hover:bg-white/10 dark:hover:border-white/20",
|
||||
"transition-all duration-200"
|
||||
)}
|
||||
>
|
||||
<PlusCircle className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t("Add Profile")}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled
|
||||
className={cn(
|
||||
"max-w-[250px] sm:max-w-xs opacity-50 cursor-not-allowed",
|
||||
"backdrop-blur-sm bg-white/50 border-gray-300/40",
|
||||
"dark:bg-white/3 dark:border-white/10"
|
||||
)}
|
||||
>
|
||||
<span className="truncate">{t("No profiles available")}</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-30" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end">
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main className="flex-1 overflow-y-auto flex items-center justify-center">
|
||||
<div className="relative flex flex-col items-center gap-8 py-10 w-full max-w-4xl px-4">
|
||||
{currentProfile?.announce && (
|
||||
<div className="absolute -top-15 w-full flex justify-center text-center max-w-lg">
|
||||
{currentProfile.announce_url ? (
|
||||
<a
|
||||
href={currentProfile.announce_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 text-base font-semibold text-foreground hover:underline hover:opacity-80 transition-all whitespace-pre-wrap"
|
||||
title={currentProfile.announce_url.replace(/\\n/g, '\n')}
|
||||
>
|
||||
<span>{currentProfile.announce.replace(/\\n/g, '\n')}</span>
|
||||
<ExternalLink className="h-4 w-4 flex-shrink-0" />
|
||||
</a>
|
||||
) : (
|
||||
<p className="text-base font-semibold text-foreground whitespace-pre-wrap">
|
||||
{currentProfile.announce}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="relative text-center">
|
||||
<h1
|
||||
className={cn(
|
||||
"text-4xl mb-2 font-semibold transition-colors duration-300",
|
||||
statusInfo.isAnimating && "animate-pulse"
|
||||
)}
|
||||
style={{ color: statusInfo.color }}
|
||||
>
|
||||
{statusInfo.text}
|
||||
</h1>
|
||||
{isProxyEnabled && (
|
||||
<div className="absolute top-full left-1/2 -translate-x-1/2 mt-52 flex justify-center items-center text-sm text-muted-foreground gap-6">
|
||||
<div className="flex items-center gap-1">
|
||||
<ArrowDown className="h-4 w-4 text-green-500" />
|
||||
{parseTraffic(connections.downloadTotal)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<ArrowUp className="h-4 w-4 text-sky-500" />
|
||||
{parseTraffic(connections.uploadTotal)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="relative -translate-y-6">
|
||||
<PowerButton
|
||||
loading={isToggling}
|
||||
checked={!!isProxyEnabled}
|
||||
onClick={handleToggleProxy}
|
||||
disabled={showTunAlert || isToggling || profileItems.length === 0}
|
||||
aria-label={t("Toggle Proxy")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{showTunAlert && (
|
||||
<div className="w-full max-w-sm">
|
||||
<Alert
|
||||
variant="destructive"
|
||||
className="flex flex-col items-center gap-2 text-center"
|
||||
>
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertTitle>{t("Attention Required")}</AlertTitle>
|
||||
<AlertDescription className="text-xs">
|
||||
{t("TUN requires Service Mode or Admin Mode")}
|
||||
</AlertDescription>
|
||||
{!isServiceMode && !isAdminMode && (
|
||||
<Button
|
||||
size="sm"
|
||||
className="mt-2"
|
||||
onClick={installServiceAndRestartCore}
|
||||
>
|
||||
<Wrench className="mr-2 h-4 w-4" />
|
||||
{t("Install Service")}
|
||||
</Button>
|
||||
)}
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="w-full max-w-sm mt-4 flex justify-center">
|
||||
{profileItems.length > 0 ? (
|
||||
<ProxySelectors />
|
||||
) : (
|
||||
<Alert className="flex flex-col items-center gap-2 text-center">
|
||||
<PlusCircle className="h-4 w-4" />
|
||||
<AlertTitle>{t("Get Started")}</AlertTitle>
|
||||
<AlertDescription className="whitespace-pre-wrap">
|
||||
{t(
|
||||
"You don't have any profiles yet. Add your first one to begin.",
|
||||
)}
|
||||
</AlertDescription>
|
||||
<Button
|
||||
className="mt-2"
|
||||
onClick={() => viewerRef.current?.create()}
|
||||
>
|
||||
{t("Add Profile")}
|
||||
</Button>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<footer className="flex justify-center p-4 flex-shrink-0">
|
||||
{currentProfile?.support_url && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span>{t("Support")}:</span>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<a href={currentProfile.support_url} target="_blank" rel="noopener noreferrer" className="transition-colors hover:text-primary">
|
||||
{(currentProfile.support_url.includes('t.me') || currentProfile.support_url.includes('telegram') || currentProfile.support_url.startsWith('tg://')) ? (
|
||||
<Send className="h-5 w-5" />
|
||||
) : (
|
||||
<Globe className="h-5 w-5" />
|
||||
)}
|
||||
</a>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{currentProfile.support_url}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
)}
|
||||
</footer>
|
||||
<ProfileViewer ref={viewerRef} onChange={() => mutateProfiles()} />
|
||||
<div className="h-full w-full flex flex-col">
|
||||
<div className="absolute inset-0 opacity-20 pointer-events-none z-0 [transform:translateZ(0)]">
|
||||
<img src={map} alt="World map" className="w-full h-full object-cover" />
|
||||
</div>
|
||||
|
||||
{isProxyEnabled && (
|
||||
<div
|
||||
className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 h-[500px] w-[500px] rounded-full pointer-events-none z-0 transition-opacity duration-500"
|
||||
style={{
|
||||
background:
|
||||
"radial-gradient(circle, rgba(34,197,94,0.3) 0%, transparent 70%)",
|
||||
filter: "blur(100px)",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
<header className="flex-shrink-0 p-5 grid grid-cols-3 items-center z-10">
|
||||
<div className="flex justify-start">
|
||||
<SidebarTrigger />
|
||||
</div>
|
||||
<div className="justify-self-center flex flex-col items-center gap-2">
|
||||
<div className="relative flex items-center justify-center">
|
||||
{profileItems.length > 0 ? (
|
||||
<>
|
||||
<div className="absolute right-full mr-2">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => viewerRef.current?.create()}
|
||||
className={cn(
|
||||
"backdrop-blur-sm bg-white/80 border-gray-300/60",
|
||||
"dark:bg-white/5 dark:border-white/15",
|
||||
"hover:bg-white/90 hover:border-gray-400/70",
|
||||
"dark:hover:bg-white/10 dark:hover:border-white/20",
|
||||
"transition-all duration-200",
|
||||
)}
|
||||
>
|
||||
<PlusCircle className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t("Add Profile")}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
className={cn(
|
||||
"w-full max-w-[250px] sm:max-w-xs",
|
||||
"backdrop-blur-sm bg-white/80 border-gray-300/60",
|
||||
"dark:bg-white/5 dark:border-white/15",
|
||||
"hover:bg-white/90 hover:border-gray-400/70",
|
||||
"dark:hover:bg-white/10 dark:hover:border-white/20",
|
||||
"transition-all duration-200",
|
||||
)}
|
||||
>
|
||||
<span className="truncate">{currentProfileName}</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className="w-[--radix-dropdown-menu-trigger-width]">
|
||||
<DropdownMenuLabel>{t("Profiles")}</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
{profileItems.map((p) => (
|
||||
<DropdownMenuItem
|
||||
key={p.uid}
|
||||
onSelect={() => handleProfileChange(p.uid)}
|
||||
>
|
||||
<span className="flex-1 truncate">{p.name}</span>
|
||||
{profiles?.current === p.uid && (
|
||||
<Check className="ml-4 h-4 w-4" />
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{currentProfile?.type === "remote" && (
|
||||
<div className="absolute left-full ml-2">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={handleUpdateProfile}
|
||||
disabled={isUpdating}
|
||||
className={cn(
|
||||
"flex-shrink-0",
|
||||
"backdrop-blur-sm bg-white/70 border border-gray-300/50",
|
||||
"dark:bg-white/5 dark:border-white/10",
|
||||
"hover:bg-white/85 hover:border-gray-400/60",
|
||||
"dark:hover:bg-white/10 dark:hover:border-white/15",
|
||||
"transition-all duration-200",
|
||||
)}
|
||||
>
|
||||
{isUpdating ? (
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-5 w-5" />
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t("Update Profile")}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="absolute right-full mr-2">
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => viewerRef.current?.create()}
|
||||
className={cn(
|
||||
"backdrop-blur-sm bg-white/80 border-gray-300/60",
|
||||
"dark:bg-white/5 dark:border-white/15",
|
||||
"hover:bg-white/90 hover:border-gray-400/70",
|
||||
"dark:hover:bg-white/10 dark:hover:border-white/20",
|
||||
"transition-all duration-200",
|
||||
)}
|
||||
>
|
||||
<PlusCircle className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t("Add Profile")}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled
|
||||
className={cn(
|
||||
"max-w-[250px] sm:max-w-xs opacity-50 cursor-not-allowed",
|
||||
"backdrop-blur-sm bg-white/50 border-gray-300/40",
|
||||
"dark:bg-white/3 dark:border-white/10",
|
||||
)}
|
||||
>
|
||||
<span className="truncate">{t("No profiles available")}</span>
|
||||
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-30" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex justify-end"></div>
|
||||
</header>
|
||||
|
||||
<main className="flex-1 overflow-y-auto flex items-center justify-center">
|
||||
<div className="relative flex flex-col items-center gap-8 py-10 w-full max-w-4xl px-4">
|
||||
{currentProfile?.announce && (
|
||||
<div className="absolute -top-15 w-full flex justify-center text-center max-w-lg">
|
||||
{currentProfile.announce_url ? (
|
||||
<a
|
||||
href={currentProfile.announce_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 text-base font-semibold text-foreground hover:underline hover:opacity-80 transition-all whitespace-pre-wrap"
|
||||
title={currentProfile.announce_url.replace(/\\n/g, "\n")}
|
||||
>
|
||||
<span>{currentProfile.announce.replace(/\\n/g, "\n")}</span>
|
||||
<ExternalLink className="h-4 w-4 flex-shrink-0" />
|
||||
</a>
|
||||
) : (
|
||||
<p className="text-base font-semibold text-foreground whitespace-pre-wrap">
|
||||
{currentProfile.announce}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<div className="relative text-center">
|
||||
<h1
|
||||
className={cn(
|
||||
"text-4xl mb-2 font-semibold transition-colors duration-300",
|
||||
statusInfo.isAnimating && "animate-pulse",
|
||||
)}
|
||||
style={{ color: statusInfo.color }}
|
||||
>
|
||||
{statusInfo.text}
|
||||
</h1>
|
||||
{isProxyEnabled && (
|
||||
<div className="absolute top-full left-1/2 -translate-x-1/2 mt-52 flex justify-center items-center text-sm text-muted-foreground gap-6">
|
||||
<div className="flex items-center gap-1">
|
||||
<ArrowDown className="h-4 w-4 text-green-500" />
|
||||
{parseTraffic(connections.downloadTotal)}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<ArrowUp className="h-4 w-4 text-sky-500" />
|
||||
{parseTraffic(connections.uploadTotal)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="relative -translate-y-6">
|
||||
<PowerButton
|
||||
loading={isToggling}
|
||||
checked={!!isProxyEnabled}
|
||||
onClick={handleToggleProxy}
|
||||
disabled={showTunAlert || isToggling || profileItems.length === 0}
|
||||
aria-label={t("Toggle Proxy")}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{showTunAlert && (
|
||||
<div className="w-full max-w-sm">
|
||||
<Alert
|
||||
variant="destructive"
|
||||
className="flex flex-col items-center gap-2 text-center"
|
||||
>
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertTitle>{t("Attention Required")}</AlertTitle>
|
||||
<AlertDescription className="text-xs">
|
||||
{t("TUN requires Service Mode or Admin Mode")}
|
||||
</AlertDescription>
|
||||
{!isServiceMode && !isAdminMode && (
|
||||
<Button
|
||||
size="sm"
|
||||
className="mt-2"
|
||||
onClick={installServiceAndRestartCore}
|
||||
>
|
||||
<Wrench className="mr-2 h-4 w-4" />
|
||||
{t("Install Service")}
|
||||
</Button>
|
||||
)}
|
||||
</Alert>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="w-full max-w-sm mt-4 flex justify-center">
|
||||
{profileItems.length > 0 ? (
|
||||
<ProxySelectors />
|
||||
) : (
|
||||
<Alert className="flex flex-col items-center gap-2 text-center">
|
||||
<PlusCircle className="h-4 w-4" />
|
||||
<AlertTitle>{t("Get Started")}</AlertTitle>
|
||||
<AlertDescription className="whitespace-pre-wrap">
|
||||
{t(
|
||||
"You don't have any profiles yet. Add your first one to begin.",
|
||||
)}
|
||||
</AlertDescription>
|
||||
<Button
|
||||
className="mt-2"
|
||||
onClick={() => viewerRef.current?.create()}
|
||||
>
|
||||
{t("Add Profile")}
|
||||
</Button>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<footer className="flex justify-center p-4 flex-shrink-0">
|
||||
{currentProfile?.support_url && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span>{t("Support")}:</span>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<a
|
||||
href={currentProfile.support_url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="transition-colors hover:text-primary"
|
||||
>
|
||||
{currentProfile.support_url.includes("t.me") ||
|
||||
currentProfile.support_url.includes("telegram") ||
|
||||
currentProfile.support_url.startsWith("tg://") ? (
|
||||
<Send className="h-5 w-5" />
|
||||
) : (
|
||||
<Globe className="h-5 w-5" />
|
||||
)}
|
||||
</a>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{currentProfile.support_url}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
</div>
|
||||
)}
|
||||
</footer>
|
||||
<ProfileViewer ref={viewerRef} onChange={() => mutateProfiles()} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ import {
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {SidebarTrigger} from "@/components/ui/sidebar";
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar";
|
||||
|
||||
const LogPage = () => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
@@ -55,13 +55,7 @@ import {
|
||||
TooltipTrigger,
|
||||
} from "@/components/ui/tooltip";
|
||||
|
||||
import {
|
||||
PlusCircle,
|
||||
RefreshCw,
|
||||
Zap,
|
||||
FileText,
|
||||
Loader2,
|
||||
} from "lucide-react";
|
||||
import { PlusCircle, RefreshCw, Zap, FileText, Loader2 } from "lucide-react";
|
||||
import { SidebarTrigger } from "@/components/ui/sidebar";
|
||||
|
||||
const ProfilePage = () => {
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import React, { useState, useMemo, useRef, useEffect, useCallback } from "react";
|
||||
import React, {
|
||||
useState,
|
||||
useMemo,
|
||||
useRef,
|
||||
useEffect,
|
||||
useCallback,
|
||||
} from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Virtuoso, VirtuosoHandle } from "react-virtuoso";
|
||||
import { useAppData } from "@/providers/app-data-provider";
|
||||
|
||||
@@ -401,6 +401,9 @@ export async function getNextUpdateTime(uid: string) {
|
||||
return invoke<number | null>("get_next_update_time", { uid });
|
||||
}
|
||||
|
||||
export async function createProfileFromShareLink(link: string, templateName: string) {
|
||||
export async function createProfileFromShareLink(
|
||||
link: string,
|
||||
templateName: string,
|
||||
) {
|
||||
return invoke<void>("create_profile_from_share_link", { link, templateName });
|
||||
}
|
||||
|
||||
@@ -1,21 +1,25 @@
|
||||
import { toast } from "sonner";
|
||||
|
||||
type NoticeType = 'success' | 'error' | 'info' | 'warning';
|
||||
type NoticeType = "success" | "error" | "info" | "warning";
|
||||
|
||||
export const showNotice = (type: NoticeType, message: string, duration?: number) => {
|
||||
export const showNotice = (
|
||||
type: NoticeType,
|
||||
message: string,
|
||||
duration?: number,
|
||||
) => {
|
||||
const options = duration ? { duration } : {};
|
||||
|
||||
switch (type) {
|
||||
case 'success':
|
||||
case "success":
|
||||
toast.success(message, options);
|
||||
break;
|
||||
case 'error':
|
||||
case "error":
|
||||
toast.error(message, options);
|
||||
break;
|
||||
case 'info':
|
||||
case "info":
|
||||
toast.info(message, options);
|
||||
break;
|
||||
case 'warning':
|
||||
case "warning":
|
||||
toast.warning(message, options);
|
||||
break;
|
||||
default:
|
||||
|
||||
Reference in New Issue
Block a user