123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431 |
- import useSWR, { mutate } from "swr";
- import { useMemo, useRef, useState } from "react";
- import { useLockFn } from "ahooks";
- import { useSetRecoilState } from "recoil";
- import {
- Box,
- Button,
- Grid,
- IconButton,
- Stack,
- TextField,
- Divider,
- } from "@mui/material";
- import {
- DndContext,
- closestCenter,
- KeyboardSensor,
- PointerSensor,
- useSensor,
- useSensors,
- DragEndEvent,
- } from "@dnd-kit/core";
- import {
- SortableContext,
- sortableKeyboardCoordinates,
- } from "@dnd-kit/sortable";
- import { LoadingButton } from "@mui/lab";
- import {
- ClearRounded,
- ContentPasteRounded,
- LocalFireDepartmentRounded,
- RefreshRounded,
- TextSnippetOutlined,
- } from "@mui/icons-material";
- import { useTranslation } from "react-i18next";
- import {
- getProfiles,
- importProfile,
- enhanceProfiles,
- getRuntimeLogs,
- deleteProfile,
- updateProfile,
- reorderProfile,
- } from "@/services/cmds";
- import { atomLoadingCache } from "@/services/states";
- import { closeAllConnections } from "@/services/api";
- import { BasePage, DialogRef, Notice } from "@/components/base";
- import {
- ProfileViewer,
- ProfileViewerRef,
- } from "@/components/profile/profile-viewer";
- import { ProfileItem } from "@/components/profile/profile-item";
- import { ProfileMore } from "@/components/profile/profile-more";
- import { useProfiles } from "@/hooks/use-profiles";
- import { ConfigViewer } from "@/components/setting/mods/config-viewer";
- import { throttle } from "lodash-es";
- import { useRecoilState } from "recoil";
- import { atomThemeMode } from "@/services/states";
- const ProfilePage = () => {
- const { t } = useTranslation();
- const [url, setUrl] = useState("");
- const [disabled, setDisabled] = useState(false);
- const [activating, setActivating] = useState("");
- const [loading, setLoading] = useState(false);
- const sensors = useSensors(
- useSensor(PointerSensor),
- useSensor(KeyboardSensor, {
- coordinateGetter: sortableKeyboardCoordinates,
- })
- );
- const {
- profiles = {},
- activateSelected,
- patchProfiles,
- mutateProfiles,
- } = useProfiles();
- const { data: chainLogs = {}, mutate: mutateLogs } = useSWR(
- "getRuntimeLogs",
- getRuntimeLogs
- );
- const chain = profiles.chain || [];
- const viewerRef = useRef<ProfileViewerRef>(null);
- const configRef = useRef<DialogRef>(null);
- // distinguish type
- const { regularItems, enhanceItems } = useMemo(() => {
- const items = profiles.items || [];
- const chain = profiles.chain || [];
- const type1 = ["local", "remote"];
- const type2 = ["merge", "script"];
- const regularItems = items.filter((i) => i && type1.includes(i.type!));
- const restItems = items.filter((i) => i && type2.includes(i.type!));
- const restMap = Object.fromEntries(restItems.map((i) => [i.uid, i]));
- const enhanceItems = chain
- .map((i) => restMap[i]!)
- .filter(Boolean)
- .concat(restItems.filter((i) => !chain.includes(i.uid)));
- return { regularItems, enhanceItems };
- }, [profiles]);
- const onImport = async () => {
- if (!url) return;
- setLoading(true);
- try {
- await importProfile(url);
- Notice.success("Successfully import profile.");
- setUrl("");
- setLoading(false);
- getProfiles().then((newProfiles) => {
- mutate("getProfiles", newProfiles);
- const remoteItem = newProfiles.items?.find((e) => e.type === "remote");
- if (!newProfiles.current && remoteItem) {
- const current = remoteItem.uid;
- patchProfiles({ current });
- mutateLogs();
- setTimeout(() => activateSelected(), 2000);
- }
- });
- } catch (err: any) {
- Notice.error(err.message || err.toString());
- setLoading(false);
- } finally {
- setDisabled(false);
- setLoading(false);
- }
- };
- const onDragEnd = async (event: DragEndEvent) => {
- const { active, over } = event;
- if (over) {
- if (active.id !== over.id) {
- await reorderProfile(active.id.toString(), over.id.toString());
- mutateProfiles();
- }
- }
- };
- const onSelect = useLockFn(async (current: string, force: boolean) => {
- if (!force && current === profiles.current) return;
- // 避免大多数情况下loading态闪烁
- const reset = setTimeout(() => setActivating(current), 100);
- try {
- await patchProfiles({ current });
- mutateLogs();
- closeAllConnections();
- setTimeout(() => activateSelected(), 2000);
- Notice.success("Refresh clash config", 1000);
- } catch (err: any) {
- Notice.error(err?.message || err.toString(), 4000);
- } finally {
- clearTimeout(reset);
- setActivating("");
- }
- });
- const onEnhance = useLockFn(async () => {
- try {
- await enhanceProfiles();
- mutateLogs();
- Notice.success("Refresh clash config", 1000);
- } catch (err: any) {
- Notice.error(err.message || err.toString(), 3000);
- }
- });
- const onEnable = useLockFn(async (uid: string) => {
- if (chain.includes(uid)) return;
- const newChain = [...chain, uid];
- await patchProfiles({ chain: newChain });
- mutateLogs();
- });
- const onDisable = useLockFn(async (uid: string) => {
- if (!chain.includes(uid)) return;
- const newChain = chain.filter((i) => i !== uid);
- await patchProfiles({ chain: newChain });
- mutateLogs();
- });
- const onDelete = useLockFn(async (uid: string) => {
- try {
- await onDisable(uid);
- await deleteProfile(uid);
- mutateProfiles();
- mutateLogs();
- } catch (err: any) {
- Notice.error(err?.message || err.toString());
- }
- });
- const onMoveTop = useLockFn(async (uid: string) => {
- if (!chain.includes(uid)) return;
- const newChain = [uid].concat(chain.filter((i) => i !== uid));
- await patchProfiles({ chain: newChain });
- mutateLogs();
- });
- const onMoveEnd = useLockFn(async (uid: string) => {
- if (!chain.includes(uid)) return;
- const newChain = chain.filter((i) => i !== uid).concat([uid]);
- await patchProfiles({ chain: newChain });
- mutateLogs();
- });
- // 更新所有订阅
- const setLoadingCache = useSetRecoilState(atomLoadingCache);
- const onUpdateAll = useLockFn(async () => {
- const throttleMutate = throttle(mutateProfiles, 2000, {
- trailing: true,
- });
- const updateOne = async (uid: string) => {
- try {
- await updateProfile(uid);
- throttleMutate();
- } finally {
- setLoadingCache((cache) => ({ ...cache, [uid]: false }));
- }
- };
- return new Promise((resolve) => {
- setLoadingCache((cache) => {
- // 获取没有正在更新的订阅
- const items = regularItems.filter(
- (e) => e.type === "remote" && !cache[e.uid]
- );
- const change = Object.fromEntries(items.map((e) => [e.uid, true]));
- Promise.allSettled(items.map((e) => updateOne(e.uid))).then(resolve);
- return { ...cache, ...change };
- });
- });
- });
- const onCopyLink = async () => {
- const text = await navigator.clipboard.readText();
- if (text) setUrl(text);
- };
- const [mode] = useRecoilState(atomThemeMode);
- const islight = mode === "light" ? true : false;
- const dividercolor = islight
- ? "rgba(0, 0, 0, 0.06)"
- : "rgba(255, 255, 255, 0.06)";
- return (
- <BasePage
- full
- title={t("Profiles")}
- contentStyle={{ height: "100%" }}
- header={
- <Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
- <IconButton
- size="small"
- color="inherit"
- title={t("Update All Profiles")}
- onClick={onUpdateAll}
- >
- <RefreshRounded />
- </IconButton>
- <IconButton
- size="small"
- color="inherit"
- title={t("View Runtime Config")}
- onClick={() => configRef.current?.open()}
- >
- <TextSnippetOutlined />
- </IconButton>
- <IconButton
- size="small"
- color="primary"
- title={t("Reactivate Profiles")}
- onClick={onEnhance}
- >
- <LocalFireDepartmentRounded />
- </IconButton>
- </Box>
- }
- >
- <Stack
- direction="row"
- spacing={1}
- sx={{
- pt: 1,
- mb: 0.5,
- mx: "10px",
- height: "36px",
- display: "flex",
- alignItems: "center",
- }}
- >
- <TextField
- hiddenLabel
- fullWidth
- size="small"
- value={url}
- variant="outlined"
- autoComplete="off"
- spellCheck="false"
- onChange={(e) => setUrl(e.target.value)}
- sx={{ input: { py: 0.65, px: 1.25 } }}
- placeholder={t("Profile URL")}
- InputProps={{
- sx: { pr: 1 },
- endAdornment: !url ? (
- <IconButton
- size="small"
- sx={{ p: 0.5 }}
- title={t("Paste")}
- onClick={onCopyLink}
- >
- <ContentPasteRounded fontSize="inherit" />
- </IconButton>
- ) : (
- <IconButton
- size="small"
- sx={{ p: 0.5 }}
- title={t("Clear")}
- onClick={() => setUrl("")}
- >
- <ClearRounded fontSize="inherit" />
- </IconButton>
- ),
- }}
- />
- <LoadingButton
- disabled={!url || disabled}
- loading={loading}
- variant="contained"
- size="small"
- sx={{ borderRadius: "6px" }}
- onClick={onImport}
- >
- {t("Import")}
- </LoadingButton>
- <Button
- variant="contained"
- size="small"
- sx={{ borderRadius: "6px" }}
- onClick={() => viewerRef.current?.create()}
- >
- {t("New")}
- </Button>
- </Stack>
- <Box
- sx={{
- pt: 1,
- mb: 0.5,
- pl: "10px",
- mr: "10px",
- height: "calc(100% - 20px)",
- overflowY: "auto",
- }}
- >
- <DndContext
- sensors={sensors}
- collisionDetection={closestCenter}
- onDragEnd={onDragEnd}
- >
- <Box sx={{ mb: 1.5 }}>
- <Grid container spacing={{ xs: 1, lg: 1 }}>
- <SortableContext
- items={regularItems.map((x) => {
- return x.uid;
- })}
- >
- {regularItems.map((item) => (
- <Grid item xs={12} sm={6} md={4} lg={3} key={item.file}>
- <ProfileItem
- id={item.uid}
- selected={profiles.current === item.uid}
- activating={activating === item.uid}
- itemData={item}
- onSelect={(f) => onSelect(item.uid, f)}
- onEdit={() => viewerRef.current?.edit(item)}
- />
- </Grid>
- ))}
- </SortableContext>
- </Grid>
- </Box>
- </DndContext>
- {enhanceItems.length > 0 && (
- <Divider
- variant="middle"
- flexItem
- sx={{ width: `calc(100% - 32px)`, borderColor: dividercolor }}
- ></Divider>
- )}
- {enhanceItems.length > 0 && (
- <Box sx={{ mt: 1.5 }}>
- <Grid container spacing={{ xs: 1, lg: 1 }}>
- {enhanceItems.map((item) => (
- <Grid item xs={12} sm={6} md={4} lg={3} key={item.file}>
- <ProfileMore
- selected={!!chain.includes(item.uid)}
- itemData={item}
- enableNum={chain.length || 0}
- logInfo={chainLogs[item.uid]}
- onEnable={() => onEnable(item.uid)}
- onDisable={() => onDisable(item.uid)}
- onDelete={() => onDelete(item.uid)}
- onMoveTop={() => onMoveTop(item.uid)}
- onMoveEnd={() => onMoveEnd(item.uid)}
- onEdit={() => viewerRef.current?.edit(item)}
- />
- </Grid>
- ))}
- </Grid>
- </Box>
- )}
- </Box>
- <ProfileViewer ref={viewerRef} onChange={() => mutateProfiles()} />
- <ConfigViewer ref={configRef} />
- </BasePage>
- );
- };
- export default ProfilePage;
|