@air-jam/sdk 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +87 -0
- package/dist/.tsbuildinfo +1 -0
- package/dist/chunk-XSXI3RIS.js +72 -0
- package/dist/chunk-XSXI3RIS.js.map +1 -0
- package/dist/index.cjs +3514 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1529 -0
- package/dist/index.d.ts +1529 -0
- package/dist/index.js +3366 -0
- package/dist/index.js.map +1 -0
- package/dist/protocol.cjs +85 -0
- package/dist/protocol.cjs.map +1 -0
- package/dist/protocol.d.cts +242 -0
- package/dist/protocol.d.ts +242 -0
- package/dist/protocol.js +3 -0
- package/dist/protocol.js.map +1 -0
- package/package.json +81 -0
- package/src/AirJamClient.ts +775 -0
- package/src/audio/audio-manager.ts +395 -0
- package/src/audio/hooks.tsx +140 -0
- package/src/audio/index.ts +3 -0
- package/src/audio/volume-store.ts +77 -0
- package/src/components/air-jam-overlay.tsx +456 -0
- package/src/components/controller-shell.tsx +329 -0
- package/src/components/qr-scanner-dialog.tsx +373 -0
- package/src/components/ui/alert.tsx +66 -0
- package/src/components/ui/avatar.tsx +46 -0
- package/src/components/ui/badge.tsx +47 -0
- package/src/components/ui/button.tsx +61 -0
- package/src/components/ui/card.tsx +92 -0
- package/src/components/ui/slider.tsx +61 -0
- package/src/components/ui/tabs.tsx +64 -0
- package/src/components/volume-controls.tsx +93 -0
- package/src/constants.ts +45 -0
- package/src/context/air-jam-context.tsx +478 -0
- package/src/context/index.ts +2 -0
- package/src/context/socket-manager.ts +98 -0
- package/src/events.ts +151 -0
- package/src/hooks/use-air-jam-controller.ts +608 -0
- package/src/hooks/use-air-jam-host.ts +624 -0
- package/src/hooks/use-air-jam-shell.ts +343 -0
- package/src/hooks/use-fullscreen.ts +108 -0
- package/src/hooks/use-get-input.ts +97 -0
- package/src/hooks/use-send-signal.ts +164 -0
- package/src/index.ts +33 -0
- package/src/internal/input-manager.ts +362 -0
- package/src/protocol.ts +331 -0
- package/src/state/connection-store.ts +84 -0
- package/src/styles.css +128 -0
- package/src/types/browser.ts +42 -0
- package/src/utils/cn.ts +4 -0
- package/src/utils/ids.ts +31 -0
- package/src/utils/index.ts +1 -0
- package/src/utils/mode.ts +13 -0
- package/src/utils/network-ip.ts +145 -0
- package/src/utils/url-builder.ts +170 -0
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module useAirJamHost
|
|
3
|
+
* @description Primary hook for host/game functionality in the AirJam SDK.
|
|
4
|
+
*
|
|
5
|
+
* This hook connects your game to the AirJam server as a "host" and provides
|
|
6
|
+
* all the functionality needed to manage a multiplayer session:
|
|
7
|
+
* - Room management (create/join rooms)
|
|
8
|
+
* - Player tracking (join/leave events, player list)
|
|
9
|
+
* - Input handling (get validated, latched input from controllers)
|
|
10
|
+
* - Signaling (send haptic feedback, toast notifications to controllers)
|
|
11
|
+
* - Game state management (pause/play, broadcast state)
|
|
12
|
+
*/
|
|
13
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
14
|
+
import type { z } from "zod";
|
|
15
|
+
import { useStore } from "zustand";
|
|
16
|
+
import { useShallow } from "zustand/react/shallow";
|
|
17
|
+
import { TOGGLE_DEBOUNCE_MS } from "../constants";
|
|
18
|
+
import { useAirJamContext } from "../context/air-jam-context";
|
|
19
|
+
import type { AirJamSocket } from "../context/socket-manager";
|
|
20
|
+
import type {
|
|
21
|
+
ConnectionStatus,
|
|
22
|
+
ControllerInputEvent,
|
|
23
|
+
ControllerStateMessage,
|
|
24
|
+
ControllerStatePayload,
|
|
25
|
+
GameState,
|
|
26
|
+
HapticSignalPayload,
|
|
27
|
+
PlayerProfile,
|
|
28
|
+
RoomCode,
|
|
29
|
+
RunMode,
|
|
30
|
+
SignalPayload,
|
|
31
|
+
SignalType,
|
|
32
|
+
ToastSignalPayload,
|
|
33
|
+
} from "../protocol";
|
|
34
|
+
import {
|
|
35
|
+
controllerStateSchema,
|
|
36
|
+
controllerSystemSchema,
|
|
37
|
+
hostRegistrationSchema,
|
|
38
|
+
roomCodeSchema,
|
|
39
|
+
} from "../protocol";
|
|
40
|
+
import { generateRoomCode } from "../utils/ids";
|
|
41
|
+
import { detectRunMode } from "../utils/mode";
|
|
42
|
+
import { urlBuilder } from "../utils/url-builder";
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Options for configuring the host connection.
|
|
46
|
+
*
|
|
47
|
+
* @example Basic usage with callbacks
|
|
48
|
+
* ```tsx
|
|
49
|
+
* const host = useAirJamHost({
|
|
50
|
+
* onPlayerJoin: (player) => {
|
|
51
|
+
* console.log(`${player.label} joined!`);
|
|
52
|
+
* spawnPlayerShip(player.id);
|
|
53
|
+
* },
|
|
54
|
+
* onPlayerLeave: (controllerId) => {
|
|
55
|
+
* console.log(`Player ${controllerId} left`);
|
|
56
|
+
* removePlayerShip(controllerId);
|
|
57
|
+
* },
|
|
58
|
+
* });
|
|
59
|
+
* ```
|
|
60
|
+
*
|
|
61
|
+
* @example With custom room ID
|
|
62
|
+
* ```tsx
|
|
63
|
+
* const host = useAirJamHost({
|
|
64
|
+
* roomId: "GAME1", // Custom 4-character room code
|
|
65
|
+
* maxPlayers: 4, // Override provider's maxPlayers
|
|
66
|
+
* });
|
|
67
|
+
* ```
|
|
68
|
+
*/
|
|
69
|
+
export interface AirJamHostOptions {
|
|
70
|
+
/**
|
|
71
|
+
* Room ID (4-character code) to use for this session.
|
|
72
|
+
* If not provided, a random room code will be generated.
|
|
73
|
+
* Can also be set via URL query parameter: `?room=XXXX`
|
|
74
|
+
*/
|
|
75
|
+
roomId?: string;
|
|
76
|
+
/**
|
|
77
|
+
* Called when a player successfully joins the room.
|
|
78
|
+
* Use this to spawn player entities, update UI, etc.
|
|
79
|
+
*/
|
|
80
|
+
onPlayerJoin?: (player: PlayerProfile) => void;
|
|
81
|
+
/**
|
|
82
|
+
* Called when a player leaves the room (disconnects or exits).
|
|
83
|
+
* Use this to remove player entities, handle cleanup.
|
|
84
|
+
*/
|
|
85
|
+
onPlayerLeave?: (controllerId: string) => void;
|
|
86
|
+
/**
|
|
87
|
+
* Called when the child window closes in Arcade mode.
|
|
88
|
+
* Only relevant when running as part of the AirJam Platform.
|
|
89
|
+
*/
|
|
90
|
+
onChildClose?: () => void;
|
|
91
|
+
/**
|
|
92
|
+
* Force connection even in non-standard modes.
|
|
93
|
+
* @default true
|
|
94
|
+
*/
|
|
95
|
+
forceConnect?: boolean;
|
|
96
|
+
/**
|
|
97
|
+
* Override the API key from provider.
|
|
98
|
+
* Useful for per-game API keys in multi-game setups.
|
|
99
|
+
*/
|
|
100
|
+
apiKey?: string;
|
|
101
|
+
/**
|
|
102
|
+
* Override the maximum players from provider.
|
|
103
|
+
* @default 8
|
|
104
|
+
*/
|
|
105
|
+
maxPlayers?: number;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Return type of useAirJamHost hook.
|
|
110
|
+
*
|
|
111
|
+
* Provides all the state and functions needed to run a multiplayer game session.
|
|
112
|
+
*
|
|
113
|
+
* @template TSchema - Zod schema type for input (inferred from provider)
|
|
114
|
+
*/
|
|
115
|
+
export interface AirJamHostApi<TSchema extends z.ZodSchema = z.ZodSchema> {
|
|
116
|
+
/** The room code for this session (e.g., "ABCD") */
|
|
117
|
+
roomId: RoomCode;
|
|
118
|
+
/** Full URL for controllers to join (display as QR code) */
|
|
119
|
+
joinUrl: string;
|
|
120
|
+
/** Current connection status to the server */
|
|
121
|
+
connectionStatus: ConnectionStatus;
|
|
122
|
+
/** List of currently connected players */
|
|
123
|
+
players: PlayerProfile[];
|
|
124
|
+
/** Last error message, if any */
|
|
125
|
+
lastError?: string;
|
|
126
|
+
/** Current run mode (standalone, arcade, platform) */
|
|
127
|
+
mode: RunMode;
|
|
128
|
+
/** Current game state (paused or playing) */
|
|
129
|
+
gameState: GameState;
|
|
130
|
+
/** Toggle between paused and playing states */
|
|
131
|
+
toggleGameState: () => void;
|
|
132
|
+
/**
|
|
133
|
+
* Send state update to all connected controllers.
|
|
134
|
+
* Use for syncing game state, messages, etc.
|
|
135
|
+
*/
|
|
136
|
+
sendState: (state: ControllerStatePayload) => boolean;
|
|
137
|
+
/**
|
|
138
|
+
* Send a signal (haptic feedback or toast) to controllers.
|
|
139
|
+
*
|
|
140
|
+
* @example Send haptic to specific player
|
|
141
|
+
* ```ts
|
|
142
|
+
* host.sendSignal("HAPTIC", { pattern: "heavy" }, playerId);
|
|
143
|
+
* ```
|
|
144
|
+
*
|
|
145
|
+
* @example Send toast to all players
|
|
146
|
+
* ```ts
|
|
147
|
+
* host.sendSignal("TOAST", {
|
|
148
|
+
* title: "Round Start!",
|
|
149
|
+
* message: "Game begins in 3 seconds",
|
|
150
|
+
* });
|
|
151
|
+
* ```
|
|
152
|
+
*/
|
|
153
|
+
sendSignal: {
|
|
154
|
+
(type: "HAPTIC", payload: HapticSignalPayload, targetId?: string): void;
|
|
155
|
+
(type: "TOAST", payload: ToastSignalPayload, targetId?: string): void;
|
|
156
|
+
};
|
|
157
|
+
/** Reconnect to the server */
|
|
158
|
+
reconnect: () => void;
|
|
159
|
+
/** Raw Socket.IO socket instance for advanced usage */
|
|
160
|
+
socket: AirJamSocket;
|
|
161
|
+
/** Whether running in child/arcade mode */
|
|
162
|
+
isChildMode: boolean;
|
|
163
|
+
/**
|
|
164
|
+
* Get the latest input from a specific controller.
|
|
165
|
+
*
|
|
166
|
+
* Returns validated, typed input based on the schema provided to AirJamProvider.
|
|
167
|
+
* If latching is configured, automatically handles latch logic (button presses
|
|
168
|
+
* and stick flicks are "held" until consumed).
|
|
169
|
+
*
|
|
170
|
+
* @example In a game loop
|
|
171
|
+
* ```ts
|
|
172
|
+
* useFrame(() => {
|
|
173
|
+
* players.forEach((player) => {
|
|
174
|
+
* const input = host.getInput(player.id);
|
|
175
|
+
* if (input?.action) {
|
|
176
|
+
* fireWeapon(player.id);
|
|
177
|
+
* }
|
|
178
|
+
* movePlayer(player.id, input?.vector ?? { x: 0, y: 0 });
|
|
179
|
+
* });
|
|
180
|
+
* });
|
|
181
|
+
* ```
|
|
182
|
+
*/
|
|
183
|
+
getInput: (controllerId: string) => z.infer<TSchema> | undefined;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Primary hook for host/game functionality.
|
|
188
|
+
*
|
|
189
|
+
* Connects to the AirJam server as a host and provides everything needed
|
|
190
|
+
* to manage a multiplayer game session. Must be used within an AirJamProvider.
|
|
191
|
+
*
|
|
192
|
+
* **Features:**
|
|
193
|
+
* - Automatic room creation and management
|
|
194
|
+
* - Real-time player join/leave events
|
|
195
|
+
* - Typed input with validation and latching
|
|
196
|
+
* - Haptic feedback and toast notifications
|
|
197
|
+
* - Game state synchronization
|
|
198
|
+
*
|
|
199
|
+
* @template TSchema - Zod schema for input validation (from provider)
|
|
200
|
+
* @param options - Configuration options for the host
|
|
201
|
+
* @returns API object with state and functions
|
|
202
|
+
*
|
|
203
|
+
* @example Basic usage
|
|
204
|
+
* ```tsx
|
|
205
|
+
* const HostView = () => {
|
|
206
|
+
* const host = useAirJamHost({
|
|
207
|
+
* onPlayerJoin: (player) => console.log(`${player.label} joined`),
|
|
208
|
+
* onPlayerLeave: (id) => console.log(`${id} left`),
|
|
209
|
+
* });
|
|
210
|
+
*
|
|
211
|
+
* return (
|
|
212
|
+
* <div>
|
|
213
|
+
* <h1>Room: {host.roomId}</h1>
|
|
214
|
+
* <QRCode value={host.joinUrl} />
|
|
215
|
+
* <p>Players: {host.players.length}</p>
|
|
216
|
+
* <button onClick={host.toggleGameState}>
|
|
217
|
+
* {host.gameState === "playing" ? "Pause" : "Play"}
|
|
218
|
+
* </button>
|
|
219
|
+
* </div>
|
|
220
|
+
* );
|
|
221
|
+
* };
|
|
222
|
+
* ```
|
|
223
|
+
*
|
|
224
|
+
* @example Reading input in a game loop
|
|
225
|
+
* ```tsx
|
|
226
|
+
* const GameScene = () => {
|
|
227
|
+
* const host = useAirJamHost();
|
|
228
|
+
*
|
|
229
|
+
* useFrame(() => {
|
|
230
|
+
* host.players.forEach((player) => {
|
|
231
|
+
* const input = host.getInput(player.id);
|
|
232
|
+
* if (!input) return;
|
|
233
|
+
*
|
|
234
|
+
* // Move player based on joystick
|
|
235
|
+
* movePlayer(player.id, input.vector);
|
|
236
|
+
*
|
|
237
|
+
* // Handle button press (auto-latched)
|
|
238
|
+
* if (input.action) {
|
|
239
|
+
* playerShoot(player.id);
|
|
240
|
+
* }
|
|
241
|
+
* });
|
|
242
|
+
* });
|
|
243
|
+
*
|
|
244
|
+
* return <GameCanvas />;
|
|
245
|
+
* };
|
|
246
|
+
* ```
|
|
247
|
+
*
|
|
248
|
+
* @example Sending haptic feedback
|
|
249
|
+
* ```tsx
|
|
250
|
+
* const handleHit = (playerId: string) => {
|
|
251
|
+
* host.sendSignal("HAPTIC", { pattern: "heavy" }, playerId);
|
|
252
|
+
* };
|
|
253
|
+
* ```
|
|
254
|
+
*/
|
|
255
|
+
export const useAirJamHost = <TSchema extends z.ZodSchema = z.ZodSchema>(
|
|
256
|
+
options: AirJamHostOptions = {},
|
|
257
|
+
): AirJamHostApi<TSchema> => {
|
|
258
|
+
// Get context (includes inputManager from provider)
|
|
259
|
+
const { config, store, getSocket, disconnectSocket, inputManager } =
|
|
260
|
+
useAirJamContext();
|
|
261
|
+
|
|
262
|
+
// Detect if running in Arcade Mode (via URL params)
|
|
263
|
+
const arcadeParams = useMemo(() => {
|
|
264
|
+
if (typeof window === "undefined") return null;
|
|
265
|
+
const params = new URLSearchParams(window.location.search);
|
|
266
|
+
const room = params.get("aj_room");
|
|
267
|
+
const token = params.get("aj_token");
|
|
268
|
+
if (room && token) {
|
|
269
|
+
return { room, token };
|
|
270
|
+
}
|
|
271
|
+
return null;
|
|
272
|
+
}, []);
|
|
273
|
+
|
|
274
|
+
const isChildMode = !!arcadeParams;
|
|
275
|
+
|
|
276
|
+
// Always connect - forceConnect kept for API compatibility
|
|
277
|
+
const shouldConnect = true;
|
|
278
|
+
|
|
279
|
+
// Generate fallback room ID once
|
|
280
|
+
const [fallbackRoomId] = useState(() => generateRoomCode());
|
|
281
|
+
|
|
282
|
+
// Parse room ID from various sources
|
|
283
|
+
const parsedRoomId = useMemo<RoomCode>(() => {
|
|
284
|
+
if (arcadeParams) {
|
|
285
|
+
return roomCodeSchema.parse(arcadeParams.room.toUpperCase());
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
if (typeof window !== "undefined") {
|
|
289
|
+
const params = new URLSearchParams(window.location.search);
|
|
290
|
+
const paramRoom = params.get("room");
|
|
291
|
+
if (paramRoom) {
|
|
292
|
+
const result = roomCodeSchema.safeParse(paramRoom.toUpperCase());
|
|
293
|
+
if (result.success) return result.data;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (options.roomId) {
|
|
298
|
+
return roomCodeSchema.parse(options.roomId.toUpperCase());
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
return fallbackRoomId;
|
|
302
|
+
}, [options.roomId, fallbackRoomId, arcadeParams]);
|
|
303
|
+
|
|
304
|
+
// Update InputManager room ID when parsedRoomId changes
|
|
305
|
+
useEffect(() => {
|
|
306
|
+
if (inputManager) {
|
|
307
|
+
inputManager.setRoomId(parsedRoomId);
|
|
308
|
+
}
|
|
309
|
+
}, [inputManager, parsedRoomId]);
|
|
310
|
+
|
|
311
|
+
const [joinUrl, setJoinUrl] = useState<string>("");
|
|
312
|
+
|
|
313
|
+
// Keep callback refs stable
|
|
314
|
+
const onPlayerJoinRef = useRef(options.onPlayerJoin);
|
|
315
|
+
const onPlayerLeaveRef = useRef(options.onPlayerLeave);
|
|
316
|
+
const onChildCloseRef = useRef(options.onChildClose);
|
|
317
|
+
|
|
318
|
+
useEffect(() => {
|
|
319
|
+
onPlayerJoinRef.current = options.onPlayerJoin;
|
|
320
|
+
onPlayerLeaveRef.current = options.onPlayerLeave;
|
|
321
|
+
onChildCloseRef.current = options.onChildClose;
|
|
322
|
+
}, [options.onPlayerJoin, options.onPlayerLeave, options.onChildClose]);
|
|
323
|
+
|
|
324
|
+
// Subscribe to store state
|
|
325
|
+
const connectionState = useStore(
|
|
326
|
+
store,
|
|
327
|
+
useShallow((state) => ({
|
|
328
|
+
connectionStatus: state.connectionStatus,
|
|
329
|
+
lastError: state.lastError,
|
|
330
|
+
players: state.players,
|
|
331
|
+
gameState: state.gameState,
|
|
332
|
+
mode: state.mode,
|
|
333
|
+
})),
|
|
334
|
+
);
|
|
335
|
+
|
|
336
|
+
// Get socket from context
|
|
337
|
+
const socket = useMemo(
|
|
338
|
+
() => (shouldConnect ? getSocket("host") : null),
|
|
339
|
+
[shouldConnect, getSocket],
|
|
340
|
+
);
|
|
341
|
+
|
|
342
|
+
const [lastToggle, setLastToggle] = useState(0);
|
|
343
|
+
|
|
344
|
+
const toggleGameState = useCallback(() => {
|
|
345
|
+
const now = Date.now();
|
|
346
|
+
if (now - lastToggle < TOGGLE_DEBOUNCE_MS) {
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
setLastToggle(now);
|
|
350
|
+
|
|
351
|
+
if (!socket || !socket.connected) {
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const payload = controllerSystemSchema.safeParse({
|
|
356
|
+
roomId: parsedRoomId,
|
|
357
|
+
command: "toggle_pause",
|
|
358
|
+
});
|
|
359
|
+
if (payload.success) {
|
|
360
|
+
socket.emit("host:system", payload.data);
|
|
361
|
+
}
|
|
362
|
+
}, [socket, parsedRoomId, lastToggle]);
|
|
363
|
+
|
|
364
|
+
const sendState = useCallback(
|
|
365
|
+
(state: ControllerStatePayload): boolean => {
|
|
366
|
+
if (!socket || !socket.connected) {
|
|
367
|
+
return false;
|
|
368
|
+
}
|
|
369
|
+
const payload = controllerStateSchema.safeParse({
|
|
370
|
+
roomId: parsedRoomId,
|
|
371
|
+
state,
|
|
372
|
+
});
|
|
373
|
+
if (!payload.success) {
|
|
374
|
+
return false;
|
|
375
|
+
}
|
|
376
|
+
socket.emit("host:state", payload.data);
|
|
377
|
+
return true;
|
|
378
|
+
},
|
|
379
|
+
[socket, parsedRoomId],
|
|
380
|
+
);
|
|
381
|
+
|
|
382
|
+
const sendSignal = useCallback(
|
|
383
|
+
(
|
|
384
|
+
type: SignalType,
|
|
385
|
+
payload: HapticSignalPayload | ToastSignalPayload,
|
|
386
|
+
targetId?: string,
|
|
387
|
+
): void => {
|
|
388
|
+
if (!socket || !socket.connected) {
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
const signal: SignalPayload = {
|
|
392
|
+
targetId,
|
|
393
|
+
type,
|
|
394
|
+
payload,
|
|
395
|
+
} as SignalPayload;
|
|
396
|
+
socket.emit("host:signal", signal);
|
|
397
|
+
},
|
|
398
|
+
[socket],
|
|
399
|
+
) as AirJamHostApi["sendSignal"];
|
|
400
|
+
|
|
401
|
+
const reconnect = useCallback(() => {
|
|
402
|
+
disconnectSocket("host");
|
|
403
|
+
if (socket) {
|
|
404
|
+
socket.connect();
|
|
405
|
+
}
|
|
406
|
+
}, [socket, disconnectSocket]);
|
|
407
|
+
|
|
408
|
+
// Build controller URL
|
|
409
|
+
useEffect(() => {
|
|
410
|
+
(async () => {
|
|
411
|
+
const url = await urlBuilder.buildControllerUrl(parsedRoomId, {
|
|
412
|
+
path: config.controllerPath,
|
|
413
|
+
host: config.publicHost,
|
|
414
|
+
});
|
|
415
|
+
setJoinUrl(url);
|
|
416
|
+
})();
|
|
417
|
+
}, [parsedRoomId, config.controllerPath, config.publicHost]);
|
|
418
|
+
|
|
419
|
+
// Get setRegisteredRoomId from store
|
|
420
|
+
const setRegisteredRoomId = useStore(store, (s) => s.setRegisteredRoomId);
|
|
421
|
+
|
|
422
|
+
// Main connection effect
|
|
423
|
+
useEffect(() => {
|
|
424
|
+
const storeState = store.getState();
|
|
425
|
+
storeState.setMode(detectRunMode());
|
|
426
|
+
storeState.setRole("host");
|
|
427
|
+
storeState.setRoomId(parsedRoomId);
|
|
428
|
+
storeState.setStatus("connecting");
|
|
429
|
+
storeState.setError(undefined);
|
|
430
|
+
|
|
431
|
+
if (!shouldConnect || !socket) {
|
|
432
|
+
storeState.setStatus("idle");
|
|
433
|
+
return;
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const registerHost = async () => {
|
|
437
|
+
const storeState = store.getState();
|
|
438
|
+
|
|
439
|
+
// Prevent duplicate registration for the same room
|
|
440
|
+
const currentRegisteredRoomId = store.getState().registeredRoomId;
|
|
441
|
+
if (currentRegisteredRoomId === parsedRoomId && socket.connected) {
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
if (arcadeParams) {
|
|
446
|
+
// Child Mode - join as child
|
|
447
|
+
const childRoomId = roomCodeSchema.parse(
|
|
448
|
+
arcadeParams.room.toUpperCase(),
|
|
449
|
+
);
|
|
450
|
+
const payload = {
|
|
451
|
+
roomId: childRoomId,
|
|
452
|
+
joinToken: arcadeParams.token,
|
|
453
|
+
};
|
|
454
|
+
socket.emit("host:joinAsChild", payload, (ack) => {
|
|
455
|
+
if (!ack.ok) {
|
|
456
|
+
storeState.setError(ack.message ?? "Failed to join as child");
|
|
457
|
+
storeState.setStatus("disconnected");
|
|
458
|
+
setRegisteredRoomId(null);
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
storeState.setStatus("connected");
|
|
462
|
+
storeState.setRoomId(childRoomId);
|
|
463
|
+
setRegisteredRoomId(childRoomId);
|
|
464
|
+
});
|
|
465
|
+
} else {
|
|
466
|
+
// Standalone Mode - register as master host
|
|
467
|
+
const payload = hostRegistrationSchema.parse({
|
|
468
|
+
roomId: parsedRoomId,
|
|
469
|
+
maxPlayers: options.maxPlayers ?? config.maxPlayers,
|
|
470
|
+
apiKey: options.apiKey ?? config.apiKey,
|
|
471
|
+
});
|
|
472
|
+
|
|
473
|
+
socket.emit("host:register", payload, (ack) => {
|
|
474
|
+
if (!ack.ok) {
|
|
475
|
+
storeState.setError(ack.message ?? "Failed to register host");
|
|
476
|
+
storeState.setStatus("disconnected");
|
|
477
|
+
setRegisteredRoomId(null);
|
|
478
|
+
return;
|
|
479
|
+
}
|
|
480
|
+
storeState.setStatus("connected");
|
|
481
|
+
if (ack.roomId) {
|
|
482
|
+
storeState.setRoomId(ack.roomId);
|
|
483
|
+
setRegisteredRoomId(ack.roomId);
|
|
484
|
+
} else {
|
|
485
|
+
setRegisteredRoomId(parsedRoomId);
|
|
486
|
+
}
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
|
|
491
|
+
const handleConnect = (): void => {
|
|
492
|
+
store.getState().setStatus("connected");
|
|
493
|
+
registerHost();
|
|
494
|
+
};
|
|
495
|
+
|
|
496
|
+
const handleDisconnect = (): void => {
|
|
497
|
+
store.getState().setStatus("disconnected");
|
|
498
|
+
};
|
|
499
|
+
|
|
500
|
+
const handleJoin = (payload: {
|
|
501
|
+
controllerId: string;
|
|
502
|
+
nickname?: string;
|
|
503
|
+
player?: PlayerProfile;
|
|
504
|
+
}): void => {
|
|
505
|
+
if (payload.player) {
|
|
506
|
+
store.getState().upsertPlayer(payload.player);
|
|
507
|
+
setTimeout(() => {
|
|
508
|
+
onPlayerJoinRef.current?.(payload.player!);
|
|
509
|
+
}, 0);
|
|
510
|
+
}
|
|
511
|
+
};
|
|
512
|
+
|
|
513
|
+
const handleLeave = (payload: { controllerId: string }): void => {
|
|
514
|
+
store.getState().removePlayer(payload.controllerId);
|
|
515
|
+
onPlayerLeaveRef.current?.(payload.controllerId);
|
|
516
|
+
};
|
|
517
|
+
|
|
518
|
+
const handleInput = (payload: ControllerInputEvent): void => {
|
|
519
|
+
// Handle input via InputManager from context (if configured in provider)
|
|
520
|
+
if (inputManager) {
|
|
521
|
+
inputManager.handleInput(payload);
|
|
522
|
+
}
|
|
523
|
+
};
|
|
524
|
+
|
|
525
|
+
const handleChildClose = (): void => {
|
|
526
|
+
onChildCloseRef.current?.();
|
|
527
|
+
};
|
|
528
|
+
|
|
529
|
+
const handleState = (payload: ControllerStateMessage): void => {
|
|
530
|
+
if (payload.roomId !== parsedRoomId) return;
|
|
531
|
+
|
|
532
|
+
const storeState = store.getState();
|
|
533
|
+
if (payload.state.gameState) {
|
|
534
|
+
storeState.setGameState(payload.state.gameState);
|
|
535
|
+
}
|
|
536
|
+
if (payload.state.message !== undefined) {
|
|
537
|
+
storeState.setStateMessage(payload.state.message);
|
|
538
|
+
}
|
|
539
|
+
};
|
|
540
|
+
|
|
541
|
+
const handleError = (payload: { message: string }): void => {
|
|
542
|
+
store.getState().setError(payload.message);
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
socket.on("connect", handleConnect);
|
|
546
|
+
socket.on("disconnect", handleDisconnect);
|
|
547
|
+
socket.on("server:controllerJoined", handleJoin);
|
|
548
|
+
socket.on("server:controllerLeft", handleLeave);
|
|
549
|
+
socket.on("server:input", handleInput);
|
|
550
|
+
socket.on("server:error", handleError);
|
|
551
|
+
socket.on("server:closeChild", handleChildClose);
|
|
552
|
+
socket.on("server:state", handleState);
|
|
553
|
+
|
|
554
|
+
// Connect the socket
|
|
555
|
+
socket.connect();
|
|
556
|
+
|
|
557
|
+
// If socket is already connected, register immediately
|
|
558
|
+
const currentRegisteredRoomId = store.getState().registeredRoomId;
|
|
559
|
+
if (socket.connected && currentRegisteredRoomId !== parsedRoomId) {
|
|
560
|
+
registerHost();
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// Reset registered room when parsedRoomId changes
|
|
564
|
+
if (currentRegisteredRoomId && currentRegisteredRoomId !== parsedRoomId) {
|
|
565
|
+
setRegisteredRoomId(null);
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
return () => {
|
|
569
|
+
socket.off("connect", handleConnect);
|
|
570
|
+
socket.off("disconnect", handleDisconnect);
|
|
571
|
+
socket.off("server:controllerJoined", handleJoin);
|
|
572
|
+
socket.off("server:controllerLeft", handleLeave);
|
|
573
|
+
socket.off("server:input", handleInput);
|
|
574
|
+
socket.off("server:error", handleError);
|
|
575
|
+
socket.off("server:closeChild", handleChildClose);
|
|
576
|
+
socket.off("server:state", handleState);
|
|
577
|
+
};
|
|
578
|
+
}, [
|
|
579
|
+
config.maxPlayers,
|
|
580
|
+
config.apiKey,
|
|
581
|
+
options.maxPlayers,
|
|
582
|
+
options.apiKey,
|
|
583
|
+
parsedRoomId,
|
|
584
|
+
arcadeParams,
|
|
585
|
+
shouldConnect,
|
|
586
|
+
socket,
|
|
587
|
+
store,
|
|
588
|
+
inputManager,
|
|
589
|
+
setRegisteredRoomId,
|
|
590
|
+
]);
|
|
591
|
+
|
|
592
|
+
// Ensure we return a valid socket
|
|
593
|
+
const returnSocket = socket ?? getSocket("host");
|
|
594
|
+
|
|
595
|
+
// Create getInput function using InputManager from context
|
|
596
|
+
const getInput = useCallback(
|
|
597
|
+
(controllerId: string): z.infer<TSchema> | undefined => {
|
|
598
|
+
if (!inputManager) {
|
|
599
|
+
return undefined;
|
|
600
|
+
}
|
|
601
|
+
return inputManager.getInput(controllerId) as
|
|
602
|
+
| z.infer<TSchema>
|
|
603
|
+
| undefined;
|
|
604
|
+
},
|
|
605
|
+
[inputManager],
|
|
606
|
+
);
|
|
607
|
+
|
|
608
|
+
return {
|
|
609
|
+
roomId: parsedRoomId,
|
|
610
|
+
joinUrl,
|
|
611
|
+
connectionStatus: connectionState.connectionStatus,
|
|
612
|
+
players: connectionState.players,
|
|
613
|
+
lastError: connectionState.lastError,
|
|
614
|
+
mode: connectionState.mode,
|
|
615
|
+
gameState: connectionState.gameState,
|
|
616
|
+
toggleGameState,
|
|
617
|
+
sendState,
|
|
618
|
+
sendSignal,
|
|
619
|
+
reconnect,
|
|
620
|
+
socket: returnSocket,
|
|
621
|
+
isChildMode,
|
|
622
|
+
getInput,
|
|
623
|
+
};
|
|
624
|
+
};
|