refactor: adjust setting dialog component

This commit is contained in:
GyDi 2022-11-20 21:48:39 +08:00
parent 572d81ecef
commit 892b919cf3
No known key found for this signature in database
GPG Key ID: 9C3AD40F1F99880A
23 changed files with 845 additions and 988 deletions

View File

@ -0,0 +1,66 @@
import { forwardRef, ReactNode, useImperativeHandle, useState } from "react";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
type SxProps,
type Theme,
} from "@mui/material";
interface Props {
title: ReactNode;
open: boolean;
okBtn?: ReactNode;
cancelBtn?: ReactNode;
disableOk?: boolean;
disableCancel?: boolean;
disableFooter?: boolean;
contentSx?: SxProps<Theme>;
onOk?: () => void;
onCancel?: () => void;
onClose?: () => void;
}
export interface DialogRef {
open: () => void;
close: () => void;
}
export const BaseDialog: React.FC<Props> = (props) => {
const {
open,
title,
children,
okBtn,
cancelBtn,
contentSx,
disableCancel,
disableOk,
disableFooter,
} = props;
return (
<Dialog open={open} onClose={props.onClose}>
<DialogTitle>{title}</DialogTitle>
<DialogContent sx={contentSx}>{children}</DialogContent>
{!disableFooter && (
<DialogActions>
{!disableCancel && (
<Button variant="outlined" onClick={props.onCancel}>
{cancelBtn}
</Button>
)}
{!disableOk && (
<Button variant="contained" onClick={props.onOk}>
{okBtn}
</Button>
)}
</DialogActions>
)}
</Dialog>
);
};

View File

@ -0,0 +1,2 @@
export { BaseDialog, type DialogRef } from "./base-dialog";
export { Notice } from "./base-notice";

View File

@ -1,36 +1,18 @@
import useSWR from "swr"; import useSWR from "swr";
import { useEffect, useState } from "react"; import { forwardRef, useImperativeHandle, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import { Checkbox, Divider, Stack, Tooltip, Typography } from "@mui/material";
Button,
Checkbox,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Divider,
Stack,
Tooltip,
Typography,
} from "@mui/material";
import { InfoRounded } from "@mui/icons-material"; import { InfoRounded } from "@mui/icons-material";
import { import { getRuntimeExists } from "@/services/cmds";
getProfiles,
getRuntimeExists,
patchProfilesConfig,
} from "@/services/cmds";
import { ModalHandler } from "@/hooks/use-modal-handler";
import { import {
HANDLE_FIELDS, HANDLE_FIELDS,
DEFAULT_FIELDS, DEFAULT_FIELDS,
OTHERS_FIELDS, OTHERS_FIELDS,
} from "@/utils/clash-fields"; } from "@/utils/clash-fields";
import { BaseDialog, DialogRef } from "@/components/base";
import { useProfiles } from "@/hooks/use-profiles";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
interface Props {
handler: ModalHandler;
}
const fieldSorter = (a: string, b: string) => { const fieldSorter = (a: string, b: string) => {
if (a.includes("-") === a.includes("-")) { if (a.includes("-") === a.includes("-")) {
if (a.length === b.length) return a.localeCompare(b); if (a.length === b.length) return a.localeCompare(b);
@ -43,13 +25,10 @@ const fieldSorter = (a: string, b: string) => {
const otherFields = [...OTHERS_FIELDS].sort(fieldSorter); const otherFields = [...OTHERS_FIELDS].sort(fieldSorter);
const handleFields = [...HANDLE_FIELDS, ...DEFAULT_FIELDS].sort(fieldSorter); const handleFields = [...HANDLE_FIELDS, ...DEFAULT_FIELDS].sort(fieldSorter);
const ClashFieldViewer = ({ handler }: Props) => { export const ClashFieldViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: profiles = {}, mutate: mutateProfile } = useSWR( const { profiles = {}, patchProfiles } = useProfiles();
"getProfiles",
getProfiles
);
const { data: existsKeys = [], mutate: mutateExists } = useSWR( const { data: existsKeys = [], mutate: mutateExists } = useSWR(
"getRuntimeExists", "getRuntimeExists",
getRuntimeExists getRuntimeExists
@ -58,20 +37,14 @@ const ClashFieldViewer = ({ handler }: Props) => {
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [selected, setSelected] = useState<string[]>([]); const [selected, setSelected] = useState<string[]>([]);
if (handler) { useImperativeHandle(ref, () => ({
handler.current = { open: () => {
open: () => setOpen(true),
close: () => setOpen(false),
};
}
useEffect(() => {
if (open) {
mutateProfile();
mutateExists(); mutateExists();
setSelected(profiles.valid || []); setSelected(profiles.valid || []);
} setOpen(true);
}, [open, profiles.valid]); },
close: () => setOpen(false),
}));
const handleChange = (item: string) => { const handleChange = (item: string) => {
if (!item) return; if (!item) return;
@ -91,8 +64,7 @@ const ClashFieldViewer = ({ handler }: Props) => {
if (curSet.size === oldSet.size && curSet.size === joinSet.size) return; if (curSet.size === oldSet.size && curSet.size === joinSet.size) return;
try { try {
await patchProfilesConfig({ valid: [...curSet] }); await patchProfiles({ valid: [...curSet] });
mutateProfile();
// Notice.success("Refresh clash config", 1000); // Notice.success("Refresh clash config", 1000);
} catch (err: any) { } catch (err: any) {
Notice.error(err?.message || err.toString()); Notice.error(err?.message || err.toString());
@ -100,62 +72,56 @@ const ClashFieldViewer = ({ handler }: Props) => {
}; };
return ( return (
<Dialog open={open} onClose={() => setOpen(false)}> <BaseDialog
<DialogTitle>{t("Clash Field")}</DialogTitle> open={open}
title={t("Clash Field")}
contentSx={{
pb: 0,
width: 320,
height: 300,
overflowY: "auto",
userSelect: "text",
}}
okBtn={t("Save")}
cancelBtn={t("Back")}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={handleSave}
>
{otherFields.map((item) => {
const inSelect = selected.includes(item);
const inConfig = existsKeys.includes(item);
<DialogContent return (
sx={{
pb: 0,
width: 320,
height: 300,
overflowY: "auto",
userSelect: "text",
}}
>
{otherFields.map((item) => {
const inSelect = selected.includes(item);
const inConfig = existsKeys.includes(item);
return (
<Stack key={item} mb={0.5} direction="row" alignItems="center">
<Checkbox
checked={inSelect}
size="small"
sx={{ p: 0.5 }}
onChange={() => handleChange(item)}
/>
<Typography width="100%">{item}</Typography>
{!inSelect && inConfig && <WarnIcon />}
</Stack>
);
})}
<Divider sx={{ my: 1 }}>
<Typography color="text.secondary" fontSize={14}>
Clash Verge Control Fields
</Typography>
</Divider>
{handleFields.map((item) => (
<Stack key={item} mb={0.5} direction="row" alignItems="center"> <Stack key={item} mb={0.5} direction="row" alignItems="center">
<Checkbox defaultChecked disabled size="small" sx={{ p: 0.5 }} /> <Checkbox
<Typography>{item}</Typography> checked={inSelect}
</Stack> size="small"
))} sx={{ p: 0.5 }}
</DialogContent> onChange={() => handleChange(item)}
/>
<Typography width="100%">{item}</Typography>
<DialogActions> {!inSelect && inConfig && <WarnIcon />}
<Button variant="outlined" onClick={() => setOpen(false)}> </Stack>
{t("Back")} );
</Button> })}
<Button variant="contained" onClick={handleSave}>
{t("Save")} <Divider sx={{ my: 1 }}>
</Button> <Typography color="text.secondary" fontSize={14}>
</DialogActions> Clash Verge Control Fields
</Dialog> </Typography>
</Divider>
{handleFields.map((item) => (
<Stack key={item} mb={0.5} direction="row" alignItems="center">
<Checkbox defaultChecked disabled size="small" sx={{ p: 0.5 }} />
<Typography>{item}</Typography>
</Stack>
))}
</BaseDialog>
); );
}; });
function WarnIcon() { function WarnIcon() {
return ( return (
@ -164,5 +130,3 @@ function WarnIcon() {
</Tooltip> </Tooltip>
); );
} }
export default ClashFieldViewer;

View File

@ -1,30 +1,16 @@
import useSWR from "swr"; import useSWR from "swr";
import { useEffect, useState } from "react"; import { forwardRef, useImperativeHandle, useState } from "react";
import { useSetRecoilState } from "recoil"; import { useSetRecoilState } from "recoil";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { import { List, ListItem, ListItemText, TextField } from "@mui/material";
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
List,
ListItem,
ListItemText,
TextField,
} from "@mui/material";
import { atomClashPort } from "@/services/states"; import { atomClashPort } from "@/services/states";
import { getClashConfig } from "@/services/api"; import { getClashConfig } from "@/services/api";
import { patchClashConfig } from "@/services/cmds"; import { patchClashConfig } from "@/services/cmds";
import { ModalHandler } from "@/hooks/use-modal-handler"; import { BaseDialog, DialogRef } from "@/components/base";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
interface Props { export const ClashPortViewer = forwardRef<DialogRef>((props, ref) => {
handler: ModalHandler;
}
const ClashPortViewer = ({ handler }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { data: config, mutate: mutateClash } = useSWR( const { data: config, mutate: mutateClash } = useSWR(
@ -37,18 +23,15 @@ const ClashPortViewer = ({ handler }: Props) => {
const setGlobalClashPort = useSetRecoilState(atomClashPort); const setGlobalClashPort = useSetRecoilState(atomClashPort);
if (handler) { useImperativeHandle(ref, () => ({
handler.current = { open: () => {
open: () => setOpen(true), if (config?.["mixed-port"]) {
close: () => setOpen(false), setPort(config["mixed-port"]);
}; }
} setOpen(true);
},
useEffect(() => { close: () => setOpen(false),
if (open && config?.["mixed-port"]) { }));
setPort(config["mixed-port"]);
}
}, [open, config?.["mixed-port"]]);
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
if (port < 1000) { if (port < 1000) {
@ -72,36 +55,30 @@ const ClashPortViewer = ({ handler }: Props) => {
}); });
return ( return (
<Dialog open={open} onClose={() => setOpen(false)}> <BaseDialog
<DialogTitle>{t("Clash Port")}</DialogTitle> open={open}
title={t("Clash Port")}
<DialogContent sx={{ width: 300 }}> contentSx={{ width: 300 }}
<List> okBtn={t("Save")}
<ListItem sx={{ padding: "5px 2px" }}> cancelBtn={t("Cancel")}
<ListItemText primary="Mixed Port" /> onClose={() => setOpen(false)}
<TextField onCancel={() => setOpen(false)}
size="small" onOk={onSave}
autoComplete="off" >
sx={{ width: 135 }} <List>
value={port} <ListItem sx={{ padding: "5px 2px" }}>
onChange={(e) => <ListItemText primary="Mixed Port" />
setPort(+e.target.value?.replace(/\D+/, "").slice(0, 5)) <TextField
} size="small"
/> autoComplete="off"
</ListItem> sx={{ width: 135 }}
</List> value={port}
</DialogContent> onChange={(e) =>
setPort(+e.target.value?.replace(/\D+/, "").slice(0, 5))
<DialogActions> }
<Button variant="outlined" onClick={() => setOpen(false)}> />
{t("Cancel")} </ListItem>
</Button> </List>
<Button onClick={onSave} variant="contained"> </BaseDialog>
{t("Save")}
</Button>
</DialogActions>
</Dialog>
); );
}; });
export default ClashPortViewer;

View File

@ -1,78 +1,76 @@
import { useEffect, useRef } from "react"; import {
forwardRef,
useEffect,
useImperativeHandle,
useRef,
useState,
} from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useRecoilValue } from "recoil"; import { useRecoilValue } from "recoil";
import { import { Chip } from "@mui/material";
Button,
Chip,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
} from "@mui/material";
import { atomThemeMode } from "@/services/states"; import { atomThemeMode } from "@/services/states";
import { getRuntimeYaml } from "@/services/cmds"; import { getRuntimeYaml } from "@/services/cmds";
import { BaseDialog, DialogRef } from "@/components/base";
import { editor } from "monaco-editor/esm/vs/editor/editor.api";
import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js"; import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js";
import "monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution.js"; import "monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution.js";
import "monaco-editor/esm/vs/editor/contrib/folding/browser/folding.js"; import "monaco-editor/esm/vs/editor/contrib/folding/browser/folding.js";
import { editor } from "monaco-editor/esm/vs/editor/editor.api";
interface Props {
open: boolean;
onClose: () => void;
}
const ConfigViewer = (props: Props) => {
const { open, onClose } = props;
export const ConfigViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [open, setOpen] = useState(false);
const editorRef = useRef<any>(); const editorRef = useRef<any>();
const instanceRef = useRef<editor.IStandaloneCodeEditor | null>(null); const instanceRef = useRef<editor.IStandaloneCodeEditor | null>(null);
const themeMode = useRecoilValue(atomThemeMode); const themeMode = useRecoilValue(atomThemeMode);
useEffect(() => { useEffect(() => {
if (!open) return;
getRuntimeYaml().then((data) => {
const dom = editorRef.current;
if (!dom) return;
if (instanceRef.current) instanceRef.current.dispose();
instanceRef.current = editor.create(editorRef.current, {
value: data ?? "# Error\n",
language: "yaml",
theme: themeMode === "light" ? "vs" : "vs-dark",
minimap: { enabled: false },
readOnly: true,
});
});
return () => { return () => {
if (instanceRef.current) { if (instanceRef.current) {
instanceRef.current.dispose(); instanceRef.current.dispose();
instanceRef.current = null; instanceRef.current = null;
} }
}; };
}, [open]); }, []);
useImperativeHandle(ref, () => ({
open: () => {
setOpen(true);
getRuntimeYaml().then((data) => {
const dom = editorRef.current;
if (!dom) return;
if (instanceRef.current) instanceRef.current.dispose();
instanceRef.current = editor.create(editorRef.current, {
value: data ?? "# Error\n",
language: "yaml",
theme: themeMode === "light" ? "vs" : "vs-dark",
minimap: { enabled: false },
readOnly: true,
});
});
},
close: () => setOpen(false),
}));
return ( return (
<Dialog open={open} onClose={onClose}> <BaseDialog
<DialogTitle> open={open}
{t("Runtime Config")} <Chip label={t("ReadOnly")} size="small" /> title={
</DialogTitle> <>
{t("Runtime Config")} <Chip label={t("ReadOnly")} size="small" />
<DialogContent sx={{ width: 520, pb: 1 }}> </>
<div style={{ width: "100%", height: "420px" }} ref={editorRef} /> }
</DialogContent> contentSx={{ width: 520, pb: 1 }}
cancelBtn={t("Back")}
<DialogActions> disableOk
<Button variant="outlined" onClick={onClose}> onClose={() => setOpen(false)}
{t("Back")} onCancel={() => setOpen(false)}
</Button> >
</DialogActions> <div style={{ width: "100%", height: "420px" }} ref={editorRef} />
</Dialog> </BaseDialog>
); );
}; });
export default ConfigViewer;

View File

@ -1,28 +1,14 @@
import useSWR from "swr"; import useSWR from "swr";
import { useState } from "react"; import { forwardRef, useImperativeHandle, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import { List, ListItem, ListItemText, TextField } from "@mui/material";
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
List,
ListItem,
ListItemText,
TextField,
} from "@mui/material";
import { getClashInfo, patchClashConfig } from "@/services/cmds"; import { getClashInfo, patchClashConfig } from "@/services/cmds";
import { ModalHandler } from "@/hooks/use-modal-handler";
import { getAxios } from "@/services/api"; import { getAxios } from "@/services/api";
import { BaseDialog, DialogRef } from "@/components/base";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
interface Props { export const ControllerViewer = forwardRef<DialogRef>((props, ref) => {
handler: ModalHandler;
}
const ControllerViewer = ({ handler }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
@ -30,16 +16,14 @@ const ControllerViewer = ({ handler }: Props) => {
const [controller, setController] = useState(clashInfo?.server || ""); const [controller, setController] = useState(clashInfo?.server || "");
const [secret, setSecret] = useState(clashInfo?.secret || ""); const [secret, setSecret] = useState(clashInfo?.secret || "");
if (handler) { useImperativeHandle(ref, () => ({
handler.current = { open: () => {
open: () => { setOpen(true);
setOpen(true); setController(clashInfo?.server || "");
setController(clashInfo?.server || ""); setSecret(clashInfo?.secret || "");
setSecret(clashInfo?.secret || ""); },
}, close: () => setOpen(false),
close: () => setOpen(false), }));
};
}
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
try { try {
@ -55,47 +39,41 @@ const ControllerViewer = ({ handler }: Props) => {
}); });
return ( return (
<Dialog open={open} onClose={() => setOpen(false)}> <BaseDialog
<DialogTitle>{t("Clash Port")}</DialogTitle> open={open}
title={t("Clash Port")}
contentSx={{ width: 400 }}
okBtn={t("Save")}
cancelBtn={t("Cancel")}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={onSave}
>
<List>
<ListItem sx={{ padding: "5px 2px" }}>
<ListItemText primary="External Controller" />
<TextField
size="small"
autoComplete="off"
sx={{ width: 175 }}
value={controller}
placeholder="Required"
onChange={(e) => setController(e.target.value)}
/>
</ListItem>
<DialogContent sx={{ width: 400 }}> <ListItem sx={{ padding: "5px 2px" }}>
<List> <ListItemText primary="Core Secret" />
<ListItem sx={{ padding: "5px 2px" }}> <TextField
<ListItemText primary="External Controller" /> size="small"
<TextField autoComplete="off"
size="small" sx={{ width: 175 }}
autoComplete="off" value={secret}
sx={{ width: 175 }} placeholder="Recommended"
value={controller} onChange={(e) => setSecret(e.target.value)}
placeholder="Required" />
onChange={(e) => setController(e.target.value)} </ListItem>
/> </List>
</ListItem> </BaseDialog>
<ListItem sx={{ padding: "5px 2px" }}>
<ListItemText primary="Core Secret" />
<TextField
size="small"
autoComplete="off"
sx={{ width: 175 }}
value={secret}
placeholder="Recommanded"
onChange={(e) => setSecret(e.target.value)}
/>
</ListItem>
</List>
</DialogContent>
<DialogActions>
<Button variant="outlined" onClick={() => setOpen(false)}>
{t("Cancel")}
</Button>
<Button onClick={onSave} variant="contained">
{t("Save")}
</Button>
</DialogActions>
</Dialog>
); );
}; });
export default ControllerViewer;

View File

@ -12,7 +12,7 @@ const VALID_CORE = [
{ name: "Clash Meta", core: "clash-meta" }, { name: "Clash Meta", core: "clash-meta" },
]; ];
const CoreSwitch = () => { export const CoreSwitch = () => {
const { verge, mutateVerge } = useVerge(); const { verge, mutateVerge } = useVerge();
const [anchorEl, setAnchorEl] = useState<any>(null); const [anchorEl, setAnchorEl] = useState<any>(null);
@ -75,5 +75,3 @@ const CoreSwitch = () => {
</> </>
); );
}; };
export default CoreSwitch;

View File

@ -13,7 +13,7 @@ interface Props<Value> {
children: ReactNode; children: ReactNode;
} }
function GuardState<T>(props: Props<T>) { export function GuardState<T>(props: Props<T>) {
const { const {
value, value,
children, children,
@ -83,5 +83,3 @@ function GuardState<T>(props: Props<T>) {
}; };
return cloneElement(children, childProps); return cloneElement(children, childProps);
} }
export default GuardState;

View File

@ -1,4 +1,3 @@
import { useState } from "react";
import { alpha, Box, IconButton, styled } from "@mui/material"; import { alpha, Box, IconButton, styled } from "@mui/material";
import { DeleteRounded } from "@mui/icons-material"; import { DeleteRounded } from "@mui/icons-material";
import parseHotkey from "@/utils/parse-hotkey"; import parseHotkey from "@/utils/parse-hotkey";
@ -52,7 +51,7 @@ interface Props {
onChange: (value: string[]) => void; onChange: (value: string[]) => void;
} }
const HotkeyInput = (props: Props) => { export const HotkeyInput = (props: Props) => {
const { value, onChange } = props; const { value, onChange } = props;
return ( return (
@ -92,5 +91,3 @@ const HotkeyInput = (props: Props) => {
</Box> </Box>
); );
}; };
export default HotkeyInput;

View File

@ -1,19 +1,11 @@
import { useEffect, useState } from "react"; import { forwardRef, useImperativeHandle, useState } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { import { styled, Typography } from "@mui/material";
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
styled,
Typography,
} from "@mui/material";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { ModalHandler } from "@/hooks/use-modal-handler"; import { BaseDialog, DialogRef } from "@/components/base";
import { HotkeyInput } from "./hotkey-input";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
import HotkeyInput from "./hotkey-input";
const ItemWrapper = styled("div")` const ItemWrapper = styled("div")`
display: flex; display: flex;
@ -35,42 +27,35 @@ const HOTKEY_FUNC = [
"disable_tun_mode", "disable_tun_mode",
]; ];
interface Props { export const HotkeyViewer = forwardRef<DialogRef>((props, ref) => {
handler: ModalHandler;
}
const HotkeyViewer = ({ handler }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
if (handler) {
handler.current = {
open: () => setOpen(true),
close: () => setOpen(false),
};
}
const { verge, patchVerge } = useVerge(); const { verge, patchVerge } = useVerge();
const [hotkeyMap, setHotkeyMap] = useState<Record<string, string[]>>({}); const [hotkeyMap, setHotkeyMap] = useState<Record<string, string[]>>({});
useEffect(() => { useImperativeHandle(ref, () => ({
if (!open) return; open: () => {
const map = {} as typeof hotkeyMap; setOpen(true);
verge?.hotkeys?.forEach((text) => { const map = {} as typeof hotkeyMap;
const [func, key] = text.split(",").map((e) => e.trim());
if (!func || !key) return; verge?.hotkeys?.forEach((text) => {
const [func, key] = text.split(",").map((e) => e.trim());
map[func] = key if (!func || !key) return;
.split("+")
.map((e) => e.trim())
.map((k) => (k === "PLUS" ? "+" : k));
});
setHotkeyMap(map); map[func] = key
}, [verge?.hotkeys, open]); .split("+")
.map((e) => e.trim())
.map((k) => (k === "PLUS" ? "+" : k));
});
setHotkeyMap(map);
},
close: () => setOpen(false),
}));
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
const hotkeys = Object.entries(hotkeyMap) const hotkeys = Object.entries(hotkeyMap)
@ -97,31 +82,25 @@ const HotkeyViewer = ({ handler }: Props) => {
}); });
return ( return (
<Dialog open={open} onClose={() => setOpen(false)}> <BaseDialog
<DialogTitle>{t("Hotkey Viewer")}</DialogTitle> open={open}
title={t("Hotkey Viewer")}
<DialogContent sx={{ width: 450, maxHeight: 330 }}> contentSx={{ width: 450, maxHeight: 330 }}
{HOTKEY_FUNC.map((func) => ( okBtn={t("Save")}
<ItemWrapper key={func}> cancelBtn={t("Cancel")}
<Typography>{t(func)}</Typography> onClose={() => setOpen(false)}
<HotkeyInput onCancel={() => setOpen(false)}
value={hotkeyMap[func] ?? []} onOk={onSave}
onChange={(v) => setHotkeyMap((m) => ({ ...m, [func]: v }))} >
/> {HOTKEY_FUNC.map((func) => (
</ItemWrapper> <ItemWrapper key={func}>
))} <Typography>{t(func)}</Typography>
</DialogContent> <HotkeyInput
value={hotkeyMap[func] ?? []}
<DialogActions> onChange={(v) => setHotkeyMap((m) => ({ ...m, [func]: v }))}
<Button variant="outlined" onClick={() => setOpen(false)}> />
{t("Cancel")} </ItemWrapper>
</Button> ))}
<Button onClick={onSave} variant="contained"> </BaseDialog>
{t("Save")}
</Button>
</DialogActions>
</Dialog>
); );
}; });
export default HotkeyViewer;

View File

@ -1,27 +1,12 @@
import { useEffect, useState } from "react"; import { forwardRef, useImperativeHandle, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import { List, ListItem, ListItemText, Switch, TextField } from "@mui/material";
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
List,
ListItem,
ListItemText,
Switch,
TextField,
} from "@mui/material";
import { ModalHandler } from "@/hooks/use-modal-handler";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { BaseDialog, DialogRef } from "@/components/base";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
interface Props { export const MiscViewer = forwardRef<DialogRef>((props, ref) => {
handler: ModalHandler;
}
const MiscViewer = ({ handler }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { verge, patchVerge } = useVerge(); const { verge, patchVerge } = useVerge();
@ -31,21 +16,16 @@ const MiscViewer = ({ handler }: Props) => {
defaultLatencyTest: "", defaultLatencyTest: "",
}); });
if (handler) { useImperativeHandle(ref, () => ({
handler.current = { open: () => {
open: () => setOpen(true), setOpen(true);
close: () => setOpen(false),
};
}
useEffect(() => {
if (open) {
setValues({ setValues({
autoCloseConnection: verge?.auto_close_connection || false, autoCloseConnection: verge?.auto_close_connection || false,
defaultLatencyTest: verge?.default_latency_test || "", defaultLatencyTest: verge?.default_latency_test || "",
}); });
} },
}, [open, verge]); close: () => setOpen(false),
}));
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
try { try {
@ -60,51 +40,45 @@ const MiscViewer = ({ handler }: Props) => {
}); });
return ( return (
<Dialog open={open} onClose={() => setOpen(false)}> <BaseDialog
<DialogTitle>{t("Miscellaneous")}</DialogTitle> open={open}
title={t("Miscellaneous")}
contentSx={{ width: 420 }}
okBtn={t("Save")}
cancelBtn={t("Cancel")}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={onSave}
>
<List>
<ListItem sx={{ padding: "5px 2px" }}>
<ListItemText primary="Auto Close Connections" />
<Switch
edge="end"
checked={values.autoCloseConnection}
onChange={(_, c) =>
setValues((v) => ({ ...v, autoCloseConnection: c }))
}
/>
</ListItem>
<DialogContent sx={{ width: 420 }}> <ListItem sx={{ padding: "5px 2px" }}>
<List> <ListItemText primary="Default Latency Test" />
<ListItem sx={{ padding: "5px 2px" }}> <TextField
<ListItemText primary="Auto Close Connections" /> size="small"
<Switch autoComplete="off"
edge="end" autoCorrect="off"
checked={values.autoCloseConnection} autoCapitalize="off"
onChange={(_, c) => spellCheck="false"
setValues((v) => ({ ...v, autoCloseConnection: c })) sx={{ width: 200 }}
} value={values.defaultLatencyTest}
/> placeholder="http://www.gstatic.com/generate_204"
</ListItem> onChange={(e) =>
setValues((v) => ({ ...v, defaultLatencyTest: e.target.value }))
<ListItem sx={{ padding: "5px 2px" }}> }
<ListItemText primary="Default Latency Test" /> />
<TextField </ListItem>
size="small" </List>
autoComplete="off" </BaseDialog>
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
sx={{ width: 200 }}
value={values.defaultLatencyTest}
placeholder="http://www.gstatic.com/generate_204"
onChange={(e) =>
setValues((v) => ({ ...v, defaultLatencyTest: e.target.value }))
}
/>
</ListItem>
</List>
</DialogContent>
<DialogActions>
<Button variant="outlined" onClick={() => setOpen(false)}>
{t("Cancel")}
</Button>
<Button onClick={onSave} variant="contained">
{t("Save")}
</Button>
</DialogActions>
</Dialog>
); );
}; });
export default MiscViewer;

View File

@ -1,117 +0,0 @@
import useSWR, { useSWRConfig } from "swr";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
DialogContent,
DialogTitle,
Stack,
Typography,
} from "@mui/material";
import {
checkService,
installService,
uninstallService,
patchVergeConfig,
} from "@/services/cmds";
import Notice from "@/components/base/base-notice";
import noop from "@/utils/noop";
interface Props {
open: boolean;
enable: boolean;
onClose: () => void;
onError?: (err: Error) => void;
}
const ServiceMode = (props: Props) => {
const { open, enable, onClose, onError = noop } = props;
const { t } = useTranslation();
const { mutate } = useSWRConfig();
const { data: status } = useSWR("checkService", checkService, {
revalidateIfStale: true,
shouldRetryOnError: false,
});
const state = status != null ? status : "pending";
const onInstall = useLockFn(async () => {
try {
await installService();
mutate("checkService");
onClose();
Notice.success("Service installed successfully");
} catch (err: any) {
mutate("checkService");
onError(err);
}
});
const onUninstall = useLockFn(async () => {
try {
if (state === "active" && enable) {
await patchVergeConfig({ enable_service_mode: false });
}
await uninstallService();
mutate("checkService");
onClose();
Notice.success("Service uninstalled successfully");
} catch (err: any) {
mutate("checkService");
onError(err);
}
});
// fix unhandle error of the service mode
const onDisable = useLockFn(async () => {
await patchVergeConfig({ enable_service_mode: false });
mutate("checkService");
onClose();
});
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>{t("Service Mode")}</DialogTitle>
<DialogContent sx={{ width: 360, userSelect: "text" }}>
<Typography>Current State: {state}</Typography>
{(state === "unknown" || state === "uninstall") && (
<Typography>
Infomation: Please make sure the Clash Verge Service is installed
and enabled
</Typography>
)}
<Stack
direction="row"
spacing={1}
sx={{ mt: 4, justifyContent: "flex-end" }}
>
{state === "uninstall" && enable && (
<Button variant="contained" onClick={onDisable}>
Disable Service Mode
</Button>
)}
{state === "uninstall" && (
<Button variant="contained" onClick={onInstall}>
Install
</Button>
)}
{(state === "active" || state === "installed") && (
<Button variant="outlined" onClick={onUninstall}>
Uninstall
</Button>
)}
</Stack>
</DialogContent>
</Dialog>
);
};
export default ServiceMode;

View File

@ -0,0 +1,109 @@
import useSWR from "swr";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import { Button, Stack, Typography } from "@mui/material";
import {
checkService,
installService,
uninstallService,
patchVergeConfig,
} from "@/services/cmds";
import { forwardRef, useState } from "react";
import { BaseDialog, DialogRef } from "@/components/base";
import Notice from "@/components/base/base-notice";
interface Props {
enable: boolean;
}
export const ServiceViewer = forwardRef<DialogRef, Props>((props, ref) => {
const { enable } = props;
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const { data: status, mutate: mutateCheck } = useSWR(
"checkService",
checkService,
{ revalidateIfStale: false, shouldRetryOnError: false }
);
const state = status != null ? status : "pending";
const onInstall = useLockFn(async () => {
try {
await installService();
mutateCheck();
setOpen(false);
Notice.success("Service installed successfully");
} catch (err: any) {
mutateCheck();
Notice.error(err.message || err.toString());
}
});
const onUninstall = useLockFn(async () => {
try {
if (state === "active" && enable) {
await patchVergeConfig({ enable_service_mode: false });
}
await uninstallService();
mutateCheck();
setOpen(false);
Notice.success("Service uninstalled successfully");
} catch (err: any) {
mutateCheck();
Notice.error(err.message || err.toString());
}
});
// fix unhandled error of the service mode
const onDisable = useLockFn(async () => {
await patchVergeConfig({ enable_service_mode: false });
mutateCheck();
setOpen(false);
});
return (
<BaseDialog
open={open}
title={t("Service Mode")}
contentSx={{ width: 360, userSelect: "text" }}
onClose={() => setOpen(false)}
>
<Typography>Current State: {state}</Typography>
{(state === "unknown" || state === "uninstall") && (
<Typography>
Information: Please make sure the Clash Verge Service is installed and
enabled
</Typography>
)}
<Stack
direction="row"
spacing={1}
sx={{ mt: 4, justifyContent: "flex-end" }}
>
{state === "uninstall" && enable && (
<Button variant="contained" onClick={onDisable}>
Disable Service Mode
</Button>
)}
{state === "uninstall" && (
<Button variant="contained" onClick={onInstall}>
Install
</Button>
)}
{(state === "active" || state === "installed") && (
<Button variant="outlined" onClick={onUninstall}>
Uninstall
</Button>
)}
</Stack>
</BaseDialog>
);
});

View File

@ -1,14 +1,8 @@
import useSWR from "swr"; import { forwardRef, useImperativeHandle, useState } from "react";
import { useEffect, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
Box, Box,
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
InputAdornment, InputAdornment,
List, List,
ListItem, ListItem,
@ -20,37 +14,19 @@ import {
} from "@mui/material"; } from "@mui/material";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { getSystemProxy } from "@/services/cmds"; import { getSystemProxy } from "@/services/cmds";
import { ModalHandler } from "@/hooks/use-modal-handler"; import { BaseDialog, DialogRef } from "@/components/base";
import Notice from "@/components/base/base-notice"; import Notice from "@/components/base/base-notice";
interface Props { export const SysproxyViewer = forwardRef<DialogRef>((props, ref) => {
handler: ModalHandler;
}
const FlexBox = styled("div")`
display: flex;
margin-top: 4px;
.label {
flex: none;
width: 80px;
}
`;
const SysproxyViewer = ({ handler }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
if (handler) {
handler.current = {
open: () => setOpen(true),
close: () => setOpen(false),
};
}
const { verge, patchVerge } = useVerge(); const { verge, patchVerge } = useVerge();
type SysProxy = Awaited<ReturnType<typeof getSystemProxy>>;
const [sysproxy, setSysproxy] = useState<SysProxy>();
const { const {
enable_system_proxy: enabled, enable_system_proxy: enabled,
enable_proxy_guard, enable_proxy_guard,
@ -58,28 +34,28 @@ const SysproxyViewer = ({ handler }: Props) => {
proxy_guard_duration, proxy_guard_duration,
} = verge ?? {}; } = verge ?? {};
const { data: sysproxy } = useSWR(
open ? "getSystemProxy" : null,
getSystemProxy
);
const [value, setValue] = useState({ const [value, setValue] = useState({
guard: enable_proxy_guard, guard: enable_proxy_guard,
bypass: system_proxy_bypass, bypass: system_proxy_bypass,
duration: proxy_guard_duration ?? 10, duration: proxy_guard_duration ?? 10,
}); });
useEffect(() => { useImperativeHandle(ref, () => ({
setValue({ open: () => {
guard: enable_proxy_guard, setOpen(true);
bypass: system_proxy_bypass, setValue({
duration: proxy_guard_duration ?? 10, guard: enable_proxy_guard,
}); bypass: system_proxy_bypass,
}, [verge]); duration: proxy_guard_duration ?? 10,
});
getSystemProxy().then((p) => setSysproxy(p));
},
close: () => setOpen(false),
}));
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
if (value.duration < 5) { if (value.duration < 1) {
Notice.error("Proxy guard duration at least 5 seconds"); Notice.error("Proxy guard duration at least 1 seconds");
return; return;
} }
@ -104,94 +80,95 @@ const SysproxyViewer = ({ handler }: Props) => {
}); });
return ( return (
<Dialog open={open} onClose={() => setOpen(false)}> <BaseDialog
<DialogTitle>{t("System Proxy Setting")}</DialogTitle> open={open}
title={t("System Proxy Setting")}
contentSx={{ width: 450, maxHeight: 300 }}
okBtn={t("Save")}
cancelBtn={t("Cancel")}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={onSave}
>
<List>
<ListItem sx={{ padding: "5px 2px" }}>
<ListItemText primary={t("Proxy Guard")} />
<Switch
edge="end"
disabled={!enabled}
checked={value.guard}
onChange={(_, e) => setValue((v) => ({ ...v, guard: e }))}
/>
</ListItem>
<DialogContent sx={{ width: 450, maxHeight: 300 }}> <ListItem sx={{ padding: "5px 2px" }}>
<List> <ListItemText primary={t("Guard Duration")} />
<ListItem sx={{ padding: "5px 2px" }}> <TextField
<ListItemText primary={t("Proxy Guard")} /> disabled={!enabled}
<Switch size="small"
edge="end" value={value.duration}
disabled={!enabled} sx={{ width: 100 }}
checked={value.guard} InputProps={{
onChange={(_, e) => setValue((v) => ({ ...v, guard: e }))} endAdornment: <InputAdornment position="end">s</InputAdornment>,
/> }}
</ListItem> onChange={(e) => {
setValue((v) => ({
...v,
duration: +e.target.value.replace(/\D/, ""),
}));
}}
/>
</ListItem>
<ListItem sx={{ padding: "5px 2px" }}> <ListItem sx={{ padding: "5px 2px", alignItems: "start" }}>
<ListItemText primary={t("Guard Duration")} /> <ListItemText primary={t("Proxy Bypass")} sx={{ padding: "3px 0" }} />
<TextField <TextField
disabled={!enabled} disabled={!enabled}
size="small" size="small"
value={value.duration} autoComplete="off"
sx={{ width: 100 }} multiline
InputProps={{ rows={3}
endAdornment: <InputAdornment position="end">s</InputAdornment>, sx={{ width: 280 }}
}} value={value.bypass}
onChange={(e) => { onChange={(e) =>
setValue((v) => ({ setValue((v) => ({ ...v, bypass: e.target.value }))
...v, }
duration: +e.target.value.replace(/\D/, ""), />
})); </ListItem>
}} </List>
/>
</ListItem>
<ListItem sx={{ padding: "5px 2px", alignItems: "start" }}> <Box sx={{ mt: 2.5 }}>
<ListItemText <Typography variant="body1" sx={{ fontSize: "18px", mb: 1 }}>
primary={t("Proxy Bypass")} {t("Current System Proxy")}
sx={{ padding: "3px 0" }} </Typography>
/>
<TextField
disabled={!enabled}
size="small"
autoComplete="off"
multiline
rows={3}
sx={{ width: 280 }}
value={value.bypass}
onChange={(e) =>
setValue((v) => ({ ...v, bypass: e.target.value }))
}
/>
</ListItem>
</List>
<Box sx={{ mt: 2.5 }}> <FlexBox>
<Typography variant="body1" sx={{ fontSize: "18px", mb: 1 }}> <Typography className="label">Enable:</Typography>
{t("Current System Proxy")} <Typography className="value">
{(!!sysproxy?.enable).toString()}
</Typography> </Typography>
</FlexBox>
<FlexBox> <FlexBox>
<Typography className="label">Enable:</Typography> <Typography className="label">Server:</Typography>
<Typography className="value"> <Typography className="value">{sysproxy?.server || "-"}</Typography>
{(!!sysproxy?.enable).toString()} </FlexBox>
</Typography>
</FlexBox>
<FlexBox> <FlexBox>
<Typography className="label">Server:</Typography> <Typography className="label">Bypass:</Typography>
<Typography className="value">{sysproxy?.server || "-"}</Typography> <Typography className="value">{sysproxy?.bypass || "-"}</Typography>
</FlexBox> </FlexBox>
</Box>
<FlexBox> </BaseDialog>
<Typography className="label">Bypass:</Typography>
<Typography className="value">{sysproxy?.bypass || "-"}</Typography>
</FlexBox>
</Box>
</DialogContent>
<DialogActions>
<Button variant="outlined" onClick={() => setOpen(false)}>
{t("Cancel")}
</Button>
<Button onClick={onSave} variant="contained">
{t("Save")}
</Button>
</DialogActions>
</Dialog>
); );
}; });
export default SysproxyViewer; const FlexBox = styled("div")`
display: flex;
margin-top: 4px;
.label {
flex: none;
width: 80px;
}
`;

View File

@ -8,7 +8,7 @@ interface Props {
onChange?: (value: ThemeValue) => void; onChange?: (value: ThemeValue) => void;
} }
const ThemeModeSwitch = (props: Props) => { export const ThemeModeSwitch = (props: Props) => {
const { value, onChange } = props; const { value, onChange } = props;
const { t } = useTranslation(); const { t } = useTranslation();
@ -29,5 +29,3 @@ const ThemeModeSwitch = (props: Props) => {
</ButtonGroup> </ButtonGroup>
); );
}; };
export default ThemeModeSwitch;

View File

@ -0,0 +1,137 @@
import { forwardRef, useImperativeHandle, useState } from "react";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import {
List,
ListItem,
ListItemText,
styled,
TextField,
useTheme,
} from "@mui/material";
import { useVerge } from "@/hooks/use-verge";
import { defaultTheme, defaultDarkTheme } from "@/pages/_theme";
import { BaseDialog, DialogRef } from "@/components/base";
import Notice from "../../base/base-notice";
export const ThemeViewer = forwardRef<DialogRef>((props, ref) => {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const { verge, patchVerge } = useVerge();
const { theme_setting } = verge ?? {};
const [theme, setTheme] = useState(theme_setting || {});
useImperativeHandle(ref, () => ({
open: () => {
setOpen(true);
setTheme({ ...theme_setting } || {});
},
close: () => setOpen(false),
}));
const textProps = {
size: "small",
autoComplete: "off",
sx: { width: 135 },
} as const;
const handleChange = (field: keyof typeof theme) => (e: any) => {
setTheme((t) => ({ ...t, [field]: e.target.value }));
};
const onSave = useLockFn(async () => {
try {
await patchVerge({ theme_setting: theme });
setOpen(false);
} catch (err: any) {
Notice.error(err.message || err.toString());
}
});
// default theme
const { palette } = useTheme();
const dt = palette.mode === "light" ? defaultTheme : defaultDarkTheme;
type ThemeKey = keyof typeof theme & keyof typeof defaultTheme;
const renderItem = (label: string, key: ThemeKey) => {
return (
<Item>
<ListItemText primary={label} />
<Round sx={{ background: theme[key] || dt[key] }} />
<TextField
{...textProps}
value={theme[key] ?? ""}
placeholder={dt[key]}
onChange={handleChange(key)}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>
</Item>
);
};
return (
<BaseDialog
open={open}
title={t("Theme Setting")}
okBtn={t("Save")}
cancelBtn={t("Cancel")}
contentSx={{ width: 400, maxHeight: 300, overflow: "auto", pb: 0 }}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={onSave}
>
<List sx={{ pt: 0 }}>
{renderItem("Primary Color", "primary_color")}
{renderItem("Secondary Color", "secondary_color")}
{renderItem("Primary Text", "primary_text")}
{renderItem("Secondary Text", "secondary_text")}
{renderItem("Info Color", "info_color")}
{renderItem("Error Color", "error_color")}
{renderItem("Warning Color", "warning_color")}
{renderItem("Success Color", "success_color")}
<Item>
<ListItemText primary="Font Family" />
<TextField
{...textProps}
value={theme.font_family ?? ""}
onChange={handleChange("font_family")}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>
</Item>
<Item>
<ListItemText primary="CSS Injection" />
<TextField
{...textProps}
value={theme.css_injection ?? ""}
onChange={handleChange("css_injection")}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>
</Item>
</List>
</BaseDialog>
);
});
const Item = styled(ListItem)(() => ({
padding: "5px 2px",
}));
const Round = styled("div")(() => ({
width: "24px",
height: "24px",
borderRadius: "18px",
display: "inline-block",
marginRight: "8px",
}));

View File

@ -23,7 +23,7 @@ interface Props {
onCancel?: () => void; onCancel?: () => void;
} }
const WebUIItem = (props: Props) => { export const WebUIItem = (props: Props) => {
const { const {
value, value,
onlyEdit = false, onlyEdit = false,
@ -128,5 +128,3 @@ const WebUIItem = (props: Props) => {
</> </>
); );
}; };
export default WebUIItem;

View File

@ -1,42 +1,31 @@
import useSWR from "swr"; import useSWR from "swr";
import { useState } from "react"; import { forwardRef, useImperativeHandle, useState } from "react";
import { useLockFn } from "ahooks"; import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import { Button, Box, Typography } from "@mui/material";
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
Typography,
} from "@mui/material";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { getClashInfo, openWebUrl } from "@/services/cmds"; import { getClashInfo, openWebUrl } from "@/services/cmds";
import { ModalHandler } from "@/hooks/use-modal-handler"; import { WebUIItem } from "./web-ui-item";
import { BaseDialog, DialogRef } from "@/components/base";
import BaseEmpty from "@/components/base/base-empty"; import BaseEmpty from "@/components/base/base-empty";
import WebUIItem from "./web-ui-item"; import Notice from "@/components/base/base-notice";
interface Props { export const WebUIViewer = forwardRef<DialogRef>((props, ref) => {
handler: ModalHandler;
onError: (err: Error) => void;
}
const WebUIViewer = ({ handler, onError }: Props) => {
const { t } = useTranslation(); const { t } = useTranslation();
const { verge, patchVerge, mutateVerge } = useVerge(); const { verge, patchVerge, mutateVerge } = useVerge();
const webUIList = verge?.web_ui_list || [];
const [open, setOpen] = useState(false); const [open, setOpen] = useState(false);
const [editing, setEditing] = useState(false); const [editing, setEditing] = useState(false);
if (handler) { const { data: clashInfo } = useSWR("getClashInfo", getClashInfo);
handler.current = {
open: () => setOpen(true), useImperativeHandle(ref, () => ({
close: () => setOpen(false), open: () => setOpen(true),
}; close: () => setOpen(false),
} }));
const webUIList = verge?.web_ui_list || [];
const handleAdd = useLockFn(async (value: string) => { const handleAdd = useLockFn(async (value: string) => {
const newList = [value, ...webUIList]; const newList = [value, ...webUIList];
@ -58,8 +47,6 @@ const WebUIViewer = ({ handler, onError }: Props) => {
await patchVerge({ web_ui_list: newList }); await patchVerge({ web_ui_list: newList });
}); });
const { data: clashInfo } = useSWR("getClashInfo", getClashInfo);
const handleOpenUrl = useLockFn(async (value?: string) => { const handleOpenUrl = useLockFn(async (value?: string) => {
if (!value) return; if (!value) return;
try { try {
@ -83,74 +70,70 @@ const WebUIViewer = ({ handler, onError }: Props) => {
await openWebUrl(url); await openWebUrl(url);
} catch (e: any) { } catch (e: any) {
onError(e); Notice.error(e.message || e.toString());
} }
}); });
return ( return (
<Dialog open={open} onClose={() => setOpen(false)}> <BaseDialog
<DialogTitle display="flex" justifyContent="space-between"> open={open}
{t("Web UI")} title={
<Button <Box display="flex" justifyContent="space-between">
variant="contained" {t("Web UI")}
size="small" <Button
disabled={editing} variant="contained"
onClick={() => setEditing(true)} size="small"
> disabled={editing}
{t("New")} onClick={() => setEditing(true)}
</Button> >
</DialogTitle> {t("New")}
</Button>
</Box>
}
contentSx={{
width: 450,
height: 300,
pb: 1,
overflowY: "auto",
userSelect: "text",
}}
cancelBtn={t("Back")}
disableOk
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
>
{editing && (
<WebUIItem
value=""
onlyEdit
onChange={(v) => {
setEditing(false);
handleAdd(v || "");
}}
onCancel={() => setEditing(false)}
/>
)}
<DialogContent {!editing && webUIList.length === 0 && (
sx={{ <BaseEmpty
width: 450, text="Empty List"
height: 300, extra={
pb: 1, <Typography mt={2} sx={{ fontSize: "12px" }}>
overflowY: "auto", Replace host, port, secret with "%host" "%port" "%secret"
userSelect: "text", </Typography>
}} }
> />
{editing && ( )}
<WebUIItem
value=""
onlyEdit
onChange={(v) => {
setEditing(false);
handleAdd(v || "");
}}
onCancel={() => setEditing(false)}
/>
)}
{!editing && webUIList.length === 0 && ( {webUIList.map((item, index) => (
<BaseEmpty <WebUIItem
text="Empty List" key={index}
extra={ value={item}
<Typography mt={2} sx={{ fontSize: "12px" }}> onChange={(v) => handleChange(index, v)}
Replace host, port, secret with "%host" "%port" "%secret" onDelete={() => handleDelete(index)}
</Typography> onOpenUrl={handleOpenUrl}
} />
/> ))}
)} </BaseDialog>
{webUIList.map((item, index) => (
<WebUIItem
key={index}
value={item}
onChange={(v) => handleChange(index, v)}
onDelete={() => handleDelete(index)}
onOpenUrl={handleOpenUrl}
/>
))}
</DialogContent>
<DialogActions>
<Button variant="outlined" onClick={() => setOpen(false)}>
{t("Back")}
</Button>
</DialogActions>
</Dialog>
); );
}; });
export default WebUIViewer;

View File

@ -1,4 +1,5 @@
import useSWR from "swr"; import useSWR from "swr";
import { useRef } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
TextField, TextField,
@ -10,15 +11,15 @@ import {
} from "@mui/material"; } from "@mui/material";
import { ArrowForward } from "@mui/icons-material"; import { ArrowForward } from "@mui/icons-material";
import { patchClashConfig } from "@/services/cmds"; import { patchClashConfig } from "@/services/cmds";
import { SettingList, SettingItem } from "./setting";
import { getClashConfig, getVersion, updateConfigs } from "@/services/api"; import { getClashConfig, getVersion, updateConfigs } from "@/services/api";
import useModalHandler from "@/hooks/use-modal-handler"; import { DialogRef } from "@/components/base";
import GuardState from "./mods/guard-state"; import { GuardState } from "./mods/guard-state";
import CoreSwitch from "./mods/core-switch"; import { CoreSwitch } from "./mods/core-switch";
import WebUIViewer from "./mods/web-ui-viewer"; import { WebUIViewer } from "./mods/web-ui-viewer";
import ClashFieldViewer from "./mods/clash-field-viewer"; import { ClashFieldViewer } from "./mods/clash-field-viewer";
import ClashPortViewer from "./mods/clash-port-viewer"; import { ClashPortViewer } from "./mods/clash-port-viewer";
import ControllerViewer from "./mods/controller-viewer"; import { ControllerViewer } from "./mods/controller-viewer";
import { SettingList, SettingItem } from "./mods/setting-comp";
interface Props { interface Props {
onError: (err: Error) => void; onError: (err: Error) => void;
@ -40,10 +41,10 @@ const SettingClash = ({ onError }: Props) => {
"mixed-port": mixedPort, "mixed-port": mixedPort,
} = clashConfig ?? {}; } = clashConfig ?? {};
const webUIHandler = useModalHandler(); const webRef = useRef<DialogRef>(null);
const fieldHandler = useModalHandler(); const fieldRef = useRef<DialogRef>(null);
const portHandler = useModalHandler(); const portRef = useRef<DialogRef>(null);
const controllerHandler = useModalHandler(); const ctrlRef = useRef<DialogRef>(null);
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<IConfigData>) => { const onChangeData = (patch: Partial<IConfigData>) => {
@ -61,10 +62,10 @@ const SettingClash = ({ onError }: Props) => {
return ( return (
<SettingList title={t("Clash Setting")}> <SettingList title={t("Clash Setting")}>
<WebUIViewer handler={webUIHandler} onError={onError} /> <WebUIViewer ref={webRef} />
<ClashFieldViewer handler={fieldHandler} /> <ClashFieldViewer ref={fieldRef} />
<ClashPortViewer handler={portHandler} /> <ClashPortViewer ref={portRef} />
<ControllerViewer handler={controllerHandler} /> <ControllerViewer ref={ctrlRef} />
<SettingItem label={t("Allow Lan")}> <SettingItem label={t("Allow Lan")}>
<GuardState <GuardState
@ -118,7 +119,7 @@ const SettingClash = ({ onError }: Props) => {
value={mixedPort ?? 0} value={mixedPort ?? 0}
sx={{ width: 100, input: { py: "7.5px", cursor: "pointer" } }} sx={{ width: 100, input: { py: "7.5px", cursor: "pointer" } }}
onClick={(e) => { onClick={(e) => {
portHandler.current.open(); portRef.current?.open();
(e.target as any).blur(); (e.target as any).blur();
}} }}
/> />
@ -129,7 +130,7 @@ const SettingClash = ({ onError }: Props) => {
color="inherit" color="inherit"
size="small" size="small"
sx={{ my: "2px" }} sx={{ my: "2px" }}
onClick={() => controllerHandler.current.open()} onClick={() => ctrlRef.current?.open()}
> >
<ArrowForward /> <ArrowForward />
</IconButton> </IconButton>
@ -140,7 +141,7 @@ const SettingClash = ({ onError }: Props) => {
color="inherit" color="inherit"
size="small" size="small"
sx={{ my: "2px" }} sx={{ my: "2px" }}
onClick={() => webUIHandler.current.open()} onClick={() => webRef.current?.open()}
> >
<ArrowForward /> <ArrowForward />
</IconButton> </IconButton>
@ -151,7 +152,7 @@ const SettingClash = ({ onError }: Props) => {
color="inherit" color="inherit"
size="small" size="small"
sx={{ my: "2px" }} sx={{ my: "2px" }}
onClick={() => fieldHandler.current.open()} onClick={() => fieldRef.current?.open()}
> >
<ArrowForward /> <ArrowForward />
</IconButton> </IconButton>

View File

@ -1,16 +1,16 @@
import useSWR from "swr"; import useSWR from "swr";
import { useState } from "react"; import { useRef } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { IconButton, Switch } from "@mui/material"; import { IconButton, Switch } from "@mui/material";
import { ArrowForward, PrivacyTipRounded, Settings } from "@mui/icons-material"; import { ArrowForward, PrivacyTipRounded, Settings } from "@mui/icons-material";
import { checkService } from "@/services/cmds"; import { checkService } from "@/services/cmds";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { SettingList, SettingItem } from "./setting"; import { DialogRef } from "@/components/base";
import useModalHandler from "@/hooks/use-modal-handler"; import { SettingList, SettingItem } from "./mods/setting-comp";
import { GuardState } from "./mods/guard-state";
import { ServiceViewer } from "./mods/service-viewer";
import { SysproxyViewer } from "./mods/sysproxy-viewer";
import getSystem from "@/utils/get-system"; import getSystem from "@/utils/get-system";
import GuardState from "./mods/guard-state";
import ServiceMode from "./mods/service-mode";
import SysproxyViewer from "./mods/sysproxy-viewer";
interface Props { interface Props {
onError?: (err: Error) => void; onError?: (err: Error) => void;
@ -24,13 +24,15 @@ const SettingSystem = ({ onError }: Props) => {
const { verge, mutateVerge, patchVerge } = useVerge(); const { verge, mutateVerge, patchVerge } = useVerge();
// service mode // service mode
const [serviceOpen, setServiceOpen] = useState(false);
const { data: serviceStatus } = useSWR( const { data: serviceStatus } = useSWR(
isWIN ? "checkService" : null, isWIN ? "checkService" : null,
checkService, checkService,
{ revalidateIfStale: false, shouldRetryOnError: false } { revalidateIfStale: false, shouldRetryOnError: false }
); );
const serviceRef = useRef<DialogRef>(null);
const sysproxyRef = useRef<DialogRef>(null);
const { const {
enable_tun_mode, enable_tun_mode,
enable_auto_launch, enable_auto_launch,
@ -44,11 +46,12 @@ const SettingSystem = ({ onError }: Props) => {
mutateVerge({ ...verge, ...patch }, false); mutateVerge({ ...verge, ...patch }, false);
}; };
const sysproxyHandler = useModalHandler();
return ( return (
<SettingList title={t("System Setting")}> <SettingList title={t("System Setting")}>
<SysproxyViewer handler={sysproxyHandler} /> <SysproxyViewer ref={sysproxyRef} />
{isWIN && (
<ServiceViewer ref={serviceRef} enable={!!enable_service_mode} />
)}
<SettingItem label={t("Tun Mode")}> <SettingItem label={t("Tun Mode")}>
<GuardState <GuardState
@ -71,7 +74,7 @@ const SettingSystem = ({ onError }: Props) => {
<PrivacyTipRounded <PrivacyTipRounded
fontSize="small" fontSize="small"
style={{ cursor: "pointer", opacity: 0.75 }} style={{ cursor: "pointer", opacity: 0.75 }}
onClick={() => setServiceOpen(true)} onClick={() => sysproxyRef.current?.open()}
/> />
) )
} }
@ -92,7 +95,7 @@ const SettingSystem = ({ onError }: Props) => {
color="inherit" color="inherit"
size="small" size="small"
sx={{ my: "2px" }} sx={{ my: "2px" }}
onClick={() => setServiceOpen(true)} onClick={() => sysproxyRef.current?.open()}
> >
<ArrowForward /> <ArrowForward />
</IconButton> </IconButton>
@ -100,22 +103,13 @@ const SettingSystem = ({ onError }: Props) => {
</SettingItem> </SettingItem>
)} )}
{isWIN && (
<ServiceMode
open={serviceOpen}
enable={!!enable_service_mode}
onError={onError}
onClose={() => setServiceOpen(false)}
/>
)}
<SettingItem <SettingItem
label={t("System Proxy")} label={t("System Proxy")}
extra={ extra={
<Settings <Settings
fontSize="small" fontSize="small"
style={{ cursor: "pointer", opacity: 0.75 }} style={{ cursor: "pointer", opacity: 0.75 }}
onClick={() => sysproxyHandler.current.open()} onClick={() => sysproxyRef.current?.open()}
/> />
} }
> >

View File

@ -1,152 +0,0 @@
import { useEffect, useState } from "react";
import { useLockFn } from "ahooks";
import { useTranslation } from "react-i18next";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogTitle,
List,
ListItem,
ListItemText,
styled,
TextField,
useTheme,
} from "@mui/material";
import { useVerge } from "@/hooks/use-verge";
import { defaultTheme, defaultDarkTheme } from "@/pages/_theme";
interface Props {
open: boolean;
onClose: () => void;
onError?: (err: Error) => void;
}
const Item = styled(ListItem)(() => ({
padding: "5px 2px",
}));
const Round = styled("div")(() => ({
width: "24px",
height: "24px",
borderRadius: "18px",
display: "inline-block",
marginRight: "8px",
}));
const SettingTheme = (props: Props) => {
const { open, onClose, onError } = props;
const { t } = useTranslation();
const { verge, patchVerge } = useVerge();
const { theme_setting } = verge ?? {};
const [theme, setTheme] = useState(theme_setting || {});
useEffect(() => {
setTheme({ ...theme_setting } || {});
}, [theme_setting]);
const textProps = {
size: "small",
autoComplete: "off",
sx: { width: 135 },
} as const;
const handleChange = (field: keyof typeof theme) => (e: any) => {
setTheme((t) => ({ ...t, [field]: e.target.value }));
};
const onSave = useLockFn(async () => {
try {
await patchVerge({ theme_setting: theme });
onClose();
} catch (err: any) {
onError?.(err);
}
});
// default theme
const { palette } = useTheme();
const dt = palette.mode === "light" ? defaultTheme : defaultDarkTheme;
type ThemeKey = keyof typeof theme & keyof typeof defaultTheme;
const renderItem = (label: string, key: ThemeKey) => {
return (
<Item>
<ListItemText primary={label} />
<Round sx={{ background: theme[key] || dt[key] }} />
<TextField
{...textProps}
value={theme[key] ?? ""}
placeholder={dt[key]}
onChange={handleChange(key)}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>
</Item>
);
};
return (
<Dialog open={open} onClose={onClose}>
<DialogTitle>{t("Theme Setting")}</DialogTitle>
<DialogContent
sx={{ width: 400, maxHeight: 300, overflow: "auto", pb: 0 }}
>
<List sx={{ pt: 0 }}>
{renderItem("Primary Color", "primary_color")}
{renderItem("Secondary Color", "secondary_color")}
{renderItem("Primary Text", "primary_text")}
{renderItem("Secondary Text", "secondary_text")}
{renderItem("Info Color", "info_color")}
{renderItem("Error Color", "error_color")}
{renderItem("Warning Color", "warning_color")}
{renderItem("Success Color", "success_color")}
<Item>
<ListItemText primary="Font Family" />
<TextField
{...textProps}
value={theme.font_family ?? ""}
onChange={handleChange("font_family")}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>
</Item>
<Item>
<ListItemText primary="CSS Injection" />
<TextField
{...textProps}
value={theme.css_injection ?? ""}
onChange={handleChange("css_injection")}
onKeyDown={(e) => e.key === "Enter" && onSave()}
/>
</Item>
</List>
</DialogContent>
<DialogActions>
<Button variant="outlined" onClick={onClose}>
{t("Cancel")}
</Button>
<Button onClick={onSave} variant="contained">
{t("Save")}
</Button>
</DialogActions>
</Dialog>
);
};
export default SettingTheme;

View File

@ -1,4 +1,4 @@
import { useState } from "react"; import { useRef } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { import {
IconButton, IconButton,
@ -10,15 +10,15 @@ import {
import { openAppDir, openLogsDir, patchVergeConfig } from "@/services/cmds"; import { openAppDir, openLogsDir, patchVergeConfig } from "@/services/cmds";
import { ArrowForward } from "@mui/icons-material"; import { ArrowForward } from "@mui/icons-material";
import { useVerge } from "@/hooks/use-verge"; import { useVerge } from "@/hooks/use-verge";
import { SettingList, SettingItem } from "./setting";
import { version } from "@root/package.json"; import { version } from "@root/package.json";
import useModalHandler from "@/hooks/use-modal-handler"; import { DialogRef } from "@/components/base";
import ThemeModeSwitch from "./mods/theme-mode-switch"; import { SettingList, SettingItem } from "./mods/setting-comp";
import ConfigViewer from "./mods/config-viewer"; import { ThemeModeSwitch } from "./mods/theme-mode-switch";
import HotkeyViewer from "./mods/hotkey-viewer"; import { ConfigViewer } from "./mods/config-viewer";
import GuardState from "./mods/guard-state"; import { HotkeyViewer } from "./mods/hotkey-viewer";
import MiscViewer from "./mods/misc-viewer"; import { MiscViewer } from "./mods/misc-viewer";
import SettingTheme from "./setting-theme"; import { ThemeViewer } from "./mods/theme-viewer";
import { GuardState } from "./mods/guard-state";
interface Props { interface Props {
onError?: (err: Error) => void; onError?: (err: Error) => void;
@ -31,21 +31,22 @@ const SettingVerge = ({ onError }: Props) => {
const { theme_mode, theme_blur, traffic_graph, language } = verge ?? {}; const { theme_mode, theme_blur, traffic_graph, language } = verge ?? {};
const [themeOpen, setThemeOpen] = useState(false); const configRef = useRef<DialogRef>(null);
const [configOpen, setConfigOpen] = useState(false); const hotkeyRef = useRef<DialogRef>(null);
const miscRef = useRef<DialogRef>(null);
const themeRef = useRef<DialogRef>(null);
const onSwitchFormat = (_e: any, value: boolean) => value; const onSwitchFormat = (_e: any, value: boolean) => value;
const onChangeData = (patch: Partial<IVergeConfig>) => { const onChangeData = (patch: Partial<IVergeConfig>) => {
mutateVerge({ ...verge, ...patch }, false); mutateVerge({ ...verge, ...patch }, false);
}; };
const miscHandler = useModalHandler();
const hotkeyHandler = useModalHandler();
return ( return (
<SettingList title={t("Verge Setting")}> <SettingList title={t("Verge Setting")}>
<HotkeyViewer handler={hotkeyHandler} /> <ThemeViewer ref={themeRef} />
<MiscViewer handler={miscHandler} /> <ConfigViewer ref={configRef} />
<HotkeyViewer ref={hotkeyRef} />
<MiscViewer ref={miscRef} />
<SettingItem label={t("Language")}> <SettingItem label={t("Language")}>
<GuardState <GuardState
@ -104,7 +105,7 @@ const SettingVerge = ({ onError }: Props) => {
color="inherit" color="inherit"
size="small" size="small"
sx={{ my: "2px" }} sx={{ my: "2px" }}
onClick={() => miscHandler.current.open()} onClick={() => miscRef.current?.open()}
> >
<ArrowForward /> <ArrowForward />
</IconButton> </IconButton>
@ -115,7 +116,7 @@ const SettingVerge = ({ onError }: Props) => {
color="inherit" color="inherit"
size="small" size="small"
sx={{ my: "2px" }} sx={{ my: "2px" }}
onClick={() => setThemeOpen(true)} onClick={() => themeRef.current?.open()}
> >
<ArrowForward /> <ArrowForward />
</IconButton> </IconButton>
@ -126,7 +127,7 @@ const SettingVerge = ({ onError }: Props) => {
color="inherit" color="inherit"
size="small" size="small"
sx={{ my: "2px" }} sx={{ my: "2px" }}
onClick={() => hotkeyHandler.current.open()} onClick={() => hotkeyRef.current?.open()}
> >
<ArrowForward /> <ArrowForward />
</IconButton> </IconButton>
@ -137,7 +138,7 @@ const SettingVerge = ({ onError }: Props) => {
color="inherit" color="inherit"
size="small" size="small"
sx={{ my: "2px" }} sx={{ my: "2px" }}
onClick={() => setConfigOpen(true)} onClick={() => configRef.current?.open()}
> >
<ArrowForward /> <ArrowForward />
</IconButton> </IconButton>
@ -168,9 +169,6 @@ const SettingVerge = ({ onError }: Props) => {
<SettingItem label={t("Verge Version")}> <SettingItem label={t("Verge Version")}>
<Typography sx={{ py: "7px" }}>v{version}</Typography> <Typography sx={{ py: "7px" }}>v{version}</Typography>
</SettingItem> </SettingItem>
<SettingTheme open={themeOpen} onClose={() => setThemeOpen(false)} />
<ConfigViewer open={configOpen} onClose={() => setConfigOpen(false)} />
</SettingList> </SettingList>
); );
}; };