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,17 +72,21 @@ const ClashFieldViewer = ({ handler }: Props) => {
}; };
return ( return (
<Dialog open={open} onClose={() => setOpen(false)}> <BaseDialog
<DialogTitle>{t("Clash Field")}</DialogTitle> open={open}
title={t("Clash Field")}
<DialogContent contentSx={{
sx={{
pb: 0, pb: 0,
width: 320, width: 320,
height: 300, height: 300,
overflowY: "auto", overflowY: "auto",
userSelect: "text", userSelect: "text",
}} }}
okBtn={t("Save")}
cancelBtn={t("Back")}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={handleSave}
> >
{otherFields.map((item) => { {otherFields.map((item) => {
const inSelect = selected.includes(item); const inSelect = selected.includes(item);
@ -143,19 +119,9 @@ const ClashFieldViewer = ({ handler }: Props) => {
<Typography>{item}</Typography> <Typography>{item}</Typography>
</Stack> </Stack>
))} ))}
</DialogContent> </BaseDialog>
<DialogActions>
<Button variant="outlined" onClick={() => setOpen(false)}>
{t("Back")}
</Button>
<Button variant="contained" onClick={handleSave}>
{t("Save")}
</Button>
</DialogActions>
</Dialog>
); );
}; });
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),
};
}
useEffect(() => {
if (open && config?.["mixed-port"]) {
setPort(config["mixed-port"]); setPort(config["mixed-port"]);
} }
}, [open, config?.["mixed-port"]]); setOpen(true);
},
close: () => setOpen(false),
}));
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
if (port < 1000) { if (port < 1000) {
@ -72,10 +55,16 @@ 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 }}
okBtn={t("Save")}
cancelBtn={t("Cancel")}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={onSave}
>
<List> <List>
<ListItem sx={{ padding: "5px 2px" }}> <ListItem sx={{ padding: "5px 2px" }}>
<ListItemText primary="Mixed Port" /> <ListItemText primary="Mixed Port" />
@ -90,18 +79,6 @@ const ClashPortViewer = ({ handler }: Props) => {
/> />
</ListItem> </ListItem>
</List> </List>
</DialogContent> </BaseDialog>
<DialogActions>
<Button variant="outlined" onClick={() => setOpen(false)}>
{t("Cancel")}
</Button>
<Button onClick={onSave} variant="contained">
{t("Save")}
</Button>
</DialogActions>
</Dialog>
); );
}; });
export default ClashPortViewer;

View File

@ -1,38 +1,42 @@
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; return () => {
if (instanceRef.current) {
instanceRef.current.dispose();
instanceRef.current = null;
}
};
}, []);
useImperativeHandle(ref, () => ({
open: () => {
setOpen(true);
getRuntimeYaml().then((data) => { getRuntimeYaml().then((data) => {
const dom = editorRef.current; const dom = editorRef.current;
@ -48,31 +52,25 @@ const ConfigViewer = (props: Props) => {
readOnly: true, readOnly: true,
}); });
}); });
},
return () => { close: () => setOpen(false),
if (instanceRef.current) { }));
instanceRef.current.dispose();
instanceRef.current = null;
}
};
}, [open]);
return ( return (
<Dialog open={open} onClose={onClose}> <BaseDialog
<DialogTitle> open={open}
title={
<>
{t("Runtime Config")} <Chip label={t("ReadOnly")} size="small" /> {t("Runtime Config")} <Chip label={t("ReadOnly")} size="small" />
</DialogTitle> </>
}
<DialogContent sx={{ width: 520, pb: 1 }}> contentSx={{ width: 520, pb: 1 }}
cancelBtn={t("Back")}
disableOk
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
>
<div style={{ width: "100%", height: "420px" }} ref={editorRef} /> <div style={{ width: "100%", height: "420px" }} ref={editorRef} />
</DialogContent> </BaseDialog>
<DialogActions>
<Button variant="outlined" onClick={onClose}>
{t("Back")}
</Button>
</DialogActions>
</Dialog>
); );
}; });
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,10 +39,16 @@ const ControllerViewer = ({ 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: 400 }}> contentSx={{ width: 400 }}
okBtn={t("Save")}
cancelBtn={t("Cancel")}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={onSave}
>
<List> <List>
<ListItem sx={{ padding: "5px 2px" }}> <ListItem sx={{ padding: "5px 2px" }}>
<ListItemText primary="External Controller" /> <ListItemText primary="External Controller" />
@ -79,23 +69,11 @@ const ControllerViewer = ({ handler }: Props) => {
autoComplete="off" autoComplete="off"
sx={{ width: 175 }} sx={{ width: 175 }}
value={secret} value={secret}
placeholder="Recommanded" placeholder="Recommended"
onChange={(e) => setSecret(e.target.value)} onChange={(e) => setSecret(e.target.value)}
/> />
</ListItem> </ListItem>
</List> </List>
</DialogContent> </BaseDialog>
<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,27 +27,18 @@ 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: () => {
setOpen(true);
const map = {} as typeof hotkeyMap; const map = {} as typeof hotkeyMap;
verge?.hotkeys?.forEach((text) => { verge?.hotkeys?.forEach((text) => {
@ -70,7 +53,9 @@ const HotkeyViewer = ({ handler }: Props) => {
}); });
setHotkeyMap(map); setHotkeyMap(map);
}, [verge?.hotkeys, open]); },
close: () => setOpen(false),
}));
const onSave = useLockFn(async () => { const onSave = useLockFn(async () => {
const hotkeys = Object.entries(hotkeyMap) const hotkeys = Object.entries(hotkeyMap)
@ -97,10 +82,16 @@ 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 }}
okBtn={t("Save")}
cancelBtn={t("Cancel")}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={onSave}
>
{HOTKEY_FUNC.map((func) => ( {HOTKEY_FUNC.map((func) => (
<ItemWrapper key={func}> <ItemWrapper key={func}>
<Typography>{t(func)}</Typography> <Typography>{t(func)}</Typography>
@ -110,18 +101,6 @@ const HotkeyViewer = ({ handler }: Props) => {
/> />
</ItemWrapper> </ItemWrapper>
))} ))}
</DialogContent> </BaseDialog>
<DialogActions>
<Button variant="outlined" onClick={() => setOpen(false)}>
{t("Cancel")}
</Button>
<Button onClick={onSave} variant="contained">
{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,10 +40,16 @@ const MiscViewer = ({ handler }: Props) => {
}); });
return ( return (
<Dialog open={open} onClose={() => setOpen(false)}> <BaseDialog
<DialogTitle>{t("Miscellaneous")}</DialogTitle> open={open}
title={t("Miscellaneous")}
<DialogContent sx={{ width: 420 }}> contentSx={{ width: 420 }}
okBtn={t("Save")}
cancelBtn={t("Cancel")}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={onSave}
>
<List> <List>
<ListItem sx={{ padding: "5px 2px" }}> <ListItem sx={{ padding: "5px 2px" }}>
<ListItemText primary="Auto Close Connections" /> <ListItemText primary="Auto Close Connections" />
@ -93,18 +79,6 @@ const MiscViewer = ({ handler }: Props) => {
/> />
</ListItem> </ListItem>
</List> </List>
</DialogContent> </BaseDialog>
<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, () => ({
open: () => {
setOpen(true);
setValue({ setValue({
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,
}); });
}, [verge]); 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,10 +80,16 @@ 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")}
<DialogContent sx={{ width: 450, maxHeight: 300 }}> contentSx={{ width: 450, maxHeight: 300 }}
okBtn={t("Save")}
cancelBtn={t("Cancel")}
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
onOk={onSave}
>
<List> <List>
<ListItem sx={{ padding: "5px 2px" }}> <ListItem sx={{ padding: "5px 2px" }}>
<ListItemText primary={t("Proxy Guard")} /> <ListItemText primary={t("Proxy Guard")} />
@ -139,10 +121,7 @@ const SysproxyViewer = ({ handler }: Props) => {
</ListItem> </ListItem>
<ListItem sx={{ padding: "5px 2px", alignItems: "start" }}> <ListItem sx={{ padding: "5px 2px", alignItems: "start" }}>
<ListItemText <ListItemText primary={t("Proxy Bypass")} sx={{ padding: "3px 0" }} />
primary={t("Proxy Bypass")}
sx={{ padding: "3px 0" }}
/>
<TextField <TextField
disabled={!enabled} disabled={!enabled}
size="small" size="small"
@ -180,18 +159,16 @@ const SysproxyViewer = ({ handler }: Props) => {
<Typography className="value">{sysproxy?.bypass || "-"}</Typography> <Typography className="value">{sysproxy?.bypass || "-"}</Typography>
</FlexBox> </FlexBox>
</Box> </Box>
</DialogContent> </BaseDialog>
<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 = {
useImperativeHandle(ref, () => ({
open: () => setOpen(true), open: () => setOpen(true),
close: () => setOpen(false), 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,13 +70,15 @@ 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}
title={
<Box display="flex" justifyContent="space-between">
{t("Web UI")} {t("Web UI")}
<Button <Button
variant="contained" variant="contained"
@ -99,16 +88,19 @@ const WebUIViewer = ({ handler, onError }: Props) => {
> >
{t("New")} {t("New")}
</Button> </Button>
</DialogTitle> </Box>
}
<DialogContent contentSx={{
sx={{
width: 450, width: 450,
height: 300, height: 300,
pb: 1, pb: 1,
overflowY: "auto", overflowY: "auto",
userSelect: "text", userSelect: "text",
}} }}
cancelBtn={t("Back")}
disableOk
onClose={() => setOpen(false)}
onCancel={() => setOpen(false)}
> >
{editing && ( {editing && (
<WebUIItem <WebUIItem
@ -142,15 +134,6 @@ const WebUIViewer = ({ handler, onError }: Props) => {
onOpenUrl={handleOpenUrl} onOpenUrl={handleOpenUrl}
/> />
))} ))}
</DialogContent> </BaseDialog>
<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>
); );
}; };