Skip to content

Commit

Permalink
feat: refactor refresh
Browse files Browse the repository at this point in the history
  • Loading branch information
hamster1963 committed Dec 26, 2024
1 parent 704818d commit 5334fd2
Show file tree
Hide file tree
Showing 10 changed files with 93 additions and 28 deletions.
3 changes: 2 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Route, BrowserRouter as Router, Routes } from "react-router-dom"

import ErrorBoundary from "./components/ErrorBoundary"
import Footer from "./components/Footer"
import Header from "./components/Header"
import Header, { RefreshToast } from "./components/Header"
import { useTheme } from "./hooks/use-theme"
import { InjectContext } from "./lib/inject"
import { fetchSetting } from "./lib/nezha-api"
Expand Down Expand Up @@ -93,6 +93,7 @@ const App: React.FC = () => {
>
<main className="flex z-20 min-h-[calc(100vh-calc(var(--spacing)*16))] flex-1 flex-col gap-4 p-4 md:p-10 md:pt-8">
<Header />
<RefreshToast />
<Routes>
<Route path="/" element={<Server />} />
<Route path="/server/:id" element={<ServerDetail />} />
Expand Down
74 changes: 59 additions & 15 deletions src/components/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ import { useWebSocketContext } from "@/hooks/use-websocket-context"
import { fetchLoginUser, fetchSetting } from "@/lib/nezha-api"
import { cn } from "@/lib/utils"
import { useQuery } from "@tanstack/react-query"
import { AnimatePresence, m } from "framer-motion"
import { DateTime } from "luxon"
import { useEffect, useRef, useState } from "react"
import { useTranslation } from "react-i18next"
import { useNavigate } from "react-router-dom"

import { LanguageSwitcher } from "./LanguageSwitcher"
import { Loader } from "./loading/Loader"
import { Loader, LoadingSpinner } from "./loading/Loader"
import { Button } from "./ui/button"

function Header() {
Expand Down Expand Up @@ -138,32 +139,75 @@ function Links() {
)
}

export function RefreshToast() {
const { t } = useTranslation()
const navigate = useNavigate()

const { needReconnect } = useWebSocketContext()

if (!needReconnect) {
return null
}

if (needReconnect) {
sessionStorage.removeItem("needRefresh")
setTimeout(() => {
navigate(0)
}, 1000)
}

return (
<div className="flex flex-col items-center justify-center">
<AnimatePresence>
<m.div
initial={{ opacity: 0, filter: "blur(10px)", scale: 0.8 }}
animate={{ opacity: 1, filter: "blur(0px)", scale: 1 }}
exit={{ opacity: 0, filter: "blur(10px)", scale: 0.8 }}
transition={{ type: "spring", duration: 0.8 }}
className="fixed overflow-hidden top-[35px] z-[999] flex items-center justify-between gap-4 rounded-[50px] border-[1px] border-solid bg-white px-2 py-1.5 shadow-xl shadow-black/5 dark:border-stone-700 dark:bg-stone-800 dark:shadow-none"
>
<section className="flex items-center gap-1.5">
<LoadingSpinner />
<p className="text-[12.5px] font-medium">{t("refreshing")}...</p>
</section>
</m.div>
</AnimatePresence>
</div>
)
}

function DashboardLink() {
const { t } = useTranslation()
const { reconnect } = useWebSocketContext()
const initRef = useRef(false)
const { data: userData } = useQuery({
const { setNeedReconnect } = useWebSocketContext()
const previousLoginState = useRef<boolean | null>(null)
const {
data: userData,
isFetched,
isLoadingError,
isError,
} = useQuery({
queryKey: ["login-user"],
queryFn: () => fetchLoginUser(),
refetchOnMount: true,
refetchOnMount: false,
refetchOnWindowFocus: true,
refetchIntervalInBackground: true,
refetchInterval: 1000 * 60 * 1,
retry: false,
refetchInterval: 1000 * 5,
retry: 0,
})

let isLogin = !!userData?.data?.id
const isLogin = isError ? false : userData ? !!userData?.data?.id && !!document.cookie : false

if (!document.cookie) {
isLogin = false
if (isLoadingError) {
previousLoginState.current = isLogin
}

useEffect(() => {
// 当登录状态变化时重新连接 WebSocket
if (initRef.current) {
reconnect()
} else {
initRef.current = true
if (isFetched || isError) {
// 只有当登录状态发生变化时才设置needReconnect
if (previousLoginState.current !== null && previousLoginState.current !== isLogin) {
setNeedReconnect(true)
}
previousLoginState.current = isLogin
}
}, [isLogin])

Expand Down
19 changes: 19 additions & 0 deletions src/components/loading/Loader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,22 @@ export const Loader = ({ visible }: { visible: boolean }) => {
</div>
)
}

export const LoadingSpinner = () => {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className={"size-4 animate-spin"}
>
<path d="M21 12a9 9 0 1 1-6.219-8.56" />
</svg>
)
}
4 changes: 4 additions & 0 deletions src/context/websocket-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,15 @@ export interface WebSocketContextType {
connected: boolean
messageHistory: { data: string }[]
reconnect: () => void
needReconnect: boolean
setNeedReconnect: (needReconnect: boolean) => void
}

export const WebSocketContext = createContext<WebSocketContextType>({
lastMessage: null,
connected: false,
messageHistory: [],
reconnect: () => {},
needReconnect: false,
setNeedReconnect: () => {},
})
Empty file removed src/context/websocket-context.tsx
Empty file.
9 changes: 6 additions & 3 deletions src/context/websocket-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export const WebSocketProvider: React.FC<WebSocketProviderProps> = ({ url, child
const [lastMessage, setLastMessage] = useState<{ data: string } | null>(null)
const [messageHistory, setMessageHistory] = useState<{ data: string }[]>([]) // 新增历史消息状态
const [connected, setConnected] = useState(false)
const [needReconnect, setNeedReconnect] = useState(false)
const ws = useRef<WebSocket | null>(null)
const reconnectTimeout = useRef<NodeJS.Timeout>(null)
const maxReconnectAttempts = 30
Expand Down Expand Up @@ -99,7 +100,7 @@ export const WebSocketProvider: React.FC<WebSocketProviderProps> = ({ url, child
cleanup()
setTimeout(() => {
connect()
}, 100)
}, 1000)
}

useEffect(() => {
Expand All @@ -113,8 +114,10 @@ export const WebSocketProvider: React.FC<WebSocketProviderProps> = ({ url, child
const contextValue: WebSocketContextType = {
lastMessage,
connected,
messageHistory, // 添加到 context value
reconnect, // 添加到 context value
messageHistory,
reconnect,
needReconnect,
setNeedReconnect,
}

return <WebSocketContext.Provider value={contextValue}>{children}</WebSocketContext.Provider>
Expand Down
1 change: 1 addition & 0 deletions src/locales/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"online": "Online",
"offline": "Offline",
"whereTheTimeIs": "Where the time is",
"refreshing": "Refreshing",
"info": {
"websocketConnecting": "WebSocket connecting",
"websocketConnected": "WebSocket connected",
Expand Down
1 change: 1 addition & 0 deletions src/locales/zh-CN/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"online": "在线",
"offline": "离线",
"whereTheTimeIs": "当前时间",
"refreshing": "刷新中",
"info": {
"websocketConnecting": "WebSocket 连接中",
"websocketConnected": "WebSocket 连接成功",
Expand Down
1 change: 1 addition & 0 deletions src/locales/zh-TW/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"online": "在線",
"offline": "離線",
"whereTheTimeIs": "目前時間",
"refreshing": "刷新中",
"info": {
"websocketConnecting": "WebSocket 連接中",
"websocketConnected": "WebSocket 連接成功",
Expand Down
9 changes: 0 additions & 9 deletions src/pages/Server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import { ArrowDownIcon, ArrowUpIcon, ArrowsUpDownIcon, ChartBarSquareIcon, MapIc
import { useQuery } from "@tanstack/react-query"
import { useEffect, useState } from "react"
import { useTranslation } from "react-i18next"
import { toast } from "sonner"

export default function Servers() {
const { t } = useTranslation()
Expand Down Expand Up @@ -56,14 +55,6 @@ export default function Servers() {

const groupTabs = ["All", ...(groupData?.data?.map((item: ServerGroup) => item.group.name) || [])]

useEffect(() => {
const hasShownToast = sessionStorage.getItem("websocket-connected-toast")
if (connected && !hasShownToast) {
toast.success(t("info.websocketConnected"))
sessionStorage.setItem("websocket-connected-toast", "true")
}
}, [connected])

if (!connected && !lastMessage) {
return (
<div className="flex flex-col items-center min-h-96 justify-center ">
Expand Down

0 comments on commit 5334fd2

Please sign in to comment.