Skip to content

Commit

Permalink
feat: server group
Browse files Browse the repository at this point in the history
  • Loading branch information
hamster1963 committed Nov 23, 2024
1 parent 0fb3f4a commit fb38b0e
Show file tree
Hide file tree
Showing 10 changed files with 167 additions and 109 deletions.
15 changes: 9 additions & 6 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,16 @@
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script>
(function() {
const storageKey = 'vite-ui-theme';
const theme = localStorage.getItem(storageKey) || 'system';
(function () {
const storageKey = "vite-ui-theme";
const theme = localStorage.getItem(storageKey) || "system";
const root = document.documentElement;

if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';

if (theme === "system") {
const systemTheme = window.matchMedia("(prefers-color-scheme: dark)")
.matches
? "dark"
: "light";
root.classList.add(systemTheme);
} else {
root.classList.add(theme);
Expand Down
21 changes: 13 additions & 8 deletions src/components/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,21 @@ const Footer: React.FC = () => {
<footer className="mx-auto w-full max-w-5xl px-4 lg:px-0 pb-4">
<section className="flex flex-col">
<section className="mt-1 flex items-center justify-between gap-2 text-[13px] font-light tracking-tight text-neutral-600/50 dark:text-neutral-300/50">
<p>©2020-{new Date().getFullYear()}{" "}
<p>
©2020-{new Date().getFullYear()}{" "}
<a href={"https://github.com/naiba/nezha"} target="_blank">
Nezha
</a></p>
<p>Theme by <a
href={"https://github.com/hamster1963/nezha-dash-react"}
target="_blank"
>
Nezha-Dash
</a></p>
</a>
</p>
<p>
Theme by{" "}
<a
href={"https://github.com/hamster1963/nezha-dash-react"}
target="_blank"
>
Nezha-Dash
</a>
</p>
</section>
</section>
</footer>
Expand Down
45 changes: 45 additions & 0 deletions src/components/GroupSwitch.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { cn } from "@/lib/utils";
import { m } from "framer-motion";

export default function GroupSwitch({
tabs,
currentTab,
setCurrentTab,
}: {
tabs: string[];
currentTab: string;
setCurrentTab: (tab: string) => void;
}) {
return (
<div className="z-50 flex flex-col items-start rounded-[50px]">
<div className="flex items-center gap-1 rounded-[50px] bg-stone-100 p-[3px] dark:bg-stone-800">
{tabs.map((tab: string) => (
<div
key={tab}
onClick={() => setCurrentTab(tab)}
className={cn(
"relative cursor-pointer rounded-3xl px-2.5 py-[8px] text-[13px] font-[600] transition-all duration-500",
currentTab === tab
? "text-black dark:text-white"
: "text-stone-400 dark:text-stone-500",
)}
>
{currentTab === tab && (
<m.div
layoutId="tab-switch"
className="absolute inset-0 z-10 h-full w-full content-center bg-white shadow-lg shadow-black/5 dark:bg-stone-700 dark:shadow-white/5"
style={{
originY: "0px",
borderRadius: 46,
}}
/>
)}
<div className="relative z-20 flex items-center gap-1">
<p className="whitespace-nowrap">{tab}</p>
</div>
</div>
))}
</div>
</div>
);
}
1 change: 1 addition & 0 deletions src/components/motion/framer-lazy-feature.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { domMax as default } from "framer-motion";
14 changes: 14 additions & 0 deletions src/components/motion/motion-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"use client";

import { LazyMotion } from "framer-motion";

const loadFeatures = () =>
import("./framer-lazy-feature").then((res) => res.default);

export const MotionProvider = ({ children }: { children: React.ReactNode }) => {
return (
<LazyMotion features={loadFeatures} strict key="framer">
{children}
</LazyMotion>
);
};
76 changes: 3 additions & 73 deletions src/lib/nezha-api.ts
Original file line number Diff line number Diff line change
@@ -1,77 +1,7 @@
export const fetchUsers = async (token: string) => {
const response = await fetch("http://localhost:8008/api/v1/user", {
headers: {
Authorization: `Bearer ${token}`,
},
});
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
return data;
};

export const createUser = async (
token: string,
username: string,
password: string,
) => {
const response = await fetch(`http://localhost:8008/api/v1/user`, {
method: "POST",
body: JSON.stringify({ username, password }),
headers: {
Authorization: `Bearer ${token}`,
},
});
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
return data;
};

export const deleteUser = async (token: string, ids: number[]) => {
const response = await fetch(
`http://localhost:8008/api/v1/batch-delete/user`,
{
method: "POST",
body: JSON.stringify(ids),
headers: {
Authorization: `Bearer ${token}`,
},
},
);
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
return data;
};

export const fetchServers = async (token: string) => {
const response = await fetch("http://localhost:8008/api/v1/server", {
headers: {
Authorization: `Bearer ${token}`,
},
});
const data = await response.json();
if (data.error) {
throw new Error(data.error);
}
return data;
};
import { ServerGroupResponse } from "@/types/nezha-api";

export const deleteServer = async (token: string, ids: number[]) => {
const response = await fetch(
`http://localhost:8008/api/v1/batch-delete/server`,
{
method: "POST",
body: JSON.stringify(ids),
headers: {
Authorization: `Bearer ${token}`,
},
},
);
export const fetchServerGroup = async (): Promise<ServerGroupResponse> => {
const response = await fetch("/api/v1/server-group");
const data = await response.json();
if (data.error) {
throw new Error(data.error);
Expand Down
36 changes: 20 additions & 16 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,26 +6,30 @@ import { ThemeProvider } from "./components/ThemeProvider";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { Toaster } from "sonner";
import { MotionProvider } from "./components/motion/motion-provider";

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<ThemeProvider storageKey="vite-ui-theme">
<QueryClientProvider client={queryClient}>
<App />
<Toaster duration={1000}
toastOptions={{
classNames: {
default:
"w-fit rounded-full px-2.5 py-1.5 bg-neutral-100 border border-neutral-200 backdrop-blur-xl shadow-none",
},
}}
position="top-center"
className={"flex items-center justify-center"}
/>
<ReactQueryDevtools />
</QueryClientProvider>
</ThemeProvider>
<MotionProvider>
<ThemeProvider storageKey="vite-ui-theme">
<QueryClientProvider client={queryClient}>
<App />
<Toaster
duration={1000}
toastOptions={{
classNames: {
default:
"w-fit rounded-full px-2.5 py-1.5 bg-neutral-100 border border-neutral-200 backdrop-blur-xl shadow-none",
},
}}
position="top-center"
className={"flex items-center justify-center"}
/>
<ReactQueryDevtools />
</QueryClientProvider>
</ThemeProvider>
</MotionProvider>
</React.StrictMode>,
);
48 changes: 42 additions & 6 deletions src/pages/Server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,34 @@ import { NezhaAPIResponse } from "@/types/nezha-api";
import ServerCard from "@/components/ServerCard";
import { formatNezhaInfo } from "@/lib/utils";
import ServerOverview from "@/components/ServerOverview";
import { useEffect } from "react";
import { useEffect, useState } from "react";
import { toast } from "sonner";
import { useQuery } from "@tanstack/react-query";
import { fetchServerGroup } from "@/lib/nezha-api";
import GroupSwitch from "@/components/GroupSwitch";
import { ServerGroup } from "@/types/nezha-api";

export default function Servers() {
const { data: groupData } = useQuery({
queryKey: ["server-group"],
queryFn: () => fetchServerGroup(),
});
const { lastMessage, readyState } = useWebSocket("/api/v1/ws/server", {
shouldReconnect: () => true, // 自动重连
reconnectInterval: 3000, // 重连间隔
shouldReconnect: () => true,
reconnectInterval: 3000,
});

// 添加分组状态
const [currentGroup, setCurrentGroup] = useState<string>("All");

// 获取所有分组名称
const groupTabs = [
"All",
...(groupData?.data?.map((item: ServerGroup) => item.group.name) || []),
];

useEffect(() => {
if (readyState == 1 ) {
if (readyState == 1) {
toast.success("WebSocket connected");
}
}, [readyState]);
Expand All @@ -40,7 +57,7 @@ export default function Servers() {
);
}

// 计算服务器总数和在线数量
// 计算所有服务器的统计数据(用于 Overview)
const totalServers = nezhaWsData.servers.length;
const onlineServers = nezhaWsData.servers.filter(
(server) => formatNezhaInfo(server).online,
Expand All @@ -57,6 +74,18 @@ export default function Servers() {
0,
);

// 根据当前选中的分组筛选服务器(用于显示列表)
const filteredServers = nezhaWsData.servers.filter((server) => {
if (currentGroup === "All") return true;
const group = groupData?.data?.find(
(g: ServerGroup) =>
g.group.name === currentGroup &&
Array.isArray(g.servers) &&
g.servers.includes(server.id),
);
return !!group;
});

return (
<div className="mx-auto w-full max-w-5xl px-0">
<ServerOverview
Expand All @@ -66,8 +95,15 @@ export default function Servers() {
up={up}
down={down}
/>
<div className="mt-6">
<GroupSwitch
tabs={groupTabs}
currentTab={currentGroup}
setCurrentTab={setCurrentGroup}
/>
</div>
<section className="grid grid-cols-1 gap-2 md:grid-cols-2 mt-6">
{nezhaWsData.servers.map((serverInfo) => (
{filteredServers.map((serverInfo) => (
<ServerCard key={serverInfo.id} serverInfo={serverInfo} />
))}
</section>
Expand Down
15 changes: 15 additions & 0 deletions src/types/nezha-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,18 @@ export interface NezhaAPIStatus {
temperatures: number;
gpu: number;
}

export interface ServerGroupResponse {
success: boolean;
data: ServerGroup[];
}

export interface ServerGroup {
group: {
id: number;
created_at: string;
updated_at: string;
name: string;
};
servers: number[];
}
5 changes: 5 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ export default defineConfig({
changeOrigin: true,
ws: true,
},
"/api/v1/": {
target: "http://localhost:8008",
changeOrigin: true,
ws: true,
},
},
},
});

0 comments on commit fb38b0e

Please sign in to comment.