23 Commits

Author SHA1 Message Date
GyDi
f4f1a0fbc6 v0.0.29 2022-04-13 01:30:08 +08:00
GyDi
74e10dc012 chore: update log 2022-04-13 01:29:48 +08:00
GyDi
359812b7ed chore: update dep 2022-04-13 01:21:49 +08:00
GyDi
c2449e53c4 chore: rename green to portable 2022-04-13 01:17:40 +08:00
GyDi
1a91249da2 feat: system tray add tun mode 2022-04-13 01:09:51 +08:00
GyDi
b9162f9576 fix: adjust log 2022-04-13 00:49:30 +08:00
GyDi
f726e8a7b3 feat: supports change config dir 2022-04-12 23:09:32 +08:00
GyDi
2f284cfdc9 chore: update clash version 2022-04-12 23:04:19 +08:00
GyDi
b74696adba feat: add default user agent 2022-04-12 01:05:51 +08:00
GyDi
c8ccba0192 chore: rm console 2022-04-11 02:26:09 +08:00
GyDi
41b0e05f62 feat: connections page supports filter 2022-04-11 02:25:34 +08:00
GyDi
847d5f1b3b feat: log page supports filter 2022-04-11 01:46:33 +08:00
GyDi
0445f9dfc2 fix: check button hover style 2022-04-10 03:33:17 +08:00
GyDi
3001c780bd feat: optimize delay checker concurrency strategy 2022-04-10 02:58:48 +08:00
GyDi
68ad5e2320 feat: support sort proxy node and custom test url 2022-04-10 02:09:36 +08:00
GyDi
b5e229b19c chore: update deps 2022-04-10 01:31:05 +08:00
GyDi
453d798fcf refactor: proxy head 2022-04-08 01:35:18 +08:00
GyDi
451afdb660 v0.0.28 2022-04-07 01:28:30 +08:00
GyDi
d298bda92c chore: update log 2022-04-07 01:27:48 +08:00
GyDi
fd99ba6255 feat: handle remote clash config fields 2022-04-07 01:20:44 +08:00
GyDi
6ade0b2b1a fix: icon button color inherit 2022-04-06 22:52:00 +08:00
GyDi
9902003da9 fix: remove the lonely zero 2022-04-06 22:48:10 +08:00
GyDi
0ff2fcac11 chore: readme 2022-04-06 01:52:20 +08:00
34 changed files with 785 additions and 327 deletions

View File

@@ -76,7 +76,7 @@ jobs:
- name: Green zip bundle - name: Green zip bundle
if: matrix.os == 'windows-latest' if: matrix.os == 'windows-latest'
run: | run: |
yarn run green yarn run portable
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -13,6 +13,7 @@ A <a href="https://github.com/Dreamacro/clash">Clash</a> GUI based on <a href="h
- Full `clash` config supported, Partial `clash premium` config supported. - Full `clash` config supported, Partial `clash premium` config supported.
- Profiles management and enhancement (by yaml and Javascript). [Doc](https://github.com/zzzgydi/clash-verge/issues/12) - Profiles management and enhancement (by yaml and Javascript). [Doc](https://github.com/zzzgydi/clash-verge/issues/12)
- Simple UI and supports custom theme color.
- System proxy setting and guard. - System proxy setting and guard.
## Install ## Install
@@ -64,6 +65,17 @@ yarn build
<img src="./docs/demo6.png" alt="demo6" width="32%" /> <img src="./docs/demo6.png" alt="demo6" width="32%" />
</div> </div>
### Custom Theme
<div align="center">
<img src="./docs/color1.png" alt="demo1" width="16%" />
<img src="./docs/color2.png" alt="demo2" width="16%" />
<img src="./docs/color3.png" alt="demo3" width="16%" />
<img src="./docs/color4.png" alt="demo4" width="16%" />
<img src="./docs/color5.png" alt="demo5" width="16%" />
<img src="./docs/color6.png" alt="demo6" width="16%" />
</div>
## Disclaimer ## Disclaimer
This is a learning project for Rust practice. This is a learning project for Rust practice.

View File

@@ -1,3 +1,28 @@
## v0.0.29
### Features
- sort proxy node
- custom proxy test url
- logs page filter
- connections page filter
- default user agent for subscription
- system tray add tun mode toggle
- enable to change the config dir (Windows only)
## v0.0.28
### Features
- enable to use clash config fields (UI)
### Bug Fixes
- remove the character
- fix some icon color
---
## v0.0.27 ## v0.0.27
### Features ### Features

BIN
docs/color1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
docs/color2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

BIN
docs/color3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
docs/color4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

BIN
docs/color5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

BIN
docs/color6.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

View File

@@ -1,6 +1,6 @@
{ {
"name": "clash-verge", "name": "clash-verge",
"version": "0.0.27", "version": "0.0.29",
"license": "GPL-3.0", "license": "GPL-3.0",
"scripts": { "scripts": {
"dev": "tauri dev", "dev": "tauri dev",
@@ -10,16 +10,16 @@
"web:build": "tsc && vite build", "web:build": "tsc && vite build",
"web:serve": "vite preview", "web:serve": "vite preview",
"check": "node scripts/check.mjs", "check": "node scripts/check.mjs",
"green": "node scripts/green.mjs",
"publish": "node scripts/publish.mjs",
"updater": "node scripts/updater.mjs", "updater": "node scripts/updater.mjs",
"publish": "node scripts/publish.mjs",
"portable": "node scripts/portable.mjs",
"prepare": "husky install" "prepare": "husky install"
}, },
"dependencies": { "dependencies": {
"@emotion/react": "^11.8.2", "@emotion/react": "^11.8.2",
"@emotion/styled": "^11.8.1", "@emotion/styled": "^11.8.1",
"@mui/icons-material": "^5.5.1", "@mui/icons-material": "^5.6.1",
"@mui/material": "^5.5.3", "@mui/material": "^5.6.1",
"@tauri-apps/api": "^1.0.0-rc.3", "@tauri-apps/api": "^1.0.0-rc.3",
"ahooks": "^3.2.0", "ahooks": "^3.2.0",
"axios": "^0.26.0", "axios": "^0.26.0",

View File

@@ -16,7 +16,7 @@ function resolveClash() {
const CLASH_URL_PREFIX = const CLASH_URL_PREFIX =
"https://github.com/Dreamacro/clash/releases/download/premium/"; "https://github.com/Dreamacro/clash/releases/download/premium/";
const CLASH_LATEST_DATE = "2022.03.21"; const CLASH_LATEST_DATE = "2022.04.11";
// todo // todo
const map = { const map = {

View File

@@ -6,7 +6,7 @@ import { getOctokit, context } from "@actions/github";
/// Script for ci /// Script for ci
/// 打包绿色版/便携版 (only Windows) /// 打包绿色版/便携版 (only Windows)
async function resolveGreen() { async function resolvePortable() {
if (process.platform !== "win32") return; if (process.platform !== "win32") return;
const releaseDir = "./src-tauri/target/release"; const releaseDir = "./src-tauri/target/release";
@@ -25,10 +25,10 @@ async function resolveGreen() {
const packageJson = require("../package.json"); const packageJson = require("../package.json");
const { version } = packageJson; const { version } = packageJson;
const zipFile = `Clash.Verge_${version}_x64_green.zip`; const zipFile = `Clash.Verge_${version}_x64_portable.zip`;
zip.writeZip(zipFile); zip.writeZip(zipFile);
console.log("[INFO]: create green zip successfully"); console.log("[INFO]: create portable zip successfully");
// push release assets // push release assets
if (process.env.GITHUB_TOKEN === undefined) { if (process.env.GITHUB_TOKEN === undefined) {
@@ -53,4 +53,4 @@ async function resolveGreen() {
}); });
} }
resolveGreen().catch(console.error); resolvePortable().catch(console.error);

View File

@@ -125,6 +125,23 @@ pub fn change_profile_chain(
wrap_err!(clash.activate_enhanced(&profiles, false, false)) wrap_err!(clash.activate_enhanced(&profiles, false, false))
} }
/// change the profile valid fields
#[tauri::command]
pub fn change_profile_valid(
valid: Option<Vec<String>>,
app_handle: tauri::AppHandle,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
profiles.put_valid(valid);
clash.set_window(app_handle.get_window("main"));
wrap_err!(clash.activate_enhanced(&profiles, false, false))
}
/// manually exec enhanced profile /// manually exec enhanced profile
#[tauri::command] #[tauri::command]
pub fn enhance_profiles( pub fn enhance_profiles(
@@ -320,15 +337,6 @@ pub fn patch_verge_config(
let mut verge = verge_state.0.lock().unwrap(); let mut verge = verge_state.0.lock().unwrap();
wrap_err!(verge.patch_config(payload))?; wrap_err!(verge.patch_config(payload))?;
// change system tray
if system_proxy.is_some() {
app_handle
.tray_handle()
.get_item("system_proxy")
.set_selected(system_proxy.unwrap())
.unwrap();
}
// change tun mode // change tun mode
if tun_mode.is_some() { if tun_mode.is_some() {
#[cfg(target_os = "windows")] #[cfg(target_os = "windows")]
@@ -346,6 +354,11 @@ pub fn patch_verge_config(
wrap_err!(clash.activate_enhanced(&profiles, false, false))?; wrap_err!(clash.activate_enhanced(&profiles, false, false))?;
} }
// change system tray
if system_proxy.is_some() || tun_mode.is_some() {
verge.update_systray(&app_handle).unwrap();
}
Ok(()) Ok(())
} }

View File

@@ -196,9 +196,8 @@ impl PrfItem {
if !with_proxy { if !with_proxy {
builder = builder.no_proxy(); builder = builder.no_proxy();
} }
if let Some(user_agent) = user_agent {
builder = builder.user_agent(user_agent); builder = builder.user_agent(user_agent.unwrap_or("clash-verge/v0.1.0".into()));
}
let resp = builder.build()?.get(url).send().await?; let resp = builder.build()?.get(url).send().await?;
let header = resp.headers(); let header = resp.headers();
@@ -316,6 +315,9 @@ pub struct Profiles {
/// same as PrfConfig.chain /// same as PrfConfig.chain
chain: Option<Vec<String>>, chain: Option<Vec<String>>,
/// record valid fields for clash
valid: Option<Vec<String>>,
/// profile list /// profile list
items: Option<Vec<PrfItem>>, items: Option<Vec<PrfItem>>,
} }
@@ -399,6 +401,11 @@ impl Profiles {
self.chain = chain; self.chain = chain;
} }
/// just change the `field`
pub fn put_valid(&mut self, valid: Option<Vec<String>>) {
self.valid = valid;
}
/// find the item by the uid /// find the item by the uid
pub fn get_item(&self, uid: &String) -> Result<&PrfItem> { pub fn get_item(&self, uid: &String) -> Result<&PrfItem> {
if self.items.is_some() { if self.items.is_some() {
@@ -599,9 +606,12 @@ impl Profiles {
None => vec![], None => vec![],
}; };
let valid = self.valid.clone().unwrap_or(vec![]);
Ok(PrfEnhanced { Ok(PrfEnhanced {
current, current,
chain, chain,
valid,
callback, callback,
}) })
} }
@@ -613,6 +623,8 @@ pub struct PrfEnhanced {
pub chain: Vec<PrfData>, pub chain: Vec<PrfData>,
pub valid: Vec<String>,
pub callback: String, pub callback: String,
} }

View File

@@ -8,6 +8,7 @@ use auto_launch::{AutoLaunch, AutoLaunchBuilder};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc; use std::sync::Arc;
use tauri::{async_runtime::Mutex, utils::platform::current_exe}; use tauri::{async_runtime::Mutex, utils::platform::current_exe};
use tauri::{AppHandle, Manager};
/// ### `verge.yaml` schema /// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)] #[derive(Default, Debug, Clone, Deserialize, Serialize)]
@@ -149,7 +150,7 @@ impl Verge {
if let Some(sysproxy) = self.old_sysproxy.take() { if let Some(sysproxy) = self.old_sysproxy.take() {
match sysproxy.set_sys() { match sysproxy.set_sys() {
Ok(_) => self.cur_sysproxy = None, Ok(_) => self.cur_sysproxy = None,
Err(_) => log::error!("failed to reset proxy for"), Err(_) => log::error!("failed to reset proxy"),
} }
} }
} }
@@ -242,7 +243,6 @@ impl Verge {
if sysproxy.set_sys().is_err() { if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy); self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
bail!("failed to set system proxy"); bail!("failed to set system proxy");
} }
self.cur_sysproxy = Some(sysproxy); self.cur_sysproxy = Some(sysproxy);
@@ -261,7 +261,6 @@ impl Verge {
if sysproxy.set_sys().is_err() { if sysproxy.set_sys().is_err() {
self.cur_sysproxy = Some(sysproxy); self.cur_sysproxy = Some(sysproxy);
log::error!("failed to set system proxy");
bail!("failed to set system proxy"); bail!("failed to set system proxy");
} }
} }
@@ -293,6 +292,35 @@ impl Verge {
self.config.save_file() self.config.save_file()
} }
/// update the system tray state
pub fn update_systray(&self, app_handle: &AppHandle) -> Result<()> {
// system proxy
let system_proxy = self.config.enable_system_proxy.as_ref();
system_proxy.map(|system_proxy| {
app_handle
.tray_handle()
.get_item("system_proxy")
.set_selected(*system_proxy)
.unwrap();
});
// tun mode
let tun_mode = self.config.enable_tun_mode.as_ref();
tun_mode.map(|tun_mode| {
app_handle
.tray_handle()
.get_item("tun_mode")
.set_selected(*tun_mode)
.unwrap();
});
// update verge config
let window = app_handle.get_window("main").unwrap();
window.emit("verge://refresh-verge-config", "yes").unwrap();
Ok(())
}
} }
impl Verge { impl Verge {

View File

@@ -10,7 +10,7 @@ mod utils;
use crate::{ use crate::{
core::VergeConfig, core::VergeConfig,
utils::{resolve, server}, utils::{dirs, resolve, server},
}; };
use tauri::{ use tauri::{
api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem, api, CustomMenuItem, Manager, SystemTray, SystemTrayEvent, SystemTrayMenu, SystemTrayMenuItem,
@@ -22,9 +22,15 @@ fn main() -> std::io::Result<()> {
return Ok(()); return Ok(());
} }
#[cfg(target_os = "windows")]
unsafe {
dirs::init_portable_flag();
}
let tray_menu = SystemTrayMenu::new() let tray_menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new("open_window", "Show")) .add_item(CustomMenuItem::new("open_window", "Show"))
.add_item(CustomMenuItem::new("system_proxy", "System Proxy")) .add_item(CustomMenuItem::new("system_proxy", "System Proxy"))
.add_item(CustomMenuItem::new("tun_mode", "Tun Mode"))
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash")) .add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
.add_native_item(SystemTrayMenuItem::Separator) .add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q")); .add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
@@ -55,17 +61,22 @@ fn main() -> std::io::Result<()> {
enable_system_proxy: Some(new_value), enable_system_proxy: Some(new_value),
..VergeConfig::default() ..VergeConfig::default()
}) { }) {
Ok(_) => { Ok(_) => verge.update_systray(app_handle).unwrap(),
app_handle Err(err) => log::error!("{err}"),
.tray_handle() }
.get_item(id.as_str()) }
.set_selected(new_value) "tun_mode" => {
.unwrap(); let verge_state = app_handle.state::<states::VergeState>();
let mut verge = verge_state.0.lock().unwrap();
// update verge config let old_value = verge.config.enable_tun_mode.clone().unwrap_or(false);
let window = app_handle.get_window("main").unwrap(); let new_value = !old_value;
window.emit("verge://refresh-verge-config", "yes").unwrap();
} match verge.patch_config(VergeConfig {
enable_tun_mode: Some(new_value),
..VergeConfig::default()
}) {
Ok(_) => verge.update_systray(app_handle).unwrap(),
Err(err) => log::error!("{err}"), Err(err) => log::error!("{err}"),
} }
} }
@@ -119,6 +130,7 @@ fn main() -> std::io::Result<()> {
cmds::sync_profiles, cmds::sync_profiles,
cmds::enhance_profiles, cmds::enhance_profiles,
cmds::change_profile_chain, cmds::change_profile_chain,
cmds::change_profile_valid,
cmds::read_profile_file, cmds::read_profile_file,
cmds::save_profile_file cmds::save_profile_file
]); ]);

View File

@@ -1,5 +1,6 @@
use std::env::temp_dir; use std::env::temp_dir;
use std::path::{Path, PathBuf}; use std::path::PathBuf;
use tauri::utils::platform::current_exe;
use tauri::{ use tauri::{
api::path::{home_dir, resource_dir}, api::path::{home_dir, resource_dir},
Env, PackageInfo, Env, PackageInfo,
@@ -15,12 +16,40 @@ static VERGE_CONFIG: &str = "verge.yaml";
static PROFILE_YAML: &str = "profiles.yaml"; static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml"; static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
/// portable flag
#[allow(unused)]
static mut PORTABLE_FLAG: bool = false;
/// initialize portable flag
pub unsafe fn init_portable_flag() {
#[cfg(target_os = "windows")]
{
let exe = current_exe().unwrap();
let dir = exe.parent().unwrap();
let dir = PathBuf::from(dir).join(".config/PORTABLE");
if dir.exists() {
PORTABLE_FLAG = true;
}
}
}
/// get the verge app home dir /// get the verge app home dir
pub fn app_home_dir() -> PathBuf { pub fn app_home_dir() -> PathBuf {
home_dir() #[cfg(target_os = "windows")]
.unwrap() unsafe {
.join(Path::new(".config")) if !PORTABLE_FLAG {
.join(Path::new(APP_DIR)) home_dir().unwrap().join(".config").join(APP_DIR)
} else {
let app_exe = current_exe().unwrap();
let app_exe = dunce::canonicalize(app_exe).unwrap();
let app_dir = app_exe.parent().unwrap();
PathBuf::from(app_dir).join(".config").join(APP_DIR)
}
}
#[cfg(not(target_os = "windows"))]
home_dir().unwrap().join(".config").join(APP_DIR)
} }
/// get the resources dir /// get the resources dir

View File

@@ -1,7 +1,7 @@
{ {
"package": { "package": {
"productName": "Clash Verge", "productName": "Clash Verge",
"version": "0.0.27" "version": "0.0.29"
}, },
"build": { "build": {
"distDir": "../dist", "distDir": "../dist",

View File

@@ -4,6 +4,7 @@ import { styled, ListItem, IconButton, ListItemText } from "@mui/material";
import { CloseRounded } from "@mui/icons-material"; import { CloseRounded } from "@mui/icons-material";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { deleteConnection } from "../../services/api"; import { deleteConnection } from "../../services/api";
import parseTraffic from "../../utils/parse-traffic";
const Tag = styled("span")(({ theme }) => ({ const Tag = styled("span")(({ theme }) => ({
display: "inline-block", display: "inline-block",
@@ -23,32 +24,39 @@ interface Props {
const ConnectionItem = (props: Props) => { const ConnectionItem = (props: Props) => {
const { value } = props; const { value } = props;
const onDelete = useLockFn(async () => deleteConnection(value.id)); const { id, metadata, chains, start, curUpload, curDownload } = value;
const onDelete = useLockFn(async () => deleteConnection(id));
const showTraffic = curUpload! > 1024 || curDownload! > 1024;
return ( return (
<ListItem <ListItem
dense dense
secondaryAction={ secondaryAction={
<IconButton edge="end" onClick={onDelete}> <IconButton edge="end" color="inherit" onClick={onDelete}>
<CloseRounded /> <CloseRounded />
</IconButton> </IconButton>
} }
> >
<ListItemText <ListItemText
primary={value.metadata.host || value.metadata.destinationIP} primary={metadata.host || metadata.destinationIP}
secondary={ secondary={
<> <>
<Tag sx={{ textTransform: "uppercase", color: "success" }}> <Tag sx={{ textTransform: "uppercase", color: "success" }}>
{value.metadata.network} {metadata.network}
</Tag> </Tag>
<Tag>{value.metadata.type}</Tag> <Tag>{metadata.type}</Tag>
{value.chains.length > 0 && ( {chains.length > 0 && <Tag>{chains[value.chains.length - 1]}</Tag>}
<Tag>{value.chains[value.chains.length - 1]}</Tag>
<Tag>{dayjs(start).fromNow()}</Tag>
{showTraffic && (
<Tag>
{parseTraffic(curUpload!)} / {parseTraffic(curDownload!)}
</Tag>
)} )}
<Tag>{dayjs(value.start).fromNow()}</Tag>
</> </>
} }
/> />

View File

@@ -1,26 +1,49 @@
import useSWR from "swr"; import useSWR from "swr";
import { useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { Box, Grid, IconButton, Stack } from "@mui/material"; import {
import { RestartAltRounded } from "@mui/icons-material"; Box,
Divider,
Grid,
IconButton,
ListItemIcon,
ListItemText,
Menu,
MenuItem,
Stack,
} from "@mui/material";
import {
AddchartRounded,
CheckRounded,
MenuRounded,
RestartAltRounded,
} from "@mui/icons-material";
import { import {
getProfiles, getProfiles,
deleteProfile, deleteProfile,
enhanceProfiles, enhanceProfiles,
changeProfileChain, changeProfileChain,
changeProfileValid,
} from "../../services/cmds"; } from "../../services/cmds";
import { CmdType } from "../../services/types"; import { CmdType } from "../../services/types";
import Notice from "../base/base-notice"; import getSystem from "../../utils/get-system";
import ProfileMore from "./profile-more"; import ProfileMore from "./profile-more";
import Notice from "../base/base-notice";
interface Props { interface Props {
items: CmdType.ProfileItem[]; items: CmdType.ProfileItem[];
chain: string[]; chain: string[];
} }
const OS = getSystem();
const EnhancedMode = (props: Props) => { const EnhancedMode = (props: Props) => {
const { items, chain } = props; const { items, chain } = props;
const { mutate } = useSWR("getProfiles", getProfiles); const { data, mutate } = useSWR("getProfiles", getProfiles);
const valid = data?.valid || [];
const [anchorEl, setAnchorEl] = useState<any>(null);
// handler // handler
const onEnhance = useLockFn(async () => { const onEnhance = useLockFn(async () => {
@@ -74,6 +97,19 @@ const EnhancedMode = (props: Props) => {
mutate((conf = {}) => ({ ...conf, chain: newChain }), true); mutate((conf = {}) => ({ ...conf, chain: newChain }), true);
}); });
// update valid list
const onToggleValid = useLockFn(async (key: string) => {
try {
const newValid = valid.includes(key)
? valid.filter((i) => i !== key)
: valid.concat(key);
await changeProfileValid(newValid);
mutate();
} catch (err: any) {
Notice.error(err.message || err.toString());
}
});
return ( return (
<Box sx={{ mt: 4 }}> <Box sx={{ mt: 4 }}>
<Stack <Stack
@@ -92,9 +128,74 @@ const EnhancedMode = (props: Props) => {
<RestartAltRounded /> <RestartAltRounded />
</IconButton> </IconButton>
{/* <IconButton size="small" color="inherit"> <IconButton
size="small"
color="inherit"
id="profile-use-button"
title="enable clash fields"
aria-controls={!!anchorEl ? "profile-use-menu" : undefined}
aria-haspopup="true"
aria-expanded={!!anchorEl ? "true" : undefined}
onClick={(e) => setAnchorEl(e.currentTarget)}
>
<MenuRounded /> <MenuRounded />
</IconButton> */} </IconButton>
<Menu
id="profile-use-menu"
open={!!anchorEl}
anchorEl={anchorEl}
onClose={() => setAnchorEl(null)}
transitionDuration={225}
TransitionProps={
OS === "macos" ? { style: { transitionDuration: "225ms" } } : {}
}
MenuListProps={{
dense: true,
"aria-labelledby": "profile-use-button",
}}
onContextMenu={(e) => {
setAnchorEl(null);
e.preventDefault();
}}
>
<MenuItem>
<ListItemIcon color="inherit">
<AddchartRounded />
</ListItemIcon>
Use Clash Fields
</MenuItem>
<Divider />
{[
"tun",
"dns",
"hosts",
"script",
"profile",
"payload",
"interface-name",
"routing-mark",
].map((key) => {
const has = valid.includes(key);
return (
<MenuItem
key={key}
sx={{ width: 180 }}
onClick={() => onToggleValid(key)}
>
{has && (
<ListItemIcon color="inherit">
<CheckRounded />
</ListItemIcon>
)}
<ListItemText inset={!has}>{key}</ListItemText>
</MenuItem>
);
})}
</Menu>
</Stack> </Stack>
<Grid container spacing={2}> <Grid container spacing={2}>

View File

@@ -2,20 +2,13 @@ import useSWR, { useSWRConfig } from "swr";
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { Box, IconButton, TextField } from "@mui/material";
import {
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api"; import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds"; import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay"; import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useFilterProxy from "./use-filter-proxy"; import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item"; import ProxyItem from "./proxy-item";
interface Props { interface Props {
@@ -30,12 +23,14 @@ const ProxyGlobal = (props: Props) => {
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [now, setNow] = useState(curProxy || "DIRECT"); const [now, setNow] = useState(curProxy || "DIRECT");
const [showType, setShowType] = useState(true); const [showType, setShowType] = useState(true);
const [showFilter, setShowFilter] = useState(false); const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState(""); const [filterText, setFilterText] = useState("");
const virtuosoRef = useRef<any>(); const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, groupName, filterText); const filterProxies = useFilterProxy(proxies, groupName, filterText);
const sortedProxies = useSortProxy(filterProxies, groupName, sortType);
const { data: profiles } = useSWR("getProfiles", getProfiles); const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -61,7 +56,7 @@ const ProxyGlobal = (props: Props) => {
}); });
const onLocation = (smooth = true) => { const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now); const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) { if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({ virtuosoRef.current?.scrollToIndex?.({
@@ -73,22 +68,15 @@ const ProxyGlobal = (props: Props) => {
}; };
const onCheckAll = useLockFn(async () => { const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name); const names = sortedProxies.map((p) => p.name);
await delayManager.checkListDelay( await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
{ names, groupName, skipNum: 8, maxTimeout: 600 }, mutate("getProxies")
() => mutate("getProxies")
); );
mutate("getProxies");
}); });
useEffect(() => onLocation(false), [groupName]); useEffect(() => onLocation(false), [groupName]);
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
useEffect(() => { useEffect(() => {
if (groupName === "DIRECT") setNow("DIRECT"); if (groupName === "DIRECT") setNow("DIRECT");
else if (groupName === "GLOBAL") { else if (groupName === "GLOBAL") {
@@ -112,66 +100,28 @@ const ProxyGlobal = (props: Props) => {
return ( return (
<> <>
<Box <ProxyHead
sx={{ sx={{ px: 3, my: 0.5, button: { mr: 0.5 } }}
px: 3, showType={showType}
my: 0.5, sortType={sortType}
display: "flex", groupName={groupName}
alignItems: "center", filterText={filterText}
button: { mr: 0.5 }, onLocation={onLocation}
}} onCheckDelay={onCheckAll}
> onShowType={setShowType}
<IconButton onSortType={setSortType}
size="small" onFilterText={setFilterText}
title="location" />
onClick={() => onLocation(true)}
>
<MyLocationRounded />
</IconButton>
<IconButton size="small" title="delay check" onClick={onCheckAll}>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
title="proxy detail"
onClick={() => setShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
title="filter"
onClick={() => setShowFilter(!showFilter)}
>
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
</IconButton>
{showFilter && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => setFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
<Virtuoso <Virtuoso
ref={virtuosoRef} ref={virtuosoRef}
style={{ height: "calc(100% - 40px)" }} style={{ height: "calc(100% - 40px)" }}
totalCount={filterProxies.length} totalCount={sortedProxies.length}
itemContent={(index) => ( itemContent={(index) => (
<ProxyItem <ProxyItem
groupName={groupName} groupName={groupName}
proxy={filterProxies[index]} proxy={sortedProxies[index]}
selected={filterProxies[index].name === now} selected={sortedProxies[index].name === now}
showType={showType} showType={showType}
onClick={onChangeProxy} onClick={onChangeProxy}
sx={{ py: 0, px: 2 }} sx={{ py: 0, px: 2 }}

View File

@@ -6,28 +6,22 @@ import {
Box, Box,
Collapse, Collapse,
Divider, Divider,
IconButton,
List, List,
ListItem, ListItem,
ListItemText, ListItemText,
TextField,
} from "@mui/material"; } from "@mui/material";
import { import {
SendRounded, SendRounded,
ExpandLessRounded, ExpandLessRounded,
ExpandMoreRounded, ExpandMoreRounded,
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
} from "@mui/icons-material"; } from "@mui/icons-material";
import { ApiType } from "../../services/types"; import { ApiType } from "../../services/types";
import { updateProxy } from "../../services/api"; import { updateProxy } from "../../services/api";
import { getProfiles, patchProfile } from "../../services/cmds"; import { getProfiles, patchProfile } from "../../services/cmds";
import delayManager from "../../services/delay"; import useSortProxy, { ProxySortType } from "./use-sort-proxy";
import useFilterProxy from "./use-filter-proxy"; import useFilterProxy from "./use-filter-proxy";
import delayManager from "../../services/delay";
import ProxyHead from "./proxy-head";
import ProxyItem from "./proxy-item"; import ProxyItem from "./proxy-item";
interface Props { interface Props {
@@ -38,13 +32,14 @@ const ProxyGroup = ({ group }: Props) => {
const { mutate } = useSWRConfig(); const { mutate } = useSWRConfig();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [now, setNow] = useState(group.now); const [now, setNow] = useState(group.now);
const [showType, setShowType] = useState(false); const [showType, setShowType] = useState(false);
const [showFilter, setShowFilter] = useState(false); const [sortType, setSortType] = useState<ProxySortType>(0);
const [filterText, setFilterText] = useState(""); const [filterText, setFilterText] = useState("");
const proxies = group.all ?? [];
const virtuosoRef = useRef<any>(); const virtuosoRef = useRef<any>();
const filterProxies = useFilterProxy(proxies, group.name, filterText); const filterProxies = useFilterProxy(group.all, group.name, filterText);
const sortedProxies = useSortProxy(filterProxies, group.name, sortType);
const { data: profiles } = useSWR("getProfiles", getProfiles); const { data: profiles } = useSWR("getProfiles", getProfiles);
@@ -82,7 +77,7 @@ const ProxyGroup = ({ group }: Props) => {
}); });
const onLocation = (smooth = true) => { const onLocation = (smooth = true) => {
const index = filterProxies.findIndex((p) => p.name === now); const index = sortedProxies.findIndex((p) => p.name === now);
if (index >= 0) { if (index >= 0) {
virtuosoRef.current?.scrollToIndex?.({ virtuosoRef.current?.scrollToIndex?.({
@@ -94,21 +89,14 @@ const ProxyGroup = ({ group }: Props) => {
}; };
const onCheckAll = useLockFn(async () => { const onCheckAll = useLockFn(async () => {
const names = filterProxies.map((p) => p.name); const names = sortedProxies.map((p) => p.name);
const groupName = group.name; const groupName = group.name;
await delayManager.checkListDelay( await delayManager.checkListDelay({ names, groupName, skipNum: 8 }, () =>
{ names, groupName, skipNum: 8, maxTimeout: 600 }, mutate("getProxies")
() => mutate("getProxies")
); );
mutate("getProxies");
}); });
useEffect(() => {
if (!showFilter) setFilterText("");
}, [showFilter]);
// auto scroll to current index // auto scroll to current index
useEffect(() => { useEffect(() => {
if (open) { if (open) {
@@ -136,58 +124,20 @@ const ProxyGroup = ({ group }: Props) => {
</ListItem> </ListItem>
<Collapse in={open} timeout="auto" unmountOnExit> <Collapse in={open} timeout="auto" unmountOnExit>
<Box <ProxyHead
sx={{ sx={{ pl: 4, pr: 3, my: 0.5, button: { mr: 0.5 } }}
pl: 4, showType={showType}
pr: 3, sortType={sortType}
my: 0.5, groupName={group.name}
display: "flex", filterText={filterText}
alignItems: "center", onLocation={onLocation}
button: { mr: 0.5 }, onCheckDelay={onCheckAll}
}} onShowType={setShowType}
> onSortType={setSortType}
<IconButton onFilterText={setFilterText}
size="small" />
title="location"
onClick={() => onLocation(true)}
>
<MyLocationRounded />
</IconButton>
<IconButton size="small" title="delay check" onClick={onCheckAll}> {!sortedProxies.length && (
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
title="proxy detail"
onClick={() => setShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
title="filter"
onClick={() => setShowFilter(!showFilter)}
>
{showFilter ? <FilterAltRounded /> : <FilterAltOffRounded />}
</IconButton>
{showFilter && (
<TextField
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => setFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
{!filterProxies.length && (
<Box <Box
sx={{ sx={{
py: 3, py: 3,
@@ -200,16 +150,16 @@ const ProxyGroup = ({ group }: Props) => {
</Box> </Box>
)} )}
{filterProxies.length >= 10 ? ( {sortedProxies.length >= 10 ? (
<Virtuoso <Virtuoso
ref={virtuosoRef} ref={virtuosoRef}
style={{ height: "320px", marginBottom: "4px" }} style={{ height: "320px", marginBottom: "4px" }}
totalCount={filterProxies.length} totalCount={sortedProxies.length}
itemContent={(index) => ( itemContent={(index) => (
<ProxyItem <ProxyItem
groupName={group.name} groupName={group.name}
proxy={filterProxies[index]} proxy={sortedProxies[index]}
selected={filterProxies[index].name === now} selected={sortedProxies[index].name === now}
showType={showType} showType={showType}
sx={{ py: 0, pl: 4 }} sx={{ py: 0, pl: 4 }}
onClick={onChangeProxy} onClick={onChangeProxy}
@@ -222,7 +172,7 @@ const ProxyGroup = ({ group }: Props) => {
disablePadding disablePadding
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }} sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
> >
{filterProxies.map((proxy) => ( {sortedProxies.map((proxy) => (
<ProxyItem <ProxyItem
key={proxy.name} key={proxy.name}
groupName={group.name} groupName={group.name}

View File

@@ -0,0 +1,147 @@
import { useState } from "react";
import { Box, IconButton, TextField, SxProps } from "@mui/material";
import {
AccessTimeRounded,
MyLocationRounded,
NetworkCheckRounded,
FilterAltRounded,
FilterAltOffRounded,
VisibilityRounded,
VisibilityOffRounded,
WifiTetheringRounded,
WifiTetheringOffRounded,
SortByAlphaRounded,
SortRounded,
} from "@mui/icons-material";
import delayManager from "../../services/delay";
import type { ProxySortType } from "./use-sort-proxy";
interface Props {
sx?: SxProps;
groupName: string;
showType: boolean;
sortType: ProxySortType;
filterText: string;
onLocation: () => void;
onCheckDelay: () => void;
onShowType: (val: boolean) => void;
onSortType: (val: ProxySortType) => void;
onFilterText: (val: string) => void;
}
const ProxyHead = (props: Props) => {
const { sx = {}, groupName, showType, sortType, filterText } = props;
const [textState, setTextState] = useState<"url" | "filter" | null>(null);
const [testUrl, setTestUrl] = useState(delayManager.getUrl(groupName) || "");
return (
<Box sx={{ display: "flex", alignItems: "center", ...sx }}>
<IconButton
size="small"
title="location"
color="inherit"
onClick={props.onLocation}
>
<MyLocationRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
title="delay check"
onClick={() => {
// Remind the user that it is custom test url
if (testUrl?.trim() && textState !== "filter") {
setTextState("url");
}
props.onCheckDelay();
}}
>
<NetworkCheckRounded />
</IconButton>
<IconButton
size="small"
color="inherit"
title={["sort by default", "sort by delay", "sort by name"][sortType]}
onClick={() => props.onSortType(((sortType + 1) % 3) as ProxySortType)}
>
{sortType === 0 && <SortRounded />}
{sortType === 1 && <AccessTimeRounded />}
{sortType === 2 && <SortByAlphaRounded />}
</IconButton>
<IconButton
size="small"
color="inherit"
title="edit test url"
onClick={() => setTextState((ts) => (ts === "url" ? null : "url"))}
>
{textState === "url" ? (
<WifiTetheringRounded />
) : (
<WifiTetheringOffRounded />
)}
</IconButton>
<IconButton
size="small"
color="inherit"
title="proxy detail"
onClick={() => props.onShowType(!showType)}
>
{showType ? <VisibilityRounded /> : <VisibilityOffRounded />}
</IconButton>
<IconButton
size="small"
color="inherit"
title="filter"
onClick={() =>
setTextState((ts) => (ts === "filter" ? null : "filter"))
}
>
{textState === "filter" ? (
<FilterAltRounded />
) : (
<FilterAltOffRounded />
)}
</IconButton>
{textState === "filter" && (
<TextField
autoFocus
hiddenLabel
value={filterText}
size="small"
variant="outlined"
placeholder="Filter conditions"
onChange={(e) => props.onFilterText(e.target.value)}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
{textState === "url" && (
<TextField
autoFocus
hiddenLabel
autoSave="off"
autoComplete="off"
value={testUrl}
size="small"
variant="outlined"
placeholder="Test url"
onChange={(e) => {
setTestUrl(e.target.value);
delayManager.setUrl(groupName, e.target.value);
}}
sx={{ ml: 0.5, flex: "1 1 auto", input: { py: 0.65, px: 1 } }}
/>
)}
</Box>
);
};
export default ProxyHead;

View File

@@ -1,4 +1,5 @@
import { useEffect, useRef, useState } from "react"; import { useEffect, useState } from "react";
import { useLockFn } from "ahooks";
import { CheckCircleOutlineRounded } from "@mui/icons-material"; import { CheckCircleOutlineRounded } from "@mui/icons-material";
import { import {
alpha, alpha,
@@ -24,8 +25,9 @@ interface Props {
} }
const Widget = styled(Box)(() => ({ const Widget = styled(Box)(() => ({
padding: "4px 6px", padding: "3px 6px",
fontSize: 14, fontSize: 14,
borderRadius: "4px",
})); }));
const TypeBox = styled(Box)(({ theme }) => ({ const TypeBox = styled(Box)(({ theme }) => ({
@@ -50,20 +52,12 @@ const ProxyItem = (props: Props) => {
} }
}, [proxy]); }, [proxy]);
const delayRef = useRef(false); const onDelay = useLockFn(async () => {
const onDelay = (e: any) => { return delayManager
e.preventDefault();
e.stopPropagation();
if (delayRef.current) return;
delayRef.current = true;
delayManager
.checkDelay(proxy.name, groupName) .checkDelay(proxy.name, groupName)
.then((result) => setDelay(result)) .then((result) => setDelay(result))
.catch(() => setDelay(1e6)) .catch(() => setDelay(1e6));
.finally(() => (delayRef.current = false)); });
};
return ( return (
<ListItem sx={sx}> <ListItem sx={sx}>
@@ -111,13 +105,27 @@ const ProxyItem = (props: Props) => {
<ListItemIcon <ListItemIcon
sx={{ justifyContent: "flex-end", color: "primary.main" }} sx={{ justifyContent: "flex-end", color: "primary.main" }}
> >
<Widget className="the-check" onClick={onDelay}> <Widget
className="the-check"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelay();
}}
sx={(theme) => ({
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
})}
>
Check Check
</Widget> </Widget>
<Widget <Widget
className="the-delay" className="the-delay"
onClick={onDelay} onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onDelay();
}}
color={ color={
delay > 500 delay > 500
? "error.main" ? "error.main"
@@ -125,6 +133,9 @@ const ProxyItem = (props: Props) => {
? "success.main" ? "success.main"
: "text.secondary" : "text.secondary"
} }
sx={(theme) => ({
":hover": { bgcolor: alpha(theme.palette.primary.main, 0.15) },
})}
> >
{delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`} {delay > 1e5 ? "Error" : delay > 3000 ? "Timeout" : `${delay}ms`}
</Widget> </Widget>

View File

@@ -15,6 +15,7 @@ export default function useFilterProxy(
filterText: string filterText: string
) { ) {
return useMemo(() => { return useMemo(() => {
if (!proxies) return [];
if (!filterText) return proxies; if (!filterText) return proxies;
const res1 = regex1.exec(filterText); const res1 = regex1.exec(filterText);

View File

@@ -0,0 +1,38 @@
import { useMemo } from "react";
import { ApiType } from "../../services/types";
import delayManager from "../../services/delay";
// default | delay | alpha
export type ProxySortType = 0 | 1 | 2;
/**
* sort the proxy
*/
export default function useSortProxy(
proxies: ApiType.ProxyItem[],
groupName: string,
sortType: ProxySortType
) {
return useMemo(() => {
if (!proxies) return [];
if (sortType === 0) return proxies;
const list = proxies.slice();
if (sortType === 1) {
list.sort((a, b) => {
const ad = delayManager.getDelay(a.name, groupName);
const bd = delayManager.getDelay(b.name, groupName);
if (ad === -1) return 1;
if (bd === -1) return -1;
return ad - bd;
});
} else {
list.sort((a, b) => a.name.localeCompare(b.name));
}
return list;
}, [proxies, groupName, sortType]);
}

View File

@@ -1,6 +1,6 @@
import { useEffect, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { Button, Paper } from "@mui/material"; import { Box, Button, Paper, TextField } from "@mui/material";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { ApiType } from "../services/types"; import { ApiType } from "../services/types";
@@ -8,12 +8,20 @@ import { closeAllConnections, getInfomation } from "../services/api";
import BasePage from "../components/base/base-page"; import BasePage from "../components/base/base-page";
import ConnectionItem from "../components/connection/connection-item"; import ConnectionItem from "../components/connection/connection-item";
const ConnectionsPage = () => { const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
const initConn = { uploadTotal: 0, downloadTotal: 0, connections: [] };
const ConnectionsPage = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const [filterText, setFilterText] = useState("");
const [connData, setConnData] = useState<ApiType.Connections>(initConn); const [connData, setConnData] = useState<ApiType.Connections>(initConn);
const filterConn = useMemo(() => {
return connData.connections.filter((conn) =>
(conn.metadata.host || conn.metadata.destinationIP)?.includes(filterText)
);
}, [connData, filterText]);
useEffect(() => { useEffect(() => {
let ws: WebSocket | null = null; let ws: WebSocket | null = null;
@@ -23,32 +31,35 @@ const ConnectionsPage = () => {
ws.addEventListener("message", (event) => { ws.addEventListener("message", (event) => {
const data = JSON.parse(event.data) as ApiType.Connections; const data = JSON.parse(event.data) as ApiType.Connections;
// 与前一次connections的展示顺序尽量保持一致
setConnData((old) => { setConnData((old) => {
const oldConn = old.connections; const oldConn = old.connections;
const oldList = oldConn.map((each) => each.id);
const maxLen = data.connections.length; const maxLen = data.connections.length;
const connections: typeof oldConn = []; const connections: typeof oldConn = [];
// 与前一次连接的顺序尽量保持一致 const rest = data.connections.filter((each) => {
data.connections const index = oldConn.findIndex((o) => o.id === each.id);
.filter((each) => {
const index = oldList.indexOf(each.id);
if (index >= 0 && index < maxLen) { if (index >= 0 && index < maxLen) {
connections[index] = each; const old = oldConn[index];
return false; each.curUpload = each.upload - old.upload;
} each.curDownload = each.download - old.download;
return true;
}) connections[index] = each;
.forEach((each) => { return false;
for (let i = 0; i < maxLen; ++i) { }
if (!connections[i]) { return true;
connections[i] = each; });
return;
} for (let i = 0; i < maxLen; ++i) {
} if (!connections[i] && rest.length > 0) {
}); connections[i] = rest.shift()!;
connections[i].curUpload = 0;
connections[i].curDownload = 0;
}
}
return { ...data, connections }; return { ...data, connections };
}); });
@@ -76,11 +87,48 @@ const ConnectionsPage = () => {
} }
> >
<Paper sx={{ boxShadow: 2, height: "100%" }}> <Paper sx={{ boxShadow: 2, height: "100%" }}>
<Virtuoso <Box
initialTopMostItemIndex={999} sx={{
data={connData.connections} pt: 1,
itemContent={(index, item) => <ConnectionItem value={item} />} mb: 0.5,
/> mx: "12px",
height: "36px",
display: "flex",
alignItems: "center",
}}
>
{/* <Select
size="small"
autoComplete="off"
value={logState}
onChange={(e) => setLogState(e.target.value)}
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
>
<MenuItem value="all">ALL</MenuItem>
<MenuItem value="info">INFO</MenuItem>
<MenuItem value="warn">WARN</MenuItem>
</Select> */}
<TextField
hiddenLabel
fullWidth
size="small"
autoComplete="off"
variant="outlined"
placeholder="Filter conditions"
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
sx={{ input: { py: 0.65, px: 1.25 } }}
/>
</Box>
<Box height="calc(100% - 50px)">
<Virtuoso
initialTopMostItemIndex={999}
data={filterConn}
itemContent={(index, item) => <ConnectionItem value={item} />}
/>
</Box>
</Paper> </Paper>
</BasePage> </BasePage>
); );

View File

@@ -1,5 +1,6 @@
import { useMemo, useState } from "react";
import { useRecoilState } from "recoil"; import { useRecoilState } from "recoil";
import { Button, Paper } from "@mui/material"; import { Box, Button, MenuItem, Paper, Select, TextField } from "@mui/material";
import { Virtuoso } from "react-virtuoso"; import { Virtuoso } from "react-virtuoso";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { atomLogData } from "../services/states"; import { atomLogData } from "../services/states";
@@ -10,6 +11,18 @@ const LogPage = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const [logData, setLogData] = useRecoilState(atomLogData); const [logData, setLogData] = useRecoilState(atomLogData);
const [logState, setLogState] = useState("all");
const [filterText, setFilterText] = useState("");
const filterLogs = useMemo(() => {
return logData.filter((data) => {
return (
data.payload.includes(filterText) &&
(logState === "all" ? true : data.type.includes(logState))
);
});
}, [logData, logState, filterText]);
return ( return (
<BasePage <BasePage
title={t("Logs")} title={t("Logs")}
@@ -25,13 +38,50 @@ const LogPage = () => {
</Button> </Button>
} }
> >
<Paper sx={{ boxShadow: 2, height: "100%" }}> <Paper sx={{ boxSizing: "border-box", boxShadow: 2, height: "100%" }}>
<Virtuoso <Box
initialTopMostItemIndex={999} sx={{
data={logData} pt: 1,
itemContent={(index, item) => <LogItem value={item} />} mb: 0.5,
followOutput={"smooth"} mx: "12px",
/> height: "36px",
display: "flex",
alignItems: "center",
}}
>
<Select
size="small"
autoComplete="off"
value={logState}
onChange={(e) => setLogState(e.target.value)}
sx={{ width: 120, mr: 1, '[role="button"]': { py: 0.65 } }}
>
<MenuItem value="all">ALL</MenuItem>
<MenuItem value="info">INFO</MenuItem>
<MenuItem value="warn">WARN</MenuItem>
</Select>
<TextField
hiddenLabel
fullWidth
size="small"
autoComplete="off"
variant="outlined"
placeholder="Filter conditions"
value={filterText}
onChange={(e) => setFilterText(e.target.value)}
sx={{ input: { py: 0.65, px: 1.25 } }}
/>
</Box>
<Box height="calc(100% - 50px)">
<Virtuoso
initialTopMostItemIndex={999}
data={filterLogs}
itemContent={(index, item) => <LogItem value={item} />}
followOutput={"smooth"}
/>
</Box>
</Paper> </Paper>
</BasePage> </BasePage>
); );

View File

@@ -165,7 +165,7 @@ const ProfilePage = () => {
))} ))}
</Grid> </Grid>
{enhanceItems.length && ( {enhanceItems.length > 0 && (
<EnhancedMode items={enhanceItems} chain={profiles.chain || []} /> <EnhancedMode items={enhanceItems} chain={profiles.chain || []} />
)} )}

View File

@@ -66,6 +66,10 @@ export async function changeProfileChain(chain?: string[]) {
return invoke<void>("change_profile_chain", { chain }); return invoke<void>("change_profile_chain", { chain });
} }
export async function changeProfileValid(valid?: string[]) {
return invoke<void>("change_profile_valid", { valid });
}
export async function getClashInfo() { export async function getClashInfo() {
return invoke<CmdType.ClashInfo | null>("get_clash_info"); return invoke<CmdType.ClashInfo | null>("get_clash_info");
} }

View File

@@ -4,6 +4,15 @@ const hashKey = (name: string, group: string) => `${group ?? ""}::${name}`;
class DelayManager { class DelayManager {
private cache = new Map<string, [number, number]>(); private cache = new Map<string, [number, number]>();
private urlMap = new Map<string, string>();
setUrl(group: string, url: string) {
this.urlMap.set(group, url);
}
getUrl(group: string) {
return this.urlMap.get(group);
}
setDelay(name: string, group: string, delay: number) { setDelay(name: string, group: string, delay: number) {
this.cache.set(hashKey(name, group), [Date.now(), delay]); this.cache.set(hashKey(name, group), [Date.now(), delay]);
@@ -23,7 +32,8 @@ class DelayManager {
let delay = -1; let delay = -1;
try { try {
const result = await getProxyDelay(name); const url = this.getUrl(group);
const result = await getProxyDelay(name, url);
delay = result.delay; delay = result.delay;
} catch { } catch {
delay = 1e6; // error delay = 1e6; // error
@@ -38,32 +48,36 @@ class DelayManager {
names: readonly string[]; names: readonly string[];
groupName: string; groupName: string;
skipNum: number; skipNum: number;
maxTimeout: number;
}, },
callback: Function callback: Function
) { ) {
let names = [...options.names]; const { groupName, skipNum } = options;
const { groupName, skipNum, maxTimeout } = options;
while (names.length) { const names = [...options.names];
const list = names.slice(0, skipNum); const total = names.length;
names = names.slice(skipNum);
let called = false; let count = 0;
setTimeout(() => { let current = 0;
if (!called) {
called = true;
callback();
}
}, maxTimeout);
await Promise.all(list.map((n) => this.checkDelay(n, groupName))); return new Promise((resolve) => {
const help = async (): Promise<void> => {
if (current >= skipNum) return;
if (!called) { const task = names.shift();
called = true; if (!task) return;
callback();
} current += 1;
} await this.checkDelay(task, groupName);
current -= 1;
if (count++ % skipNum === 0 || count === total) callback();
if (count === total) resolve(null);
return help();
};
for (let i = 0; i < skipNum; ++i) help();
});
} }
} }

View File

@@ -145,11 +145,12 @@ class Enhance {
// enhanced mode runner // enhanced mode runner
private async runner(payload: CmdType.EnhancedPayload) { private async runner(payload: CmdType.EnhancedPayload) {
const chain = payload.chain || []; const chain = payload.chain || [];
const valid = payload.valid || [];
if (!Array.isArray(chain)) throw new Error("unhandle error"); if (!Array.isArray(chain)) throw new Error("unhandle error");
let pdata = payload.current || {}; let pdata = payload.current || {};
let useList = [] as string[]; let useList = valid;
for (const each of chain) { for (const each of chain) {
const { uid, type = "" } = each.item; const { uid, type = "" } = each.item;

View File

@@ -65,6 +65,8 @@ export namespace ApiType {
chains: string[]; chains: string[];
rule: string; rule: string;
rulePayload: string; rulePayload: string;
curUpload?: number; // calculate
curDownload?: number; // calculate
} }
export interface Connections { export interface Connections {
@@ -116,6 +118,7 @@ export namespace CmdType {
export interface ProfilesConfig { export interface ProfilesConfig {
current?: string; current?: string;
chain?: string[]; chain?: string[];
valid?: string[];
items?: ProfileItem[]; items?: ProfileItem[];
} }
@@ -191,6 +194,7 @@ export namespace CmdType {
export interface EnhancedPayload { export interface EnhancedPayload {
chain: ChainItem[]; chain: ChainItem[];
valid: string[];
current: ProfileData; current: ProfileData;
callback: string; callback: string;
} }

View File

@@ -386,37 +386,37 @@
"@jridgewell/resolve-uri" "^3.0.3" "@jridgewell/resolve-uri" "^3.0.3"
"@jridgewell/sourcemap-codec" "^1.4.10" "@jridgewell/sourcemap-codec" "^1.4.10"
"@mui/base@5.0.0-alpha.74": "@mui/base@5.0.0-alpha.76":
version "5.0.0-alpha.74" version "5.0.0-alpha.76"
resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-alpha.74.tgz#15509242e7911446d5957375b1b18cbb72b3a750" resolved "https://registry.yarnpkg.com/@mui/base/-/base-5.0.0-alpha.76.tgz#683d68eff6d52e19e9962f608a5d3b8b6fb6ef55"
integrity sha512-pw3T1xNXpW8pLo9+BvtyazZb0CSjNJsjbzznlbV/aNkBfjNPXQVI3X1NDm3WSI8y6M96WDIVO7XrHAohOwALSQ== integrity sha512-Pd0l4DvjXiGRyipn/CTDlYB2XrJwhpLktVXvbvcmzL2SMDaNprSarZqBkPHIubkulmRDZEEcnFDrpKgeSJDg4A==
dependencies: dependencies:
"@babel/runtime" "^7.17.2" "@babel/runtime" "^7.17.2"
"@emotion/is-prop-valid" "^1.1.2" "@emotion/is-prop-valid" "^1.1.2"
"@mui/types" "^7.1.3" "@mui/types" "^7.1.3"
"@mui/utils" "^5.5.3" "@mui/utils" "^5.6.1"
"@popperjs/core" "^2.11.4" "@popperjs/core" "^2.11.5"
clsx "^1.1.1" clsx "^1.1.1"
prop-types "^15.7.2" prop-types "^15.7.2"
react-is "^17.0.2" react-is "^17.0.2"
"@mui/icons-material@^5.5.1": "@mui/icons-material@^5.6.1":
version "5.5.1" version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/icons-material/-/icons-material-5.5.1.tgz#848a57972617411370775980cbc6990588d4aafb" resolved "https://registry.yarnpkg.com/@mui/icons-material/-/icons-material-5.6.1.tgz#421e2b73992349abb07f8f03074d7e56e20bf7ba"
integrity sha512-40f68p5+Yhq3dCn3QYHqQt5RETPyR3AkDw+fma8PtcjqvZ+d+jF84kFmT6NqwA3he7TlwluEtkyAmPzUE4uPdA== integrity sha512-I1x8u+FRLOmoJpRJASMx9UG+jZrSkNLyRQmBXivQQwXu3m3iasMoaKYhhI0J18t8+FWktbkNTp63oEUHE9Gw0Q==
dependencies: dependencies:
"@babel/runtime" "^7.17.2" "@babel/runtime" "^7.17.2"
"@mui/material@^5.5.3": "@mui/material@^5.6.1":
version "5.5.3" version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.5.3.tgz#411e53a69da3f9d6664e99f1bdcdaf2760540fdc" resolved "https://registry.yarnpkg.com/@mui/material/-/material-5.6.1.tgz#b74cfbe4666586e054a28cf3df448369892085e1"
integrity sha512-eADa3kUYbbr1jNjcufn0a7HeU8cSo0agbrkj720hodxVFNIfzq7a2e58Z+PaZqll55kMGBvlYJ7rTcXU399x5A== integrity sha512-xg6pPq+1jxWupwmPpnfmsHNjrsOe2xynUQWrRfcH8WHrrr1sQulq0VF4gORq/l8DD8a/jb4s8SsC20e/e6mHKQ==
dependencies: dependencies:
"@babel/runtime" "^7.17.2" "@babel/runtime" "^7.17.2"
"@mui/base" "5.0.0-alpha.74" "@mui/base" "5.0.0-alpha.76"
"@mui/system" "^5.5.3" "@mui/system" "^5.6.1"
"@mui/types" "^7.1.3" "@mui/types" "^7.1.3"
"@mui/utils" "^5.5.3" "@mui/utils" "^5.6.1"
"@types/react-transition-group" "^4.4.4" "@types/react-transition-group" "^4.4.4"
clsx "^1.1.1" clsx "^1.1.1"
csstype "^3.0.11" csstype "^3.0.11"
@@ -425,34 +425,34 @@
react-is "^17.0.2" react-is "^17.0.2"
react-transition-group "^4.4.2" react-transition-group "^4.4.2"
"@mui/private-theming@^5.5.3": "@mui/private-theming@^5.6.1":
version "5.5.3" version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.5.3.tgz#c232a39dd3c268fdef7e92ccc40d51bda9eec3ab" resolved "https://registry.yarnpkg.com/@mui/private-theming/-/private-theming-5.6.1.tgz#198ccec972375db999c293109b5f26456b9c3a22"
integrity sha512-Wf7NurY7lk8SBWelSBY2U02zxLt1773JpIcXTHuEC9/GZdQA4CXCJGl2cVQzheKhee5rZ+8JwGulrRiVl1m+4A== integrity sha512-8lgh+tUt/3ftStfvml3dwAzhW3fe/cUFjLcBViOTnWk7UixWR79me4qehsO4NVj0THpu3d2qclrLzdD8qBAWAQ==
dependencies: dependencies:
"@babel/runtime" "^7.17.2" "@babel/runtime" "^7.17.2"
"@mui/utils" "^5.5.3" "@mui/utils" "^5.6.1"
prop-types "^15.7.2" prop-types "^15.7.2"
"@mui/styled-engine@^5.5.2": "@mui/styled-engine@^5.6.1":
version "5.5.2" version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.5.2.tgz#1f92dd27d76f0b7df7aa52c7c7a710e59b2275a6" resolved "https://registry.yarnpkg.com/@mui/styled-engine/-/styled-engine-5.6.1.tgz#e2c859a4dbdd65af89e77703a0725285aef471fd"
integrity sha512-jkz5AHHbA43akBo5L3y1X1/X0f+RvXvCp3eXKt+iOf3qnKSAausbtlVz7gBbC4xIWDnP1Jb/6T+t/0/7gObRYA== integrity sha512-jEhH6TBY8jc9S8yVncXmoTYTbATjEu44RMFXj6sIYfKr5NArVwTwRo3JexLL0t3BOAiYM4xsFLgfKEIvB9SAeQ==
dependencies: dependencies:
"@babel/runtime" "^7.17.2" "@babel/runtime" "^7.17.2"
"@emotion/cache" "^11.7.1" "@emotion/cache" "^11.7.1"
prop-types "^15.7.2" prop-types "^15.7.2"
"@mui/system@^5.5.3": "@mui/system@^5.6.1":
version "5.5.3" version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.5.3.tgz#c78d4c16009430389ffd3495d694945422d72ca5" resolved "https://registry.yarnpkg.com/@mui/system/-/system-5.6.1.tgz#dd47a15b82012f44464a0f25765e3dec6182ba98"
integrity sha512-J9JcySJuEqfEoP334K/2gEWm2vOx73Uqjii3qlFVhWRBOAJ0Pjyk0sN5W/eVRbwhUm95DNgh2V5s8dRK3vzyVw== integrity sha512-Y5pDvEOK6VOY+0vgNeyDuEEO5QCinhXbZQDyLOlaGLKuAoRGLXO9pcSsjZoGkewYZitXD44EDfgBQ+BqsAfgUA==
dependencies: dependencies:
"@babel/runtime" "^7.17.2" "@babel/runtime" "^7.17.2"
"@mui/private-theming" "^5.5.3" "@mui/private-theming" "^5.6.1"
"@mui/styled-engine" "^5.5.2" "@mui/styled-engine" "^5.6.1"
"@mui/types" "^7.1.3" "@mui/types" "^7.1.3"
"@mui/utils" "^5.5.3" "@mui/utils" "^5.6.1"
clsx "^1.1.1" clsx "^1.1.1"
csstype "^3.0.11" csstype "^3.0.11"
prop-types "^15.7.2" prop-types "^15.7.2"
@@ -462,10 +462,10 @@
resolved "https://registry.yarnpkg.com/@mui/types/-/types-7.1.3.tgz#d7636f3046110bcccc63e6acfd100e2ad9ca712a" resolved "https://registry.yarnpkg.com/@mui/types/-/types-7.1.3.tgz#d7636f3046110bcccc63e6acfd100e2ad9ca712a"
integrity sha512-DDF0UhMBo4Uezlk+6QxrlDbchF79XG6Zs0zIewlR4c0Dt6GKVFfUtzPtHCH1tTbcSlq/L2bGEdiaoHBJ9Y1gSA== integrity sha512-DDF0UhMBo4Uezlk+6QxrlDbchF79XG6Zs0zIewlR4c0Dt6GKVFfUtzPtHCH1tTbcSlq/L2bGEdiaoHBJ9Y1gSA==
"@mui/utils@^5.5.3": "@mui/utils@^5.6.1":
version "5.5.3" version "5.6.1"
resolved "https://registry.yarnpkg.com/@mui/utils/-/utils-5.5.3.tgz#f6e1f10c0e8f4d0bf750588c2c3a96ad819c5b65" resolved "https://registry.yarnpkg.com/@mui/utils/-/utils-5.6.1.tgz#4ab79a21bd481555d9a588f4b18061b3c28ea5db"
integrity sha512-t627eVRpl3SlxVya0cIVNs8jPl4KCEiGaTSWY9iKKTcMNaeDbuRML+zv/CFHDPr1zFv+FjJSP02ySB+tZ8xIag== integrity sha512-CPrzrkiBusCZBLWu0Sg5MJvR3fKJyK3gKecLVX012LULyqg2U64Oz04BKhfkbtBrPBbSQxM+DWW9B1c9hmV9nQ==
dependencies: dependencies:
"@babel/runtime" "^7.17.2" "@babel/runtime" "^7.17.2"
"@types/prop-types" "^15.7.4" "@types/prop-types" "^15.7.4"
@@ -559,10 +559,10 @@
dependencies: dependencies:
"@octokit/openapi-types" "^11.2.0" "@octokit/openapi-types" "^11.2.0"
"@popperjs/core@^2.11.4": "@popperjs/core@^2.11.5":
version "2.11.4" version "2.11.5"
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.4.tgz#d8c7b8db9226d2d7664553a0741ad7d0397ee503" resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.5.tgz#db5a11bf66bdab39569719555b0f76e138d7bd64"
integrity sha512-q/ytXxO5NKvyT37pmisQAItCFqA7FD/vNb8dgaJy3/630Fsc+Mz9/9f2SziBoIZ30TJooXyTwZmhi1zjXmObYg== integrity sha512-9X2obfABZuDVLCgPK9aX0a/x4jaOEweTTWE2+9sr0Qqqevj2Uv5XorvusThmc9XGYpS9yI+fhh8RTafBtGposw==
"@rollup/pluginutils@^4.1.2": "@rollup/pluginutils@^4.1.2":
version "4.2.0" version "4.2.0"