@air-jam/sdk 0.1.0 → 0.1.1

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.
@@ -0,0 +1,83 @@
1
+ import { Check, Copy } from "lucide-react";
2
+ import type { JSX } from "react";
3
+ import { useEffect, useState } from "react";
4
+ import { Button } from "./ui/button";
5
+ import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";
6
+
7
+ interface DebugStateDialogProps {
8
+ isOpen: boolean;
9
+ onClose: () => void;
10
+ getState: () => unknown;
11
+ title?: string;
12
+ updateInterval?: number;
13
+ }
14
+
15
+ export const DebugStateDialog = ({
16
+ isOpen,
17
+ onClose,
18
+ getState,
19
+ title = "Debug State",
20
+ updateInterval = 100,
21
+ }: DebugStateDialogProps): JSX.Element => {
22
+ const [state, setState] = useState<unknown>(() => getState());
23
+ const [copied, setCopied] = useState(false);
24
+
25
+ useEffect(() => {
26
+ if (!isOpen) return;
27
+
28
+ // Update state periodically to see changes
29
+ const interval = setInterval(() => {
30
+ setState(getState());
31
+ }, updateInterval);
32
+
33
+ // Update immediately on mount
34
+ const timeoutId = setTimeout(() => {
35
+ setState(getState());
36
+ }, 0);
37
+
38
+ return () => {
39
+ clearInterval(interval);
40
+ clearTimeout(timeoutId);
41
+ };
42
+ }, [isOpen, getState, updateInterval]);
43
+
44
+ const jsonString = JSON.stringify(state, null, 2);
45
+
46
+ const handleCopy = async () => {
47
+ try {
48
+ await navigator.clipboard.writeText(jsonString);
49
+ setCopied(true);
50
+ setTimeout(() => setCopied(false), 2000);
51
+ } catch (error) {
52
+ console.error("Failed to copy:", error);
53
+ }
54
+ };
55
+
56
+ return (
57
+ <Dialog open={isOpen} onOpenChange={onClose}>
58
+ <DialogContent className="dark max-h-[90vh] max-w-2xl flex-col">
59
+ <DialogHeader>
60
+ <DialogTitle className="text-foreground">{title}</DialogTitle>
61
+ </DialogHeader>
62
+ <div className="relative flex-1 overflow-auto pt-4">
63
+ <Button
64
+ variant="ghost"
65
+ size="icon-sm"
66
+ onClick={handleCopy}
67
+ className="text-muted-foreground hover:text-foreground absolute top-6 right-2 z-10"
68
+ aria-label="Copy state"
69
+ >
70
+ {copied ? (
71
+ <Check className="h-4 w-4" />
72
+ ) : (
73
+ <Copy className="h-4 w-4" />
74
+ )}
75
+ </Button>
76
+ <pre className="bg-muted text-muted-foreground overflow-auto rounded-lg border p-4 font-mono text-xs">
77
+ {jsonString}
78
+ </pre>
79
+ </div>
80
+ </DialogContent>
81
+ </Dialog>
82
+ );
83
+ };
@@ -0,0 +1,64 @@
1
+ import type { JSX } from "react";
2
+ import type { PlayerProfile } from "../protocol";
3
+
4
+ // Generate a consistent avatar URL for a player based on their ID
5
+ const getPlayerAvatarUrl = (playerId: string): string => {
6
+ // Use DiceBear API with identicon style for GitHub-like avatars
7
+ // The seed ensures the same player ID always gets the same avatar
8
+ return `https://api.dicebear.com/9.x/adventurer-neutral/svg?seed=${encodeURIComponent(
9
+ playerId,
10
+ )}`;
11
+ };
12
+
13
+ // Convert hex color to rgba with opacity
14
+ const hexToRgba = (hex: string, opacity: number): string => {
15
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
16
+ if (!result) return `rgba(0, 0, 0, ${opacity})`;
17
+ const r = parseInt(result[1], 16);
18
+ const g = parseInt(result[2], 16);
19
+ const b = parseInt(result[3], 16);
20
+ return `rgba(${r}, ${g}, ${b}, ${opacity})`;
21
+ };
22
+
23
+ interface PlayerAvatarProps {
24
+ player: PlayerProfile;
25
+ size?: "sm" | "md" | "lg";
26
+ className?: string;
27
+ }
28
+
29
+ export const PlayerAvatar = ({
30
+ player,
31
+ size = "md",
32
+ className = "",
33
+ }: PlayerAvatarProps): JSX.Element => {
34
+ const sizeClasses = {
35
+ sm: "h-8 w-8 border-2",
36
+ md: "h-12 w-12 border-4",
37
+ lg: "h-16 w-16 border-4",
38
+ };
39
+
40
+ const shadowStyles = {
41
+ sm: player.color
42
+ ? `inset 0 0 4px rgba(0, 0, 0, 0.2), 0 0 8px ${hexToRgba(player.color, 0.4)}`
43
+ : "inset 0 0 4px rgba(0, 0, 0, 0.2)",
44
+ md: player.color
45
+ ? `inset 0 0 10px rgba(0, 0, 0, 0.4), 0 0 20px ${hexToRgba(player.color, 0.6)}, 0 0 10px ${hexToRgba(player.color, 0.8)}`
46
+ : "inset 0 0 10px rgba(0, 0, 0, 0.4), 0 0 20px hsl(var(--border) / 0.5)",
47
+ lg: player.color
48
+ ? `inset 0 0 12px rgba(0, 0, 0, 0.4), 0 0 24px ${hexToRgba(player.color, 0.6)}, 0 0 12px ${hexToRgba(player.color, 0.8)}`
49
+ : "inset 0 0 12px rgba(0, 0, 0, 0.4), 0 0 24px hsl(var(--border) / 0.5)",
50
+ };
51
+
52
+ return (
53
+ <img
54
+ src={getPlayerAvatarUrl(player.id)}
55
+ alt={player.label}
56
+ className={`bg-secondary/30 shrink-0 rounded-full shadow-lg ${sizeClasses[size]} ${className}`}
57
+ style={{
58
+ borderColor: player.color || "hsl(var(--border))",
59
+ boxShadow: shadowStyles[size],
60
+ }}
61
+ />
62
+ );
63
+ };
64
+
@@ -18,7 +18,7 @@ const buttonVariants = cva(
18
18
  secondary:
19
19
  "bg-secondary text-secondary-foreground hover:bg-secondary/80",
20
20
  ghost:
21
- "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
21
+ "text-foreground hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
22
22
  link: "text-primary underline-offset-4 hover:underline",
23
23
  },
24
24
  size: {
@@ -0,0 +1,122 @@
1
+ import * as DialogPrimitive from "@radix-ui/react-dialog";
2
+ import { X } from "lucide-react";
3
+ import * as React from "react";
4
+
5
+ import { cn } from "../../utils/cn";
6
+
7
+ const Dialog = DialogPrimitive.Root;
8
+
9
+ const DialogTrigger = DialogPrimitive.Trigger;
10
+
11
+ const DialogPortal = DialogPrimitive.Portal;
12
+
13
+ const DialogClose = DialogPrimitive.Close;
14
+
15
+ const DialogOverlay = React.forwardRef<
16
+ React.ElementRef<typeof DialogPrimitive.Overlay>,
17
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
18
+ >(({ className, ...props }, ref) => (
19
+ <DialogPrimitive.Overlay
20
+ ref={ref}
21
+ className={cn(
22
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-99999 bg-black/80",
23
+ className,
24
+ )}
25
+ {...props}
26
+ />
27
+ ));
28
+ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
29
+
30
+ const DialogContent = React.forwardRef<
31
+ React.ElementRef<typeof DialogPrimitive.Content>,
32
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
33
+ >(({ className, children, ...props }, ref) => (
34
+ <DialogPortal>
35
+ <div className="dark">
36
+ <DialogOverlay />
37
+ <DialogPrimitive.Content
38
+ ref={ref}
39
+ className={cn(
40
+ "bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] fixed top-[50%] left-[50%] z-99999 w-full translate-x-[-50%] translate-y-[-50%] gap-4 rounded-xl border border-white p-6 shadow-lg duration-200",
41
+ className,
42
+ )}
43
+ {...props}
44
+ >
45
+ {children}
46
+ <DialogPrimitive.Close className="text-foreground ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-sm opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:pointer-events-none">
47
+ <X className="h-4 w-4" />
48
+ <span className="sr-only">Close</span>
49
+ </DialogPrimitive.Close>
50
+ </DialogPrimitive.Content>
51
+ </div>
52
+ </DialogPortal>
53
+ ));
54
+ DialogContent.displayName = DialogPrimitive.Content.displayName;
55
+
56
+ const DialogHeader = ({
57
+ className,
58
+ ...props
59
+ }: React.HTMLAttributes<HTMLDivElement>) => (
60
+ <div
61
+ className={cn(
62
+ "flex flex-col space-y-1.5 text-center sm:text-left",
63
+ className,
64
+ )}
65
+ {...props}
66
+ />
67
+ );
68
+ DialogHeader.displayName = "DialogHeader";
69
+
70
+ const DialogFooter = ({
71
+ className,
72
+ ...props
73
+ }: React.HTMLAttributes<HTMLDivElement>) => (
74
+ <div
75
+ className={cn(
76
+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
77
+ className,
78
+ )}
79
+ {...props}
80
+ />
81
+ );
82
+ DialogFooter.displayName = "DialogFooter";
83
+
84
+ const DialogTitle = React.forwardRef<
85
+ React.ElementRef<typeof DialogPrimitive.Title>,
86
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
87
+ >(({ className, ...props }, ref) => (
88
+ <DialogPrimitive.Title
89
+ ref={ref}
90
+ className={cn(
91
+ "text-lg leading-none font-semibold tracking-tight",
92
+ className,
93
+ )}
94
+ {...props}
95
+ />
96
+ ));
97
+ DialogTitle.displayName = DialogPrimitive.Title.displayName;
98
+
99
+ const DialogDescription = React.forwardRef<
100
+ React.ElementRef<typeof DialogPrimitive.Description>,
101
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
102
+ >(({ className, ...props }, ref) => (
103
+ <DialogPrimitive.Description
104
+ ref={ref}
105
+ className={cn("text-muted-foreground text-sm", className)}
106
+ {...props}
107
+ />
108
+ ));
109
+ DialogDescription.displayName = DialogPrimitive.Description.displayName;
110
+
111
+ export {
112
+ Dialog,
113
+ DialogClose,
114
+ DialogContent,
115
+ DialogDescription,
116
+ DialogFooter,
117
+ DialogHeader,
118
+ DialogOverlay,
119
+ DialogPortal,
120
+ DialogTitle,
121
+ DialogTrigger,
122
+ };
package/src/index.ts CHANGED
@@ -5,8 +5,11 @@ export * from "./context";
5
5
  export * from "./audio";
6
6
 
7
7
  // Components
8
+ export * from "./components/air-jam-debug";
8
9
  export * from "./components/air-jam-overlay";
9
10
  export * from "./components/controller-shell";
11
+ export * from "./components/debug-state-dialog";
12
+ export * from "./components/player-avatar";
10
13
  export * from "./components/ui/button";
11
14
  export * from "./components/ui/slider";
12
15
  export * from "./components/volume-controls";
@@ -27,6 +30,9 @@ export * from "./hooks/use-send-signal";
27
30
  // Protocol types
28
31
  export * from "./protocol";
29
32
 
33
+ // Store
34
+ export * from "./store/create-air-jam-store";
35
+
30
36
  // Utilities
31
37
  export * from "./utils/ids";
32
38
  export * from "./utils/network-ip";
package/src/protocol.ts CHANGED
@@ -238,6 +238,29 @@ export interface ClientLoadUiPayload {
238
238
  url: string;
239
239
  }
240
240
 
241
+ export interface HostStateSyncPayload {
242
+ roomId: string;
243
+ data: Record<string, unknown>;
244
+ }
245
+
246
+ export interface ControllerActionRpcPayload {
247
+ roomId: string;
248
+ actionName: string;
249
+ args: unknown[];
250
+ controllerId: string;
251
+ }
252
+
253
+ export interface AirJamStateSyncPayload {
254
+ roomId: string;
255
+ data: Record<string, unknown>;
256
+ }
257
+
258
+ export interface AirJamActionRpcPayload {
259
+ actionName: string;
260
+ args: unknown[];
261
+ controllerId: string;
262
+ }
263
+
241
264
  export interface ClientToServerEvents {
242
265
  "host:register": (
243
266
  payload: z.infer<typeof hostRegistrationSchema>,
@@ -270,6 +293,8 @@ export interface ClientToServerEvents {
270
293
  "host:signal": (payload: SignalPayload) => void;
271
294
  "host:play_sound": (payload: PlaySoundEventPayload) => void;
272
295
  "controller:play_sound": (payload: PlaySoundEventPayload) => void;
296
+ "host:state_sync": (payload: HostStateSyncPayload) => void;
297
+ "controller:action_rpc": (payload: ControllerActionRpcPayload) => void;
273
298
  }
274
299
 
275
300
  export interface PlaySoundPayload {
@@ -293,6 +318,8 @@ export interface ServerToClientEvents {
293
318
  "server:closeChild": () => void;
294
319
  "client:loadUi": (payload: ClientLoadUiPayload) => void;
295
320
  "client:unloadUi": () => void;
321
+ "airjam:state_sync": (payload: AirJamStateSyncPayload) => void;
322
+ "airjam:action_rpc": (payload: AirJamActionRpcPayload) => void;
296
323
  }
297
324
 
298
325
  export interface InterServerEvents {
@@ -0,0 +1,212 @@
1
+ import { useEffect } from "react";
2
+ import { create, type StateCreator } from "zustand";
3
+ import { useAirJamContext, useAirJamState } from "../context/air-jam-context";
4
+ import type {
5
+ AirJamActionRpcPayload,
6
+ AirJamStateSyncPayload,
7
+ } from "../protocol";
8
+
9
+ /**
10
+ * Creates a networked Zustand store that automatically syncs state between host and controllers.
11
+ *
12
+ * The store pattern works as follows:
13
+ * - Host: Stores state locally and broadcasts changes to all controllers
14
+ * - Controller: Sends action RPCs to host, receives state updates from host
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * interface GameState {
19
+ * phase: "lobby" | "playing" | "gameover";
20
+ * scores: { team1: number; team2: number };
21
+ * actions: {
22
+ * setPhase: (phase: "lobby" | "playing") => void;
23
+ * scorePoint: (team: "team1" | "team2") => void;
24
+ * };
25
+ * }
26
+ *
27
+ * export const useGameStore = createAirJamStore<GameState>((set) => ({
28
+ * phase: "lobby",
29
+ * scores: { team1: 0, team2: 0 },
30
+ * actions: {
31
+ * setPhase: (phase) => set({ phase }),
32
+ * scorePoint: (team) => set((state) => ({
33
+ * scores: { ...state.scores, [team]: state.scores[team] + 1 }
34
+ * })),
35
+ * },
36
+ * }));
37
+ * ```
38
+ */
39
+ export function createAirJamStore<
40
+ T extends {
41
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
42
+ actions: Record<string, (...args: any[]) => any>;
43
+ },
44
+ >(initializer: StateCreator<T>) {
45
+ // 1. Create the Vanilla Zustand Store with an internal sync action
46
+ const store = create<T>((set, get, api) => {
47
+ const baseState = initializer(set, get, api);
48
+ // Add internal _syncState action for external updates
49
+ return {
50
+ ...baseState,
51
+ actions: {
52
+ ...baseState.actions,
53
+ _syncState: (partial: Partial<T>) => {
54
+ set(partial as T);
55
+ },
56
+ },
57
+ } as T;
58
+ });
59
+
60
+ // 2. The Hook Component
61
+ const useSyncedStore = <U>(
62
+ selector: (state: T) => U = (s) => s as unknown as U,
63
+ ): U => {
64
+ // Standard Zustand selector behavior
65
+ const slice = store(selector);
66
+
67
+ const { getSocket } = useAirJamContext();
68
+ const role = useAirJamState((state) => state.role);
69
+ const roomId = useAirJamState((state) => state.roomId);
70
+ const controllerId = useAirJamState((state) => state.controllerId);
71
+ const socket =
72
+ role === "host" ? getSocket("host") : getSocket("controller");
73
+
74
+ // --- NETWORKING LOGIC ---
75
+ useEffect(() => {
76
+ if (!socket || !roomId || !role) {
77
+ return;
78
+ }
79
+
80
+ // HOST: Broadcast changes to everyone
81
+ if (role === "host") {
82
+ // Subscribe to store changes
83
+ const unsubscribe = store.subscribe((newState) => {
84
+ // Optimization: Don't broadcast 'actions' function
85
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
86
+ const { actions, ...stateData } = newState;
87
+ socket.emit("host:state_sync", { roomId, data: stateData });
88
+ });
89
+
90
+ // Listen for Action Requests (RPCs) from controllers
91
+ const handleAction = (payload: AirJamActionRpcPayload) => {
92
+ const { actionName, args, controllerId } = payload;
93
+ // Execute the action on the Host (Source of Truth)
94
+ // We can optionally pass controllerId as the last arg if the action expects it
95
+ const actionFn = store.getState().actions[actionName];
96
+ if (actionFn) {
97
+ // Spread args and optionally append controllerId
98
+ actionFn(...args, controllerId);
99
+ }
100
+ };
101
+
102
+ socket.on("airjam:action_rpc", handleAction);
103
+
104
+ return () => {
105
+ unsubscribe();
106
+ socket.off("airjam:action_rpc", handleAction);
107
+ };
108
+ }
109
+
110
+ // CONTROLLER: Listen for state updates
111
+ if (role === "controller") {
112
+ const handleSync = (payload: AirJamStateSyncPayload) => {
113
+ const { data } = payload;
114
+ // Merge incoming state, but KEEP the local actions
115
+ // Use the internal _syncState action to update state (triggers Zustand subscriptions)
116
+ const currentState = store.getState();
117
+ const actions = currentState.actions as T["actions"] & {
118
+ _syncState?: (partial: Partial<T>) => void;
119
+ };
120
+
121
+ // Update store using internal action - this triggers Zustand subscriptions properly
122
+ if (actions._syncState) {
123
+ actions._syncState(data as Partial<T>);
124
+ } else {
125
+ // Fallback to setState if _syncState not available
126
+ store.setState(data as Partial<T>);
127
+ }
128
+ };
129
+
130
+ socket.on("airjam:state_sync", handleSync);
131
+ return () => socket.off("airjam:state_sync", handleSync);
132
+ }
133
+ }, [socket, role, roomId]);
134
+
135
+ // --- PROXY ACTIONS (The Magic) ---
136
+ // On the Controller, we replace actions with Network Calls
137
+ if (role === "controller" && socket && roomId) {
138
+ // We need to return a modified slice where the actions are proxied
139
+ // This handles two cases:
140
+ // 1. Selector returns full state: { actions: {...}, ... }
141
+ // 2. Selector returns just actions: { joinTeam: fn, ... }
142
+
143
+ let originalActions: T["actions"] | null = null;
144
+
145
+ // Case 1: Slice has "actions" property (full state)
146
+ if (typeof slice === "object" && slice !== null && "actions" in slice) {
147
+ originalActions = (slice as { actions: T["actions"] }).actions;
148
+ }
149
+ // Case 2: Slice IS the actions object (selector returned state.actions)
150
+ else if (typeof slice === "object" && slice !== null) {
151
+ // Check if this looks like an actions object (has function properties matching store actions)
152
+ const fullState = store.getState();
153
+ if (fullState.actions) {
154
+ const sliceKeys = Object.keys(slice);
155
+ const actionKeys = Object.keys(fullState.actions);
156
+ // If slice keys match action keys and are all functions, it's the actions object
157
+ if (
158
+ sliceKeys.length > 0 &&
159
+ sliceKeys.every(
160
+ (key) =>
161
+ typeof (slice as Record<string, unknown>)[key] === "function" &&
162
+ actionKeys.includes(key),
163
+ )
164
+ ) {
165
+ originalActions = slice as T["actions"];
166
+ }
167
+ }
168
+ }
169
+
170
+ if (originalActions) {
171
+ // Use the same type as T["actions"] for proxy actions
172
+ const proxyActions = {} as T["actions"];
173
+
174
+ Object.keys(originalActions).forEach((key) => {
175
+ // Type assertion needed because we're creating proxies dynamically
176
+ // We cast to the same type as T["actions"] to maintain type compatibility
177
+ (proxyActions as Record<string, (...args: unknown[]) => void>)[key] =
178
+ (...args: unknown[]) => {
179
+ // 1. Optimistic Update (Optional, disabled for safety by default)
180
+ // originalActions[key](...args);
181
+
182
+ // 2. Send RPC to Host (include controllerId to handle reconnections)
183
+ if (!controllerId) {
184
+ console.warn(
185
+ "[AirJamStore] Cannot send action RPC: controllerId not set",
186
+ );
187
+ return;
188
+ }
189
+ socket.emit("controller:action_rpc", {
190
+ roomId,
191
+ actionName: key,
192
+ args,
193
+ controllerId,
194
+ });
195
+ };
196
+ });
197
+
198
+ // Return proxied actions - if slice was the actions object, return proxyActions directly
199
+ // Otherwise, return slice with actions replaced
200
+ if (typeof slice === "object" && slice !== null && "actions" in slice) {
201
+ return { ...slice, actions: proxyActions } as U;
202
+ } else {
203
+ return proxyActions as U;
204
+ }
205
+ }
206
+ }
207
+
208
+ return slice;
209
+ };
210
+
211
+ return useSyncedStore;
212
+ }
@@ -0,0 +1 @@
1
+ export * from "./create-air-jam-store";