fix multi tab presence

This commit is contained in:
2025-08-24 15:09:58 -04:00
parent 6c64886f2a
commit 4bcf071668
6 changed files with 59 additions and 18 deletions

View File

@@ -24,7 +24,7 @@ export type TWsIn = typeof WsIn.static;
type Attributed = { humanKey: string };
type TablePayload<GameState, GameAction> = {
inputs: {
presenceChanges: TBus<
connectionChanges: TBus<
Attributed & { presence: "joined" | "left" },
never
>;
@@ -45,23 +45,30 @@ const tables: {
export const liveTable = <GameState, GameAction>(key: string) => {
if (!(key in tables)) {
const inputs: TablePayload<GameState, GameAction>["inputs"] = {
presenceChanges: Bus(),
connectionChanges: Bus(),
gameProposals: Bus(),
gameStarts: Bus(),
gameActions: Bus(),
};
const { presenceChanges, gameProposals, gameStarts, gameActions } =
const { connectionChanges, gameProposals, gameStarts, gameActions } =
inputs;
// =======
const playersPresent = presenceChanges.scan((prev, evt) => {
if (evt.presence == "joined") {
prev.push(evt.humanKey);
} else if (evt.presence == "left") {
prev.splice(prev.indexOf(evt.humanKey), 1);
const playerConnectionCounts = connectionChanges.scan((prev, evt) => {
if (evt.presence == "left" && prev[evt.humanKey] == 1) {
const { [evt.humanKey]: _, ...rest } = prev;
return rest;
}
return prev;
}, [] as string[]);
return {
...prev,
[evt.humanKey]:
(prev[evt.humanKey] ?? 0) +
(evt.presence == "joined" ? 1 : -1),
};
}, {} as { [key: string]: number });
const playersPresent = playerConnectionCounts.map((counts) =>
Object.keys(counts)
);
const gameState = transform(
null as SimpleGameState | null,