@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.
Files changed (56) hide show
  1. package/README.md +87 -0
  2. package/dist/.tsbuildinfo +1 -0
  3. package/dist/chunk-XSXI3RIS.js +72 -0
  4. package/dist/chunk-XSXI3RIS.js.map +1 -0
  5. package/dist/index.cjs +3514 -0
  6. package/dist/index.cjs.map +1 -0
  7. package/dist/index.d.cts +1529 -0
  8. package/dist/index.d.ts +1529 -0
  9. package/dist/index.js +3366 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/protocol.cjs +85 -0
  12. package/dist/protocol.cjs.map +1 -0
  13. package/dist/protocol.d.cts +242 -0
  14. package/dist/protocol.d.ts +242 -0
  15. package/dist/protocol.js +3 -0
  16. package/dist/protocol.js.map +1 -0
  17. package/package.json +81 -0
  18. package/src/AirJamClient.ts +775 -0
  19. package/src/audio/audio-manager.ts +395 -0
  20. package/src/audio/hooks.tsx +140 -0
  21. package/src/audio/index.ts +3 -0
  22. package/src/audio/volume-store.ts +77 -0
  23. package/src/components/air-jam-overlay.tsx +456 -0
  24. package/src/components/controller-shell.tsx +329 -0
  25. package/src/components/qr-scanner-dialog.tsx +373 -0
  26. package/src/components/ui/alert.tsx +66 -0
  27. package/src/components/ui/avatar.tsx +46 -0
  28. package/src/components/ui/badge.tsx +47 -0
  29. package/src/components/ui/button.tsx +61 -0
  30. package/src/components/ui/card.tsx +92 -0
  31. package/src/components/ui/slider.tsx +61 -0
  32. package/src/components/ui/tabs.tsx +64 -0
  33. package/src/components/volume-controls.tsx +93 -0
  34. package/src/constants.ts +45 -0
  35. package/src/context/air-jam-context.tsx +478 -0
  36. package/src/context/index.ts +2 -0
  37. package/src/context/socket-manager.ts +98 -0
  38. package/src/events.ts +151 -0
  39. package/src/hooks/use-air-jam-controller.ts +608 -0
  40. package/src/hooks/use-air-jam-host.ts +624 -0
  41. package/src/hooks/use-air-jam-shell.ts +343 -0
  42. package/src/hooks/use-fullscreen.ts +108 -0
  43. package/src/hooks/use-get-input.ts +97 -0
  44. package/src/hooks/use-send-signal.ts +164 -0
  45. package/src/index.ts +33 -0
  46. package/src/internal/input-manager.ts +362 -0
  47. package/src/protocol.ts +331 -0
  48. package/src/state/connection-store.ts +84 -0
  49. package/src/styles.css +128 -0
  50. package/src/types/browser.ts +42 -0
  51. package/src/utils/cn.ts +4 -0
  52. package/src/utils/ids.ts +31 -0
  53. package/src/utils/index.ts +1 -0
  54. package/src/utils/mode.ts +13 -0
  55. package/src/utils/network-ip.ts +145 -0
  56. package/src/utils/url-builder.ts +170 -0
@@ -0,0 +1,329 @@
1
+ import {
2
+ Maximize,
3
+ Minimize,
4
+ Pause,
5
+ Play,
6
+ QrCode,
7
+ RefreshCw,
8
+ } from "lucide-react";
9
+ import type { JSX } from "react";
10
+ import { useEffect, useMemo, useState, type ReactNode } from "react";
11
+ import { useStore } from "zustand";
12
+ import { useShallow } from "zustand/react/shallow";
13
+ import { useAirJamContext } from "../context/air-jam-context";
14
+ import { useFullscreen } from "../hooks/use-fullscreen";
15
+ import type { ConnectionStatus, PlayerProfile } from "../protocol";
16
+ import { cn } from "../utils/cn";
17
+ import { detectRunMode } from "../utils/mode";
18
+ import { QRScannerDialog } from "./qr-scanner-dialog";
19
+ import { Avatar, AvatarImage } from "./ui/avatar";
20
+ import { Button } from "./ui/button";
21
+ import { VolumeControls } from "./volume-controls";
22
+
23
+ type OrientationRequirement = "portrait" | "landscape" | "any";
24
+
25
+ // Generate a consistent avatar URL for a player based on their ID
26
+ const getPlayerAvatarUrl = (playerId: string): string => {
27
+ // Use DiceBear API with identicon style for GitHub-like avatars
28
+ // The seed ensures the same player ID always gets the same avatar
29
+ return `https://api.dicebear.com/9.x/adventurer-neutral/svg?seed=${encodeURIComponent(
30
+ playerId,
31
+ )}`;
32
+ };
33
+
34
+ interface ControllerShellProps {
35
+ roomId?: string | null;
36
+ connectionStatus: ConnectionStatus;
37
+ requiredOrientation?: OrientationRequirement;
38
+ children: ReactNode;
39
+ gameState?: "paused" | "playing";
40
+ onTogglePlayPause?: () => void;
41
+ onReconnect?: (roomCode: string) => void;
42
+ onRefresh?: () => void;
43
+ customActions?: ReactNode;
44
+ }
45
+
46
+ const describeStatus = (status: ConnectionStatus): string => {
47
+ switch (status) {
48
+ case "connected":
49
+ return "Connected to host";
50
+ case "connecting":
51
+ return "Connecting…";
52
+ case "reconnecting":
53
+ return "Trying to reconnect…";
54
+ case "disconnected":
55
+ return "Disconnected";
56
+ case "idle":
57
+ default:
58
+ return "Idle";
59
+ }
60
+ };
61
+
62
+ const orientationMatches = (required: OrientationRequirement): boolean => {
63
+ if (required === "any") return true;
64
+ if (typeof window === "undefined" || !window.matchMedia) return true;
65
+ const matcher = window.matchMedia(`(orientation: ${required})`);
66
+ return matcher.matches;
67
+ };
68
+
69
+ export const ControllerShell = ({
70
+ roomId,
71
+ connectionStatus,
72
+ requiredOrientation = "landscape",
73
+ children,
74
+ gameState = "paused",
75
+ onTogglePlayPause,
76
+ onReconnect,
77
+ onRefresh,
78
+ customActions,
79
+ }: ControllerShellProps): JSX.Element => {
80
+ const isChildMode = useMemo(() => detectRunMode() === "platform", []);
81
+ const [isOrientationOk, setOrientationOk] = useState(() =>
82
+ orientationMatches(requiredOrientation),
83
+ );
84
+ const [isScannerOpen, setIsScannerOpen] = useState(false);
85
+ const { isFullscreen, toggleFullscreen } = useFullscreen();
86
+
87
+ // Get store from context
88
+ const { store } = useAirJamContext();
89
+
90
+ // Get current player info from connection store
91
+ const { controllerId, players } = useStore(
92
+ store,
93
+ useShallow(
94
+ (state: { controllerId: string | null; players: PlayerProfile[] }) => ({
95
+ controllerId: state.controllerId,
96
+ players: state.players,
97
+ }),
98
+ ),
99
+ );
100
+
101
+ // Find current player profile - must exist from server (single source of truth)
102
+ const currentPlayer = useMemo(() => {
103
+ if (!controllerId) return null;
104
+ const found = players.find((p: PlayerProfile) => p.id === controllerId);
105
+
106
+ // Only warn if we are fully connected and still can't find the player
107
+ // This avoids race conditions during the initial connection handshake
108
+ if (!found && connectionStatus === "connected" && players.length > 0) {
109
+ // Optional: Debug log here if needed
110
+ }
111
+ return found || null;
112
+ }, [controllerId, players, connectionStatus]);
113
+
114
+ useEffect(() => {
115
+ if (requiredOrientation === "any") {
116
+ return;
117
+ }
118
+
119
+ const media = window.matchMedia(`(orientation: ${requiredOrientation})`);
120
+ const handleChange = (): void => setOrientationOk(media.matches);
121
+ handleChange();
122
+ media.addEventListener("change", handleChange);
123
+ return () => media.removeEventListener("change", handleChange);
124
+ }, [requiredOrientation]);
125
+
126
+ const orientationOk = requiredOrientation === "any" ? true : isOrientationOk;
127
+
128
+ const statusDotColor = useMemo(() => {
129
+ switch (connectionStatus) {
130
+ case "connected":
131
+ return "bg-green-500";
132
+ case "connecting":
133
+ case "reconnecting":
134
+ return "bg-yellow-500";
135
+ case "disconnected":
136
+ default:
137
+ return "bg-red-500";
138
+ }
139
+ }, [connectionStatus]);
140
+
141
+ // In child mode, we only render the content and maybe orientation check.
142
+ // The parent frame provides the shell (header, volume, etc).
143
+ if (isChildMode) {
144
+ return (
145
+ <div className="text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden bg-transparent select-none">
146
+ <main className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4">
147
+ {!orientationOk && (
148
+ <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">
149
+ <p className="text-card-foreground text-xl font-semibold">
150
+ Rotate your device
151
+ </p>
152
+ <p className="text-muted-foreground mt-2 text-sm">
153
+ This game is best experienced in {requiredOrientation}{" "}
154
+ orientation.
155
+ </p>
156
+ </div>
157
+ )}
158
+ <div
159
+ className={cn(
160
+ "h-full w-full select-none",
161
+ !orientationOk && "pointer-events-none opacity-30",
162
+ )}
163
+ >
164
+ {children}
165
+ </div>
166
+ </main>
167
+ </div>
168
+ );
169
+ }
170
+
171
+ return (
172
+ <div className="bg-background text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden select-none">
173
+ <header className="pointer-events-none sticky top-0 z-50 flex items-center justify-between border-b px-6 py-2">
174
+ <div className="pointer-events-auto flex items-center gap-3">
175
+ {typeof window !== "undefined" && (currentPlayer || controllerId) && (
176
+ <div className="relative" title={describeStatus(connectionStatus)}>
177
+ <Avatar
178
+ className="h-8 w-8 border-2"
179
+ style={{
180
+ borderColor: currentPlayer?.color || "hsl(var(--border))",
181
+ }}
182
+ >
183
+ <AvatarImage
184
+ src={getPlayerAvatarUrl(
185
+ currentPlayer?.id || controllerId || "",
186
+ )}
187
+ alt={currentPlayer?.label || "Player"}
188
+ />
189
+ </Avatar>
190
+ {/* Black border circle - always visible behind */}
191
+ <span
192
+ className="absolute right-0 bottom-0 h-3 w-3 rounded-full bg-black"
193
+ aria-hidden="true"
194
+ />
195
+ {/* Colored status dot - on top */}
196
+ <span
197
+ className={cn(
198
+ "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
199
+ statusDotColor,
200
+ connectionStatus === "connected" && "animate-pulse",
201
+ )}
202
+ aria-label={describeStatus(connectionStatus)}
203
+ />
204
+ </div>
205
+ )}
206
+ <div>
207
+ <p className="text-muted-foreground text-xs tracking-[0.24em] uppercase">
208
+ Room
209
+ </p>
210
+ <p className="text-foreground text-lg font-semibold">
211
+ {typeof window !== "undefined" ? (roomId ?? "N/A") : "N/A"}
212
+ </p>
213
+ </div>
214
+ </div>
215
+ <div className="pointer-events-auto flex items-center gap-3">
216
+ {customActions}
217
+ {onRefresh && roomId && (
218
+ <Button
219
+ type="button"
220
+ variant="outline"
221
+ size="icon"
222
+ onClick={onRefresh}
223
+ disabled={
224
+ connectionStatus === "connecting" ||
225
+ connectionStatus === "reconnecting"
226
+ }
227
+ aria-label="Reconnect"
228
+ title="Reconnect to room"
229
+ >
230
+ <RefreshCw
231
+ className={cn(
232
+ "h-5 w-5",
233
+ (connectionStatus === "connecting" ||
234
+ connectionStatus === "reconnecting") &&
235
+ "animate-spin",
236
+ )}
237
+ />
238
+ </Button>
239
+ )}
240
+ {onReconnect && (
241
+ <Button
242
+ type="button"
243
+ variant="outline"
244
+ size="icon"
245
+ onClick={() => setIsScannerOpen(true)}
246
+ aria-label="Scan QR code to reconnect"
247
+ title="Scan QR code to reconnect"
248
+ >
249
+ <QrCode className="h-5 w-5" />
250
+ </Button>
251
+ )}
252
+ {onTogglePlayPause && (
253
+ <Button
254
+ type="button"
255
+ variant="outline"
256
+ size="icon"
257
+ onClick={onTogglePlayPause}
258
+ aria-label={gameState === "playing" ? "Pause" : "Play"}
259
+ title={gameState === "playing" ? "Pause" : "Play"}
260
+ >
261
+ {gameState === "playing" ? (
262
+ <Pause className="h-5 w-5" />
263
+ ) : (
264
+ <Play className="h-5 w-5" />
265
+ )}
266
+ </Button>
267
+ )}
268
+ <Button
269
+ type="button"
270
+ variant="outline"
271
+ size="icon"
272
+ onClick={() => toggleFullscreen()}
273
+ aria-label={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
274
+ title={isFullscreen ? "Exit fullscreen" : "Enter fullscreen"}
275
+ >
276
+ {isFullscreen ? (
277
+ <Minimize className="h-5 w-5" />
278
+ ) : (
279
+ <Maximize className="h-5 w-5" />
280
+ )}
281
+ </Button>
282
+ </div>
283
+ </header>
284
+
285
+ {/* Volume Controls - positioned absolutely for mobile */}
286
+ <div className="pointer-events-none fixed right-4 bottom-4 z-50">
287
+ <div className="pointer-events-auto">
288
+ <VolumeControls compact={true} />
289
+ </div>
290
+ </div>
291
+
292
+ <main className="relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4">
293
+ <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">
294
+ {!orientationOk && (
295
+ <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">
296
+ <p className="text-card-foreground text-xl font-semibold">
297
+ Rotate your device
298
+ </p>
299
+ <p className="text-muted-foreground mt-2 text-sm">
300
+ This game is best experienced in {requiredOrientation}{" "}
301
+ orientation.
302
+ </p>
303
+ </div>
304
+ )}
305
+ <div
306
+ className={cn(
307
+ "h-full w-full select-none",
308
+ !orientationOk && "pointer-events-none opacity-30",
309
+ )}
310
+ >
311
+ {children}
312
+ </div>
313
+ </div>
314
+ </main>
315
+
316
+ {onReconnect && (
317
+ <QRScannerDialog
318
+ isOpen={isScannerOpen}
319
+ onClose={() => setIsScannerOpen(false)}
320
+ onScan={(roomCode) => {
321
+ onReconnect(roomCode);
322
+ setIsScannerOpen(false);
323
+ }}
324
+ currentRoomId={roomId}
325
+ />
326
+ )}
327
+ </div>
328
+ );
329
+ };
@@ -0,0 +1,373 @@
1
+ import { Html5Qrcode } from "html5-qrcode";
2
+ import type { JSX } from "react";
3
+ import { useEffect, useRef, useState } from "react";
4
+ import { roomCodeSchema } from "../protocol";
5
+ import { urlBuilder } from "../utils/url-builder";
6
+ import { Button } from "./ui/button";
7
+
8
+ interface QRScannerDialogProps {
9
+ isOpen: boolean;
10
+ onClose: () => void;
11
+ onScan: (roomCode: string) => void;
12
+ currentRoomId?: string | null;
13
+ }
14
+
15
+ /**
16
+ * Extracts room code from a scanned URL or text.
17
+ * Supports formats like:
18
+ * - http://host/joypad?room=CODE
19
+ * - https://host/joypad?room=CODE
20
+ * - Just the room code itself
21
+ */
22
+ const extractRoomCode = (text: string): string | null => {
23
+ try {
24
+ // Try to parse as URL
25
+ const url = new URL(text);
26
+ const roomParam = url.searchParams.get("room");
27
+ if (roomParam) {
28
+ const parsed = roomCodeSchema.safeParse(roomParam.toUpperCase());
29
+ if (parsed.success) {
30
+ return parsed.data;
31
+ }
32
+ }
33
+ } catch {
34
+ // Not a URL, try as direct room code
35
+ }
36
+
37
+ // Try as direct room code
38
+ const parsed = roomCodeSchema.safeParse(text.trim().toUpperCase());
39
+ if (parsed.success) {
40
+ return parsed.data;
41
+ }
42
+
43
+ return null;
44
+ };
45
+
46
+ export const QRScannerDialog = ({
47
+ isOpen,
48
+ onClose,
49
+ onScan,
50
+ currentRoomId,
51
+ }: QRScannerDialogProps): JSX.Element | null => {
52
+ const [code, setCode] = useState("");
53
+ const [isCameraAvailable, setIsCameraAvailable] = useState(false);
54
+ const [joinUrl, setJoinUrl] = useState<string>("");
55
+ const [copied, setCopied] = useState(false);
56
+ const scannerRef = useRef<Html5Qrcode | null>(null);
57
+ const inputRef = useRef<HTMLInputElement>(null);
58
+ const prevIsOpenRef = useRef(false);
59
+
60
+ // Reset state when dialog opens and build URL
61
+ useEffect(() => {
62
+ if (isOpen && !prevIsOpenRef.current) {
63
+ // Prefill with current room code if available
64
+ const initialCode = currentRoomId || "";
65
+ setTimeout(() => {
66
+ setIsCameraAvailable(false);
67
+ setCode(initialCode);
68
+ inputRef.current?.focus();
69
+ inputRef.current?.select();
70
+ }, 0);
71
+ }
72
+ prevIsOpenRef.current = isOpen;
73
+ }, [isOpen, currentRoomId]);
74
+
75
+ // Build join URL when code changes
76
+ useEffect(() => {
77
+ const buildUrl = async (): Promise<void> => {
78
+ const trimmed = code.trim().toUpperCase();
79
+ const parsed = roomCodeSchema.safeParse(trimmed);
80
+ if (parsed.success) {
81
+ try {
82
+ const url = await urlBuilder.buildControllerUrl(parsed.data);
83
+ setJoinUrl(url);
84
+ } catch {
85
+ setJoinUrl("");
86
+ }
87
+ } else {
88
+ setJoinUrl("");
89
+ }
90
+ };
91
+ buildUrl();
92
+ }, [code]);
93
+
94
+ // Clean up scanner when dialog closes
95
+ useEffect(() => {
96
+ if (!isOpen) {
97
+ setTimeout(() => {
98
+ setIsCameraAvailable(false);
99
+ }, 0);
100
+ if (scannerRef.current) {
101
+ const scanner = scannerRef.current;
102
+ scanner
103
+ .stop()
104
+ .catch(() => {
105
+ // Ignore errors
106
+ })
107
+ .finally(() => {
108
+ try {
109
+ scanner.clear();
110
+ } catch {
111
+ // Ignore errors
112
+ }
113
+ });
114
+ scannerRef.current = null;
115
+ }
116
+ }
117
+ }, [isOpen]);
118
+
119
+ // Try to start camera (silently fail if not available)
120
+ useEffect(() => {
121
+ if (!isOpen) {
122
+ return;
123
+ }
124
+
125
+ const containerId = "qr-reader";
126
+ let scanner: Html5Qrcode | null = null;
127
+ let scannerRunning = false;
128
+ let mounted = true;
129
+
130
+ const startScanning = async (): Promise<void> => {
131
+ try {
132
+ const container = document.getElementById(containerId);
133
+ if (!container) {
134
+ return;
135
+ }
136
+
137
+ const rect = container.getBoundingClientRect();
138
+ if (rect.width === 0 || rect.height === 0) {
139
+ return;
140
+ }
141
+
142
+ scanner = new Html5Qrcode(containerId);
143
+ scannerRef.current = scanner;
144
+
145
+ // Try to get available cameras
146
+ let cameraId: string | null = null;
147
+ try {
148
+ const devices = await Html5Qrcode.getCameras();
149
+ if (devices && devices.length > 0) {
150
+ const backCamera = devices.find(
151
+ (d) =>
152
+ d.label.toLowerCase().includes("back") ||
153
+ d.label.toLowerCase().includes("rear"),
154
+ );
155
+ const envCamera = devices.find((d) => {
156
+ const label = d.label.toLowerCase();
157
+ return (
158
+ label.includes("environment") || label.includes("facing back")
159
+ );
160
+ });
161
+ cameraId = (envCamera || backCamera || devices[0])?.id || null;
162
+ }
163
+ } catch {
164
+ // Ignore camera enumeration errors
165
+ }
166
+
167
+ const config = cameraId
168
+ ? { deviceId: { exact: cameraId } }
169
+ : { facingMode: "environment" };
170
+
171
+ await scanner.start(
172
+ config,
173
+ {
174
+ fps: 10,
175
+ qrbox: (viewfinderWidth, viewfinderHeight) => {
176
+ const minEdge = Math.min(viewfinderWidth, viewfinderHeight);
177
+ const qrboxSize = Math.min(250, minEdge * 0.8);
178
+ return {
179
+ width: qrboxSize,
180
+ height: qrboxSize,
181
+ };
182
+ },
183
+ aspectRatio: 1.0,
184
+ },
185
+ (decodedText) => {
186
+ if (!mounted) return;
187
+ const roomCode = extractRoomCode(decodedText);
188
+ if (roomCode) {
189
+ setCode(roomCode);
190
+ // Stop scanner after successful scan
191
+ scannerRunning = false;
192
+ scanner
193
+ ?.stop()
194
+ .catch(() => {})
195
+ .finally(() => {
196
+ if (mounted) {
197
+ setIsCameraAvailable(false);
198
+ }
199
+ });
200
+ }
201
+ },
202
+ () => {
203
+ // Ignore scanning errors
204
+ },
205
+ );
206
+ scannerRunning = true;
207
+ if (mounted) {
208
+ setIsCameraAvailable(true);
209
+ }
210
+ } catch {
211
+ // Silently fail - camera not available or permission denied
212
+ if (mounted) {
213
+ setIsCameraAvailable(false);
214
+ }
215
+ if (scanner) {
216
+ try {
217
+ scanner.clear();
218
+ } catch {
219
+ // Ignore
220
+ }
221
+ }
222
+ scannerRef.current = null;
223
+ }
224
+ };
225
+
226
+ // Small delay to ensure DOM is ready
227
+ const timeoutId = setTimeout(() => {
228
+ startScanning();
229
+ }, 200);
230
+
231
+ return () => {
232
+ mounted = false;
233
+ clearTimeout(timeoutId);
234
+ if (scanner && scannerRunning) {
235
+ scanner
236
+ .stop()
237
+ .catch(() => {})
238
+ .finally(() => {
239
+ try {
240
+ scanner?.clear();
241
+ } catch {
242
+ // Ignore
243
+ }
244
+ });
245
+ } else if (scanner) {
246
+ try {
247
+ scanner.clear();
248
+ } catch {
249
+ // Ignore
250
+ }
251
+ }
252
+ scannerRef.current = null;
253
+ };
254
+ }, [isOpen]);
255
+
256
+ const handleSubmit = (): void => {
257
+ const trimmed = code.trim().toUpperCase();
258
+ const parsed = roomCodeSchema.safeParse(trimmed);
259
+
260
+ if (parsed.success) {
261
+ onScan(parsed.data);
262
+ onClose();
263
+ }
264
+ };
265
+
266
+ const handleInputFocus = (e: React.FocusEvent<HTMLInputElement>): void => {
267
+ e.target.select();
268
+ };
269
+
270
+ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
271
+ setCode(e.target.value.toUpperCase());
272
+ setCopied(false);
273
+ };
274
+
275
+ const handleCopyUrl = async (): Promise<void> => {
276
+ if (!joinUrl) return;
277
+ try {
278
+ await navigator.clipboard.writeText(joinUrl);
279
+ setCopied(true);
280
+ setTimeout(() => setCopied(false), 2000);
281
+ } catch {
282
+ // Fallback for older browsers
283
+ const textArea = document.createElement("textarea");
284
+ textArea.value = joinUrl;
285
+ textArea.style.position = "fixed";
286
+ textArea.style.opacity = "0";
287
+ document.body.appendChild(textArea);
288
+ textArea.select();
289
+ try {
290
+ document.execCommand("copy");
291
+ setCopied(true);
292
+ setTimeout(() => setCopied(false), 2000);
293
+ } catch {
294
+ // Ignore
295
+ }
296
+ document.body.removeChild(textArea);
297
+ }
298
+ };
299
+
300
+ if (!isOpen) {
301
+ return null;
302
+ }
303
+
304
+ const isValid = code.trim().length > 0;
305
+
306
+ return (
307
+ <div className="bg-background fixed inset-0 z-50 flex flex-col items-center justify-center">
308
+ {/* Camera view (if available) */}
309
+ <div className="flex flex-1 flex-col items-center justify-center">
310
+ {isCameraAvailable && (
311
+ <div className="relative flex aspect-square w-full items-center justify-center overflow-hidden p-6">
312
+ <div
313
+ id="qr-reader"
314
+ className="h-full w-full overflow-hidden rounded-lg bg-black"
315
+ />
316
+ </div>
317
+ )}
318
+
319
+ {/* Input field */}
320
+ <div className="w-full max-w-md px-6">
321
+ <input
322
+ ref={inputRef}
323
+ type="text"
324
+ value={code}
325
+ onChange={handleInputChange}
326
+ onFocus={handleInputFocus}
327
+ onKeyDown={(e) => {
328
+ if (e.key === "Enter" && isValid) {
329
+ handleSubmit();
330
+ }
331
+ }}
332
+ placeholder="Enter room code"
333
+ className="border-border bg-background focus:ring-primary focus:border-primary w-full rounded-lg border-2 px-6 py-4 text-center font-mono text-2xl focus:ring-2 focus:outline-none"
334
+ autoComplete="off"
335
+ autoCapitalize="characters"
336
+ />
337
+ </div>
338
+ {/* URL Display */}
339
+ {joinUrl && (
340
+ <div className="mt-4 w-full max-w-md px-6 pb-2">
341
+ <button
342
+ type="button"
343
+ onClick={handleCopyUrl}
344
+ className="text-muted-foreground hover:text-foreground bg-muted/50 hover:bg-muted w-full rounded-lg px-4 py-3 text-center font-mono text-xs break-all transition-colors"
345
+ >
346
+ {copied ? "✓ Copied!" : joinUrl}
347
+ </button>
348
+ </div>
349
+ )}
350
+ </div>
351
+
352
+ {/* Buttons */}
353
+ <div className="flex w-full max-w-md gap-4 px-6 pb-6">
354
+ <Button
355
+ type="button"
356
+ variant="outline"
357
+ onClick={onClose}
358
+ className="flex-1 py-6"
359
+ >
360
+ Cancel
361
+ </Button>
362
+ <Button
363
+ type="button"
364
+ onClick={handleSubmit}
365
+ disabled={!isValid}
366
+ className="flex-1 py-6"
367
+ >
368
+ Connect
369
+ </Button>
370
+ </div>
371
+ </div>
372
+ );
373
+ };