diff --git a/src/pages/rules.tsx b/src/pages/rules.tsx index 60f6853..72f54fb 100644 --- a/src/pages/rules.tsx +++ b/src/pages/rules.tsx @@ -1,71 +1,45 @@ import { useState } from "react"; -import { - Box, - Button, - Grid, - Slide, - Snackbar, - TextField, - Typography, -} from "@mui/material"; +import { Box, Button, TextField, Typography } from "@mui/material"; import { importProfile } from "../services/command"; +import useNotice from "../utils/use-notice"; const RulesPage = () => { const [url, setUrl] = useState(""); - const [message, setMessage] = useState(""); const [disabled, setDisabled] = useState(false); + const [notice, noticeElement] = useNotice(); + const onClick = () => { if (!url) return; setUrl(""); setDisabled(true); importProfile(url) - .then(() => setMessage("Successfully import profile.")) - .catch(() => setMessage("Failed to import profile.")) + .then(() => notice.success("Successfully import profile.")) + .catch(() => notice.error("Failed to import profile.")) .finally(() => setDisabled(false)); }; return ( - + Rules - - - setUrl(e.target.value)} - /> - - - - - + + setUrl(e.target.value)} + sx={{ mr: 4 }} + /> + + - setMessage("")} - message={message} - TransitionComponent={(p) => } - /> + {noticeElement} ); }; diff --git a/src/utils/use-notice.tsx b/src/utils/use-notice.tsx new file mode 100644 index 0000000..4999f05 --- /dev/null +++ b/src/utils/use-notice.tsx @@ -0,0 +1,55 @@ +import { useMemo, useState } from "react"; +import { IconButton, Slide, Snackbar } from "@mui/material"; +import { Close } from "@mui/icons-material"; + +interface NoticeInstance { + info: (msg: string) => void; + error: (msg: string) => void; + success: (msg: string) => void; +} + +const useNotice = () => { + const [message, setMessage] = useState(""); + const [level, setLevel] = useState<"info" | "error" | "success">("info"); + + const handleClose = (_e: any, reason: string) => { + if (reason !== "clickaway") setMessage(""); + }; + + const element = useMemo( + () => ( + } + action={ + setMessage("")} + > + + + } + /> + ), + [message] + ); + + const instance = (Object.fromEntries( + (["info", "error", "success"] as const).map((item) => [ + item, + (msg: string) => { + setLevel(item); + setMessage(msg); + }, + ]) + ) as unknown) as NoticeInstance; + + return [instance, element] as const; +}; + +export default useNotice;