@air-jam/sdk 0.1.1 → 0.1.3

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.
@@ -10,6 +10,19 @@ interface VolumeSettings {
10
10
  getEffectiveVolume: (category: "music" | "sfx") => number;
11
11
  }
12
12
 
13
+ /**
14
+ * Settings sync message from parent (arcade) to child (game) iframe.
15
+ * This allows the arcade overlay to control volume for embedded games.
16
+ */
17
+ interface AirJamSettingsSyncMessage {
18
+ type: "AIRJAM_SETTINGS_SYNC";
19
+ payload: {
20
+ masterVolume: number;
21
+ musicVolume: number;
22
+ sfxVolume: number;
23
+ };
24
+ }
25
+
13
26
  const STORAGE_KEY = "air-jam-volume-settings";
14
27
 
15
28
  // Load initial state from localStorage
@@ -75,3 +88,37 @@ export const useVolumeStore = create<VolumeSettings>((set, get) => ({
75
88
  return masterVolume * categoryVolume;
76
89
  },
77
90
  }));
91
+
92
+ /**
93
+ * Set up parent message listener for child mode (games running in arcade iframe).
94
+ * When the arcade sends AIRJAM_SETTINGS_SYNC messages, apply them to the volume store.
95
+ * This runs once at module load time and is completely transparent to game developers.
96
+ */
97
+ const setupParentSettingsListener = () => {
98
+ if (typeof window === "undefined") return;
99
+
100
+ // Only listen if we're running inside an iframe (child mode)
101
+ const isInIframe = window.parent !== window;
102
+ if (!isInIframe) return;
103
+
104
+ const handleMessage = (event: MessageEvent<AirJamSettingsSyncMessage>) => {
105
+ // Only accept settings sync messages from parent
106
+ if (event.source !== window.parent) return;
107
+ if (event.data?.type !== "AIRJAM_SETTINGS_SYNC") return;
108
+
109
+ const { masterVolume, musicVolume, sfxVolume } = event.data.payload;
110
+
111
+ // Apply settings without saving to localStorage (arcade owns the settings)
112
+ const store = useVolumeStore.getState();
113
+
114
+ // Use setters to trigger AudioManager subscription updates
115
+ if (typeof masterVolume === "number") store.setMasterVolume(masterVolume);
116
+ if (typeof musicVolume === "number") store.setMusicVolume(musicVolume);
117
+ if (typeof sfxVolume === "number") store.setSfxVolume(sfxVolume);
118
+ };
119
+
120
+ window.addEventListener("message", handleMessage);
121
+ };
122
+
123
+ // Initialize the parent settings listener
124
+ setupParentSettingsListener();
@@ -7,34 +7,36 @@ import {
7
7
  RefreshCw,
8
8
  } from "lucide-react";
9
9
  import type { JSX } from "react";
10
- import { useEffect, useMemo, useState, type ReactNode } from "react";
10
+ import {
11
+ useCallback,
12
+ useEffect,
13
+ useMemo,
14
+ useState,
15
+ type ReactNode,
16
+ } from "react";
11
17
  import { useStore } from "zustand";
12
18
  import { useShallow } from "zustand/react/shallow";
13
19
  import { useAirJamContext } from "../context/air-jam-context";
14
20
  import { useFullscreen } from "../hooks/use-fullscreen";
15
- import type { ConnectionStatus, PlayerProfile } from "../protocol";
21
+ import type { PlayerProfile } from "../protocol";
22
+ import { controllerSystemSchema } from "../protocol";
16
23
  import { cn } from "../utils/cn";
17
24
  import { detectRunMode } from "../utils/mode";
25
+ import { PlayerAvatar } from "./player-avatar";
18
26
  import { QRScannerDialog } from "./qr-scanner-dialog";
19
27
  import { Button } from "./ui/button";
20
- import { PlayerAvatar } from "./player-avatar";
21
- import { VolumeControls } from "./volume-controls";
22
-
23
- type OrientationRequirement = "portrait" | "landscape" | "any";
24
28
 
25
29
  interface ControllerShellProps {
26
- roomId?: string | null;
27
- connectionStatus: ConnectionStatus;
28
- requiredOrientation?: OrientationRequirement;
30
+ /** Optional forced orientation. If not set, no orientation enforcement is applied. */
31
+ forceOrientation?: "portrait" | "landscape";
29
32
  children: ReactNode;
30
- gameState?: "paused" | "playing";
31
- onTogglePlayPause?: () => void;
32
- onReconnect?: (roomCode: string) => void;
33
- onRefresh?: () => void;
33
+ /** Optional custom actions to display in the header */
34
34
  customActions?: ReactNode;
35
35
  }
36
36
 
37
- const describeStatus = (status: ConnectionStatus): string => {
37
+ const describeStatus = (
38
+ status: "connected" | "connecting" | "reconnecting" | "disconnected" | "idle",
39
+ ): string => {
38
40
  switch (status) {
39
41
  case "connected":
40
42
  return "Connected to host";
@@ -50,44 +52,44 @@ const describeStatus = (status: ConnectionStatus): string => {
50
52
  }
51
53
  };
52
54
 
53
- const orientationMatches = (required: OrientationRequirement): boolean => {
54
- if (required === "any") return true;
55
+ const orientationMatches = (
56
+ required: "portrait" | "landscape" | undefined,
57
+ ): boolean => {
58
+ if (!required) return true;
55
59
  if (typeof window === "undefined" || !window.matchMedia) return true;
56
60
  const matcher = window.matchMedia(`(orientation: ${required})`);
57
61
  return matcher.matches;
58
62
  };
59
63
 
60
64
  export const ControllerShell = ({
61
- roomId,
62
- connectionStatus,
63
- requiredOrientation = "landscape",
65
+ forceOrientation,
64
66
  children,
65
- gameState = "paused",
66
- onTogglePlayPause,
67
- onReconnect,
68
- onRefresh,
69
67
  customActions,
70
68
  }: ControllerShellProps): JSX.Element => {
69
+ const { store, getSocket, disconnectSocket } = useAirJamContext();
70
+
71
71
  const isChildMode = useMemo(() => detectRunMode() === "platform", []);
72
72
  const [isOrientationOk, setOrientationOk] = useState(() =>
73
- orientationMatches(requiredOrientation),
73
+ orientationMatches(forceOrientation),
74
74
  );
75
75
  const [isScannerOpen, setIsScannerOpen] = useState(false);
76
76
  const { isFullscreen, toggleFullscreen } = useFullscreen();
77
77
 
78
- // Get store from context
79
- const { store } = useAirJamContext();
80
-
81
- // Get current player info from connection store
82
- const { controllerId, players } = useStore(
83
- store,
84
- useShallow(
85
- (state: { controllerId: string | null; players: PlayerProfile[] }) => ({
78
+ // Read all state from the store (works with both useAirJamController and useAirJamShell)
79
+ const { roomId, connectionStatus, gameState, controllerId, players } =
80
+ useStore(
81
+ store,
82
+ useShallow((state) => ({
83
+ roomId: state.roomId,
84
+ connectionStatus: state.connectionStatus,
85
+ gameState: state.gameState,
86
86
  controllerId: state.controllerId,
87
87
  players: state.players,
88
- }),
89
- ),
90
- );
88
+ })),
89
+ );
90
+
91
+ // Get socket for callbacks
92
+ const socket = useMemo(() => getSocket("controller"), [getSocket]);
91
93
 
92
94
  // Find current player profile - must exist from server (single source of truth)
93
95
  const currentPlayer = useMemo(() => {
@@ -102,19 +104,48 @@ export const ControllerShell = ({
102
104
  return found || null;
103
105
  }, [controllerId, players, connectionStatus]);
104
106
 
107
+ // Implement sendSystemCommand using socket manager
108
+ const sendSystemCommand = useCallback(
109
+ (command: "exit" | "ready" | "toggle_pause") => {
110
+ const storeState = store.getState();
111
+ if (!roomId || !storeState.controllerId || !socket) return;
112
+ if (!socket.connected) return;
113
+
114
+ const payload = controllerSystemSchema.safeParse({
115
+ roomId,
116
+ command,
117
+ });
118
+
119
+ if (payload.success) {
120
+ socket.emit("controller:system", payload.data);
121
+ }
122
+ },
123
+ [roomId, socket, store],
124
+ );
125
+
126
+ // Implement reconnect
127
+ const reconnect = useCallback(() => {
128
+ if (!roomId) return;
129
+ disconnectSocket("controller");
130
+ // Force reconnection by updating room ID (triggers hook reconnection)
131
+ store.getState().setRoomId(roomId);
132
+ }, [roomId, disconnectSocket, store]);
133
+
105
134
  useEffect(() => {
106
- if (requiredOrientation === "any") {
135
+ if (!forceOrientation) {
136
+ // eslint-disable-next-line react-hooks/set-state-in-effect
137
+ setOrientationOk(true);
107
138
  return;
108
139
  }
109
140
 
110
- const media = window.matchMedia(`(orientation: ${requiredOrientation})`);
141
+ const media = window.matchMedia(`(orientation: ${forceOrientation})`);
111
142
  const handleChange = (): void => setOrientationOk(media.matches);
112
143
  handleChange();
113
144
  media.addEventListener("change", handleChange);
114
145
  return () => media.removeEventListener("change", handleChange);
115
- }, [requiredOrientation]);
146
+ }, [forceOrientation]);
116
147
 
117
- const orientationOk = requiredOrientation === "any" ? true : isOrientationOk;
148
+ const orientationOk = !forceOrientation ? true : isOrientationOk;
118
149
 
119
150
  const statusDotColor = useMemo(() => {
120
151
  switch (connectionStatus) {
@@ -134,102 +165,105 @@ export const ControllerShell = ({
134
165
  if (isChildMode) {
135
166
  return (
136
167
  <div className="dark">
137
- <div className="text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden bg-transparent select-none">
138
- <main className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4">
139
- {!orientationOk && (
140
- <div className="bg-background/95 absolute inset-0 z-50 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm">
141
- <p className="text-card-foreground text-xl font-semibold">
142
- Rotate your device
143
- </p>
144
- <p className="text-muted-foreground mt-2 text-sm">
145
- This game is best experienced in {requiredOrientation}{" "}
146
- orientation.
147
- </p>
148
- </div>
149
- )}
150
- <div
151
- className={cn(
152
- "h-full w-full select-none",
153
- !orientationOk && "pointer-events-none opacity-30",
168
+ <div className="text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden bg-black select-none">
169
+ <main className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4">
170
+ {!orientationOk && (
171
+ <div className="bg-background/95 absolute inset-0 z-50 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm">
172
+ <p className="text-card-foreground text-xl font-semibold">
173
+ Rotate your device
174
+ </p>
175
+ <p className="text-muted-foreground mt-2 text-sm">
176
+ This game is best experienced in {forceOrientation}{" "}
177
+ orientation.
178
+ </p>
179
+ </div>
154
180
  )}
155
- >
156
- {children}
157
- </div>
158
- </main>
159
- </div>
181
+ <div
182
+ className={cn(
183
+ "h-full w-full select-none",
184
+ !orientationOk && "pointer-events-none opacity-30",
185
+ )}
186
+ >
187
+ {children}
188
+ </div>
189
+ </main>
190
+ </div>
160
191
  </div>
161
192
  );
162
193
  }
163
194
 
164
195
  return (
165
196
  <div className="dark">
166
- <div className="bg-background text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden select-none">
167
- <header className="pointer-events-none sticky top-0 z-50 flex items-center justify-between border-b px-6 py-2">
168
- <div className="pointer-events-auto flex items-center gap-3">
169
- {typeof window !== "undefined" && (currentPlayer || controllerId) && (
170
- <div className="relative" title={describeStatus(connectionStatus)}>
171
- {currentPlayer ? (
172
- <PlayerAvatar player={currentPlayer} size="sm" />
173
- ) : controllerId ? (
174
- <PlayerAvatar
175
- player={{
176
- id: controllerId,
177
- label: "Player",
178
- }}
179
- size="sm"
180
- />
181
- ) : null}
182
- {/* Black border circle - always visible behind */}
183
- <span
184
- className="absolute right-0 bottom-0 h-3 w-3 rounded-full bg-black"
185
- aria-hidden="true"
186
- />
187
- {/* Colored status dot - on top */}
188
- <span
189
- className={cn(
190
- "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
191
- statusDotColor,
192
- connectionStatus === "connected" && "animate-pulse",
193
- )}
194
- aria-label={describeStatus(connectionStatus)}
195
- />
197
+ <div className="text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden bg-black select-none">
198
+ <header className="pointer-events-none sticky top-0 z-50 flex items-center justify-between border-b px-6 py-2">
199
+ <div className="pointer-events-auto flex items-center gap-3">
200
+ {typeof window !== "undefined" &&
201
+ (currentPlayer || controllerId) && (
202
+ <div
203
+ className="relative"
204
+ title={describeStatus(connectionStatus)}
205
+ >
206
+ {currentPlayer ? (
207
+ <PlayerAvatar player={currentPlayer} size="sm" />
208
+ ) : controllerId ? (
209
+ <PlayerAvatar
210
+ player={{
211
+ id: controllerId,
212
+ label: "Player",
213
+ }}
214
+ size="sm"
215
+ />
216
+ ) : null}
217
+ {/* Black border circle - always visible behind */}
218
+ <span
219
+ className="absolute right-0 bottom-0 h-3 w-3 rounded-full bg-black"
220
+ aria-hidden="true"
221
+ />
222
+ {/* Colored status dot - on top */}
223
+ <span
224
+ className={cn(
225
+ "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
226
+ statusDotColor,
227
+ connectionStatus === "connected" && "animate-pulse",
228
+ )}
229
+ aria-label={describeStatus(connectionStatus)}
230
+ />
231
+ </div>
232
+ )}
233
+ <div>
234
+ <p className="text-muted-foreground text-xs tracking-[0.24em] uppercase">
235
+ Room
236
+ </p>
237
+ <p className="text-foreground text-lg font-semibold">
238
+ {typeof window !== "undefined" ? (roomId ?? "N/A") : "N/A"}
239
+ </p>
196
240
  </div>
197
- )}
198
- <div>
199
- <p className="text-muted-foreground text-xs tracking-[0.24em] uppercase">
200
- Room
201
- </p>
202
- <p className="text-foreground text-lg font-semibold">
203
- {typeof window !== "undefined" ? (roomId ?? "N/A") : "N/A"}
204
- </p>
205
241
  </div>
206
- </div>
207
- <div className="pointer-events-auto flex items-center gap-3">
208
- {customActions}
209
- {onRefresh && roomId && (
210
- <Button
211
- type="button"
212
- variant="outline"
213
- size="icon"
214
- onClick={onRefresh}
215
- disabled={
216
- connectionStatus === "connecting" ||
217
- connectionStatus === "reconnecting"
218
- }
219
- aria-label="Reconnect"
220
- title="Reconnect to room"
221
- >
222
- <RefreshCw
223
- className={cn(
224
- "h-5 w-5",
225
- (connectionStatus === "connecting" ||
226
- connectionStatus === "reconnecting") &&
227
- "animate-spin",
228
- )}
229
- />
230
- </Button>
231
- )}
232
- {onReconnect && (
242
+ <div className="pointer-events-auto flex items-center gap-3">
243
+ {customActions}
244
+ {roomId && (
245
+ <Button
246
+ type="button"
247
+ variant="outline"
248
+ size="icon"
249
+ onClick={() => window.location.reload()}
250
+ disabled={
251
+ connectionStatus === "connecting" ||
252
+ connectionStatus === "reconnecting"
253
+ }
254
+ aria-label="Reconnect"
255
+ title="Reconnect to room"
256
+ >
257
+ <RefreshCw
258
+ className={cn(
259
+ "h-5 w-5",
260
+ (connectionStatus === "connecting" ||
261
+ connectionStatus === "reconnecting") &&
262
+ "animate-spin",
263
+ )}
264
+ />
265
+ </Button>
266
+ )}
233
267
  <Button
234
268
  type="button"
235
269
  variant="outline"
@@ -240,13 +274,11 @@ export const ControllerShell = ({
240
274
  >
241
275
  <QrCode className="h-5 w-5" />
242
276
  </Button>
243
- )}
244
- {onTogglePlayPause && (
245
277
  <Button
246
278
  type="button"
247
279
  variant="outline"
248
280
  size="icon"
249
- onClick={onTogglePlayPause}
281
+ onClick={() => sendSystemCommand("toggle_pause")}
250
282
  aria-label={gameState === "playing" ? "Pause" : "Play"}
251
283
  title={gameState === "playing" ? "Pause" : "Play"}
252
284
  >
@@ -256,66 +288,58 @@ export const ControllerShell = ({
256
288
  <Play className="h-5 w-5" />
257
289
  )}
258
290
  </Button>
259
- )}
260
- <Button
261
- type="button"
262
- variant="outline"
263
- size="icon"
264
- onClick={() => toggleFullscreen()}
265
- aria-label={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
266
- title={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
267
- >
268
- {isFullscreen ? (
269
- <Minimize className="h-5 w-5" />
270
- ) : (
271
- <Maximize className="h-5 w-5" />
272
- )}
273
- </Button>
274
- </div>
275
- </header>
276
-
277
- {/* Volume Controls - positioned absolutely for mobile */}
278
- <div className="pointer-events-none fixed right-4 bottom-4 z-50">
279
- <div className="pointer-events-auto">
280
- <VolumeControls compact={true} />
281
- </div>
282
- </div>
291
+ <Button
292
+ type="button"
293
+ variant="outline"
294
+ size="icon"
295
+ onClick={() => toggleFullscreen()}
296
+ aria-label={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
297
+ title={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
298
+ >
299
+ {isFullscreen ? (
300
+ <Minimize className="h-5 w-5" />
301
+ ) : (
302
+ <Maximize className="h-5 w-5" />
303
+ )}
304
+ </Button>
305
+ </div>
306
+ </header>
283
307
 
284
- <main className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4">
285
- <div className="bg-card/95 absolute inset-0 z-10 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm">
286
- {!orientationOk && (
287
- <div className="bg-background/95 absolute inset-0 z-10 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm">
288
- <p className="text-card-foreground text-xl font-semibold">
289
- Rotate your device
290
- </p>
291
- <p className="text-muted-foreground mt-2 text-sm">
292
- This game is best experienced in {requiredOrientation}{" "}
293
- orientation.
294
- </p>
295
- </div>
296
- )}
297
- <div
298
- className={cn(
299
- "h-full w-full select-none",
300
- !orientationOk && "pointer-events-none opacity-30",
308
+ <main className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4">
309
+ <div className="bg-card/95 absolute inset-0 z-10 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm">
310
+ {!orientationOk && forceOrientation && (
311
+ <div className="bg-background/95 absolute inset-0 z-10 flex flex-col items-center justify-center p-6 text-center shadow-lg backdrop-blur-sm">
312
+ <p className="text-card-foreground text-xl font-semibold">
313
+ Rotate your device
314
+ </p>
315
+ <p className="text-muted-foreground mt-2 text-sm">
316
+ This game is best experienced in {forceOrientation}{" "}
317
+ orientation.
318
+ </p>
319
+ </div>
301
320
  )}
302
- >
303
- {children}
321
+ <div
322
+ className={cn(
323
+ "h-full w-full select-none",
324
+ !orientationOk && "pointer-events-none opacity-30",
325
+ )}
326
+ >
327
+ {children}
328
+ </div>
304
329
  </div>
305
- </div>
306
- </main>
330
+ </main>
307
331
 
308
- {onReconnect && (
309
332
  <QRScannerDialog
310
333
  isOpen={isScannerOpen}
311
334
  onClose={() => setIsScannerOpen(false)}
312
335
  onScan={(roomCode) => {
313
- onReconnect(roomCode);
336
+ // Update room ID in the store, which will trigger reconnection
337
+ store.getState().setRoomId(roomCode);
338
+ reconnect();
314
339
  setIsScannerOpen(false);
315
340
  }}
316
341
  currentRoomId={roomId}
317
342
  />
318
- )}
319
343
  </div>
320
344
  </div>
321
345
  );