added a setting to change the proxy mode controlled by a switch on the homepage

This commit is contained in:
coolcoala
2025-07-14 05:23:02 +03:00
parent b1e3283a24
commit eb1e4fe0c3
6 changed files with 428 additions and 130 deletions

View File

@@ -74,6 +74,8 @@ pub struct IVerge {
/// enable dns settings - this controls whether dns_config.yaml is applied /// enable dns settings - this controls whether dns_config.yaml is applied
pub enable_dns_settings: Option<bool>, pub enable_dns_settings: Option<bool>,
pub primary_action: Option<String>,
/// always use default bypass /// always use default bypass
pub use_default_bypass: Option<bool>, pub use_default_bypass: Option<bool>,
@@ -401,6 +403,7 @@ impl IVerge {
enable_auto_light_weight_mode: Some(false), enable_auto_light_weight_mode: Some(false),
auto_light_weight_minutes: Some(10), auto_light_weight_minutes: Some(10),
enable_dns_settings: Some(false), enable_dns_settings: Some(false),
primary_action: Some("tun-mode".into()),
home_cards: None, home_cards: None,
service_state: None, service_state: None,
..Self::default() ..Self::default()
@@ -489,6 +492,7 @@ impl IVerge {
patch!(enable_auto_light_weight_mode); patch!(enable_auto_light_weight_mode);
patch!(auto_light_weight_minutes); patch!(auto_light_weight_minutes);
patch!(enable_dns_settings); patch!(enable_dns_settings);
patch!(primary_action);
patch!(home_cards); patch!(home_cards);
patch!(service_state); patch!(service_state);
} }
@@ -584,6 +588,7 @@ pub struct IVergeResponse {
pub enable_auto_light_weight_mode: Option<bool>, pub enable_auto_light_weight_mode: Option<bool>,
pub auto_light_weight_minutes: Option<u64>, pub auto_light_weight_minutes: Option<u64>,
pub enable_dns_settings: Option<bool>, pub enable_dns_settings: Option<bool>,
pub primary_action: Option<String>,
pub home_cards: Option<serde_json::Value>, pub home_cards: Option<serde_json::Value>,
pub enable_hover_jump_navigator: Option<bool>, pub enable_hover_jump_navigator: Option<bool>,
pub service_state: Option<crate::core::service::ServiceState>, pub service_state: Option<crate::core::service::ServiceState>,
@@ -656,6 +661,7 @@ impl From<IVerge> for IVergeResponse {
enable_auto_light_weight_mode: verge.enable_auto_light_weight_mode, enable_auto_light_weight_mode: verge.enable_auto_light_weight_mode,
auto_light_weight_minutes: verge.auto_light_weight_minutes, auto_light_weight_minutes: verge.auto_light_weight_minutes,
enable_dns_settings: verge.enable_dns_settings, enable_dns_settings: verge.enable_dns_settings,
primary_action: verge.primary_action,
home_cards: verge.home_cards, home_cards: verge.home_cards,
enable_hover_jump_navigator: verge.enable_hover_jump_navigator, enable_hover_jump_navigator: verge.enable_hover_jump_navigator,
service_state: verge.service_state, service_state: verge.service_state,

View File

@@ -10,36 +10,94 @@ import { useVerge } from "@/hooks/use-verge";
import { useSystemProxyState } from "@/hooks/use-system-proxy-state"; // Ваш хук import { useSystemProxyState } from "@/hooks/use-system-proxy-state"; // Ваш хук
import { useSystemState } from "@/hooks/use-system-state"; import { useSystemState } from "@/hooks/use-system-state";
import { useServiceInstaller } from "@/hooks/useServiceInstaller"; import { useServiceInstaller } from "@/hooks/useServiceInstaller";
import { uninstallService, restartCore, stopCore, invoke_uwp_tool } from "@/services/cmds"; import {
uninstallService,
restartCore,
stopCore,
invoke_uwp_tool,
} from "@/services/cmds";
import { showNotice } from "@/services/noticeService"; import { showNotice } from "@/services/noticeService";
// Компоненты // Компоненты
import { DialogRef, Switch } from "@/components/base"; import { DialogRef, Switch } from "@/components/base";
import { TooltipIcon } from "@/components/base/base-tooltip-icon"; import { TooltipIcon } from "@/components/base/base-tooltip-icon";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Tooltip, TooltipProvider, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip"; import {
Tooltip,
TooltipProvider,
TooltipTrigger,
TooltipContent,
} from "@/components/ui/tooltip";
import { GuardState } from "./mods/guard-state"; import { GuardState } from "./mods/guard-state";
// Иконки // Иконки
import { Settings, PlayCircle, PauseCircle, AlertTriangle, Wrench, Trash2, Funnel, Monitor, Power, BellOff, Repeat } from "lucide-react"; import {
Settings,
PlayCircle,
PauseCircle,
AlertTriangle,
Wrench,
Trash2,
Funnel,
Monitor,
Power,
BellOff,
Repeat,
} from "lucide-react";
// Модальные окна // Модальные окна
import { SysproxyViewer } from "./mods/sysproxy-viewer"; import { SysproxyViewer } from "./mods/sysproxy-viewer";
import { TunViewer } from "./mods/tun-viewer"; import { TunViewer } from "./mods/tun-viewer";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
const isWIN = getSystem() === "windows"; const isWIN = getSystem() === "windows";
interface Props { onError?: (err: Error) => void; } interface Props {
onError?: (err: Error) => void;
}
const SettingRow = ({ label, extra, children, onClick }: { label: React.ReactNode; extra?: React.ReactNode; children?: React.ReactNode; onClick?: () => void; }) => ( const SettingRow = ({
<div className={`flex items-center justify-between py-3 border-b border-border last:border-b-0 ${onClick ? 'cursor-pointer hover:bg-accent/50 -mx-3 px-3 rounded-md' : ''}`} onClick={onClick}> label,
<div className="flex items-center gap-2"><div className="text-sm font-medium">{label}</div>{extra && <div className="text-muted-foreground">{extra}</div>}</div> extra,
<div>{children}</div> children,
onClick,
}: {
label: React.ReactNode;
extra?: React.ReactNode;
children?: React.ReactNode;
onClick?: () => void;
}) => (
<div
className={`flex items-center justify-between py-3 border-b border-border last:border-b-0 ${onClick ? "cursor-pointer hover:bg-accent/50 -mx-3 px-3 rounded-md" : ""}`}
onClick={onClick}
>
<div className="flex items-center gap-2">
<div className="text-sm font-medium">{label}</div>
{extra && <div className="text-muted-foreground">{extra}</div>}
</div> </div>
<div>{children}</div>
</div>
); );
const LabelWithIcon = ({ icon, text }: { icon: React.ElementType, text: string }) => { const LabelWithIcon = ({
const Icon = icon; icon,
return ( <span className="flex items-center gap-3"><Icon className="h-4 w-4 text-muted-foreground" />{text}</span> ); text,
}: {
icon: React.ElementType;
text: string;
}) => {
const Icon = icon;
return (
<span className="flex items-center gap-3">
<Icon className="h-4 w-4 text-muted-foreground" />
{text}
</span>
);
}; };
const SettingSystem = ({ onError }: Props) => { const SettingSystem = ({ onError }: Props) => {
@@ -59,41 +117,55 @@ const SettingSystem = ({ onError }: Props) => {
const sysproxyRef = useRef<DialogRef>(null); const sysproxyRef = useRef<DialogRef>(null);
const tunRef = useRef<DialogRef>(null); const tunRef = useRef<DialogRef>(null);
const { enable_tun_mode, enable_auto_launch, enable_silent_start } = verge ?? {}; const { enable_tun_mode, enable_auto_launch, enable_silent_start } =
verge ?? {};
const onSwitchFormat = (val: boolean) => val; const onSwitchFormat = (val: boolean) => val;
const onChangeData = (patch: Partial<IVergeConfig>) => { const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...verge, ...patch }, false); mutateVerge({ ...verge, ...patch }, false);
}; };
const handleServiceOperation = useLockFn(async ({ beforeMsg, action, actionMsg, successMsg }: { beforeMsg: string; action: () => Promise<void>; actionMsg: string; successMsg: string; }) => { const handleServiceOperation = useLockFn(
try { async ({
showNotice("info", beforeMsg); beforeMsg,
await stopCore(); action,
showNotice("info", actionMsg); actionMsg,
await action(); successMsg,
showNotice("success", successMsg); }: {
showNotice("info", t("Restarting Core...")); beforeMsg: string;
await restartCore(); action: () => Promise<void>;
await mutateRunningMode(); actionMsg: string;
} catch (err: any) { successMsg: string;
showNotice("error", err.message || err.toString()); }) => {
try { try {
showNotice("info", t("Try running core as Sidecar...")); showNotice("info", beforeMsg);
await stopCore();
showNotice("info", actionMsg);
await action();
showNotice("success", successMsg);
showNotice("info", t("Restarting Core..."));
await restartCore(); await restartCore();
await mutateRunningMode(); await mutateRunningMode();
} catch (e: any) { } catch (err: any) {
showNotice("error", e?.message || e?.toString()); showNotice("error", err.message || err.toString());
try {
showNotice("info", t("Try running core as Sidecar..."));
await restartCore();
await mutateRunningMode();
} catch (e: any) {
showNotice("error", e?.message || e?.toString());
}
} }
} },
}); );
const onUninstallService = () => handleServiceOperation({ const onUninstallService = () =>
handleServiceOperation({
beforeMsg: t("Stopping Core..."), beforeMsg: t("Stopping Core..."),
action: uninstallService, action: uninstallService,
actionMsg: t("Uninstalling Service..."), actionMsg: t("Uninstalling Service..."),
successMsg: t("Service Uninstalled Successfully"), successMsg: t("Service Uninstalled Successfully"),
}); });
return ( return (
<div> <div>
@@ -106,10 +178,61 @@ const SettingSystem = ({ onError }: Props) => {
label={<LabelWithIcon icon={Funnel} text={t("Tun Mode")} />} label={<LabelWithIcon icon={Funnel} text={t("Tun Mode")} />}
extra={ extra={
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<TooltipIcon tooltip={t("Tun Mode Info")} icon={<Settings className="h-4 w-4" />} onClick={() => tunRef.current?.open()} /> <TooltipIcon
{!isTunAvailable && <TooltipProvider><Tooltip><TooltipTrigger><AlertTriangle className="h-4 w-4 text-amber-500" /></TooltipTrigger><TooltipContent><p>{t("TUN requires Service Mode or Admin Mode")}</p></TooltipContent></Tooltip></TooltipProvider>} tooltip={t("Tun Mode Info")}
{!isServiceMode && !isAdminMode && <TooltipProvider><Tooltip><TooltipTrigger asChild><Button variant="outline" size="icon" className="h-7 w-7" onClick={installServiceAndRestartCore}><Wrench className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent><p>{t("Install Service")}</p></TooltipContent></Tooltip></TooltipProvider>} icon={<Settings className="h-4 w-4" />}
{isServiceMode && <TooltipProvider><Tooltip><TooltipTrigger asChild><Button variant="destructive" size="icon" className="h-7 w-7" onClick={onUninstallService}><Trash2 className="h-4 w-4" /></Button></TooltipTrigger><TooltipContent><p>{t("Uninstall Service")}</p></TooltipContent></Tooltip></TooltipProvider>} onClick={() => tunRef.current?.open()}
/>
{!isTunAvailable && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<AlertTriangle className="h-4 w-4 text-amber-500" />
</TooltipTrigger>
<TooltipContent>
<p>{t("TUN requires Service Mode or Admin Mode")}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{!isServiceMode && !isAdminMode && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="outline"
size="icon"
className="h-7 w-7"
onClick={installServiceAndRestartCore}
>
<Wrench className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{t("Install Service")}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{isServiceMode && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="destructive"
size="icon"
className="h-7 w-7"
onClick={onUninstallService}
>
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>
<p>{t("Uninstall Service")}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
</div> </div>
} }
> >
@@ -119,7 +242,22 @@ const SettingSystem = ({ onError }: Props) => {
onChangeProps="onCheckedChange" onChangeProps="onCheckedChange"
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_tun_mode: e })} onChange={(e) => onChangeData({ enable_tun_mode: e })}
onGuard={(e) => { if (!isTunAvailable) { showNotice("error", t("TUN requires Service Mode or Admin Mode")); return Promise.reject(new Error(t("TUN requires Service Mode or Admin Mode"))); } return patchVerge({ enable_tun_mode: e }); }} onGuard={(e) => {
if (!isTunAvailable) {
showNotice(
"error",
t("TUN requires Service Mode or Admin Mode"),
);
return Promise.reject(
new Error(t("TUN requires Service Mode or Admin Mode")),
);
}
if (e) {
return patchVerge({ enable_tun_mode: true, enable_system_proxy: false });
} else {
return patchVerge({ enable_tun_mode: false });
}
}}
onCatch={onError} onCatch={onError}
> >
<Switch disabled={!isTunAvailable} /> <Switch disabled={!isTunAvailable} />
@@ -130,19 +268,54 @@ const SettingSystem = ({ onError }: Props) => {
label={<LabelWithIcon icon={Monitor} text={t("System Proxy")} />} label={<LabelWithIcon icon={Monitor} text={t("System Proxy")} />}
extra={ extra={
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<TooltipIcon tooltip={t("System Proxy Info")} icon={<Settings className="h-4 w-4" />} onClick={() => sysproxyRef.current?.open()} /> <TooltipIcon
{systemProxyIndicator ? <PlayCircle className="h-5 w-5 text-green-500" /> : <PauseCircle className="h-5 w-5 text-red-500" />} tooltip={t("System Proxy Info")}
icon={<Settings className="h-4 w-4" />}
onClick={() => sysproxyRef.current?.open()}
/>
{systemProxyIndicator ? (
<PlayCircle className="h-5 w-5 text-green-500" />
) : (
<PauseCircle className="h-5 w-5 text-red-500" />
)}
</div> </div>
} }
> >
<GuardState value={systemProxyActualState} valueProps="checked" onChangeProps="onCheckedChange" onFormat={onSwitchFormat} onGuard={(e) => toggleSystemProxy(e)} onCatch={onError}> <GuardState
value={systemProxyActualState}
valueProps="checked"
onChangeProps="onCheckedChange"
onFormat={onSwitchFormat}
onGuard={(e) => {
if (e) {
patchVerge({ enable_tun_mode: false });
return toggleSystemProxy(true);
} else {
return toggleSystemProxy(false);
}
}}
onCatch={onError}
>
<Switch /> <Switch />
</GuardState> </GuardState>
</SettingRow> </SettingRow>
<SettingRow <SettingRow
label={<LabelWithIcon icon={Power} text={t("Auto Launch")} />} label={<LabelWithIcon icon={Power} text={t("Auto Launch")} />}
extra={isAdminMode && <TooltipProvider><Tooltip><TooltipTrigger><AlertTriangle className="h-4 w-4 text-amber-500" /></TooltipTrigger><TooltipContent><p>{t("Administrator mode may not support auto launch")}</p></TooltipContent></Tooltip></TooltipProvider>} extra={
isAdminMode && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger>
<AlertTriangle className="h-4 w-4 text-amber-500" />
</TooltipTrigger>
<TooltipContent>
<p>{t("Administrator mode may not support auto launch")}</p>
</TooltipContent>
</Tooltip>
</TooltipProvider>
)
}
> >
<GuardState <GuardState
value={enable_auto_launch ?? false} value={enable_auto_launch ?? false}
@@ -150,14 +323,33 @@ const SettingSystem = ({ onError }: Props) => {
onChangeProps="onCheckedChange" onChangeProps="onCheckedChange"
onFormat={onSwitchFormat} onFormat={onSwitchFormat}
onChange={(e) => onChangeData({ enable_auto_launch: e })} onChange={(e) => onChangeData({ enable_auto_launch: e })}
onGuard={async (e) => { if (isAdminMode) { showNotice("info", t("Administrator mode may not support auto launch")); } try { onChangeData({ enable_auto_launch: e }); await patchVerge({ enable_auto_launch: e }); await mutate("getAutoLaunchStatus"); return Promise.resolve(); } catch (error) { onChangeData({ enable_auto_launch: !e }); return Promise.reject(error); } }} onGuard={async (e) => {
if (isAdminMode) {
showNotice(
"info",
t("Administrator mode may not support auto launch"),
);
}
try {
onChangeData({ enable_auto_launch: e });
await patchVerge({ enable_auto_launch: e });
await mutate("getAutoLaunchStatus");
return Promise.resolve();
} catch (error) {
onChangeData({ enable_auto_launch: !e });
return Promise.reject(error);
}
}}
onCatch={onError} onCatch={onError}
> >
<Switch /> <Switch />
</GuardState> </GuardState>
</SettingRow> </SettingRow>
<SettingRow label={<LabelWithIcon icon={BellOff} text={t("Silent Start")} />} extra={<TooltipIcon tooltip={t("Silent Start Info")} />}> <SettingRow
label={<LabelWithIcon icon={BellOff} text={t("Silent Start")} />}
extra={<TooltipIcon tooltip={t("Silent Start Info")} />}
>
<GuardState <GuardState
value={enable_silent_start ?? false} value={enable_silent_start ?? false}
valueProps="checked" valueProps="checked"
@@ -170,6 +362,34 @@ const SettingSystem = ({ onError }: Props) => {
<Switch /> <Switch />
</GuardState> </GuardState>
</SettingRow> </SettingRow>
<SettingRow
label={<LabelWithIcon icon={Repeat} text={t("Main Toggle Action")} />}
>
<GuardState
value={verge?.primary_action ?? "tun-mode"}
valueProps="value"
onChangeProps="onValueChange"
onFormat={(val) => val}
onGuard={(value) =>
patchVerge({
primary_action: value as "tun-mode" | "system-proxy",
})
}
onCatch={onError}
>
<Select>
<SelectTrigger className="w-[180px]">
<SelectValue placeholder="Select an action" />
</SelectTrigger>
<SelectContent>
<SelectItem value="tun-mode">{t("TUN Mode")}</SelectItem>
<SelectItem value="system-proxy">
{t("System Proxy")}
</SelectItem>
</SelectContent>
</Select>
</GuardState>
</SettingRow>
</div> </div>
</div> </div>
); );

View File

@@ -658,5 +658,6 @@
"Get Started": "Get Started", "Get Started": "Get Started",
"You don't have any profiles yet. Add your first one to begin.": "You don't have any profiles yet.\nAdd your first one to begin.", "You don't have any profiles yet. Add your first one to begin.": "You don't have any profiles yet.\nAdd your first one to begin.",
"Show Advanced Settings": "Show Advanced Settings", "Show Advanced Settings": "Show Advanced Settings",
"Hide Advanced Settings": "Hide Advanced Settings" "Hide Advanced Settings": "Hide Advanced Settings",
"Main Toggle Action": "Main Toggle Action"
} }

View File

@@ -610,5 +610,6 @@
"Get Started": "Приступить к работе", "Get Started": "Приступить к работе",
"You don't have any profiles yet. Add your first one to begin.": "У вас еще нет профилей.\nДобавьте свой первый профиль, чтобы начать.", "You don't have any profiles yet. Add your first one to begin.": "У вас еще нет профилей.\nДобавьте свой первый профиль, чтобы начать.",
"Show Advanced Settings": "Показать дополнительные настройки", "Show Advanced Settings": "Показать дополнительные настройки",
"Hide Advanced Settings": "Скрыть дополнительные настройки" "Hide Advanced Settings": "Скрыть дополнительные настройки",
"Main Toggle Action": "Действие главного переключателя"
} }

View File

@@ -1,55 +1,77 @@
import React, { useRef, useMemo, useCallback, useState } from 'react'; import React, { useRef, useMemo, useCallback, useState } from "react";
import { useNavigate } from 'react-router-dom'; import { useNavigate } from "react-router-dom";
import { useLockFn } from 'ahooks'; import { useLockFn } from "ahooks";
import { useTranslation } from 'react-i18next'; import { useTranslation } from "react-i18next";
import { toast } from 'sonner'; import { toast } from "sonner";
import { useProfiles } from '@/hooks/use-profiles'; import { useProfiles } from "@/hooks/use-profiles";
import { ProfileViewer, ProfileViewerRef } from '@/components/profile/profile-viewer';
import { import {
DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, ProfileViewer,
DropdownMenuSeparator, DropdownMenuTrigger, ProfileViewerRef,
} from '@/components/ui/dropdown-menu'; } from "@/components/profile/profile-viewer";
import { Button } from '@/components/ui/button'; import {
import { ChevronsUpDown, Check, PlusCircle, Menu, Wrench, AlertTriangle, Loader2 } from 'lucide-react'; DropdownMenu,
import { useVerge } from '@/hooks/use-verge'; DropdownMenuContent,
import { useSystemState } from '@/hooks/use-system-state'; DropdownMenuItem,
import { useServiceInstaller } from '@/hooks/useServiceInstaller'; DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
import {
ChevronsUpDown,
Check,
PlusCircle,
Menu,
Wrench,
AlertTriangle,
Loader2,
} from "lucide-react";
import { useVerge } from "@/hooks/use-verge";
import { useSystemState } from "@/hooks/use-system-state";
import { useServiceInstaller } from "@/hooks/useServiceInstaller";
import { Switch } from "@/components/ui/switch"; import { Switch } from "@/components/ui/switch";
import { ProxySelectors } from '@/components/home/proxy-selectors'; import { ProxySelectors } from "@/components/home/proxy-selectors";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"; import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { closeAllConnections } from '@/services/api'; import { closeAllConnections } from "@/services/api";
const MinimalHomePage: React.FC = () => { const MinimalHomePage: React.FC = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate(); const navigate = useNavigate();
const [isToggling, setIsToggling] = useState(false); const [isToggling, setIsToggling] = useState(false);
const { profiles, patchProfiles, activateSelected, mutateProfiles } = useProfiles(); const { profiles, patchProfiles, activateSelected, mutateProfiles } =
useProfiles();
const viewerRef = useRef<ProfileViewerRef>(null); const viewerRef = useRef<ProfileViewerRef>(null);
const profileItems = useMemo(() => { const profileItems = useMemo(() => {
const items = profiles && Array.isArray(profiles.items) ? profiles.items : []; const items =
profiles && Array.isArray(profiles.items) ? profiles.items : [];
const allowedTypes = ["local", "remote"]; const allowedTypes = ["local", "remote"];
return items.filter((i: any) => i && allowedTypes.includes(i.type!)); return items.filter((i: any) => i && allowedTypes.includes(i.type!));
}, [profiles]); }, [profiles]);
const currentProfileName = useMemo(() => { const currentProfileName = useMemo(() => {
return profileItems.find(p => p.uid === profiles?.current)?.name || profiles?.current; return (
profileItems.find((p) => p.uid === profiles?.current)?.name ||
profiles?.current
);
}, [profileItems, profiles?.current]); }, [profileItems, profiles?.current]);
const activateProfile = useCallback(async (uid: string, notifySuccess: boolean) => { const activateProfile = useCallback(
try { async (uid: string, notifySuccess: boolean) => {
await patchProfiles({ current: uid }); try {
await closeAllConnections(); await patchProfiles({ current: uid });
await activateSelected(); await closeAllConnections();
if (notifySuccess) { await activateSelected();
toast.success(t("Profile Switched")); if (notifySuccess) {
toast.success(t("Profile Switched"));
}
} catch (err: any) {
toast.error(err.message || err.toString());
mutateProfiles();
} }
} catch (err: any) { },
toast.error(err.message || err.toString()); [patchProfiles, activateSelected, mutateProfiles, t],
mutateProfiles(); );
}
}, [patchProfiles, activateSelected, mutateProfiles, t]);
const handleProfileChange = useLockFn(async (uid: string) => { const handleProfileChange = useLockFn(async (uid: string) => {
if (profiles?.current === uid) return; if (profiles?.current === uid) return;
@@ -61,33 +83,55 @@ const MinimalHomePage: React.FC = () => {
const { installServiceAndRestartCore } = useServiceInstaller(); const { installServiceAndRestartCore } = useServiceInstaller();
const isTunAvailable = isServiceMode || isAdminMode; const isTunAvailable = isServiceMode || isAdminMode;
const isProxyEnabled = verge?.enable_system_proxy || verge?.enable_tun_mode; const isProxyEnabled = verge?.enable_system_proxy || verge?.enable_tun_mode;
const showTunAlert =
(verge?.primary_action ?? "tun-mode") === "tun-mode" && !isTunAvailable;
const handleToggleProxy = useLockFn(async () => { const handleToggleProxy = useLockFn(async () => {
const turningOn = !isProxyEnabled; const turningOn = !isProxyEnabled;
const primaryAction = verge?.primary_action || "tun-mode";
setIsToggling(true); setIsToggling(true);
try { try {
if (turningOn) { if (turningOn) {
await patchVerge({ enable_tun_mode: true, enable_system_proxy: false }); if (primaryAction === "tun-mode") {
toast.success(t('Proxy enabled')); if (!isTunAvailable) {
toast.error(t("TUN requires Service Mode or Admin Mode"));
setIsToggling(false);
return;
}
await patchVerge({
enable_tun_mode: true,
enable_system_proxy: false,
});
} else {
await patchVerge({
enable_system_proxy: true,
enable_tun_mode: false,
});
}
toast.success(t("Proxy enabled"));
} else { } else {
await patchVerge({ enable_tun_mode: false, enable_system_proxy: false }); await patchVerge({
toast.success(t('Proxy disabled')); enable_tun_mode: false,
enable_system_proxy: false,
});
toast.success(t("Proxy disabled"));
} }
mutateVerge(); mutateVerge();
} catch (error: any) { } catch (error: any) {
toast.error(t('Failed to toggle proxy'), { description: error.message }); toast.error(t("Failed to toggle proxy"), { description: error.message });
} finally { } finally {
setIsToggling(false); setIsToggling(false);
} }
}); });
const navMenuItems = [ const navMenuItems = [
{ label: 'Profiles', path: '/profile' }, { label: "Profiles", path: "/profile" },
{ label: 'Settings', path: '/settings' }, { label: "Settings", path: "/settings" },
{ label: 'Logs', path: '/logs' }, { label: "Logs", path: "/logs" },
{ label: 'Proxies', path: '/proxies' }, { label: "Proxies", path: "/proxies" },
{ label: 'Connections', path: '/connections' }, { label: "Connections", path: "/connections" },
{ label: 'Rules', path: '/rules' }, { label: "Rules", path: "/rules" },
]; ];
return ( return (
@@ -99,7 +143,10 @@ const MinimalHomePage: React.FC = () => {
<div className="flex-shrink-0"> <div className="flex-shrink-0">
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button variant="outline" className="w-full max-w-[250px] sm:max-w-xs"> <Button
variant="outline"
className="w-full max-w-[250px] sm:max-w-xs"
>
<span className="truncate">{currentProfileName}</span> <span className="truncate">{currentProfileName}</span>
<ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" /> <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button> </Button>
@@ -108,15 +155,20 @@ const MinimalHomePage: React.FC = () => {
<DropdownMenuLabel>{t("Profiles")}</DropdownMenuLabel> <DropdownMenuLabel>{t("Profiles")}</DropdownMenuLabel>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
{profileItems.map((p) => ( {profileItems.map((p) => (
<DropdownMenuItem key={p.uid} onSelect={() => handleProfileChange(p.uid)}> <DropdownMenuItem
key={p.uid}
onSelect={() => handleProfileChange(p.uid)}
>
<span className="flex-1 truncate">{p.name}</span> <span className="flex-1 truncate">{p.name}</span>
{profiles?.current === p.uid && <Check className="ml-4 h-4 w-4" />} {profiles?.current === p.uid && (
<Check className="ml-4 h-4 w-4" />
)}
</DropdownMenuItem> </DropdownMenuItem>
))} ))}
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem onSelect={() => viewerRef.current?.create()}> <DropdownMenuItem onSelect={() => viewerRef.current?.create()}>
<PlusCircle className="mr-2 h-4 w-4" /> <PlusCircle className="mr-2 h-4 w-4" />
<span>{t("Add New Profile")}</span> <span>{t("Add Profile")}</span>
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuContent> </DropdownMenuContent>
</DropdownMenu> </DropdownMenu>
@@ -124,61 +176,74 @@ const MinimalHomePage: React.FC = () => {
)} )}
<div className="w-10"> <div className="w-10">
<DropdownMenu> <DropdownMenu>
<DropdownMenuTrigger asChild> <DropdownMenuTrigger asChild>
<Button variant="outline" size="icon"> <Button variant="outline" size="icon">
<Menu className="h-5 w-5" /> <Menu className="h-5 w-5" />
</Button> </Button>
</DropdownMenuTrigger> </DropdownMenuTrigger>
<DropdownMenuContent align="end"> <DropdownMenuContent align="end">
<DropdownMenuLabel>{t("Menu")}</DropdownMenuLabel> <DropdownMenuLabel>{t("Menu")}</DropdownMenuLabel>
<DropdownMenuSeparator /> <DropdownMenuSeparator />
{navMenuItems.map((item) => ( {navMenuItems.map((item) => (
<DropdownMenuItem key={item.path} onSelect={() => navigate(item.path)}> <DropdownMenuItem
{t(item.label)} key={item.path}
</DropdownMenuItem> onSelect={() => navigate(item.path)}
))} >
</DropdownMenuContent> {t(item.label)}
</DropdownMenu> </DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
</div> </div>
</header> </header>
<div className="flex items-center justify-center flex-grow w-full"> <div className="flex items-center justify-center flex-grow w-full">
<div className="flex flex-col items-center gap-8 pt-10"> <div className="flex flex-col items-center gap-8 pt-10">
<div className="text-center"> <div className="text-center">
<h1 className="text-4xl mb-2 font-semibold" style={{ color: isProxyEnabled ? '#22c55e' : '#ef4444' }}> <h1
{isProxyEnabled ? t('Connected') : t('Disconnected')} className="text-4xl mb-2 font-semibold"
style={{ color: isProxyEnabled ? "#22c55e" : "#ef4444" }}
>
{isProxyEnabled ? t("Connected") : t("Disconnected")}
</h1> </h1>
<p className="h-6 text-sm text-muted-foreground transition-opacity duration-300"> <p className="h-6 text-sm text-muted-foreground transition-opacity duration-300">
{isToggling && (isProxyEnabled ? t('Disconnecting...') : t('Connecting...'))} {isToggling &&
(isProxyEnabled ? t("Disconnecting...") : t("Connecting..."))}
</p> </p>
</div> </div>
<div className="scale-[7] my-16"> <div className="scale-[7] my-16">
<Switch <Switch
disabled={!isTunAvailable || isToggling} disabled={showTunAlert || isToggling}
checked={!!isProxyEnabled} checked={!!isProxyEnabled}
onCheckedChange={handleToggleProxy} onCheckedChange={handleToggleProxy}
aria-label={t("Toggle Proxy")} aria-label={t("Toggle Proxy")}
/> />
</div> </div>
{!isTunAvailable && ( {showTunAlert && (
<div className="w-full max-w-sm"> <div className="w-full max-w-sm">
<Alert variant="destructive" className="flex flex-col items-center gap-2 text-center"> <Alert
<AlertTriangle className="h-4 w-4" /> variant="destructive"
<AlertTitle>{t("Attention Required")}</AlertTitle> className="flex flex-col items-center gap-2 text-center"
<AlertDescription className="text-xs"> >
{t("TUN requires Service Mode or Admin Mode")} <AlertTriangle className="h-4 w-4" />
</AlertDescription> <AlertTitle>{t("Attention Required")}</AlertTitle>
{!isServiceMode && !isAdminMode && ( <AlertDescription className="text-xs">
<Button size="sm" className="mt-2" onClick={installServiceAndRestartCore}> {t("TUN requires Service Mode or Admin Mode")}
<Wrench className="mr-2 h-4 w-4" /> </AlertDescription>
{t("Install Service")} {!isServiceMode && !isAdminMode && (
</Button> <Button
)} size="sm"
</Alert> className="mt-2"
onClick={installServiceAndRestartCore}
>
<Wrench className="mr-2 h-4 w-4" />
{t("Install Service")}
</Button>
)}
</Alert>
</div> </div>
)} )}
@@ -190,15 +255,19 @@ const MinimalHomePage: React.FC = () => {
<PlusCircle className="h-4 w-4" /> <PlusCircle className="h-4 w-4" />
<AlertTitle>{t("Get Started")}</AlertTitle> <AlertTitle>{t("Get Started")}</AlertTitle>
<AlertDescription className="whitespace-pre-wrap"> <AlertDescription className="whitespace-pre-wrap">
{t("You don't have any profiles yet. Add your first one to begin.")} {t(
"You don't have any profiles yet. Add your first one to begin.",
)}
</AlertDescription> </AlertDescription>
<Button className="mt-2" onClick={() => viewerRef.current?.create()}> <Button
className="mt-2"
onClick={() => viewerRef.current?.create()}
>
{t("Add Profile")} {t("Add Profile")}
</Button> </Button>
</Alert> </Alert>
)} )}
</div> </div>
</div> </div>
</div> </div>

View File

@@ -748,6 +748,7 @@ interface IVergeConfig {
enable_system_proxy?: boolean; enable_system_proxy?: boolean;
enable_global_hotkey?: boolean; enable_global_hotkey?: boolean;
enable_dns_settings?: boolean; enable_dns_settings?: boolean;
primary_action?: "tun-mode" | "system-proxy";
proxy_auto_config?: boolean; proxy_auto_config?: boolean;
pac_file_content?: string; pac_file_content?: string;
proxy_host?: string; proxy_host?: string;