forked from partykit/partykit-nextjs-chat-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ConnectionStatus.tsx
60 lines (53 loc) · 1.61 KB
/
ConnectionStatus.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"use client";
import { useEffect, useState } from "react";
import PartySocket from "partysocket";
const readyStates = {
[PartySocket.CONNECTING]: {
text: "Connecting",
className: "bg-yellow-500",
},
[PartySocket.OPEN]: {
text: "Connected",
className: "bg-green-500",
},
[PartySocket.CLOSING]: {
text: "Closing",
className: "bg-orange-500",
},
[PartySocket.CLOSED]: {
text: "Not Connected",
className: "bg-red-500",
},
};
export default function ConnectionStatus(props: {
socket: PartySocket | WebSocket | null;
}) {
const { socket } = props;
const [readyState, setReadyState] = useState<number>(
socket?.readyState === 1 ? 1 : 0
);
const display = readyStates[readyState as keyof typeof readyStates];
useEffect(() => {
if (socket) {
const onStateChange = () => {
setReadyState(socket.readyState);
};
socket.addEventListener("open", onStateChange);
socket.addEventListener("close", onStateChange);
return () => {
socket.removeEventListener("open", onStateChange);
socket.removeEventListener("close", onStateChange);
};
}
}, [socket]);
return (
<div className="z-20 fixed top-0 sm:top-2 left-0 w-full flex justify-center">
<div className="flex gap-2 justify-center items-center bg-stone-50 rounded-full shadow-md border border-stone-300 px-3 py-1 sm:py-2">
<p className="text-xs font-base uppercase tracking-wider leading-none text-stone-500">
{display.text}
</p>
<div className={`w-3 h-3 rounded-full ${display.className}`}></div>
</div>
</div>
);
}