74 Commits

Author SHA1 Message Date
GyDi
cceb4bb81f v0.0.13 2022-01-25 02:11:00 +08:00
GyDi
f0f45e007d feat: global proxies use virtual list 2022-01-25 02:08:10 +08:00
GyDi
6a8ffe1642 feat: enable change proxy mode 2022-01-25 01:51:44 +08:00
GyDi
3a73868c10 feat: update styles 2022-01-25 01:48:26 +08:00
GyDi
ab1b5897a6 feat: manage clash mode 2022-01-24 23:13:13 +08:00
GyDi
f94734a5c8 chore: update readme 2022-01-22 23:57:39 +08:00
GyDi
61b86c9584 v0.0.12 2022-01-21 03:09:21 +08:00
GyDi
1ac1d6e903 chore: update ci 2022-01-21 03:08:40 +08:00
GyDi
b6c58f74c0 fix: type error 2022-01-21 03:08:20 +08:00
GyDi
c88e99d87c v0.0.12 2022-01-21 02:59:33 +08:00
GyDi
8d7ab9d05e refactor: rename profiles & command state 2022-01-21 02:57:15 +08:00
GyDi
47155a4a29 feat: change system porxy when changed port 2022-01-21 02:50:13 +08:00
GyDi
d0b87fd7c3 feat: enable change mixed port 2022-01-21 02:32:23 +08:00
GyDi
d49fd37656 feat: manage clash config 2022-01-21 02:31:44 +08:00
GyDi
0bd29d71be chore: add ahooks 2022-01-21 02:29:45 +08:00
GyDi
4b5b62c8ae fix: restart clash should update something 2022-01-21 00:29:33 +08:00
GyDi
65fb2ca2d5 feat: enable update clash info 2022-01-20 23:41:08 +08:00
GyDi
0d5bfc0997 feat: rename edit as view 2022-01-19 23:58:34 +08:00
GyDi
4f02c373c2 chore: adjust ci 2022-01-19 23:55:05 +08:00
GyDi
209a5b1207 fix: script error... 2022-01-19 00:49:23 +08:00
GyDi
95349eacab fix: tag error 2022-01-19 00:46:43 +08:00
GyDi
82ba604b99 fix: script error 2022-01-19 00:42:37 +08:00
GyDi
46a8dec655 feat: test auto gen update.json ci 2022-01-19 00:37:59 +08:00
GyDi
b5af234524 v0.0.11 2022-01-17 02:53:07 +08:00
GyDi
b5c41750f7 fix: remove cargo test 2022-01-17 02:50:19 +08:00
GyDi
6083824eec v0.0.11 2022-01-17 02:44:08 +08:00
GyDi
40977785c3 feat: adjust setting typography 2022-01-17 02:42:52 +08:00
GyDi
5eddf4f1aa feat: enable force select profile 2022-01-17 02:28:23 +08:00
GyDi
99a8e25411 feat: support edit profile item 2022-01-17 02:16:17 +08:00
GyDi
08587d8f2f fix: reduce proxy item height 2022-01-17 02:15:54 +08:00
GyDi
3480d50f61 feat: adjust control ui 2022-01-17 02:15:06 +08:00
GyDi
43af55252d feat: update profile supports noproxy 2022-01-16 22:57:42 +08:00
GyDi
9c43b31fc0 refactor: something 2022-01-16 18:30:25 +08:00
GyDi
9ec7184aa1 fix: put profile request with no proxy 2022-01-16 18:20:01 +08:00
GyDi
4e2cb30db7 refactor: notice caller 2022-01-16 17:56:43 +08:00
GyDi
9ca83d3291 chore: change ci 2022-01-16 16:03:53 +08:00
GyDi
6b2172d873 fix: ci strategy 2022-01-16 14:30:49 +08:00
GyDi
1a5d9f7dad chore: enhance ci 2022-01-16 14:27:41 +08:00
GyDi
a8425862f0 feat: rename page 2022-01-16 03:25:50 +08:00
GyDi
a3a3db6abb refactor: setting page 2022-01-16 03:22:37 +08:00
GyDi
d6c3bc57c0 feat: refactor and adjust ui 2022-01-16 03:11:07 +08:00
GyDi
59c09f90f9 feat: rm some commands 2022-01-16 03:09:36 +08:00
GyDi
d982b83e14 feat: change type 2022-01-15 21:58:13 +08:00
GyDi
cc0e930d34 feat: supports auto launch on macos and windows 2022-01-15 21:55:05 +08:00
GyDi
3c3d77fbea chore: add auto-launch 2022-01-15 21:00:19 +08:00
GyDi
da7453fdbf v0.0.10 2022-01-13 02:53:29 +08:00
GyDi
5fcd25506e feat: adjust proxy page 2022-01-13 02:51:30 +08:00
GyDi
4979a472de feat: press esc hide the window 2022-01-13 02:11:50 +08:00
GyDi
4e8d4f4591 fix: version update error 2022-01-12 22:19:44 +08:00
GyDi
0f5d2b15e0 v0.0.9 2022-01-12 02:55:07 +08:00
GyDi
7fc9631434 feat: show system proxy info 2022-01-12 02:54:50 +08:00
GyDi
df5953dd7b feat: support blur window 2022-01-12 02:27:29 +08:00
GyDi
8f5b2b4a0e chore: add macos startup todo 2022-01-11 23:14:43 +08:00
GyDi
43c63ffa70 chore: cargo update 2022-01-11 23:13:02 +08:00
GyDi
6779bc7459 v0.0.8 2022-01-11 02:27:04 +08:00
GyDi
664be2d0ba chore: update ci 2022-01-11 02:26:50 +08:00
GyDi
6113898b69 feat: windows support startup 2022-01-11 02:24:43 +08:00
GyDi
79aad6b5c2 feat: window self startup 2022-01-11 02:21:51 +08:00
GyDi
6da7757d36 fix: text 2022-01-10 22:57:21 +08:00
GyDi
dbb3cb8cc8 chore: ignore update json 2022-01-10 22:08:57 +08:00
GyDi
579f36a1dd fix: update profile after restart clash 2022-01-10 22:08:18 +08:00
GyDi
72c2b306cf fix: get proxies multiple times 2022-01-10 21:25:41 +08:00
GyDi
c2673cd396 docs: fix img width 2022-01-10 02:52:12 +08:00
GyDi
8eb152816a docs: update 2022-01-10 02:49:42 +08:00
GyDi
a0bc8a21a5 v0.0.7 2022-01-10 02:17:35 +08:00
GyDi
08e4d72758 feat: use tauri updater 2022-01-10 02:15:38 +08:00
GyDi
66340a27fa feat: support update checker 2022-01-10 02:05:35 +08:00
GyDi
83fe9835b6 v0.0.6 2022-01-09 21:36:43 +08:00
GyDi
4c1a50a3ca chore: ci add macos 2022-01-09 21:34:14 +08:00
GyDi
fe44a7b3bc feat: support macos proxy config 2022-01-09 21:19:35 +08:00
GyDi
e86d192db7 feat: custom window decorations 2022-01-08 22:23:48 +08:00
GyDi
ea8f1c52f9 feat: profiles add menu and delete button 2022-01-08 16:52:18 +08:00
GyDi
a4c1573c45 fix: delete profile item command 2022-01-08 14:21:12 +08:00
GyDi
182bf49ad0 chore: temp 2022-01-08 02:54:37 +08:00
64 changed files with 2353 additions and 1491 deletions

98
.github/workflows/ci.yml vendored Normal file
View File

@@ -0,0 +1,98 @@
name: CI
on: [push]
env:
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: short
jobs:
release:
strategy:
matrix:
os: [windows-latest, macos-11]
runs-on: ${{ matrix.os }}
if: |
startsWith(github.repository, 'zzzgydi') &&
startsWith(github.ref, 'refs/tags/v')
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Rust Cache
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Yarn install and check
run: |
yarn install --network-timeout 1000000
yarn run check
- name: Tauri build
uses: tauri-apps/tauri-action@v0
# enable cache even though failed
continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tagName: v__VERSION__
releaseName: "Clash Verge v__VERSION__"
releaseBody: "Clash Verge now supports Windows and macos(intel)."
releaseDraft: false
prerelease: true
release-update:
needs: release
runs-on: macos-11
if: |
startsWith(github.repository, 'zzzgydi') &&
startsWith(github.ref, 'refs/tags/v')
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Yarn install
run: yarn
- name: Release update.json
run: yarn run release
continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

View File

@@ -1,59 +0,0 @@
name: Release Project
on:
push:
tags:
- v*
jobs:
build-tauri:
strategy:
fail-fast: false
matrix:
platform: [windows-latest]
runs-on: ${{ matrix.platform }}
steps:
- name: Checkout repository
uses: actions/checkout@v2
- name: Install Node
uses: actions/setup-node@v1
with:
node-version: 14
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: stable
profile: minimal
override: true
- name: Get yarn cache dir path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Yarn Cache
uses: actions/cache@v2
id: yarn-cache
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Rust Cache
uses: Swatinem/rust-cache@ce325b60658c1b38465c06cc965b79baf32c1e72
- name: Yarn install and check
run: yarn && yarn run check
- name: Tauri build
uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tagName: v__VERSION__
releaseName: "Clash Verge v__VERSION__"
releaseBody: "This is a release."
releaseDraft: true
prerelease: false

1
.gitignore vendored
View File

@@ -3,3 +3,4 @@ node_modules
dist
dist-ssr
*.local
update.json

View File

@@ -26,7 +26,7 @@ yarn install
Then download the clash binary... Or you can download it from [clash premium release](https://github.com/Dreamacro/clash/releases/tag/premium) and rename it according to [tauri config](https://tauri.studio/en/docs/api/config#tauri.bundle.externalBin).
```shell
yarn run predev
yarn run check
```
Then run
@@ -42,8 +42,12 @@ yarn dev
## Screenshots
<div align="center">
<img src="./docs/demo1.png" alt="demo1" width="42%" />
<img src="./docs/demo2.png" alt="demo2" width="42%" />
<img src="./docs/demo1.png" alt="demo1" width="32%" />
<img src="./docs/demo2.png" alt="demo2" width="32%" />
<img src="./docs/demo3.png" alt="demo3" width="32%" />
<img src="./docs/demo4.png" alt="demo4" width="32%" />
<img src="./docs/demo5.png" alt="demo5" width="32%" />
<img src="./docs/demo6.png" alt="demo6" width="32%" />
</div>
## Disclaimer
@@ -54,6 +58,15 @@ This is a learning project for Rust practice.
PR welcome!
## Acknowledgement
Clash Verge was based on or inspired by these projects and so on:
- [tauri-apps/tauri](https://github.com/tauri-apps/tauri): Build smaller, faster, and more secure desktop applications with a web frontend.
- [Dreamacro/clash](https://github.com/Dreamacro/clash): A rule-based tunnel in Go.
- [Fndroid/clash_for_windows_pkg](https://github.com/Fndroid/clash_for_windows_pkg): A Windows/macOS GUI based on Clash.
- [vitejs/vite](https://github.com/vitejs/vite): Next generation frontend tooling. It's fast!
## License
GPL-3.0 License
GPL-3.0 License. See [License here](./LICENSE) for details.

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 20 KiB

BIN
docs/demo3.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

BIN
docs/demo4.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

BIN
docs/demo5.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

BIN
docs/demo6.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -1,6 +1,6 @@
{
"name": "clash-verge",
"version": "0.0.5",
"version": "0.0.13",
"license": "GPL-3.0",
"scripts": {
"dev": "cargo tauri dev",
@@ -11,6 +11,7 @@
"web:serve": "vite preview",
"check": "node scripts/check.mjs",
"publish": "node scripts/publish.mjs",
"release": "node scripts/release.mjs",
"prepare": "husky install"
},
"dependencies": {
@@ -19,6 +20,7 @@
"@mui/icons-material": "^5.2.1",
"@mui/material": "^5.2.3",
"@tauri-apps/api": "^1.0.0-beta.8",
"ahooks": "^3.1.7",
"axios": "^0.24.0",
"dayjs": "^1.10.7",
"react": "^17.0.0",
@@ -29,8 +31,10 @@
"swr": "^1.1.2-beta.0"
},
"devDependencies": {
"@actions/github": "^5.0.0",
"@tauri-apps/cli": "^1.0.0-beta.10",
"@types/fs-extra": "^9.0.13",
"@types/js-cookie": "^3.0.1",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"@vitejs/plugin-react": "^1.1.1",

View File

@@ -11,10 +11,16 @@ async function resolvePublish() {
let [a, b, c] = packageJson.version.split(".").map(Number);
if (flag === "major") a += 1;
else if (flag === "minor") b += 1;
else if (flag === "patch") c += 1;
else throw new Error(`invalid flag "${flag}"`);
if (flag === "major") {
a += 1;
b = 0;
c = 0;
} else if (flag === "minor") {
b += 1;
c = 0;
} else if (flag === "patch") {
c += 1;
} else throw new Error(`invalid flag "${flag}"`);
const nextVersion = `${a}.${b}.${c}`;
packageJson.version = nextVersion;

68
scripts/release.mjs Normal file
View File

@@ -0,0 +1,68 @@
import { createRequire } from "module";
import { getOctokit, context } from "@actions/github";
const require = createRequire(import.meta.url);
/// generate update.json
/// upload to update tag's release asset
async function resolveRelease() {
if (process.env.GITHUB_TOKEN === undefined) {
throw new Error("GITHUB_TOKEN is required");
}
const packageJson = require("../package.json");
const { version } = packageJson;
const urlPrefix = "https://github.com/zzzgydi/clash-verge/releases/download";
const updateData = {
name: `v${version}`,
notes: `Version ${version} is available now!!!`,
pub_date: new Date().toISOString(),
platforms: {
win64: {
signature: "",
url: `${urlPrefix}/v${version}/clash-verge_${version}_x64.msi.zip`,
},
darwin: {
signature: "",
url: `${urlPrefix}/v${version}/clash-verge.app.tar.gz`,
},
},
};
console.log(`Generating Version "${version}" update.json`);
const github = getOctokit(process.env.GITHUB_TOKEN);
const { data: release } = await github.rest.repos.getReleaseByTag({
owner: context.repo.owner,
repo: context.repo.repo,
tag: "updater",
});
const { data: assets } = await github.rest.repos.listReleaseAssets({
owner: context.repo.owner,
repo: context.repo.repo,
release_id: release.id,
});
for (let asset of assets) {
if (asset.name === "update.json") {
await github.rest.repos.deleteReleaseAsset({
owner: context.repo.owner,
repo: context.repo.repo,
asset_id: asset.id,
});
break;
}
}
await github.rest.repos.uploadReleaseAsset({
owner: context.repo.owner,
repo: context.repo.repo,
release_id: release.id,
name: "update.json",
data: JSON.stringify(updateData, null, 2),
});
}
resolveRelease();

769
src-tauri/Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -4,7 +4,7 @@ version = "0.1.0"
description = "clash verge"
authors = ["zzzgydi"]
license = "GPL-3.0"
repository = ""
repository = "https://github.com/zzzgydi/clash-verge.git"
default-run = "app"
edition = "2021"
build = "build.rs"
@@ -19,13 +19,18 @@ serde_json = "1.0"
serde_yaml = "0.8"
serde = { version = "1.0", features = ["derive"] }
# tauri = { version = "1.0.0-beta.8", features = ["api-all", "system-tray"] }
tauri = { git = "https://github.com/tauri-apps/tauri", rev = "5e0d59ec", features = ["api-all", "system-tray"] }
# tauri = { git = "https://github.com/tauri-apps/tauri", rev = "5e0d59ec", features = ["api-all", "system-tray"] }
tauri = { git = "https://github.com/tauri-apps/tauri", branch = "next", features = ["api-all", "system-tray", "updater"] }
tauri-plugin-shadows = { git = "https://github.com/tauri-apps/tauri-plugin-shadows", features = ["tauri-impl"] }
tauri-plugin-vibrancy = { git = "https://github.com/tauri-apps/tauri-plugin-vibrancy", features = ["tauri-impl"] }
reqwest = { version = "0.11", features = ["json"] }
tokio = { version = "1", features = ["full"] }
log = "0.4.14"
log4rs = "1.0.0"
warp = "0.3"
which = "4.2.2"
auto-launch = "0.2"
port_scanner = "0.1.5"
[target.'cfg(windows)'.dependencies]

View File

@@ -4,4 +4,5 @@ mixed-port: 7890
log-level: info
allow-lan: false
external-controller: 127.0.0.1:9090
mode: rule
secret: ""

View File

@@ -1,20 +1,17 @@
use crate::{
core::{ClashInfo, ProfileItem, ProfilesConfig, VergeConfig},
core::{ClashInfo, ProfileItem, Profiles, VergeConfig},
states::{ClashState, ProfilesState, VergeState},
utils::{
config::{read_clash, save_clash},
fetch::fetch_profile,
sysopt::SysProxyConfig,
},
utils::{dirs::app_home_dir, fetch::fetch_profile, sysopt::SysProxyConfig},
};
use serde_yaml::Mapping;
use std::process::Command;
use tauri::State;
/// get all profiles from `profiles.yaml`
/// do not acquire the lock of ProfileLock
#[tauri::command]
pub fn get_profiles(profiles: State<'_, ProfilesState>) -> Result<ProfilesConfig, String> {
match profiles.0.lock() {
pub fn get_profiles(profiles_state: State<'_, ProfilesState>) -> Result<Profiles, String> {
match profiles_state.0.lock() {
Ok(profiles) => Ok(profiles.clone()),
Err(_) => Err("failed to get profiles lock".into()),
}
@@ -22,20 +19,24 @@ pub fn get_profiles(profiles: State<'_, ProfilesState>) -> Result<ProfilesConfig
/// synchronize data irregularly
#[tauri::command]
pub fn sync_profiles(profiles: State<'_, ProfilesState>) -> Result<(), String> {
match profiles.0.lock() {
pub fn sync_profiles(profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
match profiles_state.0.lock() {
Ok(mut profiles) => profiles.sync_file(),
Err(_) => Err("failed to get profiles lock".into()),
}
}
/// Import the profile from url
/// import the profile from url
/// and save to `profiles.yaml`
#[tauri::command]
pub async fn import_profile(url: String, profiles: State<'_, ProfilesState>) -> Result<(), String> {
match fetch_profile(&url).await {
pub async fn import_profile(
url: String,
with_proxy: bool,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
match fetch_profile(&url, with_proxy).await {
Some(result) => {
let mut profiles = profiles.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
profiles.import_from_url(url, result)
}
None => Err(format!("failed to fetch profile from `{}`", url)),
@@ -43,17 +44,15 @@ pub async fn import_profile(url: String, profiles: State<'_, ProfilesState>) ->
}
/// Update the profile
/// and save to `profiles.yaml`
/// http request firstly
/// then acquire the lock of `profiles.yaml`
#[tauri::command]
pub async fn update_profile(
index: usize,
clash: State<'_, ClashState>,
profiles: State<'_, ProfilesState>,
with_proxy: bool,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
// maybe we can get the url from the web app directly
let url = match profiles.0.lock() {
let url = match profiles_state.0.lock() {
Ok(mut profile) => {
let items = profile.items.take().unwrap_or(vec![]);
if index >= items.len() {
@@ -69,16 +68,16 @@ pub async fn update_profile(
Err(_) => return Err("failed to get profiles lock".into()),
};
match fetch_profile(&url).await {
Some(result) => match profiles.0.lock() {
match fetch_profile(&url, with_proxy).await {
Some(result) => match profiles_state.0.lock() {
Ok(mut profiles) => {
profiles.update_item(index, result)?;
// reactivate the profile
let current = profiles.current.clone().unwrap_or(0);
if current == index {
let clash = clash.0.lock().unwrap();
profiles.activate(clash.info.clone())
let clash = clash_state.0.lock().unwrap();
profiles.activate(&clash)
} else {
Ok(())
}
@@ -93,27 +92,37 @@ pub async fn update_profile(
#[tauri::command]
pub fn select_profile(
index: usize,
clash: State<'_, ClashState>,
profiles: State<'_, ProfilesState>,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
match profiles.put_current(index) {
Ok(()) => {
let clash = clash.0.lock().unwrap();
profiles.activate(clash.info.clone())
let clash = clash_state.0.lock().unwrap();
profiles.activate(&clash)
}
Err(err) => Err(err),
}
}
/// todo: need to check
/// delete profile item
#[tauri::command]
pub fn delete_profile(index: usize, profiles: State<'_, ProfilesState>) -> Result<(), String> {
match profiles.0.lock() {
Ok(mut profiles) => profiles.delete_item(index),
Err(_) => Err("can not get profiles lock".into()),
pub fn delete_profile(
index: usize,
clash_state: State<'_, ClashState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
match profiles.delete_item(index) {
Ok(change) => match change {
true => {
let clash = clash_state.0.lock().unwrap();
profiles.activate(&clash)
}
false => Ok(()),
},
Err(err) => Err(err),
}
}
@@ -122,20 +131,57 @@ pub fn delete_profile(index: usize, profiles: State<'_, ProfilesState>) -> Resul
pub fn patch_profile(
index: usize,
profile: ProfileItem,
profiles: State<'_, ProfilesState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
match profiles.0.lock() {
match profiles_state.0.lock() {
Ok(mut profiles) => profiles.patch_item(index, profile),
Err(_) => Err("can not get profiles lock".into()),
}
}
/// run vscode command to edit the profile
#[tauri::command]
pub fn view_profile(index: usize, profiles_state: State<'_, ProfilesState>) -> Result<(), String> {
let mut profiles = profiles_state.0.lock().unwrap();
let items = profiles.items.take().unwrap_or(vec![]);
if index >= items.len() {
profiles.items = Some(items);
return Err("the index out of bound".into());
}
let file = items[index].file.clone().unwrap_or("".into());
profiles.items = Some(items);
let path = app_home_dir().join("profiles").join(file);
if !path.exists() {
return Err("failed to open the file".into());
}
match which::which("code") {
Ok(code) => match Command::new(code).arg(path).status() {
Ok(_) => Ok(()),
Err(_) => Err("failed to open file by VScode".into()),
},
Err(_) => Err("please install VScode for edit".into()),
}
}
/// restart the sidecar
#[tauri::command]
pub fn restart_sidecar(clash_state: State<'_, ClashState>) {
let mut clash_arc = clash_state.0.lock().unwrap();
if let Err(err) = clash_arc.restart_sidecar() {
log::error!("{}", err);
pub fn restart_sidecar(
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();
match clash.restart_sidecar(&mut profiles) {
Ok(_) => Ok(()),
Err(err) => {
log::error!("{}", err);
Err(err)
}
}
}
@@ -144,46 +190,28 @@ pub fn restart_sidecar(clash_state: State<'_, ClashState>) {
#[tauri::command]
pub fn get_clash_info(clash_state: State<'_, ClashState>) -> Result<ClashInfo, String> {
match clash_state.0.lock() {
Ok(arc) => Ok(arc.info.clone()),
Ok(clash) => Ok(clash.info.clone()),
Err(_) => Err("failed to get clash lock".into()),
}
}
/// todo: need refactor
/// update the clash core config
/// after putting the change to the clash core
/// then we should save the latest config
#[tauri::command]
pub fn patch_clash_config(payload: Mapping) -> Result<(), String> {
let mut config = read_clash();
for (key, value) in payload.iter() {
if config.contains_key(key) {
config[key] = value.clone();
} else {
config.insert(key.clone(), value.clone());
}
}
save_clash(&config)
}
/// set the system proxy
/// Tips: only support windows now
#[tauri::command]
pub fn set_sys_proxy(enable: bool, verge_state: State<'_, VergeState>) -> Result<(), String> {
pub fn patch_clash_config(
payload: Mapping,
clash_state: State<'_, ClashState>,
verge_state: State<'_, VergeState>,
profiles_state: State<'_, ProfilesState>,
) -> Result<(), String> {
let mut clash = clash_state.0.lock().unwrap();
let mut verge = verge_state.0.lock().unwrap();
if let Some(mut sysproxy) = verge.cur_sysproxy.take() {
sysproxy.enable = enable;
if sysproxy.set_sys().is_err() {
log::error!("failed to set system proxy");
}
verge.cur_sysproxy = Some(sysproxy);
}
Ok(())
let mut profiles = profiles_state.0.lock().unwrap();
clash.patch_config(payload, &mut verge, &mut profiles)
}
/// get the system proxy
/// Tips: only support windows now
#[tauri::command]
pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
match SysProxyConfig::get_sys() {
@@ -192,6 +220,8 @@ pub fn get_sys_proxy() -> Result<SysProxyConfig, String> {
}
}
/// get the current proxy config
/// which may not the same as system proxy
#[tauri::command]
pub fn get_cur_proxy(verge_state: State<'_, VergeState>) -> Result<Option<SysProxyConfig>, String> {
match verge_state.0.lock() {
@@ -217,22 +247,5 @@ pub async fn patch_verge_config(
verge_state: State<'_, VergeState>,
) -> Result<(), String> {
let mut verge = verge_state.0.lock().unwrap();
if payload.theme_mode.is_some() {
verge.config.theme_mode = payload.theme_mode;
}
if payload.enable_self_startup.is_some() {
verge.config.enable_self_startup = payload.enable_self_startup;
}
if payload.enable_system_proxy.is_some() {
verge.config.enable_system_proxy = payload.enable_system_proxy;
}
if payload.system_proxy_bypass.is_some() {
verge.config.system_proxy_bypass = payload.system_proxy_bypass;
}
verge.config.save_file()
verge.patch_config(payload)
}

View File

@@ -1,3 +1,4 @@
use super::{Profiles, Verge};
use crate::utils::{config, dirs};
use serde::{Deserialize, Serialize};
use serde_yaml::{Mapping, Value};
@@ -20,6 +21,9 @@ pub struct ClashInfo {
#[derive(Debug)]
pub struct Clash {
/// maintain the clash config
pub config: Mapping,
/// some info
pub info: ClashInfo,
@@ -32,8 +36,19 @@ static CLASH_CONFIG: &str = "config.yaml";
// todo: be able to change config field
impl Clash {
pub fn new() -> Clash {
let clash_config = config::read_yaml::<Mapping>(dirs::app_home_dir().join(CLASH_CONFIG));
let config = Clash::get_config();
let info = Clash::get_info(&config);
Clash {
config,
info,
sidecar: None,
}
}
/// parse the clash's config.yaml
/// get some information
fn get_info(clash_config: &Mapping) -> ClashInfo {
let key_port_1 = Value::String("port".to_string());
let key_port_2 = Value::String("mixed-port".to_string());
let key_server = Value::String("external-controller".to_string());
@@ -76,14 +91,11 @@ impl Clash {
_ => None,
};
Clash {
info: ClashInfo {
status: "init".into(),
port,
server,
secret,
},
sidecar: None,
ClashInfo {
status: "init".into(),
port,
server,
secret,
}
}
@@ -126,9 +138,70 @@ impl Clash {
}
/// restart clash sidecar
pub fn restart_sidecar(&mut self) -> Result<(), String> {
/// should reactivate profile after restart
pub fn restart_sidecar(&mut self, profiles: &mut Profiles) -> Result<(), String> {
self.update_config();
self.drop_sidecar()?;
self.run_sidecar()
self.run_sidecar()?;
profiles.activate(&self)
}
/// update the clash info
pub fn update_config(&mut self) {
self.config = Clash::get_config();
self.info = Clash::get_info(&self.config);
}
/// get clash config
fn get_config() -> Mapping {
config::read_yaml::<Mapping>(dirs::app_home_dir().join(CLASH_CONFIG))
}
/// save the clash config
fn save_config(&self) -> Result<(), String> {
config::save_yaml(
dirs::app_home_dir().join(CLASH_CONFIG),
&self.config,
Some("# Default Config For Clash Core\n\n"),
)
}
/// patch update the clash config
pub fn patch_config(
&mut self,
patch: Mapping,
verge: &mut Verge,
profiles: &mut Profiles,
) -> Result<(), String> {
for (key, value) in patch.iter() {
let value = value.clone();
let key_str = key.as_str().clone().unwrap_or("");
// restart the clash
if key_str == "mixed-port" {
self.restart_sidecar(profiles)?;
let port = if value.is_number() {
match value.as_i64().clone() {
Some(num) => Some(format!("{num}")),
None => None,
}
} else {
match value.as_str().clone() {
Some(num) => Some(num.into()),
None => None,
}
};
verge.init_sysproxy(port);
}
if self.config.contains_key(key) {
self.config[key] = value;
} else {
self.config.insert(key.clone(), value);
}
}
self.save_config()
}
}

View File

@@ -1,3 +1,4 @@
use super::{Clash, ClashInfo};
use crate::utils::{config, dirs};
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
@@ -8,11 +9,9 @@ use std::fs::File;
use std::io::Write;
use std::time::{SystemTime, UNIX_EPOCH};
use super::ClashInfo;
/// Define the `profiles.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct ProfilesConfig {
pub struct Profiles {
/// current profile's name
pub current: Option<usize>,
@@ -64,10 +63,10 @@ pub struct ProfileResponse {
static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
impl ProfilesConfig {
impl Profiles {
/// read the config from the file
pub fn read_file() -> Self {
config::read_yaml::<ProfilesConfig>(dirs::app_home_dir().join(PROFILE_YAML))
config::read_yaml::<Profiles>(dirs::app_home_dir().join(PROFILE_YAML))
}
/// save the config to the file
@@ -100,7 +99,7 @@ impl ProfilesConfig {
File::create(path).unwrap().write(file_data).unwrap();
// update `profiles.yaml`
let data = ProfilesConfig::read_file();
let data = Profiles::read_file();
let mut items = data.items.unwrap_or(vec![]);
let now = SystemTime::now()
@@ -195,7 +194,7 @@ impl ProfilesConfig {
}
/// delete the item
pub fn delete_item(&mut self, index: usize) -> Result<(), String> {
pub fn delete_item(&mut self, index: usize) -> Result<bool, String> {
let mut current = self.current.clone().unwrap_or(0);
let mut items = self.items.clone().unwrap_or(vec![]);
@@ -205,17 +204,26 @@ impl ProfilesConfig {
items.remove(index);
let mut should_change = false;
if current == index {
current = 0;
should_change = true;
} else if current > index {
current = current - 1;
}
self.current = Some(current);
self.save_file()
self.items = Some(items);
match self.save_file() {
Ok(_) => Ok(should_change),
Err(err) => Err(err),
}
}
/// activate current profile
pub fn activate(&self, clash_config: ClashInfo) -> Result<(), String> {
pub fn activate(&self, clash: &Clash) -> Result<(), String> {
let current = self.current.unwrap_or(0);
match self.items.clone() {
Some(items) => {
@@ -224,11 +232,13 @@ impl ProfilesConfig {
}
let profile = items[current].clone();
let clash_config = clash.config.clone();
let clash_info = clash.info.clone();
tauri::async_runtime::spawn(async move {
let mut count = 5; // retry times
let mut err = String::from("");
while count > 0 {
match activate_profile(&profile, &clash_config).await {
match activate_profile(&profile, &clash_config, &clash_info).await {
Ok(_) => return,
Err(e) => err = e,
}
@@ -245,7 +255,11 @@ impl ProfilesConfig {
}
/// put the profile to clash
pub async fn activate_profile(profile_item: &ProfileItem, info: &ClashInfo) -> Result<(), String> {
pub async fn activate_profile(
profile_item: &ProfileItem,
clash_config: &Mapping,
clash_info: &ClashInfo,
) -> Result<(), String> {
// temp profile's path
let temp_path = temp_dir().join(PROFILE_TEMP);
@@ -258,25 +272,47 @@ pub async fn activate_profile(profile_item: &ProfileItem, info: &ClashInfo) -> R
let file_path = dirs::app_home_dir().join("profiles").join(file_name);
if !file_path.exists() {
return Err(format!("profile `{:?}` not exists", file_path));
return Err(format!(
"profile `{}` not exists",
file_path.as_os_str().to_str().unwrap()
));
}
// begin to generate the new profile config
let def_config = config::read_yaml::<Mapping>(file_path.clone());
let mut new_config = Mapping::new();
// Only the following fields are allowed:
// proxies/proxy-providers/proxy-groups/rule-providers/rules
let config = config::read_yaml::<Mapping>(file_path.clone());
let mut new_config = Mapping::new();
vec![
let valid_keys = vec![
"proxies",
"proxy-providers",
"proxy-groups",
"rule-providers",
"rules",
]
.iter()
.map(|item| Value::String(item.to_string()))
.for_each(|key| {
if config.contains_key(&key) {
let value = config[&key].clone();
];
valid_keys.iter().for_each(|key| {
let key = Value::String(key.to_string());
if def_config.contains_key(&key) {
let value = def_config[&key].clone();
new_config.insert(key, value);
}
});
// add some of the clash `config.yaml` config to it
let valid_keys = vec![
"mixed-port",
"log-level",
"allow-lan",
"external-controller",
"secret",
"mode",
"ipv6",
];
valid_keys.iter().for_each(|key| {
let key = Value::String(key.to_string());
if clash_config.contains_key(&key) {
let value = clash_config[&key].clone();
new_config.insert(key, value);
}
});
@@ -288,12 +324,12 @@ pub async fn activate_profile(profile_item: &ProfileItem, info: &ClashInfo) -> R
)?
};
let server = format!("http://{}/configs", info.server.clone().unwrap());
let server = format!("http://{}/configs", clash_info.server.clone().unwrap());
let mut headers = HeaderMap::new();
headers.insert("Content-Type", "application/json".parse().unwrap());
if let Some(secret) = info.secret.clone() {
if let Some(secret) = clash_info.secret.clone() {
headers.insert(
"Authorization",
format!("Bearer {}", secret).parse().unwrap(),
@@ -303,7 +339,10 @@ pub async fn activate_profile(profile_item: &ProfileItem, info: &ClashInfo) -> R
let mut data = HashMap::new();
data.insert("path", temp_path.as_os_str().to_str().unwrap());
let client = reqwest::Client::new();
let client = match reqwest::ClientBuilder::new().no_proxy().build() {
Ok(c) => c,
Err(_) => return Err("failed to create http::put".into()),
};
match client.put(server).headers(headers).json(&data).send().await {
Ok(_) => Ok(()),
Err(err) => Err(format!("request failed `{}`", err.to_string())),

View File

@@ -1,5 +1,7 @@
use crate::utils::{config, dirs, sysopt::SysProxyConfig};
use auto_launch::{AutoLaunch, AutoLaunchBuilder};
use serde::{Deserialize, Serialize};
use tauri::api::path::resource_dir;
/// ### `verge.yaml` schema
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
@@ -7,8 +9,12 @@ pub struct VergeConfig {
/// `light` or `dark`
pub theme_mode: Option<String>,
/// enable blur mode
/// maybe be able to set the alpha
pub theme_blur: Option<bool>,
/// can the app auto startup
pub enable_self_startup: Option<bool>,
pub enable_auto_launch: Option<bool>,
/// set system proxy
pub enable_system_proxy: Option<bool>,
@@ -34,6 +40,7 @@ impl VergeConfig {
}
}
/// Verge App abilities
#[derive(Debug)]
pub struct Verge {
pub config: VergeConfig,
@@ -41,6 +48,8 @@ pub struct Verge {
pub old_sysproxy: Option<SysProxyConfig>,
pub cur_sysproxy: Option<SysProxyConfig>,
pub auto_launch: Option<AutoLaunch>,
}
impl Default for Verge {
@@ -55,6 +64,7 @@ impl Verge {
config: VergeConfig::new(),
old_sysproxy: None,
cur_sysproxy: None,
auto_launch: None,
}
}
@@ -90,4 +100,135 @@ impl Verge {
}
}
}
/// init the auto launch
pub fn init_launch(&mut self, package_info: &tauri::PackageInfo) {
let app_name = "clash-verge";
let app_path = get_app_path(app_name);
let app_path = resource_dir(package_info).unwrap().join(app_path);
let app_path = app_path.as_os_str().to_str().unwrap();
let auto = AutoLaunchBuilder::new()
.set_app_name(app_name)
.set_app_path(app_path)
.build();
self.auto_launch = Some(auto);
}
/// sync the startup when run the app
pub fn sync_launch(&self) -> Result<(), String> {
let enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if !enable {
return Ok(());
}
if self.auto_launch.is_none() {
return Err("should init the auto launch first".into());
}
let auto_launch = self.auto_launch.clone().unwrap();
let is_enabled = auto_launch.is_enabled().unwrap_or(false);
if !is_enabled {
if let Err(_) = auto_launch.enable() {
return Err("failed to enable auto-launch".into());
}
}
Ok(())
}
/// update the startup
fn update_launch(&mut self, enable: bool) -> Result<(), String> {
let conf_enable = self.config.enable_auto_launch.clone().unwrap_or(false);
if enable == conf_enable {
return Ok(());
}
let auto_launch = self.auto_launch.clone().unwrap();
let result = if enable {
auto_launch.enable()
} else {
auto_launch.disable()
};
match result {
Ok(_) => Ok(()),
Err(_) => Err("failed to set system startup info".into()),
}
}
// fn guard_thread(&mut self) -> Result<(), String> {
// let sysproxy = self.cur_sysproxy.clone();
// use std::{thread, time};
// tauri::async_runtime::spawn(async move {
// if let Some(sysproxy) = sysproxy {
// sysproxy.set_sys();
// }
// let ten_millis = time::Duration::from_millis(10);
// let now = time::Instant::now();
// thread::sleep(ten_millis);
// });
// Ok(())
// }
/// patch verge config
/// There should be only one update at a time here
/// so call the save_file at the end is savely
pub fn patch_config(&mut self, patch: VergeConfig) -> Result<(), String> {
// only change it
if patch.theme_mode.is_some() {
self.config.theme_mode = patch.theme_mode;
}
if patch.theme_blur.is_some() {
self.config.theme_blur = patch.theme_blur;
}
// should update system startup
if patch.enable_auto_launch.is_some() {
let enable = patch.enable_auto_launch.unwrap();
self.update_launch(enable)?;
self.config.enable_auto_launch = Some(enable);
}
// should update system proxy
if patch.enable_system_proxy.is_some() {
let enable = patch.enable_system_proxy.unwrap();
if let Some(mut sysproxy) = self.cur_sysproxy.take() {
sysproxy.enable = enable;
if sysproxy.set_sys().is_err() {
log::error!("failed to set system proxy");
return Err("failed to set system proxy".into());
}
self.cur_sysproxy = Some(sysproxy);
}
self.config.enable_system_proxy = Some(enable);
}
// todo
// should update system proxy too
if patch.system_proxy_bypass.is_some() {
self.config.system_proxy_bypass = patch.system_proxy_bypass;
}
self.config.save_file()
}
}
// Get the target app_path
fn get_app_path(app_name: &str) -> String {
#[cfg(target_os = "linux")]
let ext = "";
#[cfg(target_os = "macos")]
let ext = ".app";
#[cfg(target_os = "windows")]
let ext = ".exe";
String::from(app_name) + ext
}

View File

@@ -3,8 +3,6 @@
windows_subsystem = "windows"
)]
extern crate tauri;
mod cmds;
mod core;
mod states;
@@ -22,10 +20,10 @@ fn main() -> std::io::Result<()> {
}
let menu = SystemTrayMenu::new()
.add_item(CustomMenuItem::new("open_window", "显示应用"))
.add_item(CustomMenuItem::new("restart_clash", "重启clash"))
.add_item(CustomMenuItem::new("open_window", "Show"))
.add_item(CustomMenuItem::new("restart_clash", "Restart Clash"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(CustomMenuItem::new("quit", "退出").accelerator("CmdOrControl+Q"));
.add_item(CustomMenuItem::new("quit", "Quit").accelerator("CmdOrControl+Q"));
tauri::Builder::default()
.manage(states::VergeState::default())
@@ -37,14 +35,21 @@ fn main() -> std::io::Result<()> {
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"open_window" => {
let window = app_handle.get_window("main").unwrap();
window.unminimize().unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
"restart_clash" => {
let clash_state = app_handle.state::<states::ClashState>();
let mut clash_arc = clash_state.0.lock().unwrap();
if let Err(err) = clash_arc.restart_sidecar() {
log::error!("{}", err);
let profiles_state = app_handle.state::<states::ProfilesState>();
let mut clash = clash_state.0.lock().unwrap();
let mut profiles = profiles_state.0.lock().unwrap();
match clash.restart_sidecar(&mut profiles) {
Ok(_) => {
let window = app_handle.get_window("main").unwrap();
window.emit("restart_clash", "yes").unwrap();
}
Err(err) => log::error!("{}", err),
}
}
"quit" => {
@@ -56,27 +61,32 @@ fn main() -> std::io::Result<()> {
},
SystemTrayEvent::LeftClick { .. } => {
let window = app_handle.get_window("main").unwrap();
window.unminimize().unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
_ => {}
})
.invoke_handler(tauri::generate_handler![
// common
cmds::restart_sidecar,
cmds::set_sys_proxy,
cmds::get_sys_proxy,
cmds::get_cur_proxy,
// clash
cmds::get_clash_info,
cmds::patch_clash_config,
// verge
cmds::get_verge_config,
cmds::patch_verge_config,
// profile
cmds::view_profile,
cmds::patch_profile,
cmds::import_profile,
cmds::update_profile,
cmds::delete_profile,
cmds::select_profile,
cmds::patch_profile,
cmds::sync_profiles,
cmds::get_profiles,
cmds::sync_profiles,
])
.build(tauri::generate_context!())
.expect("error while running tauri application")
@@ -86,10 +96,7 @@ fn main() -> std::io::Result<()> {
api.prevent_close();
app_handle.get_window(&label).unwrap().hide().unwrap();
}
tauri::Event::ExitRequested { api, .. } => {
api.prevent_exit();
}
tauri::Event::Exit => {
tauri::Event::ExitRequested { .. } => {
resolve::resolve_reset(app_handle);
api::process::kill_children();
}

View File

@@ -1,8 +1,8 @@
use crate::core::{Clash, ProfilesConfig, Verge};
use crate::core::{Clash, Profiles, Verge};
use std::sync::{Arc, Mutex};
#[derive(Default)]
pub struct ProfilesState(pub Arc<Mutex<ProfilesConfig>>);
pub struct ProfilesState(pub Arc<Mutex<Profiles>>);
#[derive(Default)]
pub struct ClashState(pub Arc<Mutex<Clash>>);

View File

@@ -1,6 +1,4 @@
use crate::utils::dirs;
use serde::{de::DeserializeOwned, Serialize};
use serde_yaml::Mapping;
use std::{fs, path::PathBuf};
/// read data from yaml as struct T
@@ -32,17 +30,3 @@ pub fn save_yaml<T: Serialize>(
Err(_) => Err("can not convert the data to yaml".into()),
}
}
/// Get Clash Core Config `config.yaml`
pub fn read_clash() -> Mapping {
read_yaml::<Mapping>(dirs::app_home_dir().join("config.yaml"))
}
/// Save the clash core Config `config.yaml`
pub fn save_clash(config: &Mapping) -> Result<(), String> {
save_yaml(
dirs::app_home_dir().join("config.yaml"),
config,
Some("# Default Config For Clash Core\n\n"),
)
}

View File

@@ -23,11 +23,20 @@ fn parse_string<T: FromStr>(target: &str, key: &str) -> Option<T> {
}
/// fetch and parse the profile
pub async fn fetch_profile(url: &str) -> Option<ProfileResponse> {
let resp = match reqwest::get(url).await {
Ok(res) => res,
pub async fn fetch_profile(url: &str, with_proxy: bool) -> Option<ProfileResponse> {
let builder = reqwest::ClientBuilder::new();
let client = match with_proxy {
true => builder.build(),
false => builder.no_proxy().build(),
};
let resp = match client {
Ok(client) => match client.get(url).send().await {
Ok(res) => res,
Err(_) => return None,
},
Err(_) => return None,
};
let header = resp.headers();
// parse the Subscription Userinfo

View File

@@ -1,9 +1,24 @@
use super::{init, server};
use crate::{core::ProfilesConfig, states};
use crate::{core::Profiles, states};
use tauri::{App, AppHandle, Manager};
use tauri_plugin_shadows::Shadows;
/// handle something when start app
pub fn resolve_setup(app: &App) {
// set shadow when window decorations
let window = app.get_window("main").unwrap();
window.set_shadow(true);
// enable system blur
use tauri_plugin_vibrancy::Vibrancy;
#[cfg(target_os = "windows")]
window.apply_blur();
#[cfg(target_os = "macos")]
{
use tauri_plugin_vibrancy::MacOSVibrancy;
window.apply_vibrancy(MacOSVibrancy::AppearanceBased);
}
// setup a simple http server for singleton
server::embed_server(&app.handle());
@@ -23,18 +38,22 @@ pub fn resolve_setup(app: &App) {
log::error!("{}", err);
}
*profiles = ProfilesConfig::read_file();
if let Err(err) = profiles.activate(clash.info.clone()) {
*profiles = Profiles::read_file();
if let Err(err) = profiles.activate(&clash) {
log::error!("{}", err);
}
verge.init_sysproxy(clash.info.port.clone());
verge.init_launch(app.package_info());
if let Err(err) = verge.sync_launch() {
log::error!("{}", err);
}
}
/// reset system proxy
pub fn resolve_reset(app_handle: &AppHandle) {
let verge_state = app_handle.state::<states::VergeState>();
let mut verge_arc = verge_state.0.lock().unwrap();
let mut verge = verge_state.0.lock().unwrap();
verge_arc.reset_sysproxy();
verge.reset_sysproxy();
}

156
src-tauri/src/utils/sysopt.rs Normal file → Executable file
View File

@@ -1,7 +1,13 @@
use serde::{Deserialize, Serialize};
use std::io;
#[cfg(target_os = "windows")]
static DEFAULT_BYPASS: &str = "localhost;127.*;10.*;172.16.*;172.17.*;172.18.*;172.19.*;172.20.*;172.21.*;172.22.*;172.23.*;172.24.*;172.25.*;172.26.*;172.27.*;172.28.*;172.29.*;172.30.*;172.31.*;192.168.*;<local>";
#[cfg(target_os = "macos")]
static DEFAULT_BYPASS: &str =
"192.168.0.0/16\n10.0.0.0/8\n172.16.0.0/12\n127.0.0.1\nlocalhost\n*.local\ntimestamp.apple.com\n";
#[cfg(target_os = "macos")]
static MACOS_SERVICE: &str = "Wi-Fi";
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct SysProxyConfig {
@@ -29,8 +35,8 @@ impl SysProxyConfig {
}
}
/// Get the windows system proxy config
#[cfg(target_os = "windows")]
/// Get the windows system proxy config
pub fn get_sys() -> io::Result<Self> {
use winreg::enums::*;
use winreg::RegKey;
@@ -48,6 +54,43 @@ impl SysProxyConfig {
})
}
#[cfg(target_os = "macos")]
/// Get the macos system proxy config
pub fn get_sys() -> io::Result<Self> {
use std::process::Command;
let http = macproxy::get_proxy(&["-getwebproxy", MACOS_SERVICE])?;
let https = macproxy::get_proxy(&["-getsecurewebproxy", MACOS_SERVICE])?;
let sock = macproxy::get_proxy(&["-getsocksfirewallproxy", MACOS_SERVICE])?;
let mut enable = false;
let mut server = "".into();
if sock.0 == "Yes" {
enable = true;
server = sock.1;
}
if https.0 == "Yes" {
enable = true;
server = https.1;
}
if http.0 == "Yes" || !enable {
enable = http.0 == "Yes";
server = http.1;
}
let bypass_output = Command::new("networksetup")
.args(["-getproxybypassdomains", MACOS_SERVICE])
.output()?;
let bypass = std::str::from_utf8(&bypass_output.stdout).unwrap_or(DEFAULT_BYPASS);
Ok(SysProxyConfig {
enable,
server,
bypass: bypass.into(),
})
}
#[cfg(target_os = "windows")]
/// Set the windows system proxy config
pub fn set_sys(&self) -> io::Result<()> {
@@ -65,21 +108,104 @@ impl SysProxyConfig {
cur_var.set_value("ProxyServer", &self.server)?;
cur_var.set_value("ProxyOverride", &self.bypass)
}
#[cfg(target_os = "macos")]
/// Set the macos system proxy config
pub fn set_sys(&self) -> io::Result<()> {
let enable = self.enable;
let server = self.server.as_str();
macproxy::set_proxy("-setwebproxy", MACOS_SERVICE, enable, server)?;
macproxy::set_proxy("-setsecurewebproxy", MACOS_SERVICE, enable, server)?;
macproxy::set_proxy("-setsocksfirewallproxy", MACOS_SERVICE, enable, server)
}
}
// #[cfg(target_os = "macos")]
// mod macos {
// use super::*;
#[cfg(target_os = "macos")]
mod macproxy {
use super::*;
use std::process::Command;
// pub fn get_proxy_config() -> io::Result<SysProxyConfig> {
// Ok(SysProxyConfig {
// enable: false,
// server: "server".into(),
// bypass: "bypass".into(),
// })
// }
/// use networksetup
/// get the target proxy config
pub(super) fn get_proxy(args: &[&str; 2]) -> io::Result<(String, String)> {
let output = Command::new("networksetup").args(args).output()?;
match std::str::from_utf8(&output.stdout) {
Ok(stdout) => {
let enable = parse(stdout, "Enabled:");
let server = parse(stdout, "Server:");
let port = parse(stdout, "Port:");
let server = format!("{}:{}", server, port);
Ok((enable.into(), server))
}
Err(_) => Err(io::Error::from_raw_os_error(1)),
}
}
// pub fn set_proxy_config(config: &SysProxyConfig) -> io::Result<()> {
// Ok(())
// }
// }
/// use networksetup
/// set the target proxy config
pub(super) fn set_proxy(
target: &str, // like: -setwebproxy
device: &str,
enable: bool,
server: &str,
) -> io::Result<()> {
let mut split = server.split(":");
let domain = split.next();
let port = split.next();
// can not parse the field
if domain.is_none() || port.is_none() {
return Err(io::Error::from_raw_os_error(1));
}
let args = vec![target, device, domain.unwrap(), port.unwrap()];
Command::new("networksetup").args(&args).status()?;
let target_state = String::from(target) + "state";
let enable = if enable { "on" } else { "off" };
let args = vec![target_state.as_str(), device, enable];
Command::new("networksetup").args(&args).status()?;
Ok(())
}
/// parse the networksetup output
pub(super) fn parse<'a>(target: &'a str, key: &'a str) -> &'a str {
match target.find(key) {
Some(idx) => {
let idx = idx + key.len();
let value = &target[idx..];
let value = match value.find("\n") {
Some(end) => &value[..end],
None => value,
};
value.trim()
}
None => "",
}
}
#[test]
fn test_get() {
use std::process::Command;
let output = Command::new("networksetup")
.args(["-getwebproxy", "Wi-Fi"])
.output();
let output = output.unwrap();
let stdout = std::str::from_utf8(&output.stdout).unwrap();
let enable = parse(stdout, "Enabled:");
let server = parse(stdout, "Server:");
let port = parse(stdout, "Port:");
println!("enable: {}, server: {}, port: {}", enable, server, port);
dbg!(SysProxyConfig::get_sys().unwrap());
}
#[test]
fn test_set() {
let sysproxy = SysProxyConfig::new(true, "7890".into(), None);
dbg!(sysproxy.set_sys().unwrap());
}
}

View File

@@ -1,11 +1,11 @@
{
"package": {
"productName": "clash-verge",
"version": "0.0.5"
"version": "0.0.13"
},
"build": {
"distDir": "../dist",
"devPath": "http://localhost:3000/proxy",
"devPath": "http://localhost:3000/",
"beforeDevCommand": "yarn run web:dev",
"beforeBuildCommand": "yarn run web:build"
},
@@ -50,7 +50,11 @@
}
},
"updater": {
"active": false
"active": true,
"endpoints": [
"https://github.com/zzzgydi/clash-verge/releases/download/updater/update.json"
],
"dialog": false
},
"allowlist": {
"all": true
@@ -62,8 +66,8 @@
"height": 600,
"resizable": true,
"fullscreen": false,
"decorations": true,
"transparent": false,
"decorations": false,
"transparent": true,
"minWidth": 600,
"minHeight": 520
}

View File

@@ -28,3 +28,4 @@ body {
}
@import "./layout.scss";
@import "./page.scss";

View File

@@ -1,46 +1,81 @@
.layout {
width: 100%;
height: 100vh;
display: flex;
overflow: hidden;
&__sidebar {
position: relative;
&__left {
flex: 1 0 25%;
height: 100vh;
display: flex;
height: 100%;
max-width: 225px;
min-width: 125px;
overflow: hidden auto;
padding: 8px 0;
flex-direction: column;
box-sizing: border-box;
user-select: none;
overflow: hidden;
.the-logo {
position: relative;
flex: 0 1 180px;
width: 100%;
max-width: 180px;
max-height: 180px;
margin: 0 auto;
padding: 0 8px;
text-align: center;
box-sizing: border-box;
img {
width: 100%;
}
.the-newbtn {
position: absolute;
right: 20px;
bottom: 12px;
transform: scale(0.8);
}
}
.the-menu {
flex: 1 1 75%;
overflow-y: auto;
margin-bottom: 8px;
}
.the-traffic {
flex: 0 0 60px;
> div {
margin: 0 auto;
}
}
}
&__content {
&__right {
position: relative;
flex: 1 1 75%;
height: 100vh;
overflow: auto;
box-sizing: border-box;
scrollbar-gutter: "stable";
}
height: 100%;
&__logo {
width: 100%;
height: auto;
max-width: 180px;
max-height: 180px;
margin: 0 auto;
padding: 8px 8px 0;
user-select: none;
text-align: center;
box-sizing: border-box;
}
.the-bar {
position: absolute;
top: 2px;
right: 8px;
height: 36px;
display: flex;
align-items: center;
box-sizing: border-box;
z-index: 2;
}
&__traffic {
position: absolute;
left: 0;
right: 0;
bottom: 8px;
> div {
margin: 0 auto;
.the-content {
position: absolute;
top: 30px;
left: 0;
right: 2px;
bottom: 10px;
}
}
}

View File

@@ -0,0 +1,35 @@
.base-page {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
> header {
flex: 0 0 58px;
width: 90%;
max-width: 850px;
margin: 0 auto;
padding-right: 4px;
box-sizing: border-box;
display: flex;
align-items: center;
justify-content: space-between;
}
> section {
position: relative;
flex: 1 1 100%;
width: 100%;
height: 100%;
overflow: auto;
padding: 8px 0;
box-sizing: border-box;
scrollbar-gutter: stable;
.base-content {
width: 90%;
max-width: 850px;
margin: 0 auto;
}
}
}

View File

@@ -0,0 +1,32 @@
import { Typography } from "@mui/material";
import React from "react";
interface Props {
title?: React.ReactNode; // the page title
header?: React.ReactNode; // something behind title
contentStyle?: React.CSSProperties;
}
const BasePage: React.FC<Props> = (props) => {
const { title, header, contentStyle, children } = props;
return (
<div className="base-page" data-windrag>
<header data-windrag>
<Typography variant="h4" component="h1">
{title}
</Typography>
{header}
</header>
<section>
<div className="base-content" style={contentStyle} data-windrag>
{children}
</div>
</section>
</div>
);
};
export default BasePage;

View File

@@ -0,0 +1,41 @@
import { Button } from "@mui/material";
import { appWindow } from "@tauri-apps/api/window";
import {
CloseRounded,
CropSquareRounded,
HorizontalRuleRounded,
} from "@mui/icons-material";
const LayoutControl = () => {
const minWidth = 40;
return (
<>
<Button
size="small"
sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
onClick={() => appWindow.minimize()}
>
<HorizontalRuleRounded fontSize="small" />
</Button>
<Button
size="small"
sx={{ minWidth, svg: { transform: "scale(0.9)" } }}
onClick={() => appWindow.toggleMaximize()}
>
<CropSquareRounded fontSize="small" />
</Button>
<Button
size="small"
sx={{ minWidth, svg: { transform: "scale(1.05)" } }}
onClick={() => appWindow.hide()}
>
<CloseRounded fontSize="small" />
</Button>
</>
);
};
export default LayoutControl;

92
src/components/notice.tsx Normal file
View File

@@ -0,0 +1,92 @@
import ReactDOM from "react-dom";
import { ReactNode, useState } from "react";
import { Box, IconButton, Slide, Snackbar, Typography } from "@mui/material";
import { Close, CheckCircleRounded, ErrorRounded } from "@mui/icons-material";
interface InnerProps {
type: string;
duration?: number;
message: ReactNode;
onClose: () => void;
}
const NoticeInner = (props: InnerProps) => {
const { type, message, duration = 2000, onClose } = props;
const [visible, setVisible] = useState(true);
const onBtnClose = () => {
setVisible(false);
onClose();
};
const onAutoClose = (_e: any, reason: string) => {
if (reason !== "clickaway") onBtnClose();
};
const msgElement =
type === "info" ? (
message
) : (
<Box sx={{ display: "flex", alignItems: "center" }}>
{type === "error" && <ErrorRounded color="error" />}
{type === "success" && <CheckCircleRounded color="success" />}
<Typography
sx={{ ml: 1, wordWrap: "break-word", wordBreak: "break-all" }}
>
{message}
</Typography>
</Box>
);
return (
<Snackbar
open={visible}
anchorOrigin={{ vertical: "top", horizontal: "right" }}
autoHideDuration={duration}
onClose={onAutoClose}
message={msgElement}
sx={{ maxWidth: 360 }}
TransitionComponent={(p) => <Slide {...p} direction="left" />}
transitionDuration={200}
action={
<IconButton size="small" color="inherit" onClick={onBtnClose}>
<Close fontSize="inherit" />
</IconButton>
}
/>
);
};
interface NoticeInstance {
(props: Omit<InnerProps, "onClose">): void;
info(message: ReactNode, duration?: number): void;
error(message: ReactNode, duration?: number): void;
success(message: ReactNode, duration?: number): void;
}
let parent: HTMLDivElement = null!;
// @ts-ignore
const Notice: NoticeInstance = (props) => {
if (!parent) {
parent = document.createElement("div");
document.body.appendChild(parent);
}
const container = document.createElement("div");
parent.appendChild(container);
const onUnmount = () => {
const result = ReactDOM.unmountComponentAtNode(container);
if (result && parent) parent.removeChild(container);
};
ReactDOM.render(<NoticeInner {...props} onClose={onUnmount} />, container);
};
(["info", "error", "success"] as const).forEach((type) => {
Notice[type] = (message, duration) => Notice({ type, message, duration });
});
export default Notice;

View File

@@ -1,4 +1,4 @@
import React, { useState } from "react";
import React, { useRef, useState } from "react";
import dayjs from "dayjs";
import {
alpha,
@@ -8,13 +8,16 @@ import {
LinearProgress,
IconButton,
keyframes,
MenuItem,
Menu,
} from "@mui/material";
import { useSWRConfig } from "swr";
import { RefreshRounded } from "@mui/icons-material";
import { CmdType } from "../services/types";
import { updateProfile, deleteProfile, viewProfile } from "../services/cmds";
import Notice from "./notice";
import parseTraffic from "../utils/parse-traffic";
import relativeTime from "dayjs/plugin/relativeTime";
import { updateProfile } from "../services/cmds";
dayjs.extend(relativeTime);
@@ -30,22 +33,24 @@ const Wrapper = styled(Box)(({ theme }) => ({
}));
const round = keyframes`
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
`;
interface Props {
index: number;
selected: boolean;
itemData: CmdType.ProfileItem;
onClick: () => void;
onSelect: (force: boolean) => void;
}
const ProfileItemComp: React.FC<Props> = (props) => {
const { index, selected, itemData, onClick } = props;
const ProfileItem: React.FC<Props> = (props) => {
const { index, selected, itemData, onSelect } = props;
const { mutate } = useSWRConfig();
const [loading, setLoading] = useState(false);
const [anchorEl, setAnchorEl] = useState<any>(null);
const [position, setPosition] = useState({ left: 0, top: 0 });
const { name = "Profile", extra, updated = 0 } = itemData;
const { upload = 0, download = 0, total = 0 } = extra ?? {};
@@ -54,111 +59,170 @@ const ProfileItemComp: React.FC<Props> = (props) => {
const progress = Math.round(((download + upload) * 100) / (total + 0.1));
const fromnow = updated > 0 ? dayjs(updated * 1000).fromNow() : "";
const onUpdate = async () => {
const onView = async () => {
setAnchorEl(null);
try {
await viewProfile(index);
} catch (err: any) {
Notice.error(err.toString());
}
};
const onForceSelect = () => {
setAnchorEl(null);
onSelect(true);
};
const onUpdateWrapper = (withProxy: boolean) => async () => {
setAnchorEl(null);
if (loading) return;
setLoading(true);
try {
await updateProfile(index);
await updateProfile(index, withProxy);
mutate("getProfiles");
} catch (err) {
console.error(err);
} catch (err: any) {
Notice.error(err.toString());
} finally {
setLoading(false);
}
};
const deleteRef = useRef(false);
const onDelete = async () => {
setAnchorEl(null);
if (deleteRef.current) return;
deleteRef.current = true;
try {
await deleteProfile(index);
mutate("getProfiles");
} catch (err: any) {
Notice.error(err.toString());
} finally {
deleteRef.current = false;
}
};
const handleContextMenu = (
event: React.MouseEvent<HTMLDivElement, MouseEvent>
) => {
const { clientX, clientY } = event;
setPosition({ top: clientY, left: clientX });
setAnchorEl(event.currentTarget);
event.preventDefault();
};
return (
<Wrapper
sx={({ palette }) => {
const { mode, primary, text, grey } = palette;
const isDark = mode === "dark";
<>
<Wrapper
sx={({ palette }) => {
const { mode, primary, text, grey } = palette;
const key = `${mode}-${selected}`;
if (selected) {
const bgcolor = isDark
? alpha(primary.main, 0.35)
: alpha(primary.main, 0.15);
const bgcolor = {
"light-true": alpha(primary.main, 0.15),
"light-false": palette.background.paper,
"dark-true": alpha(primary.main, 0.35),
"dark-false": alpha(grey[700], 0.35),
}[key]!;
return {
bgcolor,
color: isDark ? alpha(text.secondary, 0.6) : text.secondary,
"& h2": {
color: isDark ? primary.light : primary.main,
},
};
}
const bgcolor = isDark
? alpha(grey[700], 0.35)
: palette.background.paper;
return {
bgcolor,
color: isDark ? alpha(text.secondary, 0.6) : text.secondary,
"& h2": {
color: isDark ? text.primary : text.primary,
},
};
}}
onClick={onClick}
>
<Box display="flex" justifyContent="space-between">
<Typography
width="calc(100% - 40px)"
variant="h6"
component="h2"
noWrap
title={name}
>
{name}
</Typography>
const color = {
"light-true": text.secondary,
"light-false": text.secondary,
"dark-true": alpha(text.secondary, 0.6),
"dark-false": alpha(text.secondary, 0.6),
}[key]!;
<IconButton
sx={{
width: 30,
height: 30,
animation: loading ? `1s linear infinite ${round}` : "none",
}}
color="inherit"
disabled={loading}
onClick={(e) => {
e.stopPropagation();
onUpdate();
}}
>
<RefreshRounded />
</IconButton>
</Box>
const h2color = {
"light-true": primary.main,
"light-false": text.primary,
"dark-true": primary.light,
"dark-false": text.primary,
}[key]!;
<Box display="flex" justifyContent="space-between" alignItems="center">
<Typography noWrap title={`From: ${from}`}>
{from}
</Typography>
<Typography
noWrap
flex="1 0 auto"
fontSize={14}
textAlign="right"
title="updated time"
>
{fromnow}
</Typography>
</Box>
<Box
sx={{
my: 0.5,
fontSize: 14,
display: "flex",
justifyContent: "space-between",
return { bgcolor, color, "& h2": { color: h2color } };
}}
onClick={() => onSelect(false)}
onContextMenu={handleContextMenu}
>
<span title="used / total">
{parseTraffic(upload + download)} / {parseTraffic(total)}
</span>
<span title="expire time">{expire}</span>
</Box>
<Box display="flex" justifyContent="space-between">
<Typography
width="calc(100% - 40px)"
variant="h6"
component="h2"
noWrap
title={name}
>
{name}
</Typography>
<LinearProgress variant="determinate" value={progress} color="inherit" />
</Wrapper>
<IconButton
sx={{
width: 30,
height: 30,
animation: loading ? `1s linear infinite ${round}` : "none",
}}
color="inherit"
disabled={loading}
onClick={(e) => {
e.stopPropagation();
onUpdateWrapper(false)();
}}
>
<RefreshRounded />
</IconButton>
</Box>
<Box display="flex" justifyContent="space-between" alignItems="center">
<Typography noWrap title={`From: ${from}`}>
{from}
</Typography>
<Typography
noWrap
flex="1 0 auto"
fontSize={14}
textAlign="right"
title="updated time"
>
{fromnow}
</Typography>
</Box>
<Box
sx={{
my: 0.5,
fontSize: 14,
display: "flex",
justifyContent: "space-between",
}}
>
<span title="used / total">
{parseTraffic(upload + download)} / {parseTraffic(total)}
</span>
<span title="expire time">{expire}</span>
</Box>
<LinearProgress
variant="determinate"
value={progress}
color="inherit"
/>
</Wrapper>
<Menu
open={!!anchorEl}
anchorEl={anchorEl}
onClose={() => setAnchorEl(null)}
anchorPosition={position}
anchorReference="anchorPosition"
>
<MenuItem onClick={onForceSelect}>Select</MenuItem>
<MenuItem onClick={onView}>View</MenuItem>
<MenuItem onClick={onUpdateWrapper(false)}>Update</MenuItem>
<MenuItem onClick={onUpdateWrapper(true)}>Update(Proxy)</MenuItem>
<MenuItem onClick={onDelete}>Delete</MenuItem>
</Menu>
</>
);
};
@@ -174,4 +238,4 @@ function parseExpire(expire?: number) {
return dayjs(expire * 1000).format("YYYY-MM-DD");
}
export default ProfileItemComp;
export default ProfileItem;

View File

@@ -1,15 +1,12 @@
import { useState } from "react";
import { Virtuoso } from "react-virtuoso";
import {
alpha,
Box,
Collapse,
Divider,
IconButton,
List,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
} from "@mui/material";
import {
@@ -18,53 +15,11 @@ import {
ExpandMoreRounded,
MyLocationRounded,
NetworkCheckRounded,
CheckCircleOutlineRounded,
} from "@mui/icons-material";
import { updateProxy } from "../services/api";
import { ApiType } from "../services/types";
import { getProfiles, patchProfile } from "../services/cmds";
interface ItemProps {
proxy: ApiType.ProxyItem;
selected: boolean;
onClick?: (name: string) => void;
}
const Item = ({ proxy, selected, onClick }: ItemProps) => {
return (
<ListItem sx={{ py: 0, pl: 4 }}>
<ListItemButton
dense
selected={selected}
onClick={() => onClick?.(proxy.name)}
sx={[
{
borderRadius: 1,
},
({ palette: { mode, primary } }) => {
const bgcolor =
mode === "light"
? alpha(primary.main, 0.15)
: alpha(primary.main, 0.35);
const color = mode === "light" ? primary.main : primary.light;
return {
"&.Mui-selected": { bgcolor },
"&.Mui-selected .MuiListItemText-secondary": { color },
};
},
]}
>
<ListItemText title={proxy.name} secondary={proxy.name} />
<ListItemIcon
sx={{ justifyContent: "flex-end", color: "primary.main" }}
>
{selected && <CheckCircleOutlineRounded sx={{ fontSize: 16 }} />}
</ListItemIcon>
</ListItemButton>
</ListItem>
);
};
import ProxyItem from "./proxy-item";
interface Props {
group: ApiType.ProxyGroupItem;
@@ -143,12 +98,13 @@ const ProxyGroup = ({ group }: Props) => {
{proxies.length >= 10 ? (
<Virtuoso
style={{ height: "400px", marginBottom: "4px" }}
style={{ height: "320px", marginBottom: "4px" }}
totalCount={proxies.length}
itemContent={(index) => (
<Item
<ProxyItem
proxy={proxies[index]}
selected={proxies[index].name === now}
sx={{ py: 0, pl: 4 }}
onClick={onUpdate}
/>
)}
@@ -157,13 +113,14 @@ const ProxyGroup = ({ group }: Props) => {
<List
component="div"
disablePadding
sx={{ maxHeight: "400px", overflow: "auto", mb: "4px" }}
sx={{ maxHeight: "320px", overflow: "auto", mb: "4px" }}
>
{proxies.map((proxy) => (
<Item
<ProxyItem
key={proxy.name}
proxy={proxy}
selected={proxy.name === now}
sx={{ py: 0, pl: 4 }}
onClick={onUpdate}
/>
))}

View File

@@ -0,0 +1,58 @@
import { CheckCircleOutlineRounded } from "@mui/icons-material";
import {
alpha,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
SxProps,
Theme,
} from "@mui/material";
import { ApiType } from "../services/types";
interface Props {
proxy: ApiType.ProxyItem;
selected: boolean;
sx?: SxProps<Theme>;
onClick?: (name: string) => void;
}
const ProxyItem = (props: Props) => {
const { proxy, selected, sx, onClick } = props;
return (
<ListItem sx={sx}>
<ListItemButton
dense
selected={selected}
onClick={() => onClick?.(proxy.name)}
sx={[
{
borderRadius: 1,
},
({ palette: { mode, primary } }) => {
const bgcolor =
mode === "light"
? alpha(primary.main, 0.15)
: alpha(primary.main, 0.35);
const color = mode === "light" ? primary.main : primary.light;
return {
"&.Mui-selected": { bgcolor },
"&.Mui-selected .MuiListItemText-secondary": { color },
};
},
]}
>
<ListItemText title={proxy.name} secondary={proxy.name} />
<ListItemIcon
sx={{ justifyContent: "flex-end", color: "primary.main" }}
>
{selected && <CheckCircleOutlineRounded sx={{ fontSize: 16 }} />}
</ListItemIcon>
</ListItemButton>
</ListItem>
);
};
export default ProxyItem;

View File

@@ -1,8 +0,0 @@
import { ListItem, styled } from "@mui/material";
const SettingItem = styled(ListItem)(() => ({
paddingTop: 5,
paddingBottom: 5,
}));
export default SettingItem;

View File

@@ -1,101 +0,0 @@
import useSWR, { useSWRConfig } from "swr";
import {
List,
ListItemText,
ListSubheader,
Switch,
Typography,
} from "@mui/material";
import {
getVergeConfig,
patchVergeConfig,
setSysProxy,
} from "../services/cmds";
import { CmdType } from "../services/types";
import GuardState from "./guard-state";
import SettingItem from "./setting-item";
import PaletteSwitch from "./palette-switch";
import { version } from "../../package.json";
interface Props {
onError?: (err: Error) => void;
}
const SettingVerge = ({ onError }: Props) => {
const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const {
theme_mode: mode = "light",
enable_self_startup: startup = false,
enable_system_proxy: proxy = false,
} = vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
};
return (
<List>
<ListSubheader sx={{ background: "transparent" }}></ListSubheader>
<SettingItem>
<ListItemText primary="外观主题" />
<GuardState
value={mode === "dark"}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
onGuard={async (c) => {
await patchVergeConfig({ theme_mode: c ? "dark" : "light" });
}}
>
<PaletteSwitch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="开机自启" />
<GuardState
value={startup}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_self_startup: e })}
onGuard={async (e) => {
await patchVergeConfig({ enable_self_startup: e });
}}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="设置系统代理" />
<GuardState
value={proxy}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_system_proxy: e })}
onGuard={async (e) => {
await setSysProxy(e);
await patchVergeConfig({ enable_system_proxy: e });
}}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="Version" />
<Typography sx={{ py: "6px" }}>v{version}</Typography>
</SettingItem>
</List>
);
};
export default SettingVerge;

View File

@@ -1,5 +1,5 @@
import { cloneElement, isValidElement, ReactNode, useRef } from "react";
import noop from "../utils/noop";
import noop from "../../utils/noop";
interface Props<Value> {
value?: Value;
@@ -7,7 +7,7 @@ interface Props<Value> {
onChangeProps?: string;
onChange?: (value: Value) => void;
onFormat?: (...args: any[]) => Value;
onGuard?: (value: Value) => Promise<void>;
onGuard?: (value: Value, oldValue: Value) => Promise<void>;
onCatch?: (error: Error) => void;
children: ReactNode;
}
@@ -41,7 +41,7 @@ function GuardState<T>(props: Props<T>) {
const newValue = (onFormat as any)(...args);
// 先在ui上响应操作
onChange(newValue);
await onGuard(newValue);
await onGuard(newValue, oldValue!);
} catch (err: any) {
// 状态回退
onChange(oldValue!);

View File

@@ -1,21 +1,24 @@
import { useEffect, useState } from "react";
import { useDebounceFn } from "ahooks";
import { useSetRecoilState } from "recoil";
import useSWR, { useSWRConfig } from "swr";
import {
List,
ListItemText,
ListSubheader,
TextField,
Switch,
Select,
MenuItem,
} from "@mui/material";
import { getClashConfig, updateConfigs } from "../services/api";
import { patchClashConfig } from "../services/cmds";
import { ApiType } from "../services/types";
import { getClashConfig, updateConfigs } from "../../services/api";
import { SettingList, SettingItem } from "./setting";
import { patchClashConfig } from "../../services/cmds";
import { atomClashPort } from "../../states/setting";
import { ApiType } from "../../services/types";
import GuardState from "./guard-state";
import SettingItem from "./setting-item";
import Notice from "../notice";
interface Props {
onError?: (err: Error) => void;
onError: (err: Error) => void;
}
const SettingClash = ({ onError }: Props) => {
@@ -26,28 +29,49 @@ const SettingClash = ({ onError }: Props) => {
ipv6 = false,
"allow-lan": allowLan = false,
"log-level": logLevel = "silent",
"mixed-port": mixedPort = 7890,
"mixed-port": thePort = 0,
} = clashConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value;
const setPort = useSetRecoilState(atomClashPort);
const [mixedPort, setMixedPort] = useState(thePort);
useEffect(() => setMixedPort(thePort), [thePort]);
const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<ApiType.ConfigData>) => {
mutate("getClashConfig", { ...clashConfig, ...patch }, false);
};
const onUpdateData = async (patch: Partial<ApiType.ConfigData>) => {
await updateConfigs(patch);
await patchClashConfig(patch);
};
return (
<List>
<ListSubheader sx={{ background: "transparent" }}>
Clash设置
</ListSubheader>
// restart clash when port is changed
const { run: onUpdatePort } = useDebounceFn(
async (port: number) => {
(async () => {
if (port < 1000) {
throw new Error("The port should not < 1000");
}
if (port > 65536) {
throw new Error("The port should not > 65536");
}
await patchClashConfig({ "mixed-port": port });
onChangeData({ "mixed-port": port });
setPort(port);
Notice.success("Change Clash port successfully!");
})().catch((err: any) => {
setMixedPort(thePort); // back to old port value
Notice.error(err.message ?? err.toString());
});
},
{ wait: 1000 }
);
return (
<SettingList title="Clash Setting">
<SettingItem>
<ListItemText primary="局域网连接" />
<ListItemText primary="Allow Lan" />
<GuardState
value={allowLan}
valueProps="checked"
@@ -75,7 +99,7 @@ const SettingClash = ({ onError }: Props) => {
</SettingItem>
<SettingItem>
<ListItemText primary="日志等级" />
<ListItemText primary="Log Level" />
<GuardState
value={logLevel}
onCatch={onError}
@@ -94,15 +118,17 @@ const SettingClash = ({ onError }: Props) => {
</SettingItem>
<SettingItem>
<ListItemText primary="混合代理端口" />
<TextField
size="small"
<ListItemText primary="Mixed Port" />
<GuardState
value={mixedPort!}
sx={{ width: 120 }}
disabled
/>
onFormat={(e: any) => +e.target.value?.replace(/\D+/, "")}
onChange={setMixedPort}
onGuard={onUpdatePort}
>
<TextField autoComplete="off" size="small" sx={{ width: 120 }} />
</GuardState>
</SettingItem>
</List>
</SettingList>
);
};

View File

@@ -0,0 +1,67 @@
import useSWR, { useSWRConfig } from "swr";
import { Box, ListItemText, Switch } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import { SettingList, SettingItem } from "./setting";
import { CmdType } from "../../services/types";
import GuardState from "./guard-state";
import SysproxyTooltip from "./sysproxy-tooltip";
interface Props {
onError?: (err: Error) => void;
}
const SettingSystem = ({ onError }: Props) => {
const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const {
enable_auto_launch: startup = false,
enable_system_proxy: proxy = false,
} = vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
};
return (
<SettingList title="System Setting">
<SettingItem>
<ListItemText primary="Auto Launch" />
<GuardState
value={startup}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_auto_launch: e })}
onGuard={(e) => patchVergeConfig({ enable_auto_launch: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText
primary={
<Box sx={{ display: "flex", alignItems: "center" }}>
System Proxy
<SysproxyTooltip />
</Box>
}
/>
<GuardState
value={proxy}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_system_proxy: e })}
onGuard={(e) => patchVergeConfig({ enable_system_proxy: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
</SettingList>
);
};
export default SettingSystem;

View File

@@ -0,0 +1,66 @@
import useSWR, { useSWRConfig } from "swr";
import { ListItemText, Switch, Typography } from "@mui/material";
import { getVergeConfig, patchVergeConfig } from "../../services/cmds";
import { SettingList, SettingItem } from "./setting";
import { CmdType } from "../../services/types";
import { version } from "../../../package.json";
import GuardState from "./guard-state";
import PaletteSwitch from "./palette-switch";
interface Props {
onError?: (err: Error) => void;
}
const SettingVerge = ({ onError }: Props) => {
const { mutate } = useSWRConfig();
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
const { theme_mode: mode = "light", theme_blur: blur = false } =
vergeConfig ?? {};
const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<CmdType.VergeConfig>) => {
mutate("getVergeConfig", { ...vergeConfig, ...patch }, false);
};
return (
<SettingList title="Verge Setting">
<SettingItem>
<ListItemText primary="Theme Mode" />
<GuardState
value={mode === "dark"}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ theme_mode: e ? "dark" : "light" })}
onGuard={(c) =>
patchVergeConfig({ theme_mode: c ? "dark" : "light" })
}
>
<PaletteSwitch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="Theme Blur" />
<GuardState
value={blur}
valueProps="checked"
onCatch={onError}
onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ theme_blur: e })}
onGuard={(e) => patchVergeConfig({ theme_blur: e })}
>
<Switch edge="end" />
</GuardState>
</SettingItem>
<SettingItem>
<ListItemText primary="Version" />
<Typography sx={{ py: "6px" }}>v{version}</Typography>
</SettingItem>
</SettingList>
);
};
export default SettingVerge;

View File

@@ -0,0 +1,17 @@
import React from "react";
import { List, ListItem, ListSubheader, styled } from "@mui/material";
export const SettingItem = styled(ListItem)(() => ({
paddingTop: 5,
paddingBottom: 5,
}));
export const SettingList: React.FC<{ title: string }> = (props) => (
<List>
<ListSubheader sx={{ background: "transparent" }} disableSticky>
{props.title}
</ListSubheader>
{props.children}
</List>
);

View File

@@ -0,0 +1,52 @@
import { useEffect, useState } from "react";
import { InfoRounded } from "@mui/icons-material";
import { ClickAwayListener, Tooltip } from "@mui/material";
import { getSystemProxy } from "../../services/cmds";
const SysproxyTooltip = () => {
const [open, setOpen] = useState(false);
const [info, setInfo] = useState<any>({});
const onShow = async () => {
const data = await getSystemProxy();
setInfo(data ?? {});
setOpen(true);
};
useEffect(() => {
if (!open) return;
const timer = setTimeout(() => setOpen(false), 2000);
return () => clearTimeout(timer);
}, [open]);
// todo: add error info
const showTitle = (
<div>
<div>Enable: {(!!info.enable).toString()}</div>
<div>Server: {info.server}</div>
<div>Bypass: {info.bypass}</div>
</div>
);
return (
<ClickAwayListener onClickAway={() => setOpen(false)}>
<Tooltip
PopperProps={{
disablePortal: true,
}}
onClose={() => setOpen(false)}
open={open}
disableFocusListener
disableHoverListener
disableTouchListener
placement="top"
title={showTitle}
arrow
>
<InfoRounded fontSize="small" onClick={onShow} />
</Tooltip>
</ClickAwayListener>
);
};
export default SysproxyTooltip;

View File

@@ -1,11 +1,14 @@
import { useEffect, useState } from "react";
import { useRecoilValue } from "recoil";
import { Box, Typography } from "@mui/material";
import { ArrowDownward, ArrowUpward } from "@mui/icons-material";
import { getInfomation } from "../services/api";
import { ApiType } from "../services/types";
import { atomClashPort } from "../states/setting";
import parseTraffic from "../utils/parse-traffic";
const Traffic = () => {
const portValue = useRecoilValue(atomClashPort);
const [traffic, setTraffic] = useState({ up: 0, down: 0 });
useEffect(() => {
@@ -21,7 +24,7 @@ const Traffic = () => {
});
return () => ws?.close();
}, []);
}, [portValue]);
const [up, upUnit] = parseTraffic(traffic.up);
const [down, downUnit] = parseTraffic(traffic.down);

View File

@@ -0,0 +1,40 @@
import useSWR from "swr";
import { useState } from "react";
import { Button } from "@mui/material";
import { checkUpdate } from "@tauri-apps/api/updater";
import UpdateDialog from "./update-dialog";
interface Props {
className?: string;
}
const UpdateButton = (props: Props) => {
const { className } = props;
const [dialogOpen, setDialogOpen] = useState(false);
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
errorRetryCount: 2,
revalidateIfStale: false,
focusThrottleInterval: 36e5, // 1 hour
});
if (!updateInfo?.shouldUpdate) return null;
return (
<>
<Button
color="error"
variant="contained"
size="small"
className={className}
onClick={() => setDialogOpen(true)}
>
New
</Button>
<UpdateDialog open={dialogOpen} onClose={() => setDialogOpen(false)} />
</>
);
};
export default UpdateButton;

View File

@@ -0,0 +1,66 @@
import useSWR from "swr";
import { useState } from "react";
import { checkUpdate, installUpdate } from "@tauri-apps/api/updater";
import { relaunch } from "@tauri-apps/api/process";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
} from "@mui/material";
interface Props {
open: boolean;
onClose: () => void;
}
let uploadingState = false;
const UpdateDialog = (props: Props) => {
const { open, onClose } = props;
const { data: updateInfo } = useSWR("checkUpdate", checkUpdate, {
errorRetryCount: 2,
revalidateIfStale: false,
focusThrottleInterval: 36e5, // 1 hour
});
const [uploading, setUploading] = useState(uploadingState);
const onUpdate = async () => {
try {
setUploading(true);
uploadingState = true;
await installUpdate();
await relaunch();
} catch (error) {
console.log(error);
window.alert("Failed to upload, please try again.");
} finally {
setUploading(true);
uploadingState = true;
}
};
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>New Version v{updateInfo?.manifest?.version}</DialogTitle>
<DialogContent sx={{ minWidth: 360, maxWidth: 400, maxHeight: "50vh" }}>
<DialogContentText>{updateInfo?.manifest?.body}</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={onClose}>Cancel</Button>
<Button
variant="contained"
autoFocus
onClick={onUpdate}
disabled={uploading}
>
Update
</Button>
</DialogActions>
</Dialog>
);
};
export default UpdateDialog;

View File

@@ -1,99 +1,95 @@
import useSWR, { SWRConfig, useSWRConfig } from "swr";
import { useEffect, useMemo } from "react";
import useSWR, { SWRConfig } from "swr";
import { Route, Routes } from "react-router-dom";
import { useRecoilState } from "recoil";
import { createTheme, List, Paper, ThemeProvider } from "@mui/material";
import { atomPaletteMode } from "../states/setting";
import { alpha, createTheme, List, Paper, ThemeProvider } from "@mui/material";
import { listen } from "@tauri-apps/api/event";
import { appWindow } from "@tauri-apps/api/window";
import { atomPaletteMode, atomThemeBlur } from "../states/setting";
import { getVergeConfig } from "../services/cmds";
import { getAxios } from "../services/api";
import { routers } from "./_routers";
import LogoSvg from "../assets/image/logo.svg";
import LogPage from "./log";
import HomePage from "./home";
import ProfilePage from "./profile";
import ProxyPage from "./proxy";
import SettingPage from "./setting";
import ConnectionsPage from "./connections";
import LayoutItem from "../components/layout-item";
import Traffic from "../components/traffic";
const routers = [
{
label: "代理",
link: "/proxy",
},
{
label: "配置",
link: "/profile",
},
{
label: "连接",
link: "/connections",
},
{
label: "日志",
link: "/log",
},
{
label: "设置",
link: "/setting",
},
];
import LayoutItem from "../components/layout-item";
import UpdateButton from "../components/update-button";
import LayoutControl from "../components/layout-control";
const Layout = () => {
const { mutate } = useSWRConfig();
const [mode, setMode] = useRecoilState(atomPaletteMode);
const [blur, setBlur] = useRecoilState(atomThemeBlur);
const { data: vergeConfig } = useSWR("getVergeConfig", getVergeConfig);
useEffect(() => {
setMode(vergeConfig?.theme_mode ?? "light");
}, [vergeConfig?.theme_mode]);
window.addEventListener("keydown", (e) => {
if (e.key === "Escape") appWindow.hide();
});
listen("restart_clash", async () => {
// the clash info may be updated
await getAxios(true);
// make sure that the clash is ok
setTimeout(() => mutate("getProxies"), 1000);
setTimeout(() => mutate("getProxies"), 2000);
mutate("getClashConfig");
});
}, []);
useEffect(() => {
if (!vergeConfig) return;
setBlur(!!vergeConfig.theme_blur);
setMode(vergeConfig.theme_mode ?? "light");
}, [vergeConfig]);
const theme = useMemo(() => {
if (mode === "light") {
document.documentElement.style.background = "#f5f5f5";
document.documentElement.style.setProperty(
"--selection-color",
"#f5f5f5"
);
} else {
document.documentElement.style.background = "#000";
document.documentElement.style.setProperty(
"--selection-color",
"#d5d5d5"
);
}
// const background = mode === "light" ? "#f5f5f5" : "#000";
const selectColor = mode === "light" ? "#f5f5f5" : "#d5d5d5";
const rootEle = document.documentElement;
rootEle.style.background = "transparent";
rootEle.style.setProperty("--selection-color", selectColor);
return createTheme({
breakpoints: {
values: {
xs: 0,
sm: 650,
md: 900,
lg: 1200,
xl: 1536,
},
values: { xs: 0, sm: 650, md: 900, lg: 1200, xl: 1536 },
},
palette: {
mode,
primary: {
main: "#5b5c9d",
},
text: {
primary: "#637381",
secondary: "#909399",
},
primary: { main: "#5b5c9d" },
text: { primary: "#637381", secondary: "#909399" },
},
});
}, [mode]);
const onDragging = (e: any) => {
if (e?.target?.dataset?.windrag) {
appWindow.startDragging();
}
};
return (
<SWRConfig value={{}}>
<ThemeProvider theme={theme}>
<Paper square elevation={0} className="layout">
<div className="layout__sidebar">
<div className="layout__logo">
<img src={LogoSvg} width="100%" alt="" />
<Paper
square
elevation={0}
className="layout"
onPointerDown={onDragging}
sx={[
(theme) => ({
bgcolor: alpha(theme.palette.background.paper, blur ? 0.85 : 1),
}),
]}
>
<div className="layout__left" data-windrag>
<div className="the-logo" data-windrag>
<img src={LogoSvg} alt="" data-windrag />
<UpdateButton className="the-newbtn" />
</div>
<List sx={{ userSelect: "none" }}>
<List className="the-menu" data-windrag>
{routers.map((router) => (
<LayoutItem key={router.label} to={router.link}>
{router.label}
@@ -101,20 +97,23 @@ const Layout = () => {
))}
</List>
<div className="layout__traffic">
<div className="the-traffic" data-windrag>
<Traffic />
</div>
</div>
<div className="layout__content">
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/proxy" element={<ProxyPage />} />
<Route path="/profile" element={<ProfilePage />} />
<Route path="/log" element={<LogPage />} />
<Route path="/connections" element={<ConnectionsPage />} />
<Route path="/setting" element={<SettingPage />} />
</Routes>
<div className="layout__right" data-windrag>
<div className="the-bar">
<LayoutControl />
</div>
<div className="the-content">
<Routes>
{routers.map(({ label, link, ele: Ele }) => (
<Route key={label} path={link} element={<Ele />} />
))}
</Routes>
</div>
</div>
</Paper>
</ThemeProvider>

33
src/pages/_routers.tsx Normal file
View File

@@ -0,0 +1,33 @@
import LogsPage from "./logs";
import ProxiesPage from "./proxies";
import ProfilesPage from "./profiles";
import SettingsPage from "./settings";
import ConnectionsPage from "./connections";
export const routers = [
{
label: "Proxies",
link: "/",
ele: ProxiesPage,
},
{
label: "Profiles",
link: "/profile",
ele: ProfilesPage,
},
{
label: "Connections",
link: "/connections",
ele: ConnectionsPage,
},
{
label: "Logs",
link: "/logs",
ele: LogsPage,
},
{
label: "Settings",
link: "/settings",
ele: SettingsPage,
},
];

View File

@@ -1,8 +1,9 @@
import { useEffect, useState } from "react";
import { Box, Paper, Typography } from "@mui/material";
import { Paper } from "@mui/material";
import { Virtuoso } from "react-virtuoso";
import { getInfomation } from "../services/api";
import { ApiType } from "../services/types";
import { getInfomation } from "../services/api";
import BasePage from "../components/base-page";
import ConnectionItem from "../components/connection-item";
const ConnectionsPage = () => {
@@ -26,25 +27,14 @@ const ConnectionsPage = () => {
}, []);
return (
<Box
sx={{
width: 0.9,
maxWidth: "850px",
height: "100%",
mx: "auto",
}}
>
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
Connections
</Typography>
<Paper sx={{ boxShadow: 2, height: "calc(100% - 100px)" }}>
<BasePage title="Connections" contentStyle={{ height: "100%" }}>
<Paper sx={{ boxShadow: 2, height: "100%" }}>
<Virtuoso
data={conn.connections}
itemContent={(index, item) => <ConnectionItem value={item} />}
/>
</Paper>
</Box>
</BasePage>
);
};

View File

@@ -1,11 +0,0 @@
import { Typography } from "@mui/material";
const HomePage = () => {
return (
<Typography variant="h1" textAlign="center" mt={10}>
Hello Clash!
</Typography>
);
};
export default HomePage;

View File

@@ -1,9 +1,10 @@
import dayjs from "dayjs";
import { useEffect, useRef, useState } from "react";
import { Box, Button, Paper, Typography } from "@mui/material";
import { useEffect, useState } from "react";
import { Button, Paper } from "@mui/material";
import { Virtuoso } from "react-virtuoso";
import { ApiType } from "../services/types";
import { getInfomation } from "../services/api";
import BasePage from "../components/base-page";
import LogItem from "../components/log-item";
let logCache: ApiType.LogItem[] = [];
@@ -28,33 +29,27 @@ const LogPage = () => {
return () => ws?.close();
}, []);
const onClear = () => {
setLogData([]);
logCache = [];
};
return (
<Box
sx={{
position: "relative",
width: 0.9,
maxWidth: "850px",
height: "100%",
mx: "auto",
}}
<BasePage
title="Logs"
contentStyle={{ height: "100%" }}
header={
<Button
size="small"
sx={{ mt: 1 }}
variant="contained"
onClick={onClear}
>
Clear
</Button>
}
>
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
Logs
</Typography>
<Button
size="small"
variant="contained"
sx={{ position: "absolute", top: 22, right: 0 }}
onClick={() => {
setLogData([]);
logCache = [];
}}
>
Clear
</Button>
<Paper sx={{ boxShadow: 2, height: "calc(100% - 100px)" }}>
<Paper sx={{ boxShadow: 2, height: "100%" }}>
<Virtuoso
initialTopMostItemIndex={999}
data={logData}
@@ -62,7 +57,7 @@ const LogPage = () => {
followOutput={"smooth"}
/>
</Paper>
</Box>
</BasePage>
);
};

View File

@@ -1,6 +1,6 @@
import { useEffect, useRef, useState } from "react";
import useSWR, { useSWRConfig } from "swr";
import { Box, Button, Grid, TextField, Typography } from "@mui/material";
import { useEffect, useRef, useState } from "react";
import { Box, Button, Grid, TextField } from "@mui/material";
import {
getProfiles,
selectProfile,
@@ -8,14 +8,14 @@ import {
importProfile,
} from "../services/cmds";
import { getProxies, updateProxy } from "../services/api";
import ProfileItemComp from "../components/profile-item";
import useNotice from "../utils/use-notice";
import noop from "../utils/noop";
import Notice from "../components/notice";
import BasePage from "../components/base-page";
import ProfileItem from "../components/profile-item";
const ProfilePage = () => {
const [url, setUrl] = useState("");
const [disabled, setDisabled] = useState(false);
const [notice, noticeElement] = useNotice();
const { mutate } = useSWRConfig();
const { data: profiles = {} } = useSWR("getProfiles", getProfiles);
@@ -24,16 +24,20 @@ const ProfilePage = () => {
if (profiles.current == null) return;
if (!profiles.items) profiles.items = [];
const profile = profiles.items![profiles.current];
const current = profiles.current;
const profile = profiles.items![current];
if (!profile) return;
getProxies().then((proxiesData) => {
setTimeout(async () => {
const proxiesData = await getProxies();
mutate("getProxies", proxiesData);
// init selected array
const { selected = [] } = profile;
const selectedMap = Object.fromEntries(
selected.map((each) => [each.name!, each.now!])
);
// todo: enhance error handle
let hasChange = false;
proxiesData.groups.forEach((group) => {
@@ -52,10 +56,10 @@ const ProfilePage = () => {
name,
now,
}));
patchProfile(profiles.current!, profile).catch(console.error);
patchProfile(current!, profile).catch(console.error);
// update proxies cache
if (hasChange) mutate("getProxies", getProxies());
});
}, 100);
}, [profiles]);
const onImport = async () => {
@@ -67,37 +71,31 @@ const ProfilePage = () => {
await importProfile(url);
mutate("getProfiles", getProfiles());
if (!profiles.items?.length) selectProfile(0).catch(noop);
notice.success("Successfully import profile.");
Notice.success("Successfully import profile.");
} catch {
notice.error("Failed to import profile.");
Notice.error("Failed to import profile.");
} finally {
setDisabled(false);
}
};
const lockRef = useRef(false);
const onProfileChange = (index: number) => {
if (index === profiles.current || lockRef.current) return;
const onSelect = async (index: number, force: boolean) => {
if (lockRef.current) return;
if (!force && index === profiles.current) return;
lockRef.current = true;
selectProfile(index)
.then(() => {
mutate("getProfiles", { ...profiles, current: index }, true);
})
.catch((err) => {
console.error(err);
})
.finally(() => {
lockRef.current = false;
});
try {
await selectProfile(index);
mutate("getProfiles", { ...profiles, current: index }, true);
} catch (err: any) {
err && Notice.error(err.toString());
} finally {
lockRef.current = false;
}
};
return (
<Box sx={{ width: 0.9, maxWidth: "850px", mx: "auto", mb: 2 }}>
<Typography variant="h4" component="h1" sx={{ py: 2, mb: 1 }}>
Profiles
</Typography>
<BasePage title="Profiles">
<Box sx={{ display: "flex", mb: 3 }}>
<TextField
id="profile_url"
@@ -107,7 +105,7 @@ const ProfilePage = () => {
fullWidth
value={url}
onChange={(e) => setUrl(e.target.value)}
sx={{ mr: 4 }}
sx={{ mr: 2 }}
/>
<Button
disabled={!url || disabled}
@@ -121,18 +119,16 @@ const ProfilePage = () => {
<Grid container spacing={3}>
{profiles?.items?.map((item, idx) => (
<Grid item xs={12} sm={6} key={item.file}>
<ProfileItemComp
<ProfileItem
index={idx}
selected={profiles.current === idx}
itemData={item}
onClick={() => onProfileChange(idx)}
onSelect={(f) => onSelect(idx, f)}
/>
</Grid>
))}
</Grid>
{noticeElement}
</Box>
</BasePage>
);
};

130
src/pages/proxies.tsx Normal file
View File

@@ -0,0 +1,130 @@
import useSWR, { useSWRConfig } from "swr";
import { useEffect, useMemo, useRef, useState } from "react";
import { Virtuoso } from "react-virtuoso";
import { Button, ButtonGroup, List, Paper } from "@mui/material";
import { getClashConfig, updateConfigs, updateProxy } from "../services/api";
import { patchClashConfig } from "../services/cmds";
import { getProxies } from "../services/api";
import BasePage from "../components/base-page";
import ProxyItem from "../components/proxy-item";
import ProxyGroup from "../components/proxy-group";
const ProxyPage = () => {
const { mutate } = useSWRConfig();
const { data: proxiesData } = useSWR("getProxies", getProxies);
const { data: clashConfig } = useSWR("getClashConfig", getClashConfig);
const [curProxy, setCurProxy] = useState<string>("DIRECT");
const curMode = clashConfig?.mode.toLowerCase();
// proxy groups
const { groups = [] } = proxiesData ?? {};
// proxies and sorted
const filterProxies = useMemo(() => {
if (!proxiesData?.proxies) return [];
const list = Object.values(proxiesData.proxies);
const retList = list.filter(
(p) => !p.all?.length && p.name !== "DIRECT" && p.name !== "REJECT"
);
const direct = list.filter((p) => p.name === "DIRECT");
const reject = list.filter((p) => p.name === "REJECT");
return direct.concat(retList).concat(reject);
}, [proxiesData]);
const modeList = ["rule", "global", "direct"];
const asGroup = curMode === "rule" || !groups.length;
// make sure that fetch the proxies successfully
useEffect(() => {
if (
(curMode === "rule" && !groups.length) ||
(curMode === "global" && filterProxies.length < 4)
) {
setTimeout(() => mutate("getProxies"), 500);
}
}, [groups, filterProxies, curMode]);
// update the current proxy
useEffect(() => {
if (curMode === "direct") setCurProxy("DIRECT");
if (curMode === "global") {
const globalNow = proxiesData?.proxies?.GLOBAL?.now;
setCurProxy(globalNow || "DIRECT");
}
}, [curMode, proxiesData]);
const changeLockRef = useRef(false);
const onChangeMode = async (mode: string) => {
if (changeLockRef.current) return;
changeLockRef.current = true;
try {
// switch rapidly
await updateConfigs({ mode });
await patchClashConfig({ mode });
mutate("getClashConfig");
} finally {
changeLockRef.current = false;
}
};
const onChangeProxy = async (name: string) => {
if (curMode !== "global") return;
await updateProxy("GLOBAL", name);
setCurProxy(name);
};
// difference style
const pageStyle = asGroup ? {} : { height: "100%" };
const paperStyle: any = asGroup
? { mb: 0.5 }
: { py: 1, height: "100%", boxSizing: "border-box" };
return (
<BasePage
contentStyle={pageStyle}
title={asGroup ? "Proxy Groups" : "Proxies"}
header={
<ButtonGroup size="small">
{modeList.map((mode) => (
<Button
key={mode}
variant={mode === curMode ? "contained" : "outlined"}
onClick={() => onChangeMode(mode)}
sx={{ textTransform: "capitalize" }}
>
{mode}
</Button>
))}
</ButtonGroup>
}
>
<Paper sx={{ borderRadius: 1, boxShadow: 2, ...paperStyle }}>
{asGroup ? (
<List>
{groups.map((group) => (
<ProxyGroup key={group.name} group={group} />
))}
</List>
) : (
// virtual list
<Virtuoso
style={{ height: "100%" }}
totalCount={filterProxies.length}
itemContent={(index) => (
<ProxyItem
proxy={filterProxies[index]}
selected={filterProxies[index].name === curProxy}
onClick={onChangeProxy}
sx={{ py: 0, px: 2 }}
/>
)}
/>
)}
</Paper>
</BasePage>
);
};
export default ProxyPage;

View File

@@ -1,29 +0,0 @@
import useSWR from "swr";
import { Box, List, Paper, Typography } from "@mui/material";
import { getProxies } from "../services/api";
import ProxyGroup from "../components/proxy-group";
const ProxyPage = () => {
const { data: proxiesData } = useSWR("getProxies", getProxies);
const { groups = [] } = proxiesData ?? {};
return (
<Box sx={{ width: 0.9, maxWidth: "850px", mx: "auto", mb: 2 }}>
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
Proxy Groups
</Typography>
{groups.length > 0 && (
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
<List>
{groups.map((group) => (
<ProxyGroup key={group.name} group={group} />
))}
</List>
</Paper>
)}
</Box>
);
};
export default ProxyPage;

View File

@@ -1,23 +0,0 @@
import { Box, Paper, Typography } from "@mui/material";
import SettingVerge from "../components/setting-verge";
import SettingClash from "../components/setting-clash";
const SettingPage = () => {
return (
<Box sx={{ width: 0.9, maxWidth: 850, mx: "auto", mb: 2 }}>
<Typography variant="h4" component="h1" sx={{ py: 2 }}>
Setting
</Typography>
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
<SettingVerge />
</Paper>
<Paper sx={{ borderRadius: 1, boxShadow: 2, mt: 3 }}>
<SettingClash />
</Paper>
</Box>
);
};
export default SettingPage;

30
src/pages/settings.tsx Normal file
View File

@@ -0,0 +1,30 @@
import { Paper } from "@mui/material";
import BasePage from "../components/base-page";
import SettingVerge from "../components/setting/setting-verge";
import SettingClash from "../components/setting/setting-clash";
import SettingSystem from "../components/setting/setting-system";
import Notice from "../components/notice";
const SettingPage = () => {
const onError = (error: any) => {
error && Notice.error(error.toString());
};
return (
<BasePage title="Settings">
<Paper sx={{ borderRadius: 1, boxShadow: 2, mb: 3 }}>
<SettingClash onError={onError} />
</Paper>
<Paper sx={{ borderRadius: 1, boxShadow: 2, mb: 3 }}>
<SettingSystem onError={onError} />
</Paper>
<Paper sx={{ borderRadius: 1, boxShadow: 2 }}>
<SettingVerge onError={onError} />
</Paper>
</BasePage>
);
};
export default SettingPage;

View File

@@ -7,8 +7,9 @@ let server = "";
let secret = "";
/// initialize some infomation
export async function getAxios() {
if (axiosIns) return axiosIns;
/// enable force update axiosIns
export async function getAxios(force: boolean = false) {
if (axiosIns && !force) return axiosIns;
try {
const info = await getClashInfo();

View File

@@ -9,12 +9,16 @@ export async function syncProfiles() {
return invoke<void>("sync_profiles");
}
export async function importProfile(url: string) {
return invoke<void>("import_profile", { url });
export async function viewProfile(index: number) {
return invoke<void>("view_profile", { index });
}
export async function updateProfile(index: number) {
return invoke<void>("update_profile", { index });
export async function importProfile(url: string) {
return invoke<void>("import_profile", { url, withProxy: true });
}
export async function updateProfile(index: number, withProxy: boolean) {
return invoke<void>("update_profile", { index, withProxy });
}
export async function deleteProfile(index: number) {
@@ -44,10 +48,6 @@ export async function patchClashConfig(payload: Partial<ApiType.ConfigData>) {
return invoke<void>("patch_clash_config", { payload });
}
export async function setSysProxy(enable: boolean) {
return invoke<void>("set_sys_proxy", { enable });
}
export async function getVergeConfig() {
return invoke<CmdType.VergeConfig>("get_verge_config");
}
@@ -55,3 +55,7 @@ export async function getVergeConfig() {
export async function patchVergeConfig(payload: CmdType.VergeConfig) {
return invoke<void>("patch_verge_config", { payload });
}
export async function getSystemProxy() {
return invoke<any>("get_sys_proxy");
}

View File

@@ -110,7 +110,8 @@ export namespace CmdType {
export interface VergeConfig {
theme_mode?: "light" | "dark";
enable_self_startup?: boolean;
theme_blur?: boolean;
enable_auto_launch?: boolean;
enable_system_proxy?: boolean;
}
}

View File

@@ -4,3 +4,13 @@ export const atomPaletteMode = atom<"light" | "dark">({
key: "atomPaletteMode",
default: "light",
});
export const atomThemeBlur = atom<boolean>({
key: "atomThemeBlur",
default: false,
});
export const atomClashPort = atom<number>({
key: "atomClashPort",
default: 0,
});

View File

@@ -1,68 +0,0 @@
import { useMemo, useState } from "react";
import { Box, IconButton, Slide, Snackbar } from "@mui/material";
import { Close, CheckCircleRounded, ErrorRounded } from "@mui/icons-material";
interface NoticeInstance {
info: (msg: string) => void;
error: (msg: string) => void;
success: (msg: string) => void;
}
const useNotice = () => {
const [message, setMessage] = useState("");
const [level, setLevel] = useState<"info" | "error" | "success">("info");
const handleClose = (_e: any, reason: string) => {
if (reason !== "clickaway") setMessage("");
};
const msgElement =
level === "info" ? (
message
) : (
<Box sx={{ display: "flex", alignItems: "center" }}>
{level === "error" && <ErrorRounded color="error" />}
{level === "success" && <CheckCircleRounded color="success" />}
<span style={{ marginLeft: 4 }}>{message}</span>
</Box>
);
const element = useMemo(
() => (
<Snackbar
open={!!message}
anchorOrigin={{ vertical: "top", horizontal: "right" }}
autoHideDuration={3000}
onClose={handleClose}
message={msgElement}
sx={{ maxWidth: 360 }}
TransitionComponent={(p) => <Slide {...p} direction="left" />}
transitionDuration={200}
action={
<IconButton
size="small"
color="inherit"
onClick={() => setMessage("")}
>
<Close fontSize="small" />
</IconButton>
}
/>
),
[message]
);
const instance = (Object.fromEntries(
(["info", "error", "success"] as const).map((item) => [
item,
(msg: string) => {
setLevel(item);
setMessage(msg);
},
])
) as unknown) as NoticeInstance;
return [instance, element] as const;
};
export default useNotice;

198
yarn.lock
View File

@@ -2,6 +2,23 @@
# yarn lockfile v1
"@actions/github@^5.0.0":
version "5.0.0"
resolved "https://registry.yarnpkg.com/@actions/github/-/github-5.0.0.tgz#1754127976c50bd88b2e905f10d204d76d1472f8"
integrity sha512-QvE9eAAfEsS+yOOk0cylLBIO/d6WyWIOvsxxzdrPFaud39G6BOkUwScXZn1iBzQzHyu9SBkkLSWlohDWdsasAQ==
dependencies:
"@actions/http-client" "^1.0.11"
"@octokit/core" "^3.4.0"
"@octokit/plugin-paginate-rest" "^2.13.3"
"@octokit/plugin-rest-endpoint-methods" "^5.1.1"
"@actions/http-client@^1.0.11":
version "1.0.11"
resolved "https://registry.yarnpkg.com/@actions/http-client/-/http-client-1.0.11.tgz#c58b12e9aa8b159ee39e7dd6cbd0e91d905633c0"
integrity sha512-VRYHGQV1rqnROJqdMvGUbY/Kn8vriQe/F9HR2AlYHzmKuM/p3kjNuXhmdBfcVgsvRWTz5C5XW5xvndZrVBuAYg==
dependencies:
tunnel "0.0.6"
"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.16.0":
version "7.16.0"
resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.16.0.tgz#0dfc80309beec8411e65e706461c408b0bb9b431"
@@ -467,6 +484,92 @@
"@nodelib/fs.scandir" "2.1.5"
fastq "^1.6.0"
"@octokit/auth-token@^2.4.4":
version "2.5.0"
resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-2.5.0.tgz#27c37ea26c205f28443402477ffd261311f21e36"
integrity sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g==
dependencies:
"@octokit/types" "^6.0.3"
"@octokit/core@^3.4.0":
version "3.5.1"
resolved "https://registry.yarnpkg.com/@octokit/core/-/core-3.5.1.tgz#8601ceeb1ec0e1b1b8217b960a413ed8e947809b"
integrity sha512-omncwpLVxMP+GLpLPgeGJBF6IWJFjXDS5flY5VbppePYX9XehevbDykRH9PdCdvqt9TS5AOTiDide7h0qrkHjw==
dependencies:
"@octokit/auth-token" "^2.4.4"
"@octokit/graphql" "^4.5.8"
"@octokit/request" "^5.6.0"
"@octokit/request-error" "^2.0.5"
"@octokit/types" "^6.0.3"
before-after-hook "^2.2.0"
universal-user-agent "^6.0.0"
"@octokit/endpoint@^6.0.1":
version "6.0.12"
resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-6.0.12.tgz#3b4d47a4b0e79b1027fb8d75d4221928b2d05658"
integrity sha512-lF3puPwkQWGfkMClXb4k/eUT/nZKQfxinRWJrdZaJO85Dqwo/G0yOC434Jr2ojwafWJMYqFGFa5ms4jJUgujdA==
dependencies:
"@octokit/types" "^6.0.3"
is-plain-object "^5.0.0"
universal-user-agent "^6.0.0"
"@octokit/graphql@^4.5.8":
version "4.8.0"
resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.8.0.tgz#664d9b11c0e12112cbf78e10f49a05959aa22cc3"
integrity sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg==
dependencies:
"@octokit/request" "^5.6.0"
"@octokit/types" "^6.0.3"
universal-user-agent "^6.0.0"
"@octokit/openapi-types@^11.2.0":
version "11.2.0"
resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-11.2.0.tgz#b38d7fc3736d52a1e96b230c1ccd4a58a2f400a6"
integrity sha512-PBsVO+15KSlGmiI8QAzaqvsNlZlrDlyAJYcrXBCvVUxCp7VnXjkwPoFHgjEJXx3WF9BAwkA6nfCUA7i9sODzKA==
"@octokit/plugin-paginate-rest@^2.13.3":
version "2.17.0"
resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.17.0.tgz#32e9c7cab2a374421d3d0de239102287d791bce7"
integrity sha512-tzMbrbnam2Mt4AhuyCHvpRkS0oZ5MvwwcQPYGtMv4tUa5kkzG58SVB0fcsLulOZQeRnOgdkZWkRUiyBlh0Bkyw==
dependencies:
"@octokit/types" "^6.34.0"
"@octokit/plugin-rest-endpoint-methods@^5.1.1":
version "5.13.0"
resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.13.0.tgz#8c46109021a3412233f6f50d28786f8e552427ba"
integrity sha512-uJjMTkN1KaOIgNtUPMtIXDOjx6dGYysdIFhgA52x4xSadQCz3b/zJexvITDVpANnfKPW/+E0xkOvLntqMYpviA==
dependencies:
"@octokit/types" "^6.34.0"
deprecation "^2.3.1"
"@octokit/request-error@^2.0.5", "@octokit/request-error@^2.1.0":
version "2.1.0"
resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-2.1.0.tgz#9e150357831bfc788d13a4fd4b1913d60c74d677"
integrity sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg==
dependencies:
"@octokit/types" "^6.0.3"
deprecation "^2.0.0"
once "^1.4.0"
"@octokit/request@^5.6.0":
version "5.6.2"
resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.6.2.tgz#1aa74d5da7b9e04ac60ef232edd9a7438dcf32d8"
integrity sha512-je66CvSEVf0jCpRISxkUcCa0UkxmFs6eGDRSbfJtAVwbLH5ceqF+YEyC8lj8ystKyZTy8adWr0qmkY52EfOeLA==
dependencies:
"@octokit/endpoint" "^6.0.1"
"@octokit/request-error" "^2.1.0"
"@octokit/types" "^6.16.1"
is-plain-object "^5.0.0"
node-fetch "^2.6.1"
universal-user-agent "^6.0.0"
"@octokit/types@^6.0.3", "@octokit/types@^6.16.1", "@octokit/types@^6.34.0":
version "6.34.0"
resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.34.0.tgz#c6021333334d1ecfb5d370a8798162ddf1ae8218"
integrity sha512-s1zLBjWhdEI2zwaoSgyOFoKSl109CUcVBCc7biPJ3aAf6LGLU6szDvi31JPU7bxfla2lqfhjbbg/5DdFNxOwHw==
dependencies:
"@octokit/openapi-types" "^11.2.0"
"@popperjs/core@^2.4.4":
version "2.11.0"
resolved "https://registry.yarnpkg.com/@popperjs/core/-/core-2.11.0.tgz#6734f8ebc106a0860dff7f92bf90df193f0935d7"
@@ -571,6 +674,11 @@
resolved "https://registry.yarnpkg.com/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz#0ea7b61496902b95890dc4c3a116b60cb8dae812"
integrity sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ==
"@types/js-cookie@^3.0.1":
version "3.0.1"
resolved "https://registry.yarnpkg.com/@types/js-cookie/-/js-cookie-3.0.1.tgz#04aa743e2e0a85a22ee9aa61f6591a8bc19b5d68"
integrity sha512-7wg/8gfHltklehP+oyJnZrz9XBuX5ZPP4zB6UsI84utdlkRYLnOm2HfpLXazTwZA+fpGn0ir8tGNgVnMEleBGQ==
"@types/keyv@*":
version "3.1.3"
resolved "https://registry.yarnpkg.com/@types/keyv/-/keyv-3.1.3.tgz#1c9aae32872ec1f20dcdaee89a9f3ba88f465e41"
@@ -671,6 +779,24 @@ adm-zip@^0.5.9:
resolved "https://registry.yarnpkg.com/adm-zip/-/adm-zip-0.5.9.tgz#b33691028333821c0cf95c31374c5462f2905a83"
integrity sha512-s+3fXLkeeLjZ2kLjCBwQufpI5fuN+kIGBxu6530nVQZGVol0d7Y/M88/xw9HGGUcJjKf8LutN3VPRUBq6N7Ajg==
ahooks-v3-count@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/ahooks-v3-count/-/ahooks-v3-count-1.0.0.tgz#ddeb392e009ad6e748905b3cbf63a9fd8262ca80"
integrity sha512-V7uUvAwnimu6eh/PED4mCDjE7tokeZQLKlxg9lCTMPhN+NjsSbtdacByVlR1oluXQzD3MOw55wylDmQo4+S9ZQ==
ahooks@^3.1.7:
version "3.1.7"
resolved "https://registry.yarnpkg.com/ahooks/-/ahooks-3.1.7.tgz#e5a7096608e2d82f74eaaf9bb038a81fc097a825"
integrity sha512-H+5LCbOXs7rpHkegiBApGgI6U/Ute8P93elU+bGsgdXkUsElJjYuEmWY6RujSr/IkV/dskFb7iptce3tLbYxng==
dependencies:
ahooks-v3-count "^1.0.0"
dayjs "^1.9.1"
intersection-observer "^0.12.0"
js-cookie "^2.x.x"
lodash "^4.17.21"
resize-observer-polyfill "^1.5.1"
screenfull "^5.0.0"
ansi-align@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/ansi-align/-/ansi-align-3.0.1.tgz#0cdf12e111ace773a86e9a1fad1225c43cb19a59"
@@ -798,6 +924,11 @@ base64-js@^1.3.1:
resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a"
integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==
before-after-hook@^2.2.0:
version "2.2.2"
resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.2.2.tgz#a6e8ca41028d90ee2c24222f201c90956091613e"
integrity sha512-3pZEU3NT5BFUo/AD5ERPWOgQOCZITni6iavr5AUw5AUwQjMlI0kzu5btnyD39AF0gUEsDPwJT+oY1ORBJijPjQ==
bin-build@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/bin-build/-/bin-build-3.0.0.tgz#c5780a25a8a9f966d8244217e6c1f5082a143861"
@@ -1304,7 +1435,7 @@ data-uri-to-buffer@^4.0.0:
resolved "https://registry.yarnpkg.com/data-uri-to-buffer/-/data-uri-to-buffer-4.0.0.tgz#b5db46aea50f6176428ac05b73be39a57701a64b"
integrity sha512-Vr3mLBA8qWmcuschSLAOogKgQ/Jwxulv3RNE4FXnYWRGujzrRWQI4m12fQqRkwX06C0KanhLr4hK+GydchZsaA==
dayjs@^1.10.7:
dayjs@^1.10.7, dayjs@^1.9.1:
version "1.10.7"
resolved "https://registry.yarnpkg.com/dayjs/-/dayjs-1.10.7.tgz#2cf5f91add28116748440866a0a1d26f3a6ce468"
integrity sha512-P6twpd70BcPK34K26uJ1KT3wlhpuOAPoMwJzpsIWUxHZ7wpmbdZL/hQqBDfz7hGurYSa5PhzdhDHtt319hL3ig==
@@ -1434,6 +1565,11 @@ delegates@^1.0.0:
resolved "https://registry.yarnpkg.com/delegates/-/delegates-1.0.0.tgz#84c6e159b81904fdca59a0ef44cd870d31250f9a"
integrity sha1-hMbhWbgZBP3KWaDvRM2HDTElD5o=
deprecation@^2.0.0, deprecation@^2.3.1:
version "2.3.1"
resolved "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919"
integrity sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==
detect-libc@^1.0.3:
version "1.0.3"
resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-1.0.3.tgz#fa137c4bd698edf55cd5cd02ac559f91a4c4ba9b"
@@ -2371,6 +2507,11 @@ inquirer@8.1.2:
strip-ansi "^6.0.0"
through "^2.3.6"
intersection-observer@^0.12.0:
version "0.12.0"
resolved "https://registry.yarnpkg.com/intersection-observer/-/intersection-observer-0.12.0.tgz#6c84628f67ce8698e5f9ccf857d97718745837aa"
integrity sha512-2Vkz8z46Dv401zTWudDGwO7KiGHNDkMv417T5ItcNYfmvHR/1qCTVBO9vwH8zZmQ0WkA/1ARwpysR9bsnop4NQ==
into-stream@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/into-stream/-/into-stream-3.1.0.tgz#96fb0a936c12babd6ff1752a17d05616abd094c6"
@@ -2487,6 +2628,11 @@ is-plain-obj@^1.0.0, is-plain-obj@^1.1.0:
resolved "https://registry.yarnpkg.com/is-plain-obj/-/is-plain-obj-1.1.0.tgz#71a50c8429dfca773c92a390a4a03b39fcd51d3e"
integrity sha1-caUMhCnfync8kqOQpKA7OfzVHT4=
is-plain-object@^5.0.0:
version "5.0.0"
resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344"
integrity sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==
is-png@3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/is-png/-/is-png-3.0.0.tgz#7bf5db7f32527d10c90594a751c15f74d46c8f5e"
@@ -2550,6 +2696,11 @@ isurl@^1.0.0-alpha5:
has-to-string-tag-x "^1.2.0"
is-object "^1.0.1"
js-cookie@^2.x.x:
version "2.2.1"
resolved "https://registry.yarnpkg.com/js-cookie/-/js-cookie-2.2.1.tgz#69e106dc5d5806894562902aa5baec3744e9b2b8"
integrity sha512-HvdH2LzI/EAZcUwA8+0nKNtWHqS+ZmijLA30RwZA0bo7ToCckjK5MkGhjED9KoRcXO6BaGI3I9UIzSA1FKFPOQ==
"js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"
@@ -2893,6 +3044,13 @@ node-addon-api@^3.2.0:
resolved "https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-3.2.1.tgz#81325e0a2117789c0128dab65e7e38f07ceba161"
integrity sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A==
node-fetch@^2.6.1:
version "2.6.7"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.7.tgz#24de9fba827e3b4ae44dc8b20256a379160052ad"
integrity sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==
dependencies:
whatwg-url "^5.0.0"
node-fetch@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-3.1.0.tgz#714f4922dc270239487654eaeeab86b8206cb52e"
@@ -3553,6 +3711,11 @@ replace-ext@^2.0.0:
resolved "https://registry.yarnpkg.com/replace-ext/-/replace-ext-2.0.0.tgz#9471c213d22e1bcc26717cd6e50881d88f812b06"
integrity sha512-UszKE5KVK6JvyD92nzMn9cDapSk6w/CaFZ96CnmDMUqH9oowfxF/ZjRITD25H4DnOQClLA4/j7jLGXXLVKxAug==
resize-observer-polyfill@^1.5.1:
version "1.5.1"
resolved "https://registry.yarnpkg.com/resize-observer-polyfill/-/resize-observer-polyfill-1.5.1.tgz#0e9020dd3d21024458d4ebd27e23e40269810464"
integrity sha512-LwZrotdHOo12nQuZlHEmtuXdqGoOD0OhaxopaNFxWzInpEgaLWoVuAMbTzixuosCx2nEG58ngzW3vxdWoxIgdg==
resolve-alpn@^1.0.0:
version "1.2.1"
resolved "https://registry.yarnpkg.com/resolve-alpn/-/resolve-alpn-1.2.1.tgz#b7adbdac3546aaaec20b45e7d8265927072726f9"
@@ -3674,6 +3837,11 @@ scheduler@^0.20.2:
loose-envify "^1.1.0"
object-assign "^4.1.1"
screenfull@^5.0.0:
version "5.2.0"
resolved "https://registry.yarnpkg.com/screenfull/-/screenfull-5.2.0.tgz#6533d524d30621fc1283b9692146f3f13a93d1ba"
integrity sha512-9BakfsO2aUQN2K9Fdbj87RJIEZ82Q9IGim7FqM5OsebfoFC6ZHXgDq/KvniuLTPdeM8wY2o6Dj3WQ7KeQCj3cA==
seek-bzip@^1.0.5:
version "1.0.6"
resolved "https://registry.yarnpkg.com/seek-bzip/-/seek-bzip-1.0.6.tgz#35c4171f55a680916b52a07859ecf3b5857f21c4"
@@ -4104,6 +4272,11 @@ token-types@^4.1.1:
"@tokenizer/token" "^0.3.0"
ieee754 "^1.2.1"
tr46@~0.0.3:
version "0.0.3"
resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a"
integrity sha1-gYT9NH2snNwYWZLzpmIuFLnZq2o=
trim-newlines@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/trim-newlines/-/trim-newlines-1.0.0.tgz#5887966bb582a4503a41eb524f7d35011815a613"
@@ -4128,6 +4301,11 @@ tunnel-agent@^0.6.0:
dependencies:
safe-buffer "^5.0.1"
tunnel@0.0.6:
version "0.0.6"
resolved "https://registry.yarnpkg.com/tunnel/-/tunnel-0.0.6.tgz#72f1314b34a5b192db012324df2cc587ca47f92c"
integrity sha512-1h/Lnq9yajKY2PEbBadPXj3VxsDDu844OnaAo52UVmIzIvwwtBPIuNvkjuzBlTWpfJyUbG3ez0KSBibQkj4ojg==
type-fest@^0.13.1:
version "0.13.1"
resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.13.1.tgz#0172cb5bce80b0bd542ea348db50c7e21834d934"
@@ -4170,6 +4348,11 @@ unique-string@^2.0.0:
dependencies:
crypto-random-string "^2.0.0"
universal-user-agent@^6.0.0:
version "6.0.0"
resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee"
integrity sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==
universalify@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/universalify/-/universalify-2.0.0.tgz#75a4984efedc4b08975c5aeb73f530d02df25717"
@@ -4256,6 +4439,19 @@ web-streams-polyfill@^3.0.3:
resolved "https://registry.yarnpkg.com/web-streams-polyfill/-/web-streams-polyfill-3.2.0.tgz#a6b74026b38e4885869fb5c589e90b95ccfc7965"
integrity sha512-EqPmREeOzttaLRm5HS7io98goBgZ7IVz79aDvqjD0kYXLtFZTc0T/U6wHTPKyIjb+MdN7DFIIX6hgdBEpWmfPA==
webidl-conversions@^3.0.0:
version "3.0.1"
resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871"
integrity sha1-JFNCdeKnvGvnvIZhHMFq4KVlSHE=
whatwg-url@^5.0.0:
version "5.0.0"
resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d"
integrity sha1-lmRU6HZUYuN2RNNib2dCzotwll0=
dependencies:
tr46 "~0.0.3"
webidl-conversions "^3.0.0"
which@^1.2.9:
version "1.3.1"
resolved "https://registry.yarnpkg.com/which/-/which-1.3.1.tgz#a45043d54f5805316da8d62f9f50918d3da70b0a"