add online user count

This commit is contained in:
Grant 2024-03-13 10:54:10 -06:00
parent 004e4926c4
commit 8d136c3fb1
2 changed files with 34 additions and 6 deletions

View File

@ -10,6 +10,7 @@ import { useAppContext } from "../contexts/AppContext";
import { Canvas } from "../lib/canvas";
import { useEffect, useState } from "react";
import { ClientConfig } from "@sc07-canvas/lib/src/net";
import network from "../lib/network";
const getTimeLeft = (pixels: { available: number }, config: ClientConfig) => {
// this implementation matches the server's implementation
@ -40,10 +41,33 @@ const PlaceCountdown = () => {
}, [pixels]);
return (
<>{pixels.available + 1 < config.canvas.pixel.maxStack && timeLeft + "s"}</>
<>
{timeLeft
? pixels.available + 1 < config.canvas.pixel.maxStack && timeLeft + "s"
: ""}
</>
);
};
const OnlineCount = () => {
const [online, setOnline] = useState<number>();
useEffect(() => {
function handleOnline(count: number) {
setOnline(count);
}
network.waitFor("online").then(([count]) => setOnline(count));
network.on("online", handleOnline);
return () => {
network.off("online", handleOnline);
};
}, []);
return <>{typeof online === "number" ? online : "???"}</>;
};
export const CanvasMeta = () => {
const { canvasPosition, cursorPosition, pixels, config } = useAppContext();
const { isOpen, onOpen, onOpenChange } = useDisclosure();
@ -74,7 +98,10 @@ export const CanvasMeta = () => {
<PlaceCountdown />
</span>
<span>
Users Online: <span>321</span>
Users Online:{" "}
<span>
<OnlineCount />
</span>
</span>
</div>
<ShareModal isOpen={isOpen} onOpenChange={onOpenChange} />

View File

@ -13,6 +13,7 @@ export interface INetworkEvents {
canvas: (pixels: string[]) => void;
pixels: (data: { available: number }) => void;
pixelLastPlaced: (time: number) => void;
online: (count: number) => void;
}
type SentEventValue<K extends keyof INetworkEvents> = EventEmitter.ArgumentMap<
@ -55,6 +56,10 @@ class Network extends EventEmitter<INetworkEvents> {
this._emit("pixelLastPlaced", time);
});
this.socket.on("online", ({ count }) => {
this._emit("online", count);
});
// this.socket.on("config", (config) => {
// Pallete.load(config.pallete);
// Canvas.load(config.canvas);
@ -67,10 +72,6 @@ class Network extends EventEmitter<INetworkEvents> {
// this.socket.on("canvas", (data: SCanvasPacket) => {
// Canvas.handleBatch(data);
// });
// this.socket.on("online", (data: { count: number }) => {
// this.online_count = data.count;
// });
}
private _emit: typeof this.emit = (event, ...args) => {