import { useRef, useState } from "react"; import useSWR, { useSWRConfig } from "swr"; import { Box, Button, Grid, TextField, Typography } from "@mui/material"; import { getProfiles, importProfile, putProfiles, updateProfile, } from "../services/cmds"; import { getProxies } from "../services/api"; import ProfileItemComp from "../components/profile-item"; import useNotice from "../utils/use-notice"; import noop from "../utils/noop"; const ProfilePage = () => { const [url, setUrl] = useState(""); const [disabled, setDisabled] = useState(false); const [notice, noticeElement] = useNotice(); const { mutate } = useSWRConfig(); const { data: profiles = {} } = useSWR("getProfiles", getProfiles); const onImport = async () => { if (!url) return; setUrl(""); setDisabled(true); try { await importProfile(url); mutate("getProfiles", getProfiles()); if (!profiles.items?.length) putProfiles(0).catch(noop); notice.success("Successfully import profile."); } catch { notice.error("Failed to import profile."); } finally { setDisabled(false); } }; const lockRef = useRef(false); const onProfileChange = (index: number) => { if (lockRef.current) return; lockRef.current = true; putProfiles(index) .then(() => { mutate("getProfiles", { ...profiles, current: index }, true); mutate("getProxies", getProxies()); }) .catch((err) => { console.error(err); }) .finally(() => { lockRef.current = false; }); }; const onUpdateProfile = (index: number) => { updateProfile(index) .then(() => { mutate("getProfiles"); }) .catch((err) => { console.error(err); }); }; return ( Profiles setUrl(e.target.value)} sx={{ mr: 4 }} /> {profiles?.items?.map((item, idx) => ( onProfileChange(idx)} onUpdate={() => onUpdateProfile(idx)} /> ))} {noticeElement} ); }; export default ProfilePage;