@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,608 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module useAirJamController
|
|
3
|
+
* @description Hook for building mobile/web controllers that connect to AirJam hosts.
|
|
4
|
+
*
|
|
5
|
+
* This hook is used on the controller side (typically a mobile phone) to:
|
|
6
|
+
* - Connect to a game session via room code
|
|
7
|
+
* - Send input (joystick, buttons) to the host
|
|
8
|
+
* - Receive game state updates
|
|
9
|
+
* - Handle haptic feedback signals
|
|
10
|
+
*
|
|
11
|
+
* Controllers automatically handle:
|
|
12
|
+
* - Room joining via URL parameter (?room=XXXX) or props
|
|
13
|
+
* - Haptic feedback (vibration patterns on signal receipt)
|
|
14
|
+
* - Bridge mode for iframe embedding in the AirJam Platform
|
|
15
|
+
*/
|
|
16
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
17
|
+
import { useStore } from "zustand";
|
|
18
|
+
import { useShallow } from "zustand/react/shallow";
|
|
19
|
+
import { useAirJamContext } from "../context/air-jam-context";
|
|
20
|
+
import type { AirJamSocket } from "../context/socket-manager";
|
|
21
|
+
import type {
|
|
22
|
+
ConnectionStatus,
|
|
23
|
+
ControllerInputPayload,
|
|
24
|
+
ControllerStateMessage,
|
|
25
|
+
GameState,
|
|
26
|
+
PlayerProfile,
|
|
27
|
+
RoomCode,
|
|
28
|
+
SignalPayload,
|
|
29
|
+
} from "../protocol";
|
|
30
|
+
import {
|
|
31
|
+
controllerInputSchema,
|
|
32
|
+
controllerJoinSchema,
|
|
33
|
+
controllerSystemSchema,
|
|
34
|
+
roomCodeSchema,
|
|
35
|
+
type ControllerStatePayload,
|
|
36
|
+
} from "../protocol";
|
|
37
|
+
import { generateControllerId } from "../utils/ids";
|
|
38
|
+
import { detectRunMode } from "../utils/mode";
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Options for configuring the controller connection.
|
|
42
|
+
*
|
|
43
|
+
* @example Basic usage (room from URL)
|
|
44
|
+
* ```tsx
|
|
45
|
+
* // URL: https://yourgame.com/joypad?room=ABCD
|
|
46
|
+
* const controller = useAirJamController();
|
|
47
|
+
* // Automatically joins room ABCD
|
|
48
|
+
* ```
|
|
49
|
+
*
|
|
50
|
+
* @example With nickname
|
|
51
|
+
* ```tsx
|
|
52
|
+
* const controller = useAirJamController({
|
|
53
|
+
* nickname: playerName,
|
|
54
|
+
* onState: (state) => {
|
|
55
|
+
* if (state.gameState === "playing") startGame();
|
|
56
|
+
* },
|
|
57
|
+
* });
|
|
58
|
+
* ```
|
|
59
|
+
*/
|
|
60
|
+
export interface AirJamControllerOptions {
|
|
61
|
+
/**
|
|
62
|
+
* Room ID (4-character code) to join.
|
|
63
|
+
* Can also be provided via URL query parameter: `?room=XXXX`
|
|
64
|
+
* The URL parameter takes precedence if both are provided.
|
|
65
|
+
*/
|
|
66
|
+
roomId?: string;
|
|
67
|
+
/**
|
|
68
|
+
* Player nickname to display in the game.
|
|
69
|
+
* If not provided, the server assigns a random label.
|
|
70
|
+
*/
|
|
71
|
+
nickname?: string;
|
|
72
|
+
/**
|
|
73
|
+
* Controller ID for this instance.
|
|
74
|
+
* Auto-generated if not provided. Persists across reconnects.
|
|
75
|
+
*/
|
|
76
|
+
controllerId?: string;
|
|
77
|
+
/**
|
|
78
|
+
* Force connection even in non-standard modes (e.g., iframe).
|
|
79
|
+
* @default false
|
|
80
|
+
*/
|
|
81
|
+
forceConnect?: boolean;
|
|
82
|
+
/**
|
|
83
|
+
* Called when the host sends a state update (game state, messages, etc.)
|
|
84
|
+
*/
|
|
85
|
+
onState?: (state: ControllerStatePayload) => void;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Return type of useAirJamController hook.
|
|
90
|
+
*
|
|
91
|
+
* Provides state and functions for a mobile/web controller interface.
|
|
92
|
+
*/
|
|
93
|
+
export interface AirJamControllerApi {
|
|
94
|
+
/** Room code this controller is connected to (or attempting to join) */
|
|
95
|
+
roomId: RoomCode | null;
|
|
96
|
+
/** This controller's unique ID */
|
|
97
|
+
controllerId: string | null;
|
|
98
|
+
/** Current connection status */
|
|
99
|
+
connectionStatus: ConnectionStatus;
|
|
100
|
+
/** Last error message, if any */
|
|
101
|
+
lastError?: string;
|
|
102
|
+
/** Current game state (paused or playing) */
|
|
103
|
+
gameState: GameState;
|
|
104
|
+
/** Optional message from the host (e.g., "Get Ready!") */
|
|
105
|
+
stateMessage?: string;
|
|
106
|
+
/**
|
|
107
|
+
* Send input to the host.
|
|
108
|
+
*
|
|
109
|
+
* @example Sending joystick and button input
|
|
110
|
+
* ```ts
|
|
111
|
+
* controller.sendInput({
|
|
112
|
+
* vector: { x: joystickX, y: joystickY },
|
|
113
|
+
* action: isFirePressed,
|
|
114
|
+
* ability: isAbilityPressed,
|
|
115
|
+
* timestamp: Date.now(),
|
|
116
|
+
* });
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
sendInput: (input: ControllerInputPayload) => boolean;
|
|
120
|
+
/**
|
|
121
|
+
* Send a system command to the host.
|
|
122
|
+
*
|
|
123
|
+
* @example Toggle pause
|
|
124
|
+
* ```ts
|
|
125
|
+
* controller.sendSystemCommand("toggle_pause");
|
|
126
|
+
* ```
|
|
127
|
+
*/
|
|
128
|
+
sendSystemCommand: (command: "exit" | "ready" | "toggle_pause") => void;
|
|
129
|
+
/**
|
|
130
|
+
* Update the player nickname.
|
|
131
|
+
* Changes take effect on next connection.
|
|
132
|
+
*/
|
|
133
|
+
setNickname: (value: string) => void;
|
|
134
|
+
/** Force reconnection to the room */
|
|
135
|
+
reconnect: () => void;
|
|
136
|
+
/** List of all connected players in the room */
|
|
137
|
+
players: PlayerProfile[];
|
|
138
|
+
/** Raw Socket.IO socket instance (null if not connected) */
|
|
139
|
+
socket: AirJamSocket | null;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const getRoomFromLocation = (): string | null => {
|
|
143
|
+
if (typeof window === "undefined") {
|
|
144
|
+
return null;
|
|
145
|
+
}
|
|
146
|
+
const params = new URLSearchParams(window.location.search);
|
|
147
|
+
const code = params.get("room");
|
|
148
|
+
return code ? code.toUpperCase() : null;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Hook for building mobile/web controllers that connect to AirJam hosts.
|
|
153
|
+
*
|
|
154
|
+
* This hook handles all the complexity of connecting a mobile controller to a game:
|
|
155
|
+
* - Automatic room joining from URL parameters
|
|
156
|
+
* - Input sending with validation
|
|
157
|
+
* - Haptic feedback on signal receipt (vibration)
|
|
158
|
+
* - Game state synchronization
|
|
159
|
+
* - Auto-reconnection on disconnect
|
|
160
|
+
*
|
|
161
|
+
* **Typical usage flow:**
|
|
162
|
+
* 1. Player scans QR code on game screen
|
|
163
|
+
* 2. Opens controller URL with ?room=XXXX parameter
|
|
164
|
+
* 3. Controller auto-connects to the game session
|
|
165
|
+
* 4. Player uses joystick/buttons to send input
|
|
166
|
+
* 5. Receives haptic feedback on game events
|
|
167
|
+
*
|
|
168
|
+
* @param options - Configuration options
|
|
169
|
+
* @returns Controller API with state and functions
|
|
170
|
+
*
|
|
171
|
+
* @example Basic controller setup
|
|
172
|
+
* ```tsx
|
|
173
|
+
* const ControllerView = () => {
|
|
174
|
+
* const controller = useAirJamController();
|
|
175
|
+
*
|
|
176
|
+
* const handleJoystickMove = (x: number, y: number) => {
|
|
177
|
+
* controller.sendInput({
|
|
178
|
+
* vector: { x, y },
|
|
179
|
+
* action: false,
|
|
180
|
+
* timestamp: Date.now(),
|
|
181
|
+
* });
|
|
182
|
+
* };
|
|
183
|
+
*
|
|
184
|
+
* const handleFirePress = () => {
|
|
185
|
+
* controller.sendInput({
|
|
186
|
+
* vector: { x: 0, y: 0 },
|
|
187
|
+
* action: true,
|
|
188
|
+
* timestamp: Date.now(),
|
|
189
|
+
* });
|
|
190
|
+
* };
|
|
191
|
+
*
|
|
192
|
+
* if (controller.connectionStatus !== "connected") {
|
|
193
|
+
* return <div>Connecting to room {controller.roomId}...</div>;
|
|
194
|
+
* }
|
|
195
|
+
*
|
|
196
|
+
* return (
|
|
197
|
+
* <div>
|
|
198
|
+
* <Joystick onMove={handleJoystickMove} />
|
|
199
|
+
* <FireButton onPress={handleFirePress} />
|
|
200
|
+
* <p>Game: {controller.gameState}</p>
|
|
201
|
+
* </div>
|
|
202
|
+
* );
|
|
203
|
+
* };
|
|
204
|
+
* ```
|
|
205
|
+
*
|
|
206
|
+
* @example With state callback
|
|
207
|
+
* ```tsx
|
|
208
|
+
* const controller = useAirJamController({
|
|
209
|
+
* onState: (state) => {
|
|
210
|
+
* if (state.message) {
|
|
211
|
+
* showNotification(state.message);
|
|
212
|
+
* }
|
|
213
|
+
* },
|
|
214
|
+
* });
|
|
215
|
+
* ```
|
|
216
|
+
*/
|
|
217
|
+
export const useAirJamController = (
|
|
218
|
+
options: AirJamControllerOptions = {},
|
|
219
|
+
): AirJamControllerApi => {
|
|
220
|
+
// Get context
|
|
221
|
+
const { store, getSocket, disconnectSocket } = useAirJamContext();
|
|
222
|
+
|
|
223
|
+
const nicknameRef = useRef(options.nickname ?? "");
|
|
224
|
+
|
|
225
|
+
// Detect Sub-Controller Mode (via URL params)
|
|
226
|
+
const subControllerParams = useMemo(() => {
|
|
227
|
+
if (typeof window === "undefined") return null;
|
|
228
|
+
const params = new URLSearchParams(window.location.search);
|
|
229
|
+
const room = params.get("aj_room");
|
|
230
|
+
const controllerId = params.get("aj_controller_id");
|
|
231
|
+
if (room && controllerId) {
|
|
232
|
+
return { room, controllerId };
|
|
233
|
+
}
|
|
234
|
+
return null;
|
|
235
|
+
}, []);
|
|
236
|
+
|
|
237
|
+
// Parse room ID
|
|
238
|
+
const parsedRoomId = useMemo<RoomCode | null>(() => {
|
|
239
|
+
const code =
|
|
240
|
+
subControllerParams?.room ?? options.roomId ?? getRoomFromLocation();
|
|
241
|
+
if (!code) return null;
|
|
242
|
+
try {
|
|
243
|
+
return roomCodeSchema.parse(code.toUpperCase());
|
|
244
|
+
} catch {
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
}, [options.roomId, subControllerParams]);
|
|
248
|
+
|
|
249
|
+
// Generate or use provided controller ID
|
|
250
|
+
const controllerId = useMemo<string>(() => {
|
|
251
|
+
if (subControllerParams?.controllerId) {
|
|
252
|
+
return subControllerParams.controllerId;
|
|
253
|
+
}
|
|
254
|
+
if (options.controllerId) {
|
|
255
|
+
return options.controllerId;
|
|
256
|
+
}
|
|
257
|
+
if (typeof window !== "undefined") {
|
|
258
|
+
const params = new URLSearchParams(window.location.search);
|
|
259
|
+
const urlControllerId = params.get("controllerId");
|
|
260
|
+
if (urlControllerId) return urlControllerId;
|
|
261
|
+
}
|
|
262
|
+
return generateControllerId();
|
|
263
|
+
}, [options.controllerId, subControllerParams]);
|
|
264
|
+
|
|
265
|
+
const onStateRef = useRef<AirJamControllerOptions["onState"]>(
|
|
266
|
+
options.onState,
|
|
267
|
+
);
|
|
268
|
+
useEffect(() => {
|
|
269
|
+
onStateRef.current = options.onState;
|
|
270
|
+
}, [options.onState]);
|
|
271
|
+
|
|
272
|
+
// Subscribe to store state
|
|
273
|
+
const connectionState = useStore(
|
|
274
|
+
store,
|
|
275
|
+
useShallow((state) => ({
|
|
276
|
+
connectionStatus: state.connectionStatus,
|
|
277
|
+
lastError: state.lastError,
|
|
278
|
+
controllerId: state.controllerId,
|
|
279
|
+
players: state.players,
|
|
280
|
+
gameState: state.gameState,
|
|
281
|
+
stateMessage: state.stateMessage,
|
|
282
|
+
})),
|
|
283
|
+
);
|
|
284
|
+
|
|
285
|
+
// Reconnect key for forcing reconnection
|
|
286
|
+
const [reconnectKey, setReconnectKey] = useState(0);
|
|
287
|
+
|
|
288
|
+
const reconnect = useCallback(() => {
|
|
289
|
+
if (!parsedRoomId) return;
|
|
290
|
+
disconnectSocket("controller");
|
|
291
|
+
setReconnectKey((prev) => prev + 1);
|
|
292
|
+
}, [parsedRoomId, disconnectSocket]);
|
|
293
|
+
|
|
294
|
+
const isChildMode = useMemo(() => {
|
|
295
|
+
if (typeof window === "undefined") return false;
|
|
296
|
+
const params = new URLSearchParams(window.location.search);
|
|
297
|
+
return params.get("airjam_mode") === "child";
|
|
298
|
+
}, []);
|
|
299
|
+
|
|
300
|
+
const shouldConnect = useMemo(() => {
|
|
301
|
+
if (options.forceConnect) return true;
|
|
302
|
+
if (subControllerParams) return true;
|
|
303
|
+
if (typeof window !== "undefined") {
|
|
304
|
+
const params = new URLSearchParams(window.location.search);
|
|
305
|
+
return params.get("airjam_force_connect") === "true";
|
|
306
|
+
}
|
|
307
|
+
return false;
|
|
308
|
+
}, [options.forceConnect, subControllerParams]);
|
|
309
|
+
|
|
310
|
+
const canConnect = useMemo(
|
|
311
|
+
() => !isChildMode || shouldConnect,
|
|
312
|
+
[isChildMode, shouldConnect],
|
|
313
|
+
);
|
|
314
|
+
|
|
315
|
+
// Get socket from context (only if can connect and have room)
|
|
316
|
+
const socket = useMemo(
|
|
317
|
+
() => (canConnect && parsedRoomId ? getSocket("controller") : null),
|
|
318
|
+
[canConnect, parsedRoomId, getSocket],
|
|
319
|
+
);
|
|
320
|
+
|
|
321
|
+
// Automatically listen for haptic signals
|
|
322
|
+
useEffect(() => {
|
|
323
|
+
if (!socket) return;
|
|
324
|
+
|
|
325
|
+
const handleSignal = (signal: SignalPayload) => {
|
|
326
|
+
if (signal.type !== "HAPTIC") return;
|
|
327
|
+
|
|
328
|
+
// Browser compatibility check
|
|
329
|
+
if (typeof navigator === "undefined" || !navigator.vibrate) return;
|
|
330
|
+
|
|
331
|
+
// TypeScript now knows payload is HapticSignalPayload
|
|
332
|
+
const payload = signal.payload;
|
|
333
|
+
|
|
334
|
+
switch (payload.pattern) {
|
|
335
|
+
case "light":
|
|
336
|
+
navigator.vibrate(10);
|
|
337
|
+
break;
|
|
338
|
+
case "medium":
|
|
339
|
+
navigator.vibrate(30);
|
|
340
|
+
break;
|
|
341
|
+
case "heavy":
|
|
342
|
+
navigator.vibrate([50, 20, 50]); // Pulse
|
|
343
|
+
break;
|
|
344
|
+
case "success":
|
|
345
|
+
navigator.vibrate([10, 30, 10]);
|
|
346
|
+
break;
|
|
347
|
+
case "failure":
|
|
348
|
+
navigator.vibrate([50, 50, 50, 50]);
|
|
349
|
+
break;
|
|
350
|
+
case "custom":
|
|
351
|
+
if (Array.isArray(payload.sequence)) {
|
|
352
|
+
navigator.vibrate(payload.sequence);
|
|
353
|
+
} else if (typeof payload.sequence === "number") {
|
|
354
|
+
navigator.vibrate(payload.sequence);
|
|
355
|
+
}
|
|
356
|
+
break;
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
|
|
360
|
+
socket.on("server:signal", handleSignal);
|
|
361
|
+
return () => {
|
|
362
|
+
socket.off("server:signal", handleSignal);
|
|
363
|
+
};
|
|
364
|
+
}, [socket]);
|
|
365
|
+
|
|
366
|
+
// Main connection effect
|
|
367
|
+
useEffect(() => {
|
|
368
|
+
const storeState = store.getState();
|
|
369
|
+
storeState.setMode(detectRunMode());
|
|
370
|
+
storeState.setRole("controller");
|
|
371
|
+
storeState.setRoomId(parsedRoomId);
|
|
372
|
+
storeState.setStatus(parsedRoomId ? "connecting" : "idle");
|
|
373
|
+
storeState.setError(undefined);
|
|
374
|
+
|
|
375
|
+
if (!canConnect) {
|
|
376
|
+
// --- BRIDGE MODE (Iframe Child) ---
|
|
377
|
+
storeState.setStatus("connected");
|
|
378
|
+
|
|
379
|
+
const handleMessage = (event: MessageEvent) => {
|
|
380
|
+
if (event.source !== window.parent) return;
|
|
381
|
+
|
|
382
|
+
const data = event.data;
|
|
383
|
+
if (data?.type === "AIRJAM_STATE") {
|
|
384
|
+
const payload = data.payload as ControllerStatePayload;
|
|
385
|
+
if (payload.gameState) storeState.setGameState(payload.gameState);
|
|
386
|
+
if (payload.message !== undefined)
|
|
387
|
+
storeState.setStateMessage(payload.message);
|
|
388
|
+
onStateRef.current?.(payload);
|
|
389
|
+
}
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
window.addEventListener("message", handleMessage);
|
|
393
|
+
window.parent.postMessage({ type: "AIRJAM_READY" }, "*");
|
|
394
|
+
|
|
395
|
+
return () => {
|
|
396
|
+
window.removeEventListener("message", handleMessage);
|
|
397
|
+
storeState.setStatus("disconnected");
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// --- NORMAL MODE (Direct Socket Connection) ---
|
|
402
|
+
if (!parsedRoomId || !socket || !controllerId) {
|
|
403
|
+
storeState.setStatus("idle");
|
|
404
|
+
return;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
storeState.setControllerId(controllerId);
|
|
408
|
+
|
|
409
|
+
const handleConnect = (): void => {
|
|
410
|
+
store.getState().setStatus("connected");
|
|
411
|
+
|
|
412
|
+
if (subControllerParams) {
|
|
413
|
+
// Sub-Controller Mode - skip join
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const payload = controllerJoinSchema.parse({
|
|
418
|
+
roomId: parsedRoomId,
|
|
419
|
+
controllerId,
|
|
420
|
+
nickname: nicknameRef.current || undefined,
|
|
421
|
+
});
|
|
422
|
+
socket.emit("controller:join", payload, (ack) => {
|
|
423
|
+
const storeState = store.getState();
|
|
424
|
+
if (!ack.ok) {
|
|
425
|
+
storeState.setError(ack.message ?? "Unable to join room");
|
|
426
|
+
storeState.setStatus("disconnected");
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (ack.controllerId) {
|
|
430
|
+
storeState.setControllerId(ack.controllerId);
|
|
431
|
+
}
|
|
432
|
+
storeState.setStatus("connected");
|
|
433
|
+
});
|
|
434
|
+
};
|
|
435
|
+
|
|
436
|
+
const handleDisconnect = (): void => {
|
|
437
|
+
store.getState().setStatus("disconnected");
|
|
438
|
+
};
|
|
439
|
+
|
|
440
|
+
const handleWelcome = (payload: {
|
|
441
|
+
controllerId: string;
|
|
442
|
+
roomId: RoomCode;
|
|
443
|
+
player?: PlayerProfile;
|
|
444
|
+
}): void => {
|
|
445
|
+
const storeState = store.getState();
|
|
446
|
+
const storeRoomId = storeState.roomId;
|
|
447
|
+
if (
|
|
448
|
+
storeRoomId &&
|
|
449
|
+
payload.roomId.toUpperCase() !== storeRoomId.toUpperCase()
|
|
450
|
+
) {
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (!storeRoomId && payload.roomId) {
|
|
454
|
+
storeState.setRoomId(payload.roomId);
|
|
455
|
+
}
|
|
456
|
+
if (!payload.player) {
|
|
457
|
+
storeState.setError(
|
|
458
|
+
"Welcome message received but no player profile included.",
|
|
459
|
+
);
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
storeState.upsertPlayer(payload.player);
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
const handleState = (payload: ControllerStateMessage): void => {
|
|
466
|
+
if (payload.roomId !== parsedRoomId) return;
|
|
467
|
+
|
|
468
|
+
const storeState = store.getState();
|
|
469
|
+
if (payload.state.gameState) {
|
|
470
|
+
storeState.setGameState(payload.state.gameState);
|
|
471
|
+
}
|
|
472
|
+
if (payload.state.message !== undefined) {
|
|
473
|
+
storeState.setStateMessage(payload.state.message);
|
|
474
|
+
}
|
|
475
|
+
onStateRef.current?.(payload.state);
|
|
476
|
+
};
|
|
477
|
+
|
|
478
|
+
const handleHostLeft = (payload: { reason: string }): void => {
|
|
479
|
+
const storeState = store.getState();
|
|
480
|
+
storeState.setError(payload.reason);
|
|
481
|
+
storeState.setStatus("disconnected");
|
|
482
|
+
storeState.resetGameState();
|
|
483
|
+
|
|
484
|
+
setTimeout(() => {
|
|
485
|
+
disconnectSocket("controller");
|
|
486
|
+
setReconnectKey((prev) => prev + 1);
|
|
487
|
+
}, 1000);
|
|
488
|
+
};
|
|
489
|
+
|
|
490
|
+
const handleError = (payload: { message: string }): void => {
|
|
491
|
+
store.getState().setError(payload.message);
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
socket.on("connect", handleConnect);
|
|
495
|
+
socket.on("disconnect", handleDisconnect);
|
|
496
|
+
socket.on("server:welcome", handleWelcome);
|
|
497
|
+
socket.on("server:state", handleState);
|
|
498
|
+
socket.on("server:hostLeft", handleHostLeft);
|
|
499
|
+
socket.on("server:error", handleError);
|
|
500
|
+
|
|
501
|
+
// Connect the socket
|
|
502
|
+
socket.connect();
|
|
503
|
+
|
|
504
|
+
return () => {
|
|
505
|
+
socket.off("connect", handleConnect);
|
|
506
|
+
socket.off("disconnect", handleDisconnect);
|
|
507
|
+
socket.off("server:welcome", handleWelcome);
|
|
508
|
+
socket.off("server:state", handleState);
|
|
509
|
+
socket.off("server:hostLeft", handleHostLeft);
|
|
510
|
+
socket.off("server:error", handleError);
|
|
511
|
+
};
|
|
512
|
+
}, [
|
|
513
|
+
parsedRoomId,
|
|
514
|
+
reconnectKey,
|
|
515
|
+
canConnect,
|
|
516
|
+
socket,
|
|
517
|
+
controllerId,
|
|
518
|
+
subControllerParams,
|
|
519
|
+
store,
|
|
520
|
+
disconnectSocket,
|
|
521
|
+
]);
|
|
522
|
+
|
|
523
|
+
const setNickname = useCallback((value: string) => {
|
|
524
|
+
nicknameRef.current = value;
|
|
525
|
+
}, []);
|
|
526
|
+
|
|
527
|
+
const sendInput = useCallback(
|
|
528
|
+
(input: ControllerInputPayload): boolean => {
|
|
529
|
+
const storeState = store.getState();
|
|
530
|
+
|
|
531
|
+
if (!canConnect) {
|
|
532
|
+
// Bridge Mode
|
|
533
|
+
if (typeof window !== "undefined") {
|
|
534
|
+
window.parent.postMessage(
|
|
535
|
+
{
|
|
536
|
+
type: "AIRJAM_INPUT",
|
|
537
|
+
payload: input,
|
|
538
|
+
},
|
|
539
|
+
"*",
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
return true;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
if (!parsedRoomId || !storeState.controllerId || !socket) {
|
|
546
|
+
storeState.setError("Not connected to a room");
|
|
547
|
+
return false;
|
|
548
|
+
}
|
|
549
|
+
if (!socket.connected) {
|
|
550
|
+
return false;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
if (typeof input !== "object" || input === null || Array.isArray(input)) {
|
|
554
|
+
storeState.setError("Input must be an object");
|
|
555
|
+
return false;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const payload = controllerInputSchema.safeParse({
|
|
559
|
+
roomId: parsedRoomId,
|
|
560
|
+
controllerId: storeState.controllerId,
|
|
561
|
+
input,
|
|
562
|
+
});
|
|
563
|
+
if (!payload.success) {
|
|
564
|
+
storeState.setError(payload.error.message);
|
|
565
|
+
return false;
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
socket.emit("controller:input", payload.data);
|
|
569
|
+
return true;
|
|
570
|
+
},
|
|
571
|
+
[parsedRoomId, canConnect, socket, store],
|
|
572
|
+
);
|
|
573
|
+
|
|
574
|
+
const sendSystemCommand = useCallback(
|
|
575
|
+
(command: "exit" | "ready" | "toggle_pause") => {
|
|
576
|
+
const storeState = store.getState();
|
|
577
|
+
|
|
578
|
+
if (!canConnect) return;
|
|
579
|
+
if (!parsedRoomId || !storeState.controllerId || !socket) return;
|
|
580
|
+
if (!socket.connected) return;
|
|
581
|
+
|
|
582
|
+
const payload = controllerSystemSchema.safeParse({
|
|
583
|
+
roomId: parsedRoomId,
|
|
584
|
+
command,
|
|
585
|
+
});
|
|
586
|
+
|
|
587
|
+
if (payload.success) {
|
|
588
|
+
socket.emit("controller:system", payload.data);
|
|
589
|
+
}
|
|
590
|
+
},
|
|
591
|
+
[parsedRoomId, canConnect, socket, store],
|
|
592
|
+
);
|
|
593
|
+
|
|
594
|
+
return {
|
|
595
|
+
roomId: parsedRoomId,
|
|
596
|
+
controllerId: connectionState.controllerId,
|
|
597
|
+
connectionStatus: connectionState.connectionStatus,
|
|
598
|
+
lastError: connectionState.lastError,
|
|
599
|
+
gameState: connectionState.gameState,
|
|
600
|
+
stateMessage: connectionState.stateMessage,
|
|
601
|
+
sendInput,
|
|
602
|
+
sendSystemCommand,
|
|
603
|
+
setNickname,
|
|
604
|
+
reconnect,
|
|
605
|
+
players: connectionState.players,
|
|
606
|
+
socket,
|
|
607
|
+
};
|
|
608
|
+
};
|