fix: Fix socket state and onClick function in CounterCard

Fix socket state initialization, onClick function, and modify component rendering in CounterCard
This commit is contained in:
Ayase Minori 2023-11-22 06:51:17 +00:00
parent 0f63c6f833
commit 2d82486c48
2 changed files with 42 additions and 14 deletions

View file

@ -6,7 +6,6 @@ import * as $0 from "./routes/_404.tsx";
import * as $1 from "./routes/_app.tsx"; import * as $1 from "./routes/_app.tsx";
import * as $2 from "./routes/index.tsx"; import * as $2 from "./routes/index.tsx";
import * as $$0 from "./islands/CounterCard.tsx"; import * as $$0 from "./islands/CounterCard.tsx";
import * as $$1 from "./components/MarkdownContent.tsx";
const manifest = { const manifest = {
routes: { routes: {
@ -16,7 +15,6 @@ const manifest = {
}, },
islands: { islands: {
"./islands/CounterCard.tsx": $$0, "./islands/CounterCard.tsx": $$0,
"./islands/MarkdownContent.tsx": $$1,
}, },
baseUrl: import.meta.url, baseUrl: import.meta.url,
}; };

View file

@ -49,7 +49,8 @@ export default function Counter(props: SharedProps) {
); );
const [internalCount, setInternalCount] = useState(0); const [internalCount, setInternalCount] = useState(0);
const [timer, setTimer] = useState(0); const [timer, setTimer] = useState(0);
const ipc = new BroadcastChannel("counterIpc"); const [socketState, setSocketState] = useState(0);
const ipc = new BroadcastChannel("counter-ipc");
const THRESHOLD_CLICKS = 30; // Maximum number of clicks in an interval const THRESHOLD_CLICKS = 30; // Maximum number of clicks in an interval
const INTERVAL_TIME_SECONDS = 60 * 0.5; // Every 30 seconds const INTERVAL_TIME_SECONDS = 60 * 0.5; // Every 30 seconds
@ -58,15 +59,14 @@ export default function Counter(props: SharedProps) {
const clickThresholdSurpassed = () => { const clickThresholdSurpassed = () => {
return clicksInInterval >= THRESHOLD_CLICKS; return clicksInInterval >= THRESHOLD_CLICKS;
} };
useEffect(() => { useEffect(() => {
if (clickThresholdSurpassed()) { if (clickThresholdSurpassed()) {
// Setup a timer // Setup a timer
const intervalId = setTimeout(() => { const intervalId = setTimeout(() => {
// Update interval time // Update interval time
setIntervalTime(prevTime => prevTime + 1); setIntervalTime((prevTime) => prevTime + 1);
// Reset interval if expired // Reset interval if expired
if (intervalTime >= INTERVAL_TIME_SECONDS) { if (intervalTime >= INTERVAL_TIME_SECONDS) {
@ -75,11 +75,13 @@ export default function Counter(props: SharedProps) {
} }
}, 1000 * 1); }, 1000 * 1);
return () => { clearInterval(intervalId) } return () => {
clearInterval(intervalId);
};
} }
}, [clicksInInterval, intervalTime]); }, [clicksInInterval, intervalTime]);
const onClick = () => { function handleClick() {
setInternalCount(internalCount + 1); setInternalCount(internalCount + 1);
setClicksInInterval(clicksInInterval + 1); setClicksInInterval(clicksInInterval + 1);
setCount(count + 1); setCount(count + 1);
@ -122,6 +124,17 @@ export default function Counter(props: SharedProps) {
setInternalCount(0); setInternalCount(0);
} }
}, 2048)); }, 2048));
}
const onClick = () => {
switch(socketState) {
case 1:
handleClick();
break;
default:
console.warn("WARN: Attempted to interact while the socket is not ready!");
break;
}
}; };
const handleWSEvents = (ws: WebSocket) => { const handleWSEvents = (ws: WebSocket) => {
@ -145,7 +158,8 @@ export default function Counter(props: SharedProps) {
console.log( console.log(
`[${new Date().toISOString()}] Connected to statistics socket`, `[${new Date().toISOString()}] Connected to statistics socket`,
); );
ws.send(0x0.toString()); setSocketState(1);
ws.send((0x0).toString());
}; };
ws.onmessage = (e) => { ws.onmessage = (e) => {
@ -165,23 +179,26 @@ export default function Counter(props: SharedProps) {
}; };
ws.onclose = () => { ws.onclose = () => {
setSocketState(3);
console.warn( console.warn(
`[${new Date().toISOString()}] Disconnected from statistics socket.`, `[${new Date().toISOString()}] Disconnected from statistics socket.`,
); );
}; };
ws.onerror = (e) => { ws.onerror = (e) => {
setSocketState(3);
console.error(`[${new Date().toISOString()}] Socket Errored. ${e.type}`); console.error(`[${new Date().toISOString()}] Socket Errored. ${e.type}`);
}; };
}; };
useEffect(() => { useEffect(() => {
let ws = new WebSocket(window.location.href.replace("http", "ws")); let ws = new WebSocket(globalThis.window.location.href.replace("http", "ws"));
setSocketState(1);
handleWSEvents(ws); handleWSEvents(ws);
ipc.addEventListener("message", (e) => { ipc.addEventListener("message", (e) => {
ws.send(JSON.stringify({data: e.data})); ws!.send(JSON.stringify({ data: e.data }));
}); });
const onlineHandler = () => { const onlineHandler = () => {
@ -216,8 +233,21 @@ export default function Counter(props: SharedProps) {
<p class="text-gray-100">Times the kuru was squished~</p> <p class="text-gray-100">Times the kuru was squished~</p>
</div> </div>
<div class="px-6 pt-4 pb-2"> <div class="px-6 pt-4 pb-2">
{!clickThresholdSurpassed() && <Button id="ctr-btn" onClick={onClick}>Squish that kuru~</Button>} {!clickThresholdSurpassed() && socketState === 1 && (
{clickThresholdSurpassed() && <p class="text-red-600 font-bold">Too many squishes! Wait until {INTERVAL_TIME_SECONDS - intervalTime} seconds.</p>} <Button id="ctr-btn" onClick={onClick}>Squish that kuru~</Button>
)}
{socketState !== 1 && (
<p class="px-6 pt-4 pb-2 text-gray-100">
Please wait...
</p>
)}
{clickThresholdSurpassed() && (
<p class="text-red-600 font-bold">
Too many squishes! Wait until {INTERVAL_TIME_SECONDS - intervalTime}
{" "}
seconds.
</p>
)}
</div> </div>
<div class="px-6 pt-4 pb-2 text-white"> <div class="px-6 pt-4 pb-2 text-white">
<p> <p>