Skip to content

Commit

Permalink
perf: use websocket context
Browse files Browse the repository at this point in the history
  • Loading branch information
hamster1963 committed Nov 24, 2024
1 parent 56d6305 commit 5364d5c
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 34 deletions.
11 changes: 3 additions & 8 deletions src/components/ServerDetailChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { formatNezhaInfo, formatRelativeTime } from "@/lib/utils";
import { NezhaAPI, NezhaAPIResponse } from "@/types/nezha-api";
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import useWebSocket from "react-use-websocket";
import {
Area,
AreaChart,
Expand All @@ -18,6 +17,7 @@ import {
} from "recharts";
import { ServerDetailChartLoading } from "./loading/ServerDetailLoading";
import AnimatedCircularProgressBar from "./ui/animated-circular-progress-bar";
import { useWebSocketContext } from "@/hooks/use-websocket-context";

type cpuChartData = {
timeStamp: string;
Expand Down Expand Up @@ -54,16 +54,11 @@ type connectChartData = {

export default function ServerDetailChart() {
const { id } = useParams();
const { lastMessage, readyState } = useWebSocket("/api/v1/ws/server", {
shouldReconnect: () => true,
reconnectInterval: 3000,
});
const { lastMessage, readyState } = useWebSocketContext();

// 检查连接状态
if (readyState !== 1) {
return (
<ServerDetailChartLoading />
);
return <ServerDetailChartLoading />;
}

// 解析消息
Expand Down
11 changes: 3 additions & 8 deletions src/components/ServerDetailOverview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,19 @@ import { ServerDetailLoading } from "@/components/loading/ServerDetailLoading";
import ServerFlag from "@/components/ServerFlag";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent } from "@/components/ui/card";
import { useWebSocketContext } from "@/hooks/use-websocket-context";
import { cn, formatBytes, formatNezhaInfo } from "@/lib/utils";
import { NezhaAPIResponse } from "@/types/nezha-api";
import { useNavigate, useParams } from "react-router-dom";
import useWebSocket from "react-use-websocket";

export default function ServerDetailOverview() {
const navigate = useNavigate();
const { id } = useParams();
const { lastMessage, readyState } = useWebSocket("/api/v1/ws/server", {
shouldReconnect: () => true,
reconnectInterval: 3000,
});
const { lastMessage, readyState } = useWebSocketContext();

// 检查连接状态
if (readyState !== 1) {
return (
<ServerDetailLoading />
);
return <ServerDetailLoading />;
}

// 解析消息
Expand Down
11 changes: 11 additions & 0 deletions src/context/websocket-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { createContext } from "react";

export interface WebSocketContextType {
sendMessage: (message: string) => void;
lastMessage: MessageEvent | null;
readyState: number;
}

export const WebSocketContext = createContext<WebSocketContextType | undefined>(
undefined,
);
34 changes: 34 additions & 0 deletions src/context/websocket-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import React from "react";
import {
WebSocketContext,
type WebSocketContextType,
} from "./websocket-context";
import useWebSocket from "react-use-websocket";

interface WebSocketProviderProps {
url: string;
children: React.ReactNode;
}

export const WebSocketProvider: React.FC<WebSocketProviderProps> = ({
url,
children,
}) => {
const { sendMessage, lastMessage, readyState } = useWebSocket(url, {
reconnectAttempts: 10,
reconnectInterval: 3000,
shouldReconnect: () => true,
});

const contextValue: WebSocketContextType = {
sendMessage,
lastMessage,
readyState,
};

return (
<WebSocketContext.Provider value={contextValue}>
{children}
</WebSocketContext.Provider>
);
};
12 changes: 12 additions & 0 deletions src/hooks/use-websocket-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { useContext } from "react";
import { WebSocketContext } from "../context/websocket-context";

export const useWebSocketContext = () => {
const context = useContext(WebSocketContext);
if (context === undefined) {
throw new Error(
"useWebSocketContext must be used within a WebSocketProvider",
);
}
return context;
};
29 changes: 16 additions & 13 deletions src/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ 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";
import { WebSocketProvider } from "./context/websocket-provider";

const queryClient = new QueryClient();

Expand All @@ -15,19 +16,21 @@ ReactDOM.createRoot(document.getElementById("root")!).render(
<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 />
<WebSocketProvider url="/api/v1/ws/server">
<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 />
</WebSocketProvider>
</QueryClientProvider>
</ThemeProvider>
</MotionProvider>
Expand Down
7 changes: 2 additions & 5 deletions src/pages/Server.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import useWebSocket from "react-use-websocket";
import { NezhaAPIResponse } from "@/types/nezha-api";
import ServerCard from "@/components/ServerCard";
import { formatNezhaInfo } from "@/lib/utils";
Expand All @@ -9,16 +8,14 @@ import { useQuery } from "@tanstack/react-query";
import { fetchServerGroup } from "@/lib/nezha-api";
import GroupSwitch from "@/components/GroupSwitch";
import { ServerGroup } from "@/types/nezha-api";
import { useWebSocketContext } from "@/hooks/use-websocket-context";

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,
});
const { lastMessage, readyState } = useWebSocketContext();

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

0 comments on commit 5364d5c

Please sign in to comment.