@air-jam/sdk 0.1.0 → 0.1.2

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 (37) hide show
  1. package/dist/{chunk-XSXI3RIS.js → chunk-B5DURUWT.js} +11 -3
  2. package/dist/chunk-B5DURUWT.js.map +1 -0
  3. package/dist/index.cjs +2346 -1931
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +97 -41
  6. package/dist/index.d.ts +97 -41
  7. package/dist/index.js +2401 -2001
  8. package/dist/index.js.map +1 -1
  9. package/dist/protocol.cjs +10 -0
  10. package/dist/protocol.cjs.map +1 -1
  11. package/dist/protocol.d.cts +42 -1
  12. package/dist/protocol.d.ts +42 -1
  13. package/dist/protocol.js +1 -1
  14. package/package.json +5 -1
  15. package/src/AirJamClient.ts +1 -552
  16. package/src/audio/audio-manager.ts +12 -1
  17. package/src/audio/volume-store.ts +47 -0
  18. package/src/components/air-jam-debug.tsx +77 -0
  19. package/src/components/air-jam-overlay.tsx +243 -186
  20. package/src/components/controller-shell.tsx +174 -182
  21. package/src/components/debug-state-dialog.tsx +83 -0
  22. package/src/components/player-avatar.tsx +64 -0
  23. package/src/components/qr-scanner-dialog.tsx +2 -2
  24. package/src/components/ui/button.tsx +1 -1
  25. package/src/components/ui/dialog.tsx +122 -0
  26. package/src/constants.ts +3 -2
  27. package/src/context/air-jam-context.tsx +3 -14
  28. package/src/hooks/use-air-jam-controller.ts +1 -1
  29. package/src/hooks/use-air-jam-host.ts +94 -49
  30. package/src/hooks/use-air-jam-shell.ts +36 -0
  31. package/src/index.ts +6 -0
  32. package/src/internal/input-manager.ts +28 -14
  33. package/src/protocol.ts +55 -0
  34. package/src/store/create-air-jam-store.ts +274 -0
  35. package/src/store/index.ts +1 -0
  36. package/src/utils/url-builder.ts +3 -3
  37. package/dist/chunk-XSXI3RIS.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { roomCodeSchema, controllerInputSchema, controllerSystemSchema, controllerStateSchema, controllerJoinSchema, hostRegistrationSchema } from './chunk-XSXI3RIS.js';
2
- export { AIRJAM_PROXY_PREFIX, ErrorCode, controllerInputSchema, controllerJoinSchema, controllerLeaveSchema, controllerStateSchema, controllerSystemSchema, hostJoinAsChildSchema, hostRegisterSystemSchema, hostRegistrationSchema, roomCodeSchema, systemLaunchGameSchema } from './chunk-XSXI3RIS.js';
1
+ import { roomCodeSchema, controllerSystemSchema, controllerStateSchema, controllerInputSchema, controllerJoinSchema, hostReconnectSchema, hostCreateRoomSchema } from './chunk-B5DURUWT.js';
2
+ export { AIRJAM_PROXY_PREFIX, ErrorCode, controllerInputSchema, controllerJoinSchema, controllerLeaveSchema, controllerStateSchema, controllerSystemSchema, hostCreateRoomSchema, hostJoinAsChildSchema, hostReconnectSchema, hostRegisterSystemSchema, hostRegistrationSchema, roomCodeSchema, systemLaunchGameSchema } from './chunk-B5DURUWT.js';
3
3
  import * as React from 'react';
4
4
  import { createContext, useMemo, useEffect, useCallback, useContext, useRef, useState } from 'react';
5
5
  import { create, useStore } from 'zustand';
@@ -7,19 +7,20 @@ import { useShallow } from 'zustand/react/shallow';
7
7
  import { io } from 'socket.io-client';
8
8
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
9
9
  import { Howler, Howl } from 'howler';
10
- import { Volume2, Music, Headphones, Pause, Play, QrCode, MonitorSmartphone, Settings, RefreshCw, Minimize, Maximize } from 'lucide-react';
11
- import QRCode from 'qrcode';
10
+ import { X, Check, Copy, Bug, Volume2, Music, Headphones, Pause, Play, QrCode, MonitorSmartphone, Settings, ExternalLink, RefreshCw, Minimize, Maximize } from 'lucide-react';
11
+ import { Slot } from '@radix-ui/react-slot';
12
12
  import { cva } from 'class-variance-authority';
13
13
  import { clsx } from 'clsx';
14
14
  import { twMerge } from 'tailwind-merge';
15
- import { Slot } from '@radix-ui/react-slot';
15
+ import * as DialogPrimitive from '@radix-ui/react-dialog';
16
+ import QRCode from 'qrcode';
16
17
  import * as TabsPrimitive from '@radix-ui/react-tabs';
17
18
  import * as SliderPrimitive from '@radix-ui/react-slider';
18
19
  import { Html5Qrcode } from 'html5-qrcode';
19
20
 
20
21
  // src/constants.ts
21
22
  var DEFAULT_SERVER_PORT = 4e3;
22
- var DEFAULT_CONTROLLER_PATH = "/joypad";
23
+ var CONTROLLER_PATH = "/controller";
23
24
  var INPUT_DEBOUNCE_MS = 200;
24
25
  var TOGGLE_DEBOUNCE_MS = 300;
25
26
  var SOCKET_CONFIG = {
@@ -33,26 +34,21 @@ var SOCKET_CONFIG = {
33
34
  PING_TIMEOUT: 5e3
34
35
  };
35
36
  var DEFAULT_MAX_PLAYERS = 8;
36
-
37
- // src/internal/input-manager.ts
38
37
  var InputManager = class {
39
38
  inputBuffer = /* @__PURE__ */ new Map();
40
39
  latchState = /* @__PURE__ */ new Map();
41
40
  config;
42
- roomId;
43
- constructor(config = {}, roomId) {
41
+ constructor(config = {}) {
44
42
  this.config = config;
45
- this.roomId = roomId;
46
43
  }
47
44
  /**
48
45
  * Handles incoming input events from the socket.
49
46
  * Should be called when 'server:input' event is received.
50
47
  */
51
48
  handleInput(payload) {
52
- if (this.roomId && payload.roomId !== this.roomId) {
53
- return;
54
- }
55
49
  this.inputBuffer.set(payload.controllerId, payload.input);
50
+ const input = payload?.input;
51
+ input && (input.action === true || typeof input.vector === "object" && input.vector !== null && (Math.abs(input.vector.x ?? 0) > 0.01 || Math.abs(input.vector.y ?? 0) > 0.01));
56
52
  }
57
53
  /**
58
54
  * Gets input for a specific controller.
@@ -91,12 +87,6 @@ var InputManager = class {
91
87
  this.inputBuffer.delete(controllerId);
92
88
  this.latchState.delete(controllerId);
93
89
  }
94
- /**
95
- * Updates the room ID filter.
96
- */
97
- setRoomId(roomId) {
98
- this.roomId = roomId;
99
- }
100
90
  /**
101
91
  * Internal method to apply latching logic.
102
92
  */
@@ -320,7 +310,6 @@ var AirJamProvider = ({
320
310
  children,
321
311
  serverUrl,
322
312
  apiKey,
323
- controllerPath = DEFAULT_CONTROLLER_PATH,
324
313
  maxPlayers = DEFAULT_MAX_PLAYERS,
325
314
  publicHost,
326
315
  input
@@ -329,11 +318,10 @@ var AirJamProvider = ({
329
318
  () => ({
330
319
  serverUrl: serverUrl ?? getEnvServerUrl(),
331
320
  apiKey: apiKey ?? getEnvApiKey(),
332
- controllerPath,
333
321
  maxPlayers,
334
322
  publicHost
335
323
  }),
336
- [serverUrl, apiKey, controllerPath, maxPlayers, publicHost]
324
+ [serverUrl, apiKey, maxPlayers, publicHost]
337
325
  );
338
326
  const inputManager = useMemo(() => {
339
327
  if (!input) {
@@ -450,6 +438,22 @@ var useVolumeStore = create((set, get) => ({
450
438
  return masterVolume * categoryVolume;
451
439
  }
452
440
  }));
441
+ var setupParentSettingsListener = () => {
442
+ if (typeof window === "undefined") return;
443
+ const isInIframe = window.parent !== window;
444
+ if (!isInIframe) return;
445
+ const handleMessage = (event) => {
446
+ if (event.source !== window.parent) return;
447
+ if (event.data?.type !== "AIRJAM_SETTINGS_SYNC") return;
448
+ const { masterVolume, musicVolume, sfxVolume } = event.data.payload;
449
+ const store = useVolumeStore.getState();
450
+ if (typeof masterVolume === "number") store.setMasterVolume(masterVolume);
451
+ if (typeof musicVolume === "number") store.setMusicVolume(musicVolume);
452
+ if (typeof sfxVolume === "number") store.setSfxVolume(sfxVolume);
453
+ };
454
+ window.addEventListener("message", handleMessage);
455
+ };
456
+ setupParentSettingsListener();
453
457
 
454
458
  // src/audio/audio-manager.ts
455
459
  function detectSoundCategory(config) {
@@ -518,7 +522,12 @@ var AudioManager = class {
518
522
  if (roomId) this.roomId = roomId;
519
523
  }
520
524
  /**
521
- * Initialize audio context (must be called on user interaction)
525
+ * Resume audio context if suspended. This is automatically called by play(),
526
+ * so you typically don't need to call this manually.
527
+ *
528
+ * Note: Due to browser autoplay policies, audio context starts suspended
529
+ * and can only be resumed in response to a user gesture. The useAudio hook
530
+ * handles this automatically, and play() also calls init() internally.
522
531
  */
523
532
  init() {
524
533
  if (Howler.ctx && Howler.ctx.state === "suspended") {
@@ -562,6 +571,7 @@ var AudioManager = class {
562
571
  sprite,
563
572
  pitch
564
573
  } = options || {};
574
+ this.init();
565
575
  if (remote) {
566
576
  this.playRemote(id, target, volume, loop);
567
577
  return null;
@@ -619,6 +629,7 @@ var AudioManager = class {
619
629
  * Play a sound at a specific 3D position
620
630
  */
621
631
  playSpatial(id, pos, sprite) {
632
+ this.init();
622
633
  const soundId = this.playLocal(id, void 0, void 0, sprite);
623
634
  if (soundId !== null) {
624
635
  const sound = this.sounds.get(id);
@@ -782,116 +793,6 @@ var useAudioManager = (manifest) => {
782
793
  return managerRef.current;
783
794
  };
784
795
  var cn = (...inputs) => twMerge(clsx(inputs));
785
- var alertVariants = cva(
786
- "relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
787
- {
788
- variants: {
789
- variant: {
790
- default: "bg-card text-card-foreground",
791
- destructive: "text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"
792
- }
793
- },
794
- defaultVariants: {
795
- variant: "default"
796
- }
797
- }
798
- );
799
- function Alert({
800
- className,
801
- variant,
802
- ...props
803
- }) {
804
- return /* @__PURE__ */ jsx(
805
- "div",
806
- {
807
- "data-slot": "alert",
808
- role: "alert",
809
- className: cn(alertVariants({ variant }), className),
810
- ...props
811
- }
812
- );
813
- }
814
- function AlertDescription({
815
- className,
816
- ...props
817
- }) {
818
- return /* @__PURE__ */ jsx(
819
- "div",
820
- {
821
- "data-slot": "alert-description",
822
- className: cn(
823
- "text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
824
- className
825
- ),
826
- ...props
827
- }
828
- );
829
- }
830
- var Avatar = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
831
- "div",
832
- {
833
- ref,
834
- className: cn(
835
- "relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",
836
- className
837
- ),
838
- ...props
839
- }
840
- ));
841
- Avatar.displayName = "Avatar";
842
- var AvatarImage = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
843
- "img",
844
- {
845
- ref,
846
- className: cn("aspect-square h-full w-full", className),
847
- ...props
848
- }
849
- ));
850
- AvatarImage.displayName = "AvatarImage";
851
- var AvatarFallback = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
852
- "div",
853
- {
854
- ref,
855
- className: cn(
856
- "bg-muted flex h-full w-full items-center justify-center rounded-full",
857
- className
858
- ),
859
- ...props
860
- }
861
- ));
862
- AvatarFallback.displayName = "AvatarFallback";
863
- var badgeVariants = cva(
864
- "inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
865
- {
866
- variants: {
867
- variant: {
868
- default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
869
- secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
870
- destructive: "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
871
- outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"
872
- }
873
- },
874
- defaultVariants: {
875
- variant: "default"
876
- }
877
- }
878
- );
879
- function Badge({
880
- className,
881
- variant,
882
- asChild = false,
883
- ...props
884
- }) {
885
- const Comp = asChild ? Slot : "span";
886
- return /* @__PURE__ */ jsx(
887
- Comp,
888
- {
889
- "data-slot": "badge",
890
- className: cn(badgeVariants({ variant }), className),
891
- ...props
892
- }
893
- );
894
- }
895
796
  var buttonVariants = cva(
896
797
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all cursor-pointer disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
897
798
  {
@@ -901,7 +802,7 @@ var buttonVariants = cva(
901
802
  destructive: "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
902
803
  outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
903
804
  secondary: "bg-secondary text-secondary-foreground hover:bg-secondary/80",
904
- ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
805
+ ghost: "text-foreground hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
905
806
  link: "text-primary underline-offset-4 hover:underline"
906
807
  },
907
808
  size: {
@@ -936,757 +837,270 @@ function Button({
936
837
  }
937
838
  );
938
839
  }
939
- function Card({ className, ...props }) {
940
- return /* @__PURE__ */ jsx(
941
- "div",
942
- {
943
- "data-slot": "card",
944
- className: cn(
945
- "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
946
- className
947
- ),
948
- ...props
949
- }
950
- );
951
- }
952
- function CardHeader({ className, ...props }) {
953
- return /* @__PURE__ */ jsx(
954
- "div",
840
+ var Dialog = DialogPrimitive.Root;
841
+ var DialogPortal = DialogPrimitive.Portal;
842
+ var DialogOverlay = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
843
+ DialogPrimitive.Overlay,
844
+ {
845
+ ref,
846
+ className: cn(
847
+ "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",
848
+ className
849
+ ),
850
+ ...props
851
+ }
852
+ ));
853
+ DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
854
+ var DialogContent = React.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ jsx(DialogPortal, { children: /* @__PURE__ */ jsxs("div", { className: "dark", children: [
855
+ /* @__PURE__ */ jsx(DialogOverlay, {}),
856
+ /* @__PURE__ */ jsxs(
857
+ DialogPrimitive.Content,
955
858
  {
956
- "data-slot": "card-header",
859
+ ref,
957
860
  className: cn(
958
- "@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
861
+ "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",
959
862
  className
960
863
  ),
961
- ...props
962
- }
963
- );
964
- }
965
- function CardTitle({ className, ...props }) {
966
- return /* @__PURE__ */ jsx(
967
- "div",
968
- {
969
- "data-slot": "card-title",
970
- className: cn("leading-none font-semibold", className),
971
- ...props
972
- }
973
- );
974
- }
975
- function CardDescription({ className, ...props }) {
976
- return /* @__PURE__ */ jsx(
977
- "div",
978
- {
979
- "data-slot": "card-description",
980
- className: cn("text-muted-foreground text-sm", className),
981
- ...props
982
- }
983
- );
984
- }
985
- function CardContent({ className, ...props }) {
986
- return /* @__PURE__ */ jsx(
987
- "div",
988
- {
989
- "data-slot": "card-content",
990
- className: cn("px-6", className),
991
- ...props
992
- }
993
- );
994
- }
995
- function Tabs({
996
- className,
997
- ...props
998
- }) {
999
- return /* @__PURE__ */ jsx(
1000
- TabsPrimitive.Root,
1001
- {
1002
- "data-slot": "tabs",
1003
- className: cn("flex flex-col gap-2", className),
1004
- ...props
864
+ ...props,
865
+ children: [
866
+ children,
867
+ /* @__PURE__ */ jsxs(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", children: [
868
+ /* @__PURE__ */ jsx(X, { className: "h-4 w-4" }),
869
+ /* @__PURE__ */ jsx("span", { className: "sr-only", children: "Close" })
870
+ ] })
871
+ ]
1005
872
  }
1006
- );
1007
- }
1008
- function TabsList({
873
+ )
874
+ ] }) }));
875
+ DialogContent.displayName = DialogPrimitive.Content.displayName;
876
+ var DialogHeader = ({
1009
877
  className,
1010
878
  ...props
1011
- }) {
1012
- return /* @__PURE__ */ jsx(
1013
- TabsPrimitive.List,
1014
- {
1015
- "data-slot": "tabs-list",
1016
- className: cn(
1017
- "bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
1018
- className
1019
- ),
1020
- ...props
879
+ }) => /* @__PURE__ */ jsx(
880
+ "div",
881
+ {
882
+ className: cn(
883
+ "flex flex-col space-y-1.5 text-center sm:text-left",
884
+ className
885
+ ),
886
+ ...props
887
+ }
888
+ );
889
+ DialogHeader.displayName = "DialogHeader";
890
+ var DialogTitle = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
891
+ DialogPrimitive.Title,
892
+ {
893
+ ref,
894
+ className: cn(
895
+ "text-lg leading-none font-semibold tracking-tight",
896
+ className
897
+ ),
898
+ ...props
899
+ }
900
+ ));
901
+ DialogTitle.displayName = DialogPrimitive.Title.displayName;
902
+ var DialogDescription = React.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(
903
+ DialogPrimitive.Description,
904
+ {
905
+ ref,
906
+ className: cn("text-muted-foreground text-sm", className),
907
+ ...props
908
+ }
909
+ ));
910
+ DialogDescription.displayName = DialogPrimitive.Description.displayName;
911
+ var DebugStateDialog = ({
912
+ isOpen,
913
+ onClose,
914
+ getState,
915
+ title = "Debug State",
916
+ updateInterval = 100
917
+ }) => {
918
+ const [state, setState] = useState(() => getState());
919
+ const [copied, setCopied] = useState(false);
920
+ useEffect(() => {
921
+ if (!isOpen) return;
922
+ const interval = setInterval(() => {
923
+ setState(getState());
924
+ }, updateInterval);
925
+ const timeoutId = setTimeout(() => {
926
+ setState(getState());
927
+ }, 0);
928
+ return () => {
929
+ clearInterval(interval);
930
+ clearTimeout(timeoutId);
931
+ };
932
+ }, [isOpen, getState, updateInterval]);
933
+ const jsonString = JSON.stringify(state, null, 2);
934
+ const handleCopy = async () => {
935
+ try {
936
+ await navigator.clipboard.writeText(jsonString);
937
+ setCopied(true);
938
+ setTimeout(() => setCopied(false), 2e3);
939
+ } catch (error) {
940
+ console.error("Failed to copy:", error);
1021
941
  }
1022
- );
1023
- }
1024
- function TabsTrigger({
1025
- className,
1026
- ...props
1027
- }) {
1028
- return /* @__PURE__ */ jsx(
1029
- TabsPrimitive.Trigger,
1030
- {
1031
- "data-slot": "tabs-trigger",
1032
- className: cn(
1033
- "data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
1034
- className
942
+ };
943
+ return /* @__PURE__ */ jsx(Dialog, { open: isOpen, onOpenChange: onClose, children: /* @__PURE__ */ jsxs(DialogContent, { className: "dark max-h-[90vh] max-w-2xl flex-col", children: [
944
+ /* @__PURE__ */ jsx(DialogHeader, { children: /* @__PURE__ */ jsx(DialogTitle, { className: "text-foreground", children: title }) }),
945
+ /* @__PURE__ */ jsxs("div", { className: "relative flex-1 overflow-auto pt-4", children: [
946
+ /* @__PURE__ */ jsx(
947
+ Button,
948
+ {
949
+ variant: "ghost",
950
+ size: "icon-sm",
951
+ onClick: handleCopy,
952
+ className: "text-muted-foreground hover:text-foreground absolute top-6 right-2 z-10",
953
+ "aria-label": "Copy state",
954
+ children: copied ? /* @__PURE__ */ jsx(Check, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4" })
955
+ }
1035
956
  ),
1036
- ...props
1037
- }
1038
- );
1039
- }
1040
- function TabsContent({
1041
- className,
1042
- ...props
1043
- }) {
1044
- return /* @__PURE__ */ jsx(
1045
- TabsPrimitive.Content,
1046
- {
1047
- "data-slot": "tabs-content",
1048
- className: cn("flex-1 outline-none", className),
1049
- ...props
1050
- }
1051
- );
1052
- }
1053
- function Slider({
1054
- className,
1055
- defaultValue,
1056
- value,
1057
- min = 0,
1058
- max = 100,
1059
- ...props
1060
- }) {
1061
- const _values = React.useMemo(
1062
- () => Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min, max],
1063
- [value, defaultValue, min, max]
1064
- );
1065
- return /* @__PURE__ */ jsxs(
1066
- SliderPrimitive.Root,
1067
- {
1068
- "data-slot": "slider",
1069
- defaultValue,
1070
- value,
1071
- min,
1072
- max,
1073
- className: cn(
1074
- "relative flex w-full cursor-pointer touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
1075
- className
1076
- ),
1077
- ...props,
1078
- children: [
1079
- /* @__PURE__ */ jsx(
1080
- SliderPrimitive.Track,
1081
- {
1082
- "data-slot": "slider-track",
1083
- className: cn(
1084
- "bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
1085
- ),
1086
- children: /* @__PURE__ */ jsx(
1087
- SliderPrimitive.Range,
1088
- {
1089
- "data-slot": "slider-range",
1090
- className: cn(
1091
- "bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
1092
- )
1093
- }
1094
- )
1095
- }
1096
- ),
1097
- Array.from({ length: _values.length }, (_, index) => /* @__PURE__ */ jsx(
1098
- SliderPrimitive.Thumb,
1099
- {
1100
- "data-slot": "slider-thumb",
1101
- className: "border-primary ring-ring/50 block size-4 shrink-0 cursor-pointer rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
1102
- },
1103
- index
1104
- ))
1105
- ]
1106
- }
1107
- );
1108
- }
1109
- function VolumeControls({ className, compact }) {
1110
- const {
1111
- masterVolume,
1112
- musicVolume,
1113
- sfxVolume,
1114
- setMasterVolume,
1115
- setMusicVolume,
1116
- setSfxVolume
1117
- } = useVolumeStore();
1118
- return /* @__PURE__ */ jsxs("div", { className: cn("flex flex-col gap-3", compact && "gap-1", className), children: [
1119
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
1120
- /* @__PURE__ */ jsx(Volume2, { className: "text-muted-foreground h-4 w-4" }),
1121
- /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Volume" })
1122
- ] }),
1123
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1124
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1125
- /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "Master" }),
1126
- /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1127
- Math.round(masterVolume * 100),
1128
- "%"
1129
- ] })
1130
- ] }),
1131
- /* @__PURE__ */ jsx(
1132
- Slider,
1133
- {
1134
- value: [masterVolume * 100],
1135
- onValueChange: (values) => setMasterVolume(values[0] / 100),
1136
- min: 0,
1137
- max: 100,
1138
- step: 1,
1139
- className: "w-full",
1140
- "aria-label": "Master volume"
1141
- }
1142
- )
1143
- ] }),
1144
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1145
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1146
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
1147
- /* @__PURE__ */ jsx(Music, { className: "text-muted-foreground h-3 w-3" }),
1148
- /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "Music" })
1149
- ] }),
1150
- /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1151
- Math.round(musicVolume * 100),
1152
- "%"
1153
- ] })
1154
- ] }),
1155
- /* @__PURE__ */ jsx(
1156
- Slider,
1157
- {
1158
- value: [musicVolume * 100],
1159
- onValueChange: (values) => setMusicVolume(values[0] / 100),
1160
- min: 0,
1161
- max: 100,
1162
- step: 1,
1163
- className: "w-full",
1164
- "aria-label": "Music volume"
1165
- }
1166
- )
1167
- ] }),
1168
- /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1169
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1170
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
1171
- /* @__PURE__ */ jsx(Headphones, { className: "text-muted-foreground h-3 w-3" }),
1172
- /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "SFX" })
1173
- ] }),
1174
- /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1175
- Math.round(sfxVolume * 100),
1176
- "%"
1177
- ] })
1178
- ] }),
1179
- /* @__PURE__ */ jsx(
1180
- Slider,
1181
- {
1182
- value: [sfxVolume * 100],
1183
- onValueChange: (values) => setSfxVolume(values[0] / 100),
1184
- min: 0,
1185
- max: 100,
1186
- step: 1,
1187
- className: "w-full",
1188
- "aria-label": "SFX volume"
1189
- }
1190
- )
957
+ /* @__PURE__ */ jsx("pre", { className: "bg-muted text-muted-foreground overflow-auto rounded-lg border p-4 font-mono text-xs", children: jsonString })
1191
958
  ] })
1192
- ] });
1193
- }
1194
- var statusCopy = {
1195
- idle: "Idle",
1196
- connecting: "Waiting for server\u2026",
1197
- connected: "Ready for controllers",
1198
- disconnected: "Disconnected",
1199
- reconnecting: "Reconnecting\u2026"
1200
- };
1201
- var getPlayerAvatarUrl = (playerId) => {
1202
- return `https://api.dicebear.com/9.x/adventurer-neutral/svg?seed=${encodeURIComponent(
1203
- playerId
1204
- )}`;
959
+ ] }) });
1205
960
  };
1206
- var AirJamOverlay = ({
1207
- roomId,
1208
- joinUrl,
1209
- connectionStatus,
1210
- players,
1211
- lastError,
1212
- gameState,
1213
- onTogglePlayPause,
1214
- isChildMode = false
961
+ var AirJamDebug = ({
962
+ state,
963
+ title = "Debug State",
964
+ updateInterval = 100,
965
+ className
1215
966
  }) => {
1216
- const [qrUrl, setQrUrl] = useState(null);
1217
- const [qrError, setQrError] = useState(null);
967
+ const [isOpen, setIsOpen] = useState(false);
968
+ const [currentState, setCurrentState] = useState(state);
1218
969
  useEffect(() => {
1219
- if (isChildMode) return;
1220
- let mounted = true;
1221
- QRCode.toDataURL(joinUrl, {
1222
- margin: 1,
1223
- color: {
1224
- dark: "#0f172a",
1225
- light: "#ffffff"
1226
- },
1227
- width: 320
1228
- }).then((value) => {
1229
- if (mounted) {
1230
- setQrUrl(value);
1231
- setQrError(null);
970
+ if (!isOpen) return;
971
+ const interval = setInterval(() => {
972
+ setCurrentState(state);
973
+ }, updateInterval);
974
+ setCurrentState(state);
975
+ return () => clearInterval(interval);
976
+ }, [isOpen, state, updateInterval]);
977
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
978
+ /* @__PURE__ */ jsx(
979
+ Button,
980
+ {
981
+ type: "button",
982
+ variant: "ghost",
983
+ size: "icon",
984
+ onClick: () => setIsOpen(true),
985
+ "aria-label": "Debug state",
986
+ title,
987
+ className: `text-white hover:bg-white/20 hover:text-white ${className || ""}`,
988
+ children: /* @__PURE__ */ jsx(Bug, { className: "h-4 w-4" })
1232
989
  }
1233
- }).catch((err) => {
1234
- if (mounted) {
1235
- setQrError(err.message);
990
+ ),
991
+ /* @__PURE__ */ jsx(
992
+ DebugStateDialog,
993
+ {
994
+ isOpen,
995
+ onClose: () => setIsOpen(false),
996
+ getState: () => currentState,
997
+ title,
998
+ updateInterval
1236
999
  }
1000
+ )
1001
+ ] });
1002
+ };
1003
+
1004
+ // src/utils/mode.ts
1005
+ var detectRunMode = () => {
1006
+ if (typeof window === "undefined") {
1007
+ return "standalone";
1008
+ }
1009
+ try {
1010
+ return window.self !== window.top ? "platform" : "standalone";
1011
+ } catch {
1012
+ return "platform";
1013
+ }
1014
+ };
1015
+
1016
+ // src/utils/network-ip.ts
1017
+ var isVirtualNetwork = (ip) => {
1018
+ if (ip.startsWith("192.168.64.") || ip.startsWith("192.168.65.")) {
1019
+ return true;
1020
+ }
1021
+ if (ip.startsWith("172.17.")) {
1022
+ return true;
1023
+ }
1024
+ if (ip.startsWith("172.18.") || ip.startsWith("172.19.")) {
1025
+ return true;
1026
+ }
1027
+ if (ip.startsWith("169.254.")) {
1028
+ return true;
1029
+ }
1030
+ return false;
1031
+ };
1032
+ var scoreIp = (ip) => {
1033
+ if (ip.startsWith("192.168.")) {
1034
+ const parts = ip.split(".");
1035
+ const thirdOctet = parseInt(parts[2] || "0", 10);
1036
+ if (thirdOctet < 64) {
1037
+ return 100 - thirdOctet;
1038
+ }
1039
+ return 10;
1040
+ }
1041
+ if (ip.startsWith("10.")) {
1042
+ return 50;
1043
+ }
1044
+ if (/^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip)) {
1045
+ return 30;
1046
+ }
1047
+ return 0;
1048
+ };
1049
+ var getLocalNetworkIp = () => {
1050
+ return new Promise((resolve) => {
1051
+ if (typeof window === "undefined" || typeof RTCPeerConnection === "undefined") {
1052
+ resolve(null);
1053
+ return;
1054
+ }
1055
+ const pc = new RTCPeerConnection({
1056
+ iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
1237
1057
  });
1238
- return () => {
1239
- mounted = false;
1058
+ const candidates = [];
1059
+ let candidateGatheringComplete = false;
1060
+ const resolveOnce = (ip) => {
1061
+ pc.close();
1062
+ resolve(ip);
1240
1063
  };
1241
- }, [joinUrl, isChildMode]);
1242
- const connectionVariant = useMemo(() => {
1243
- switch (connectionStatus) {
1244
- case "connected":
1245
- return "default";
1246
- case "connecting":
1247
- case "reconnecting":
1248
- return "secondary";
1249
- default:
1250
- return "destructive";
1251
- }
1252
- }, [connectionStatus]);
1253
- if (isChildMode) return null;
1254
- return /* @__PURE__ */ jsxs(Fragment, { children: [
1255
- !isChildMode && /* @__PURE__ */ jsx("div", { className: "pointer-events-none absolute inset-x-0 top-0 z-99999", children: /* @__PURE__ */ jsx("div", { className: "mx-auto w-full", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-4 py-2", children: [
1256
- /* @__PURE__ */ jsx("div", { className: "flex items-center gap-3", children: /* @__PURE__ */ jsxs("div", { children: [
1257
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs tracking-[0.18em] uppercase", children: "Room" }),
1258
- /* @__PURE__ */ jsx("p", { className: "text-foreground text-lg font-semibold", children: roomId })
1259
- ] }) }),
1260
- /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
1261
- players.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-center -space-x-2", children: [
1262
- players.slice(0, 4).map((player) => /* @__PURE__ */ jsx(
1263
- Avatar,
1264
- {
1265
- className: "h-8 w-8 border-2",
1266
- style: {
1267
- borderColor: player.color || "hsl(var(--border))"
1268
- },
1269
- children: /* @__PURE__ */ jsx(
1270
- AvatarImage,
1271
- {
1272
- src: getPlayerAvatarUrl(player.id),
1273
- alt: player.label
1274
- }
1275
- )
1276
- },
1277
- player.id
1278
- )),
1279
- players.length > 4 && /* @__PURE__ */ jsxs("div", { className: "border-background bg-muted flex h-8 w-8 items-center justify-center rounded-full border-2 text-xs font-medium", children: [
1280
- "+",
1281
- players.length - 4
1282
- ] })
1283
- ] }),
1284
- onTogglePlayPause && /* @__PURE__ */ jsx(
1285
- Button,
1286
- {
1287
- type: "button",
1288
- variant: "ghost",
1289
- size: "icon",
1290
- onClick: onTogglePlayPause,
1291
- "aria-label": gameState === "playing" ? "Pause" : "Play",
1292
- className: "h-8 w-8",
1293
- children: gameState === "playing" ? /* @__PURE__ */ jsx(Pause, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Play, { className: "h-4 w-4" })
1294
- }
1295
- )
1296
- ] })
1297
- ] }) }) }),
1298
- gameState === "paused" && /* @__PURE__ */ jsx("div", { className: "pointer-events-none fixed inset-0 z-99998 flex items-center justify-center p-4", children: /* @__PURE__ */ jsx("div", { className: "pointer-events-auto w-full max-w-2xl", children: /* @__PURE__ */ jsx(Card, { className: "bg-card/20 flex h-[80vh] flex-col overflow-hidden border py-0 shadow-lg backdrop-blur-sm", children: /* @__PURE__ */ jsxs(
1299
- Tabs,
1300
- {
1301
- defaultValue: isChildMode ? "settings" : "room-code",
1302
- className: "flex h-full w-full flex-col gap-0",
1303
- children: [
1304
- /* @__PURE__ */ jsxs(TabsList, { className: "border-border grid w-full shrink-0 grid-cols-2 rounded-none border-b bg-transparent p-0", children: [
1305
- !isChildMode && /* @__PURE__ */ jsxs(
1306
- TabsTrigger,
1307
- {
1308
- value: "room-code",
1309
- className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
1310
- children: [
1311
- /* @__PURE__ */ jsx(QrCode, { className: "h-4 w-4" }),
1312
- "Room Code"
1313
- ]
1314
- }
1315
- ),
1316
- isChildMode && /* @__PURE__ */ jsxs(
1317
- TabsTrigger,
1318
- {
1319
- value: "info",
1320
- className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
1321
- children: [
1322
- /* @__PURE__ */ jsx(MonitorSmartphone, { className: "h-4 w-4" }),
1323
- "Platform"
1324
- ]
1325
- }
1326
- ),
1327
- /* @__PURE__ */ jsxs(
1328
- TabsTrigger,
1329
- {
1330
- value: "settings",
1331
- className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
1332
- children: [
1333
- /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4" }),
1334
- "Settings"
1335
- ]
1336
- }
1337
- )
1338
- ] }),
1339
- !isChildMode && /* @__PURE__ */ jsx(
1340
- TabsContent,
1341
- {
1342
- value: "room-code",
1343
- className: "mt-0 min-h-0 flex-1 overflow-y-auto",
1344
- children: /* @__PURE__ */ jsxs("div", { className: "space-y-6 pb-6", children: [
1345
- /* @__PURE__ */ jsxs(CardHeader, { className: "pt-6 text-center", children: [
1346
- /* @__PURE__ */ jsx(CardTitle, { className: "text-4xl font-bold tracking-wider", children: roomId }),
1347
- /* @__PURE__ */ jsx(
1348
- Badge,
1349
- {
1350
- variant: connectionVariant,
1351
- className: "mx-auto mt-3",
1352
- children: statusCopy[connectionStatus]
1353
- }
1354
- )
1355
- ] }),
1356
- /* @__PURE__ */ jsx(CardContent, { className: "space-y-6", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center space-y-4", children: [
1357
- /* @__PURE__ */ jsx(CardDescription, { className: "text-xs tracking-[0.18em] uppercase", children: "Join URL" }),
1358
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-center font-mono text-xs break-all", children: joinUrl }),
1359
- /* @__PURE__ */ jsx("div", { className: "border-border bg-card w-48 overflow-hidden rounded-lg border-2 shadow-md", children: qrUrl ? /* @__PURE__ */ jsx(
1360
- "img",
1361
- {
1362
- src: qrUrl,
1363
- alt: `Join room ${roomId}`,
1364
- className: "w-full rounded bg-white"
1365
- }
1366
- ) : /* @__PURE__ */ jsx("div", { className: "text-muted-foreground flex h-48 items-center justify-center text-sm", children: qrError ? `QR failed: ${qrError}` : "Generating QR code\u2026" }) }),
1367
- /* @__PURE__ */ jsx("div", { className: "w-full", children: players.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-muted-foreground py-4 text-center text-sm", children: "Waiting for controllers to join\u2026" }) : /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
1368
- /* @__PURE__ */ jsxs("p", { className: "text-foreground text-center text-sm font-medium", children: [
1369
- "Connected Players (",
1370
- players.length,
1371
- ")"
1372
- ] }),
1373
- /* @__PURE__ */ jsx("ul", { className: "flex flex-wrap items-center justify-center gap-4", children: players.map((player) => /* @__PURE__ */ jsxs(
1374
- "li",
1375
- {
1376
- className: "flex flex-col items-center gap-2",
1377
- children: [
1378
- /* @__PURE__ */ jsx(
1379
- "img",
1380
- {
1381
- src: getPlayerAvatarUrl(player.id),
1382
- alt: player.label,
1383
- className: "bg-secondary/30 h-16 w-16 rounded-full border-4 shadow-md",
1384
- style: {
1385
- borderColor: player.color || "hsl(var(--border))"
1386
- }
1387
- }
1388
- ),
1389
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-0.5", children: [
1390
- /* @__PURE__ */ jsx("span", { className: "text-card-foreground max-w-[100px] truncate text-center text-sm font-medium", children: player.label }),
1391
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground font-mono text-xs", children: player.id.slice(0, 8) })
1392
- ] })
1393
- ]
1394
- },
1395
- player.id
1396
- )) })
1397
- ] }) }),
1398
- lastError && /* @__PURE__ */ jsx(Alert, { variant: "destructive", className: "w-full", children: /* @__PURE__ */ jsx(AlertDescription, { children: lastError }) }),
1399
- onTogglePlayPause && /* @__PURE__ */ jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxs(
1400
- Button,
1401
- {
1402
- type: "button",
1403
- onClick: onTogglePlayPause,
1404
- size: "lg",
1405
- children: [
1406
- /* @__PURE__ */ jsx(Play, { className: "mr-2 h-5 w-5" }),
1407
- "Start Game"
1408
- ]
1409
- }
1410
- ) })
1411
- ] }) })
1412
- ] })
1413
- }
1414
- ),
1415
- isChildMode && /* @__PURE__ */ jsx(
1416
- TabsContent,
1417
- {
1418
- value: "info",
1419
- className: "mt-0 min-h-0 flex-1 overflow-y-auto",
1420
- children: /* @__PURE__ */ jsxs("div", { className: "space-y-6 pb-6", children: [
1421
- /* @__PURE__ */ jsxs(CardHeader, { className: "pt-6 text-center", children: [
1422
- /* @__PURE__ */ jsx(CardTitle, { className: "text-2xl font-bold tracking-wider", children: "Connected to Platform" }),
1423
- /* @__PURE__ */ jsx(CardDescription, { className: "mt-2", children: "This game is running inside the Air Jam Platform." })
1424
- ] }),
1425
- /* @__PURE__ */ jsx(CardContent, { className: "space-y-6", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center space-y-4", children: [
1426
- /* @__PURE__ */ jsx("div", { className: "w-full", children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
1427
- /* @__PURE__ */ jsxs("p", { className: "text-foreground text-center text-sm font-medium", children: [
1428
- "Connected Players (",
1429
- players.length,
1430
- ")"
1431
- ] }),
1432
- /* @__PURE__ */ jsx("ul", { className: "flex flex-wrap items-center justify-center gap-4", children: players.map((player) => /* @__PURE__ */ jsxs(
1433
- "li",
1434
- {
1435
- className: "flex flex-col items-center gap-2",
1436
- children: [
1437
- /* @__PURE__ */ jsx(
1438
- "img",
1439
- {
1440
- src: getPlayerAvatarUrl(player.id),
1441
- alt: player.label,
1442
- className: "bg-secondary/30 h-16 w-16 rounded-full border-4 shadow-md",
1443
- style: {
1444
- borderColor: player.color || "hsl(var(--border))"
1445
- }
1446
- }
1447
- ),
1448
- /* @__PURE__ */ jsx("div", { className: "flex flex-col items-center gap-0.5", children: /* @__PURE__ */ jsx("span", { className: "text-card-foreground max-w-[100px] truncate text-center text-sm font-medium", children: player.label }) })
1449
- ]
1450
- },
1451
- player.id
1452
- )) })
1453
- ] }) }),
1454
- onTogglePlayPause && /* @__PURE__ */ jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxs(
1455
- Button,
1456
- {
1457
- type: "button",
1458
- onClick: onTogglePlayPause,
1459
- size: "lg",
1460
- children: [
1461
- /* @__PURE__ */ jsx(Play, { className: "mr-2 h-5 w-5" }),
1462
- "Resume Game"
1463
- ]
1464
- }
1465
- ) })
1466
- ] }) })
1467
- ] })
1468
- }
1469
- ),
1470
- /* @__PURE__ */ jsx(
1471
- TabsContent,
1472
- {
1473
- value: "settings",
1474
- className: "mt-0 min-h-0 flex-1 overflow-y-auto",
1475
- children: /* @__PURE__ */ jsx(CardContent, { className: "pt-6 pb-6", children: /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
1476
- /* @__PURE__ */ jsx("div", { className: "space-y-4", children: /* @__PURE__ */ jsx(VolumeControls, {}) }),
1477
- /* @__PURE__ */ jsxs("div", { className: "space-y-4 border-t pt-4", children: [
1478
- /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: "Connection" }),
1479
- /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
1480
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1481
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: "Status" }),
1482
- /* @__PURE__ */ jsx(Badge, { variant: connectionVariant, children: statusCopy[connectionStatus] })
1483
- ] }),
1484
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1485
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: "Room ID" }),
1486
- /* @__PURE__ */ jsx("span", { className: "font-mono text-sm", children: roomId })
1487
- ] }),
1488
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1489
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: "Players" }),
1490
- /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: players.length })
1491
- ] })
1492
- ] })
1493
- ] }),
1494
- /* @__PURE__ */ jsxs("div", { className: "space-y-4 border-t pt-4", children: [
1495
- /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: "Display" }),
1496
- /* @__PURE__ */ jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1497
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: "Game State" }),
1498
- /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "capitalize", children: gameState })
1499
- ] }) })
1500
- ] })
1501
- ] }) })
1502
- }
1503
- )
1504
- ]
1064
+ const timeout = setTimeout(() => {
1065
+ if (candidateGatheringComplete) {
1066
+ pickBestCandidate();
1067
+ } else {
1068
+ setTimeout(() => {
1069
+ pickBestCandidate();
1070
+ }, 500);
1505
1071
  }
1506
- ) }) }) })
1507
- ] });
1508
- };
1509
- var useFullscreen = () => {
1510
- const [isFullscreen, setIsFullscreen] = useState(false);
1511
- useEffect(() => {
1512
- const handleFullscreenChange = () => {
1513
- const doc = document;
1514
- setIsFullscreen(
1515
- !!(document.fullscreenElement || doc.webkitFullscreenElement || doc.mozFullScreenElement || doc.msFullscreenElement)
1516
- );
1072
+ }, 3e3);
1073
+ const pickBestCandidate = () => {
1074
+ if (candidates.length === 0) {
1075
+ resolveOnce(null);
1076
+ return;
1077
+ }
1078
+ candidates.sort((a, b) => b.score - a.score);
1079
+ const best = candidates[0];
1080
+ clearTimeout(timeout);
1081
+ resolveOnce(best.ip);
1517
1082
  };
1518
- document.addEventListener("fullscreenchange", handleFullscreenChange);
1519
- document.addEventListener("webkitfullscreenchange", handleFullscreenChange);
1520
- document.addEventListener("mozfullscreenchange", handleFullscreenChange);
1521
- document.addEventListener("msfullscreenchange", handleFullscreenChange);
1522
- return () => {
1523
- document.removeEventListener("fullscreenchange", handleFullscreenChange);
1524
- document.removeEventListener(
1525
- "webkitfullscreenchange",
1526
- handleFullscreenChange
1527
- );
1528
- document.removeEventListener(
1529
- "mozfullscreenchange",
1530
- handleFullscreenChange
1531
- );
1532
- document.removeEventListener(
1533
- "msfullscreenchange",
1534
- handleFullscreenChange
1535
- );
1536
- };
1537
- }, []);
1538
- const exitFullscreen = useCallback(async () => {
1539
- try {
1540
- const doc = document;
1541
- if (document.fullscreenElement || doc.webkitFullscreenElement || doc.mozFullScreenElement || doc.msFullscreenElement) {
1542
- if (document.exitFullscreen) {
1543
- await document.exitFullscreen();
1544
- } else if (doc.webkitExitFullscreen) {
1545
- await doc.webkitExitFullscreen();
1546
- } else if (doc.mozCancelFullScreen) {
1547
- await doc.mozCancelFullScreen();
1548
- } else if (doc.msExitFullscreen) {
1549
- await doc.msExitFullscreen();
1550
- }
1551
- }
1552
- } catch (error) {
1553
- console.error("Error exiting fullscreen:", error);
1554
- }
1555
- }, []);
1556
- const enterFullscreen = useCallback(async (element) => {
1557
- try {
1558
- const elem = element || document.documentElement;
1559
- if (elem.requestFullscreen) {
1560
- await elem.requestFullscreen();
1561
- } else if (elem.webkitRequestFullscreen) {
1562
- await elem.webkitRequestFullscreen();
1563
- } else if (elem.mozRequestFullScreen) {
1564
- await elem.mozRequestFullScreen();
1565
- } else if (elem.msRequestFullscreen) {
1566
- await elem.msRequestFullscreen();
1567
- }
1568
- } catch (error) {
1569
- console.error("Error entering fullscreen:", error);
1570
- }
1571
- }, []);
1572
- const toggleFullscreen = useCallback(
1573
- async (element) => {
1574
- if (isFullscreen) {
1575
- await exitFullscreen();
1576
- } else {
1577
- await enterFullscreen(element);
1578
- }
1579
- },
1580
- [isFullscreen, exitFullscreen, enterFullscreen]
1581
- );
1582
- return {
1583
- isFullscreen,
1584
- enterFullscreen,
1585
- exitFullscreen,
1586
- toggleFullscreen
1587
- };
1588
- };
1589
-
1590
- // src/utils/mode.ts
1591
- var detectRunMode = () => {
1592
- if (typeof window === "undefined") {
1593
- return "standalone";
1594
- }
1595
- try {
1596
- return window.self !== window.top ? "platform" : "standalone";
1597
- } catch {
1598
- return "platform";
1599
- }
1600
- };
1601
-
1602
- // src/utils/network-ip.ts
1603
- var isVirtualNetwork = (ip) => {
1604
- if (ip.startsWith("192.168.64.") || ip.startsWith("192.168.65.")) {
1605
- return true;
1606
- }
1607
- if (ip.startsWith("172.17.")) {
1608
- return true;
1609
- }
1610
- if (ip.startsWith("172.18.") || ip.startsWith("172.19.")) {
1611
- return true;
1612
- }
1613
- if (ip.startsWith("169.254.")) {
1614
- return true;
1615
- }
1616
- return false;
1617
- };
1618
- var scoreIp = (ip) => {
1619
- if (ip.startsWith("192.168.")) {
1620
- const parts = ip.split(".");
1621
- const thirdOctet = parseInt(parts[2] || "0", 10);
1622
- if (thirdOctet < 64) {
1623
- return 100 - thirdOctet;
1624
- }
1625
- return 10;
1626
- }
1627
- if (ip.startsWith("10.")) {
1628
- return 50;
1629
- }
1630
- if (/^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip)) {
1631
- return 30;
1632
- }
1633
- return 0;
1634
- };
1635
- var getLocalNetworkIp = () => {
1636
- return new Promise((resolve) => {
1637
- if (typeof window === "undefined" || typeof RTCPeerConnection === "undefined") {
1638
- resolve(null);
1639
- return;
1640
- }
1641
- const pc = new RTCPeerConnection({
1642
- iceServers: [{ urls: "stun:stun.l.google.com:19302" }]
1643
- });
1644
- const candidates = [];
1645
- let candidateGatheringComplete = false;
1646
- const resolveOnce = (ip) => {
1647
- pc.close();
1648
- resolve(ip);
1649
- };
1650
- const timeout = setTimeout(() => {
1651
- if (candidateGatheringComplete) {
1652
- pickBestCandidate();
1653
- } else {
1654
- setTimeout(() => {
1655
- pickBestCandidate();
1656
- }, 500);
1657
- }
1658
- }, 3e3);
1659
- const pickBestCandidate = () => {
1660
- if (candidates.length === 0) {
1661
- resolveOnce(null);
1662
- return;
1663
- }
1664
- candidates.sort((a, b) => b.score - a.score);
1665
- const best = candidates[0];
1666
- clearTimeout(timeout);
1667
- resolveOnce(best.ip);
1668
- };
1669
- pc.onicecandidate = (event) => {
1670
- if (event.candidate) {
1671
- const candidate = event.candidate.candidate;
1672
- const match = candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3})/);
1673
- if (match) {
1674
- const ip = match[1];
1675
- if (ip === "127.0.0.1") {
1676
- return;
1677
- }
1678
- const isPrivate = ip.startsWith("192.168.") || ip.startsWith("10.") || /^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip);
1679
- if (isPrivate && !isVirtualNetwork(ip)) {
1680
- const score = scoreIp(ip);
1681
- candidates.push({ ip, score });
1682
- }
1683
- }
1684
- } else {
1685
- candidateGatheringComplete = true;
1686
- setTimeout(() => {
1687
- pickBestCandidate();
1688
- }, 200);
1689
- }
1083
+ pc.onicecandidate = (event) => {
1084
+ if (event.candidate) {
1085
+ const candidate = event.candidate.candidate;
1086
+ const match = candidate.match(/([0-9]{1,3}(\.[0-9]{1,3}){3})/);
1087
+ if (match) {
1088
+ const ip = match[1];
1089
+ if (ip === "127.0.0.1") {
1090
+ return;
1091
+ }
1092
+ const isPrivate = ip.startsWith("192.168.") || ip.startsWith("10.") || /^172\.(1[6-9]|2[0-9]|3[01])\./.test(ip);
1093
+ if (isPrivate && !isVirtualNetwork(ip)) {
1094
+ const score = scoreIp(ip);
1095
+ candidates.push({ ip, score });
1096
+ }
1097
+ }
1098
+ } else {
1099
+ candidateGatheringComplete = true;
1100
+ setTimeout(() => {
1101
+ pickBestCandidate();
1102
+ }, 200);
1103
+ }
1690
1104
  };
1691
1105
  pc.createDataChannel("");
1692
1106
  pc.createOffer().then((offer) => pc.setLocalDescription(offer)).catch(() => {
@@ -1750,10 +1164,11 @@ var UrlBuilder = class {
1750
1164
  }
1751
1165
  /**
1752
1166
  * Build a controller URL with room code.
1167
+ * Controller is always at {baseUrl}/controller (standardized convention).
1753
1168
  * Automatically uses local IP when running on localhost.
1754
1169
  */
1755
1170
  async buildControllerUrl(roomId, options) {
1756
- const path = options?.path || DEFAULT_CONTROLLER_PATH;
1171
+ const path = CONTROLLER_PATH;
1757
1172
  if (options?.host) {
1758
1173
  const url2 = new URL(path, this.normalizeOrigin(options.host));
1759
1174
  url2.searchParams.set("room", roomId);
@@ -1812,1206 +1227,2007 @@ var UrlBuilder = class {
1812
1227
  }
1813
1228
  };
1814
1229
  var urlBuilder = new UrlBuilder();
1815
- var extractRoomCode = (text) => {
1816
- try {
1817
- const url = new URL(text);
1818
- const roomParam = url.searchParams.get("room");
1819
- if (roomParam) {
1820
- const parsed2 = roomCodeSchema.safeParse(roomParam.toUpperCase());
1821
- if (parsed2.success) {
1822
- return parsed2.data;
1230
+
1231
+ // src/hooks/use-air-jam-host.ts
1232
+ var useAirJamHost = (options = {}) => {
1233
+ const { config, store, getSocket, disconnectSocket, inputManager } = useAirJamContext();
1234
+ const arcadeParams = useMemo(() => {
1235
+ if (typeof window === "undefined") return null;
1236
+ const params = new URLSearchParams(window.location.search);
1237
+ const room = params.get("aj_room");
1238
+ const token = params.get("aj_token");
1239
+ if (room && token) {
1240
+ return { room, token };
1241
+ }
1242
+ return null;
1243
+ }, []);
1244
+ const isChildMode = !!arcadeParams;
1245
+ const shouldConnect = true;
1246
+ const storeRoomId = useStore(store, (s) => s.roomId);
1247
+ const parsedRoomId = useMemo(() => {
1248
+ if (arcadeParams) {
1249
+ return roomCodeSchema.parse(arcadeParams.room.toUpperCase());
1250
+ }
1251
+ if (storeRoomId) {
1252
+ return roomCodeSchema.parse(storeRoomId.toUpperCase());
1253
+ }
1254
+ if (typeof window !== "undefined") {
1255
+ const params = new URLSearchParams(window.location.search);
1256
+ const paramRoom = params.get("room");
1257
+ if (paramRoom) {
1258
+ const result = roomCodeSchema.safeParse(paramRoom.toUpperCase());
1259
+ if (result.success) return result.data;
1823
1260
  }
1824
1261
  }
1825
- } catch {
1826
- }
1827
- const parsed = roomCodeSchema.safeParse(text.trim().toUpperCase());
1828
- if (parsed.success) {
1829
- return parsed.data;
1830
- }
1831
- return null;
1832
- };
1833
- var QRScannerDialog = ({
1834
- isOpen,
1835
- onClose,
1836
- onScan,
1837
- currentRoomId
1838
- }) => {
1839
- const [code, setCode] = useState("");
1840
- const [isCameraAvailable, setIsCameraAvailable] = useState(false);
1262
+ if (options.roomId) {
1263
+ return roomCodeSchema.parse(options.roomId.toUpperCase());
1264
+ }
1265
+ return null;
1266
+ }, [options.roomId, storeRoomId, arcadeParams]);
1841
1267
  const [joinUrl, setJoinUrl] = useState("");
1842
- const [copied, setCopied] = useState(false);
1843
- const scannerRef = useRef(null);
1844
- const inputRef = useRef(null);
1845
- const prevIsOpenRef = useRef(false);
1268
+ const onPlayerJoinRef = useRef(options.onPlayerJoin);
1269
+ const onPlayerLeaveRef = useRef(options.onPlayerLeave);
1270
+ const onChildCloseRef = useRef(options.onChildClose);
1846
1271
  useEffect(() => {
1847
- if (isOpen && !prevIsOpenRef.current) {
1848
- const initialCode = currentRoomId || "";
1849
- setTimeout(() => {
1850
- setIsCameraAvailable(false);
1851
- setCode(initialCode);
1852
- inputRef.current?.focus();
1853
- inputRef.current?.select();
1854
- }, 0);
1272
+ onPlayerJoinRef.current = options.onPlayerJoin;
1273
+ onPlayerLeaveRef.current = options.onPlayerLeave;
1274
+ onChildCloseRef.current = options.onChildClose;
1275
+ }, [options.onPlayerJoin, options.onPlayerLeave, options.onChildClose]);
1276
+ const connectionState = useStore(
1277
+ store,
1278
+ useShallow((state) => ({
1279
+ connectionStatus: state.connectionStatus,
1280
+ lastError: state.lastError,
1281
+ players: state.players,
1282
+ gameState: state.gameState,
1283
+ mode: state.mode,
1284
+ roomId: state.roomId
1285
+ }))
1286
+ );
1287
+ const socket = useMemo(
1288
+ () => getSocket("host") ,
1289
+ [shouldConnect, getSocket]
1290
+ );
1291
+ const [lastToggle, setLastToggle] = useState(0);
1292
+ const toggleGameState = useCallback(() => {
1293
+ const now = Date.now();
1294
+ if (now - lastToggle < TOGGLE_DEBOUNCE_MS) {
1295
+ return;
1855
1296
  }
1856
- prevIsOpenRef.current = isOpen;
1857
- }, [isOpen, currentRoomId]);
1858
- useEffect(() => {
1859
- const buildUrl = async () => {
1860
- const trimmed = code.trim().toUpperCase();
1861
- const parsed = roomCodeSchema.safeParse(trimmed);
1862
- if (parsed.success) {
1863
- try {
1864
- const url = await urlBuilder.buildControllerUrl(parsed.data);
1865
- setJoinUrl(url);
1866
- } catch {
1867
- setJoinUrl("");
1868
- }
1869
- } else {
1870
- setJoinUrl("");
1297
+ setLastToggle(now);
1298
+ if (!socket || !socket.connected) {
1299
+ return;
1300
+ }
1301
+ if (!parsedRoomId) return;
1302
+ const payload = controllerSystemSchema.safeParse({
1303
+ roomId: parsedRoomId,
1304
+ command: "toggle_pause"
1305
+ });
1306
+ if (payload.success) {
1307
+ socket.emit("host:system", payload.data);
1308
+ }
1309
+ }, [socket, parsedRoomId, lastToggle]);
1310
+ const sendState = useCallback(
1311
+ (state) => {
1312
+ if (!socket || !socket.connected || !parsedRoomId) {
1313
+ return false;
1871
1314
  }
1872
- };
1873
- buildUrl();
1874
- }, [code]);
1875
- useEffect(() => {
1876
- if (!isOpen) {
1877
- setTimeout(() => {
1878
- setIsCameraAvailable(false);
1879
- }, 0);
1880
- if (scannerRef.current) {
1881
- const scanner = scannerRef.current;
1882
- scanner.stop().catch(() => {
1883
- }).finally(() => {
1884
- try {
1885
- scanner.clear();
1886
- } catch {
1887
- }
1888
- });
1889
- scannerRef.current = null;
1315
+ const payload = controllerStateSchema.safeParse({
1316
+ roomId: parsedRoomId,
1317
+ state
1318
+ });
1319
+ if (!payload.success) {
1320
+ return false;
1321
+ }
1322
+ socket.emit("host:state", payload.data);
1323
+ return true;
1324
+ },
1325
+ [socket, parsedRoomId]
1326
+ );
1327
+ const sendSignal = useCallback(
1328
+ (type, payload, targetId) => {
1329
+ if (!socket || !socket.connected) {
1330
+ return;
1890
1331
  }
1332
+ const signal = {
1333
+ targetId,
1334
+ type,
1335
+ payload
1336
+ };
1337
+ socket.emit("host:signal", signal);
1338
+ },
1339
+ [socket]
1340
+ );
1341
+ const reconnect = useCallback(() => {
1342
+ disconnectSocket("host");
1343
+ if (socket) {
1344
+ socket.connect();
1891
1345
  }
1892
- }, [isOpen]);
1346
+ }, [socket, disconnectSocket]);
1893
1347
  useEffect(() => {
1894
- if (!isOpen) {
1348
+ if (!parsedRoomId) return;
1349
+ (async () => {
1350
+ const url = await urlBuilder.buildControllerUrl(parsedRoomId, {
1351
+ host: config.publicHost
1352
+ });
1353
+ setJoinUrl(url);
1354
+ })();
1355
+ }, [parsedRoomId, config.publicHost, options.roomId]);
1356
+ const setRegisteredRoomId = useStore(store, (s) => s.setRegisteredRoomId);
1357
+ useEffect(() => {
1358
+ const storeState = store.getState();
1359
+ storeState.setMode(detectRunMode());
1360
+ storeState.setRole("host");
1361
+ if (parsedRoomId) {
1362
+ storeState.setRoomId(parsedRoomId);
1363
+ }
1364
+ storeState.setStatus("connecting");
1365
+ storeState.setError(void 0);
1366
+ if (!socket) {
1367
+ storeState.setStatus("idle");
1895
1368
  return;
1896
1369
  }
1897
- const containerId = "qr-reader";
1898
- let scanner = null;
1899
- let scannerRunning = false;
1900
- let mounted = true;
1901
- const startScanning = async () => {
1902
- try {
1903
- const container = document.getElementById(containerId);
1904
- if (!container) {
1905
- return;
1906
- }
1907
- const rect = container.getBoundingClientRect();
1908
- if (rect.width === 0 || rect.height === 0) {
1909
- return;
1910
- }
1911
- scanner = new Html5Qrcode(containerId);
1912
- scannerRef.current = scanner;
1913
- let cameraId = null;
1914
- try {
1915
- const devices = await Html5Qrcode.getCameras();
1916
- if (devices && devices.length > 0) {
1917
- const backCamera = devices.find(
1918
- (d) => d.label.toLowerCase().includes("back") || d.label.toLowerCase().includes("rear")
1919
- );
1920
- const envCamera = devices.find((d) => {
1921
- const label = d.label.toLowerCase();
1922
- return label.includes("environment") || label.includes("facing back");
1923
- });
1924
- cameraId = (envCamera || backCamera || devices[0])?.id || null;
1370
+ const registerHost = async () => {
1371
+ const storeState2 = store.getState();
1372
+ const currentRegisteredRoomId2 = store.getState().registeredRoomId;
1373
+ if (currentRegisteredRoomId2 && socket.connected) {
1374
+ return;
1375
+ }
1376
+ if (arcadeParams) {
1377
+ const childRoomId = roomCodeSchema.parse(
1378
+ arcadeParams.room.toUpperCase()
1379
+ );
1380
+ const payload = {
1381
+ roomId: childRoomId,
1382
+ joinToken: arcadeParams.token
1383
+ };
1384
+ socket.emit("host:joinAsChild", payload, (ack) => {
1385
+ if (!ack.ok) {
1386
+ storeState2.setError(ack.message ?? "Failed to join as child");
1387
+ storeState2.setStatus("disconnected");
1388
+ setRegisteredRoomId(null);
1389
+ return;
1925
1390
  }
1926
- } catch {
1927
- }
1928
- const config = cameraId ? { deviceId: { exact: cameraId } } : { facingMode: "environment" };
1929
- await scanner.start(
1930
- config,
1931
- {
1932
- fps: 10,
1933
- qrbox: (viewfinderWidth, viewfinderHeight) => {
1934
- const minEdge = Math.min(viewfinderWidth, viewfinderHeight);
1935
- const qrboxSize = Math.min(250, minEdge * 0.8);
1936
- return {
1937
- width: qrboxSize,
1938
- height: qrboxSize
1939
- };
1940
- },
1941
- aspectRatio: 1
1942
- },
1943
- (decodedText) => {
1944
- if (!mounted) return;
1945
- const roomCode = extractRoomCode(decodedText);
1946
- if (roomCode) {
1947
- setCode(roomCode);
1948
- scannerRunning = false;
1949
- scanner?.stop().catch(() => {
1950
- }).finally(() => {
1951
- if (mounted) {
1952
- setIsCameraAvailable(false);
1953
- }
1954
- });
1391
+ storeState2.setStatus("connected");
1392
+ storeState2.setRoomId(childRoomId);
1393
+ setRegisteredRoomId(childRoomId);
1394
+ });
1395
+ } else {
1396
+ const createNewRoom = () => {
1397
+ const payload = hostCreateRoomSchema.parse({
1398
+ maxPlayers: options.maxPlayers ?? config.maxPlayers,
1399
+ apiKey: options.apiKey ?? config.apiKey
1400
+ });
1401
+ socket.emit("host:createRoom", payload, (ack) => {
1402
+ if (!ack.ok) {
1403
+ storeState2.setError(ack.message ?? "Failed to create room");
1404
+ storeState2.setStatus("disconnected");
1405
+ setRegisteredRoomId(null);
1406
+ return;
1955
1407
  }
1956
- },
1957
- () => {
1958
- }
1959
- );
1960
- scannerRunning = true;
1961
- if (mounted) {
1962
- setIsCameraAvailable(true);
1963
- }
1964
- } catch {
1965
- if (mounted) {
1966
- setIsCameraAvailable(false);
1967
- }
1968
- if (scanner) {
1969
- try {
1970
- scanner.clear();
1971
- } catch {
1408
+ if (ack.roomId) {
1409
+ storeState2.setStatus("connected");
1410
+ storeState2.setRoomId(ack.roomId);
1411
+ setRegisteredRoomId(ack.roomId);
1412
+ if (typeof window !== "undefined") {
1413
+ sessionStorage.setItem("airjam_room_id", ack.roomId);
1414
+ }
1415
+ } else {
1416
+ storeState2.setError("Server did not return room ID");
1417
+ storeState2.setStatus("disconnected");
1418
+ }
1419
+ });
1420
+ };
1421
+ if (typeof window !== "undefined") {
1422
+ const savedRoomId = sessionStorage.getItem("airjam_room_id");
1423
+ if (savedRoomId) {
1424
+ const reconnectPayload = hostReconnectSchema.parse({
1425
+ roomId: savedRoomId,
1426
+ apiKey: options.apiKey ?? config.apiKey
1427
+ });
1428
+ socket.emit("host:reconnect", reconnectPayload, (ack) => {
1429
+ if (ack.ok && ack.roomId) {
1430
+ storeState2.setStatus("connected");
1431
+ storeState2.setRoomId(ack.roomId);
1432
+ setRegisteredRoomId(ack.roomId);
1433
+ } else {
1434
+ if (typeof window !== "undefined") {
1435
+ sessionStorage.removeItem("airjam_room_id");
1436
+ }
1437
+ createNewRoom();
1438
+ }
1439
+ });
1440
+ } else {
1441
+ createNewRoom();
1972
1442
  }
1443
+ } else {
1444
+ createNewRoom();
1973
1445
  }
1974
- scannerRef.current = null;
1975
1446
  }
1976
1447
  };
1977
- const timeoutId = setTimeout(() => {
1978
- startScanning();
1979
- }, 200);
1980
- return () => {
1981
- mounted = false;
1982
- clearTimeout(timeoutId);
1983
- if (scanner && scannerRunning) {
1984
- scanner.stop().catch(() => {
1985
- }).finally(() => {
1986
- try {
1987
- scanner?.clear();
1988
- } catch {
1989
- }
1990
- });
1991
- } else if (scanner) {
1992
- try {
1993
- scanner.clear();
1994
- } catch {
1995
- }
1448
+ const handleConnect = () => {
1449
+ store.getState().setStatus("connected");
1450
+ registerHost();
1451
+ };
1452
+ const handleDisconnect = () => {
1453
+ store.getState().setStatus("disconnected");
1454
+ };
1455
+ const handleJoin = (payload) => {
1456
+ if (payload.player) {
1457
+ store.getState().upsertPlayer(payload.player);
1458
+ setTimeout(() => {
1459
+ onPlayerJoinRef.current?.(payload.player);
1460
+ }, 0);
1996
1461
  }
1997
- scannerRef.current = null;
1998
1462
  };
1999
- }, [isOpen]);
2000
- const handleSubmit = () => {
2001
- const trimmed = code.trim().toUpperCase();
2002
- const parsed = roomCodeSchema.safeParse(trimmed);
2003
- if (parsed.success) {
2004
- onScan(parsed.data);
2005
- onClose();
2006
- }
2007
- };
2008
- const handleInputFocus = (e) => {
2009
- e.target.select();
2010
- };
2011
- const handleInputChange = (e) => {
2012
- setCode(e.target.value.toUpperCase());
2013
- setCopied(false);
2014
- };
2015
- const handleCopyUrl = async () => {
2016
- if (!joinUrl) return;
2017
- try {
2018
- await navigator.clipboard.writeText(joinUrl);
2019
- setCopied(true);
2020
- setTimeout(() => setCopied(false), 2e3);
2021
- } catch {
2022
- const textArea = document.createElement("textarea");
2023
- textArea.value = joinUrl;
2024
- textArea.style.position = "fixed";
2025
- textArea.style.opacity = "0";
2026
- document.body.appendChild(textArea);
2027
- textArea.select();
2028
- try {
2029
- document.execCommand("copy");
2030
- setCopied(true);
2031
- setTimeout(() => setCopied(false), 2e3);
2032
- } catch {
1463
+ const handleLeave = (payload) => {
1464
+ store.getState().removePlayer(payload.controllerId);
1465
+ onPlayerLeaveRef.current?.(payload.controllerId);
1466
+ };
1467
+ const handleInput = (payload) => {
1468
+ if (inputManager) {
1469
+ inputManager.handleInput(payload);
2033
1470
  }
2034
- document.body.removeChild(textArea);
1471
+ };
1472
+ const handleChildClose = () => {
1473
+ onChildCloseRef.current?.();
1474
+ };
1475
+ const handleState = (payload) => {
1476
+ if (!parsedRoomId || payload.roomId !== parsedRoomId) return;
1477
+ const storeState2 = store.getState();
1478
+ if (payload.state.gameState) {
1479
+ storeState2.setGameState(payload.state.gameState);
1480
+ }
1481
+ if (payload.state.message !== void 0) {
1482
+ storeState2.setStateMessage(payload.state.message);
1483
+ }
1484
+ };
1485
+ const handleError = (payload) => {
1486
+ store.getState().setError(payload.message);
1487
+ };
1488
+ socket.on("connect", handleConnect);
1489
+ socket.on("disconnect", handleDisconnect);
1490
+ socket.on("server:controllerJoined", handleJoin);
1491
+ socket.on("server:controllerLeft", handleLeave);
1492
+ socket.on("server:input", handleInput);
1493
+ socket.on("server:error", handleError);
1494
+ socket.on("server:closeChild", handleChildClose);
1495
+ socket.on("server:state", handleState);
1496
+ socket.connect();
1497
+ const currentRegisteredRoomId = store.getState().registeredRoomId;
1498
+ if (socket.connected && !currentRegisteredRoomId) {
1499
+ registerHost();
2035
1500
  }
1501
+ return () => {
1502
+ socket.off("connect", handleConnect);
1503
+ socket.off("disconnect", handleDisconnect);
1504
+ socket.off("server:controllerJoined", handleJoin);
1505
+ socket.off("server:controllerLeft", handleLeave);
1506
+ socket.off("server:input", handleInput);
1507
+ socket.off("server:error", handleError);
1508
+ socket.off("server:closeChild", handleChildClose);
1509
+ socket.off("server:state", handleState);
1510
+ };
1511
+ }, [
1512
+ config.maxPlayers,
1513
+ config.apiKey,
1514
+ options.maxPlayers,
1515
+ options.apiKey,
1516
+ arcadeParams,
1517
+ parsedRoomId,
1518
+ // Include parsedRoomId since it's used in handleState callback
1519
+ shouldConnect,
1520
+ socket,
1521
+ store,
1522
+ inputManager,
1523
+ setRegisteredRoomId
1524
+ ]);
1525
+ const returnSocket = socket ?? getSocket("host");
1526
+ const getInput = useCallback(
1527
+ (controllerId) => {
1528
+ if (!inputManager) {
1529
+ return void 0;
1530
+ }
1531
+ return inputManager.getInput(controllerId);
1532
+ },
1533
+ [inputManager]
1534
+ );
1535
+ return {
1536
+ roomId: parsedRoomId ?? "",
1537
+ // Return empty string as fallback if not yet available
1538
+ joinUrl,
1539
+ connectionStatus: connectionState.connectionStatus,
1540
+ players: connectionState.players,
1541
+ lastError: connectionState.lastError,
1542
+ mode: connectionState.mode,
1543
+ gameState: connectionState.gameState,
1544
+ toggleGameState,
1545
+ sendState,
1546
+ sendSignal,
1547
+ reconnect,
1548
+ socket: returnSocket,
1549
+ isChildMode,
1550
+ getInput
2036
1551
  };
2037
- if (!isOpen) {
2038
- return null;
2039
- }
2040
- const isValid = code.trim().length > 0;
2041
- return /* @__PURE__ */ jsxs("div", { className: "bg-background fixed inset-0 z-50 flex flex-col items-center justify-center", children: [
2042
- /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col items-center justify-center", children: [
2043
- isCameraAvailable && /* @__PURE__ */ jsx("div", { className: "relative flex aspect-square w-full items-center justify-center overflow-hidden p-6", children: /* @__PURE__ */ jsx(
2044
- "div",
2045
- {
2046
- id: "qr-reader",
2047
- className: "h-full w-full overflow-hidden rounded-lg bg-black"
2048
- }
2049
- ) }),
2050
- /* @__PURE__ */ jsx("div", { className: "w-full max-w-md px-6", children: /* @__PURE__ */ jsx(
2051
- "input",
2052
- {
2053
- ref: inputRef,
2054
- type: "text",
2055
- value: code,
2056
- onChange: handleInputChange,
2057
- onFocus: handleInputFocus,
2058
- onKeyDown: (e) => {
2059
- if (e.key === "Enter" && isValid) {
2060
- handleSubmit();
2061
- }
2062
- },
2063
- placeholder: "Enter room code",
2064
- 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",
2065
- autoComplete: "off",
2066
- autoCapitalize: "characters"
2067
- }
2068
- ) }),
2069
- joinUrl && /* @__PURE__ */ jsx("div", { className: "mt-4 w-full max-w-md px-6 pb-2", children: /* @__PURE__ */ jsx(
2070
- "button",
2071
- {
2072
- type: "button",
2073
- onClick: handleCopyUrl,
2074
- 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",
2075
- children: copied ? "\u2713 Copied!" : joinUrl
2076
- }
2077
- ) })
2078
- ] }),
2079
- /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-md gap-4 px-6 pb-6", children: [
2080
- /* @__PURE__ */ jsx(
2081
- Button,
2082
- {
2083
- type: "button",
2084
- variant: "outline",
2085
- onClick: onClose,
2086
- className: "flex-1 py-6",
2087
- children: "Cancel"
2088
- }
2089
- ),
2090
- /* @__PURE__ */ jsx(
2091
- Button,
2092
- {
2093
- type: "button",
2094
- onClick: handleSubmit,
2095
- disabled: !isValid,
2096
- className: "flex-1 py-6",
2097
- children: "Connect"
2098
- }
2099
- )
2100
- ] })
2101
- ] });
2102
1552
  };
2103
- var getPlayerAvatarUrl2 = (playerId) => {
1553
+ var getPlayerAvatarUrl = (playerId) => {
2104
1554
  return `https://api.dicebear.com/9.x/adventurer-neutral/svg?seed=${encodeURIComponent(
2105
1555
  playerId
2106
1556
  )}`;
2107
1557
  };
2108
- var describeStatus = (status) => {
2109
- switch (status) {
2110
- case "connected":
2111
- return "Connected to host";
2112
- case "connecting":
2113
- return "Connecting\u2026";
2114
- case "reconnecting":
2115
- return "Trying to reconnect\u2026";
2116
- case "disconnected":
2117
- return "Disconnected";
2118
- case "idle":
2119
- default:
2120
- return "Idle";
2121
- }
2122
- };
2123
- var orientationMatches = (required) => {
2124
- if (required === "any") return true;
2125
- if (typeof window === "undefined" || !window.matchMedia) return true;
2126
- const matcher = window.matchMedia(`(orientation: ${required})`);
2127
- return matcher.matches;
1558
+ var hexToRgba = (hex, opacity) => {
1559
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
1560
+ if (!result) return `rgba(0, 0, 0, ${opacity})`;
1561
+ const r = parseInt(result[1], 16);
1562
+ const g = parseInt(result[2], 16);
1563
+ const b = parseInt(result[3], 16);
1564
+ return `rgba(${r}, ${g}, ${b}, ${opacity})`;
2128
1565
  };
2129
- var ControllerShell = ({
2130
- roomId,
2131
- connectionStatus,
2132
- requiredOrientation = "landscape",
2133
- children,
2134
- gameState = "paused",
2135
- onTogglePlayPause,
2136
- onReconnect,
2137
- onRefresh,
2138
- customActions
1566
+ var PlayerAvatar = ({
1567
+ player,
1568
+ size = "md",
1569
+ className = ""
2139
1570
  }) => {
2140
- const isChildMode = useMemo(() => detectRunMode() === "platform", []);
2141
- const [isOrientationOk, setOrientationOk] = useState(
2142
- () => orientationMatches(requiredOrientation)
2143
- );
2144
- const [isScannerOpen, setIsScannerOpen] = useState(false);
2145
- const { isFullscreen, toggleFullscreen } = useFullscreen();
2146
- const { store } = useAirJamContext();
2147
- const { controllerId, players } = useStore(
2148
- store,
2149
- useShallow(
2150
- (state) => ({
2151
- controllerId: state.controllerId,
2152
- players: state.players
2153
- })
2154
- )
1571
+ const sizeClasses = {
1572
+ sm: "h-8 w-8 border-2",
1573
+ md: "h-12 w-12 border-4",
1574
+ lg: "h-16 w-16 border-4"
1575
+ };
1576
+ const shadowStyles = {
1577
+ sm: player.color ? `inset 0 0 4px rgba(0, 0, 0, 0.2), 0 0 8px ${hexToRgba(player.color, 0.4)}` : "inset 0 0 4px rgba(0, 0, 0, 0.2)",
1578
+ md: player.color ? `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)}` : "inset 0 0 10px rgba(0, 0, 0, 0.4), 0 0 20px hsl(var(--border) / 0.5)",
1579
+ lg: player.color ? `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)}` : "inset 0 0 12px rgba(0, 0, 0, 0.4), 0 0 24px hsl(var(--border) / 0.5)"
1580
+ };
1581
+ return /* @__PURE__ */ jsx(
1582
+ "img",
1583
+ {
1584
+ src: getPlayerAvatarUrl(player.id),
1585
+ alt: player.label,
1586
+ className: `bg-secondary/30 shrink-0 rounded-full shadow-lg ${sizeClasses[size]} ${className}`,
1587
+ style: {
1588
+ borderColor: player.color || "hsl(var(--border))",
1589
+ boxShadow: shadowStyles[size]
1590
+ }
1591
+ }
2155
1592
  );
2156
- const currentPlayer = useMemo(() => {
2157
- if (!controllerId) return null;
2158
- const found = players.find((p) => p.id === controllerId);
2159
- if (!found && connectionStatus === "connected" && players.length > 0) ;
2160
- return found || null;
2161
- }, [controllerId, players, connectionStatus]);
2162
- useEffect(() => {
2163
- if (requiredOrientation === "any") {
2164
- return;
1593
+ };
1594
+ var alertVariants = cva(
1595
+ "relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
1596
+ {
1597
+ variants: {
1598
+ variant: {
1599
+ default: "bg-card text-card-foreground",
1600
+ destructive: "text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90"
1601
+ }
1602
+ },
1603
+ defaultVariants: {
1604
+ variant: "default"
2165
1605
  }
2166
- const media = window.matchMedia(`(orientation: ${requiredOrientation})`);
2167
- const handleChange = () => setOrientationOk(media.matches);
2168
- handleChange();
2169
- media.addEventListener("change", handleChange);
2170
- return () => media.removeEventListener("change", handleChange);
2171
- }, [requiredOrientation]);
2172
- const orientationOk = requiredOrientation === "any" ? true : isOrientationOk;
2173
- const statusDotColor = useMemo(() => {
2174
- switch (connectionStatus) {
2175
- case "connected":
2176
- return "bg-green-500";
2177
- case "connecting":
2178
- case "reconnecting":
2179
- return "bg-yellow-500";
2180
- case "disconnected":
2181
- default:
2182
- return "bg-red-500";
1606
+ }
1607
+ );
1608
+ function Alert({
1609
+ className,
1610
+ variant,
1611
+ ...props
1612
+ }) {
1613
+ return /* @__PURE__ */ jsx(
1614
+ "div",
1615
+ {
1616
+ "data-slot": "alert",
1617
+ role: "alert",
1618
+ className: cn(alertVariants({ variant }), className),
1619
+ ...props
1620
+ }
1621
+ );
1622
+ }
1623
+ function AlertDescription({
1624
+ className,
1625
+ ...props
1626
+ }) {
1627
+ return /* @__PURE__ */ jsx(
1628
+ "div",
1629
+ {
1630
+ "data-slot": "alert-description",
1631
+ className: cn(
1632
+ "text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
1633
+ className
1634
+ ),
1635
+ ...props
1636
+ }
1637
+ );
1638
+ }
1639
+ var badgeVariants = cva(
1640
+ "inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
1641
+ {
1642
+ variants: {
1643
+ variant: {
1644
+ default: "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
1645
+ secondary: "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
1646
+ destructive: "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
1647
+ outline: "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"
1648
+ }
1649
+ },
1650
+ defaultVariants: {
1651
+ variant: "default"
2183
1652
  }
2184
- }, [connectionStatus]);
2185
- if (isChildMode) {
2186
- return /* @__PURE__ */ jsx("div", { className: "text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden bg-transparent select-none", children: /* @__PURE__ */ jsxs("main", { className: "relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4", children: [
2187
- !orientationOk && /* @__PURE__ */ jsxs("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", children: [
2188
- /* @__PURE__ */ jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2189
- /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2190
- "This game is best experienced in ",
2191
- requiredOrientation,
2192
- " ",
2193
- "orientation."
2194
- ] })
2195
- ] }),
2196
- /* @__PURE__ */ jsx(
2197
- "div",
2198
- {
2199
- className: cn(
2200
- "h-full w-full select-none",
2201
- !orientationOk && "pointer-events-none opacity-30"
2202
- ),
2203
- children
2204
- }
2205
- )
2206
- ] }) });
2207
1653
  }
2208
- return /* @__PURE__ */ jsxs("div", { className: "bg-background text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden select-none", children: [
2209
- /* @__PURE__ */ jsxs("header", { className: "pointer-events-none sticky top-0 z-50 flex items-center justify-between border-b px-6 py-2", children: [
2210
- /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2211
- typeof window !== "undefined" && (currentPlayer || controllerId) && /* @__PURE__ */ jsxs("div", { className: "relative", title: describeStatus(connectionStatus), children: [
2212
- /* @__PURE__ */ jsx(
2213
- Avatar,
2214
- {
2215
- className: "h-8 w-8 border-2",
2216
- style: {
2217
- borderColor: currentPlayer?.color || "hsl(var(--border))"
2218
- },
2219
- children: /* @__PURE__ */ jsx(
2220
- AvatarImage,
2221
- {
2222
- src: getPlayerAvatarUrl2(
2223
- currentPlayer?.id || controllerId || ""
2224
- ),
2225
- alt: currentPlayer?.label || "Player"
2226
- }
2227
- )
2228
- }
2229
- ),
2230
- /* @__PURE__ */ jsx(
2231
- "span",
2232
- {
2233
- className: "absolute right-0 bottom-0 h-3 w-3 rounded-full bg-black",
2234
- "aria-hidden": "true"
2235
- }
2236
- ),
2237
- /* @__PURE__ */ jsx(
2238
- "span",
2239
- {
2240
- className: cn(
2241
- "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
2242
- statusDotColor,
2243
- connectionStatus === "connected" && "animate-pulse"
2244
- ),
2245
- "aria-label": describeStatus(connectionStatus)
2246
- }
2247
- )
2248
- ] }),
2249
- /* @__PURE__ */ jsxs("div", { children: [
2250
- /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs tracking-[0.24em] uppercase", children: "Room" }),
2251
- /* @__PURE__ */ jsx("p", { className: "text-foreground text-lg font-semibold", children: typeof window !== "undefined" ? roomId ?? "N/A" : "N/A" })
2252
- ] })
2253
- ] }),
2254
- /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2255
- customActions,
2256
- onRefresh && roomId && /* @__PURE__ */ jsx(
2257
- Button,
1654
+ );
1655
+ function Badge({
1656
+ className,
1657
+ variant,
1658
+ asChild = false,
1659
+ ...props
1660
+ }) {
1661
+ const Comp = asChild ? Slot : "span";
1662
+ return /* @__PURE__ */ jsx(
1663
+ Comp,
1664
+ {
1665
+ "data-slot": "badge",
1666
+ className: cn(badgeVariants({ variant }), className),
1667
+ ...props
1668
+ }
1669
+ );
1670
+ }
1671
+ function Card({ className, ...props }) {
1672
+ return /* @__PURE__ */ jsx(
1673
+ "div",
1674
+ {
1675
+ "data-slot": "card",
1676
+ className: cn(
1677
+ "bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
1678
+ className
1679
+ ),
1680
+ ...props
1681
+ }
1682
+ );
1683
+ }
1684
+ function CardTitle({ className, ...props }) {
1685
+ return /* @__PURE__ */ jsx(
1686
+ "div",
1687
+ {
1688
+ "data-slot": "card-title",
1689
+ className: cn("leading-none font-semibold", className),
1690
+ ...props
1691
+ }
1692
+ );
1693
+ }
1694
+ function CardDescription({ className, ...props }) {
1695
+ return /* @__PURE__ */ jsx(
1696
+ "div",
1697
+ {
1698
+ "data-slot": "card-description",
1699
+ className: cn("text-muted-foreground text-sm", className),
1700
+ ...props
1701
+ }
1702
+ );
1703
+ }
1704
+ function CardContent({ className, ...props }) {
1705
+ return /* @__PURE__ */ jsx(
1706
+ "div",
1707
+ {
1708
+ "data-slot": "card-content",
1709
+ className: cn("px-6", className),
1710
+ ...props
1711
+ }
1712
+ );
1713
+ }
1714
+ function Tabs({
1715
+ className,
1716
+ ...props
1717
+ }) {
1718
+ return /* @__PURE__ */ jsx(
1719
+ TabsPrimitive.Root,
1720
+ {
1721
+ "data-slot": "tabs",
1722
+ className: cn("flex flex-col gap-2", className),
1723
+ ...props
1724
+ }
1725
+ );
1726
+ }
1727
+ function TabsList({
1728
+ className,
1729
+ ...props
1730
+ }) {
1731
+ return /* @__PURE__ */ jsx(
1732
+ TabsPrimitive.List,
1733
+ {
1734
+ "data-slot": "tabs-list",
1735
+ className: cn(
1736
+ "bg-muted text-muted-foreground inline-flex h-9 w-fit items-center justify-center rounded-lg p-[3px]",
1737
+ className
1738
+ ),
1739
+ ...props
1740
+ }
1741
+ );
1742
+ }
1743
+ function TabsTrigger({
1744
+ className,
1745
+ ...props
1746
+ }) {
1747
+ return /* @__PURE__ */ jsx(
1748
+ TabsPrimitive.Trigger,
1749
+ {
1750
+ "data-slot": "tabs-trigger",
1751
+ className: cn(
1752
+ "data-[state=active]:bg-background dark:data-[state=active]:text-foreground focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 text-foreground dark:text-muted-foreground inline-flex h-[calc(100%-1px)] flex-1 cursor-pointer items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-[color,box-shadow] focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:shadow-sm [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
1753
+ className
1754
+ ),
1755
+ ...props
1756
+ }
1757
+ );
1758
+ }
1759
+ function TabsContent({
1760
+ className,
1761
+ ...props
1762
+ }) {
1763
+ return /* @__PURE__ */ jsx(
1764
+ TabsPrimitive.Content,
1765
+ {
1766
+ "data-slot": "tabs-content",
1767
+ className: cn("flex-1 outline-none", className),
1768
+ ...props
1769
+ }
1770
+ );
1771
+ }
1772
+ function Slider({
1773
+ className,
1774
+ defaultValue,
1775
+ value,
1776
+ min = 0,
1777
+ max = 100,
1778
+ ...props
1779
+ }) {
1780
+ const _values = React.useMemo(
1781
+ () => Array.isArray(value) ? value : Array.isArray(defaultValue) ? defaultValue : [min, max],
1782
+ [value, defaultValue, min, max]
1783
+ );
1784
+ return /* @__PURE__ */ jsxs(
1785
+ SliderPrimitive.Root,
1786
+ {
1787
+ "data-slot": "slider",
1788
+ defaultValue,
1789
+ value,
1790
+ min,
1791
+ max,
1792
+ className: cn(
1793
+ "relative flex w-full cursor-pointer touch-none items-center select-none data-disabled:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
1794
+ className
1795
+ ),
1796
+ ...props,
1797
+ children: [
1798
+ /* @__PURE__ */ jsx(
1799
+ SliderPrimitive.Track,
2258
1800
  {
2259
- type: "button",
2260
- variant: "outline",
2261
- size: "icon",
2262
- onClick: onRefresh,
2263
- disabled: connectionStatus === "connecting" || connectionStatus === "reconnecting",
2264
- "aria-label": "Reconnect",
2265
- title: "Reconnect to room",
1801
+ "data-slot": "slider-track",
1802
+ className: cn(
1803
+ "bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
1804
+ ),
2266
1805
  children: /* @__PURE__ */ jsx(
2267
- RefreshCw,
1806
+ SliderPrimitive.Range,
2268
1807
  {
1808
+ "data-slot": "slider-range",
2269
1809
  className: cn(
2270
- "h-5 w-5",
2271
- (connectionStatus === "connecting" || connectionStatus === "reconnecting") && "animate-spin"
1810
+ "bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
2272
1811
  )
2273
1812
  }
2274
1813
  )
2275
1814
  }
2276
1815
  ),
2277
- onReconnect && /* @__PURE__ */ jsx(
2278
- Button,
2279
- {
2280
- type: "button",
2281
- variant: "outline",
2282
- size: "icon",
2283
- onClick: () => setIsScannerOpen(true),
2284
- "aria-label": "Scan QR code to reconnect",
2285
- title: "Scan QR code to reconnect",
2286
- children: /* @__PURE__ */ jsx(QrCode, { className: "h-5 w-5" })
2287
- }
2288
- ),
2289
- onTogglePlayPause && /* @__PURE__ */ jsx(
2290
- Button,
1816
+ Array.from({ length: _values.length }, (_, index) => /* @__PURE__ */ jsx(
1817
+ SliderPrimitive.Thumb,
2291
1818
  {
2292
- type: "button",
2293
- variant: "outline",
2294
- size: "icon",
2295
- onClick: onTogglePlayPause,
2296
- "aria-label": gameState === "playing" ? "Pause" : "Play",
2297
- title: gameState === "playing" ? "Pause" : "Play",
2298
- children: gameState === "playing" ? /* @__PURE__ */ jsx(Pause, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Play, { className: "h-5 w-5" })
2299
- }
2300
- ),
2301
- /* @__PURE__ */ jsx(
2302
- Button,
2303
- {
2304
- type: "button",
2305
- variant: "outline",
2306
- size: "icon",
2307
- onClick: () => toggleFullscreen(),
2308
- "aria-label": isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2309
- title: isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2310
- children: isFullscreen ? /* @__PURE__ */ jsx(Minimize, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Maximize, { className: "h-5 w-5" })
2311
- }
2312
- )
2313
- ] })
1819
+ "data-slot": "slider-thumb",
1820
+ className: "border-primary ring-ring/50 block size-4 shrink-0 cursor-pointer rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
1821
+ },
1822
+ index
1823
+ ))
1824
+ ]
1825
+ }
1826
+ );
1827
+ }
1828
+ function VolumeControls({ className, compact }) {
1829
+ const {
1830
+ masterVolume,
1831
+ musicVolume,
1832
+ sfxVolume,
1833
+ setMasterVolume,
1834
+ setMusicVolume,
1835
+ setSfxVolume
1836
+ } = useVolumeStore();
1837
+ return /* @__PURE__ */ jsxs("div", { className: cn("flex flex-col gap-3", compact && "gap-1", className), children: [
1838
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
1839
+ /* @__PURE__ */ jsx(Volume2, { className: "text-muted-foreground h-4 w-4" }),
1840
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: "Volume" })
2314
1841
  ] }),
2315
- /* @__PURE__ */ jsx("div", { className: "pointer-events-none fixed right-4 bottom-4 z-50", children: /* @__PURE__ */ jsx("div", { className: "pointer-events-auto", children: /* @__PURE__ */ jsx(VolumeControls, { compact: true }) }) }),
2316
- /* @__PURE__ */ jsx("main", { className: "relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4", children: /* @__PURE__ */ jsxs("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", children: [
2317
- !orientationOk && /* @__PURE__ */ jsxs("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", children: [
2318
- /* @__PURE__ */ jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2319
- /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2320
- "This game is best experienced in ",
2321
- requiredOrientation,
2322
- " ",
2323
- "orientation."
1842
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1843
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1844
+ /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "Master" }),
1845
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1846
+ Math.round(masterVolume * 100),
1847
+ "%"
2324
1848
  ] })
2325
1849
  ] }),
2326
1850
  /* @__PURE__ */ jsx(
2327
- "div",
1851
+ Slider,
2328
1852
  {
2329
- className: cn(
2330
- "h-full w-full select-none",
2331
- !orientationOk && "pointer-events-none opacity-30"
2332
- ),
2333
- children
1853
+ value: [masterVolume * 100],
1854
+ onValueChange: (values) => setMasterVolume(values[0] / 100),
1855
+ min: 0,
1856
+ max: 100,
1857
+ step: 1,
1858
+ className: "w-full",
1859
+ "aria-label": "Master volume"
2334
1860
  }
2335
1861
  )
2336
- ] }) }),
2337
- onReconnect && /* @__PURE__ */ jsx(
2338
- QRScannerDialog,
2339
- {
2340
- isOpen: isScannerOpen,
2341
- onClose: () => setIsScannerOpen(false),
2342
- onScan: (roomCode) => {
2343
- onReconnect(roomCode);
2344
- setIsScannerOpen(false);
2345
- },
2346
- currentRoomId: roomId
2347
- }
2348
- )
1862
+ ] }),
1863
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1864
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1865
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
1866
+ /* @__PURE__ */ jsx(Music, { className: "text-muted-foreground h-3 w-3" }),
1867
+ /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "Music" })
1868
+ ] }),
1869
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1870
+ Math.round(musicVolume * 100),
1871
+ "%"
1872
+ ] })
1873
+ ] }),
1874
+ /* @__PURE__ */ jsx(
1875
+ Slider,
1876
+ {
1877
+ value: [musicVolume * 100],
1878
+ onValueChange: (values) => setMusicVolume(values[0] / 100),
1879
+ min: 0,
1880
+ max: 100,
1881
+ step: 1,
1882
+ className: "w-full",
1883
+ "aria-label": "Music volume"
1884
+ }
1885
+ )
1886
+ ] }),
1887
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
1888
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
1889
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
1890
+ /* @__PURE__ */ jsx(Headphones, { className: "text-muted-foreground h-3 w-3" }),
1891
+ /* @__PURE__ */ jsx("label", { className: "text-muted-foreground text-xs", children: "SFX" })
1892
+ ] }),
1893
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground font-mono text-xs", children: [
1894
+ Math.round(sfxVolume * 100),
1895
+ "%"
1896
+ ] })
1897
+ ] }),
1898
+ /* @__PURE__ */ jsx(
1899
+ Slider,
1900
+ {
1901
+ value: [sfxVolume * 100],
1902
+ onValueChange: (values) => setSfxVolume(values[0] / 100),
1903
+ min: 0,
1904
+ max: 100,
1905
+ step: 1,
1906
+ className: "w-full",
1907
+ "aria-label": "SFX volume"
1908
+ }
1909
+ )
1910
+ ] })
2349
1911
  ] });
1912
+ }
1913
+ var statusCopy = {
1914
+ idle: "Idle",
1915
+ connecting: "Waiting for server\u2026",
1916
+ connected: "Ready for controllers",
1917
+ disconnected: "Disconnected",
1918
+ reconnecting: "Reconnecting\u2026"
2350
1919
  };
2351
-
2352
- // src/events.ts
2353
- var HostEvents = {
2354
- /**
2355
- * Register as a master host (standalone mode)
2356
- */
2357
- REGISTER: "host:register",
2358
- /**
2359
- * Register as the system/arcade master host
2360
- */
2361
- REGISTER_SYSTEM: "host:registerSystem",
2362
- /**
2363
- * Join as a child host (game launched from arcade)
2364
- */
2365
- JOIN_AS_CHILD: "host:joinAsChild"
2366
- };
2367
- var ControllerEvents = {
2368
- /**
2369
- * Controller joins a room
2370
- */
2371
- JOIN: "controller:join",
2372
- /**
2373
- * Controller sends input
2374
- */
2375
- INPUT: "controller:input",
2376
- /**
2377
- * Controller leaves a room
2378
- */
2379
- LEAVE: "controller:leave",
2380
- /**
2381
- * Controller sends game state update
2382
- */
2383
- STATE: "controller:state",
2384
- /**
2385
- * Controller sends system command
2386
- */
2387
- SYSTEM: "controller:system"
2388
- };
2389
- var SystemEvents = {
2390
- /**
2391
- * Arcade launches a game
2392
- */
2393
- LAUNCH_GAME: "system:launchGame",
2394
- /**
2395
- * Arcade closes a game
2396
- */
2397
- CLOSE_GAME: "system:closeGame"
2398
- };
2399
- var ServerEvents = {
2400
- /**
2401
- * Welcome message with room/controller info
2402
- */
2403
- WELCOME: "server:welcome",
2404
- /**
2405
- * Room is ready
2406
- */
2407
- ROOM_READY: "server:roomReady",
2408
- /**
2409
- * Controller joined notification
2410
- */
2411
- CONTROLLER_JOINED: "server:controllerJoined",
2412
- /**
2413
- * Controller left notification
2414
- */
2415
- CONTROLLER_LEFT: "server:controllerLeft",
2416
- /**
2417
- * Host left notification
2418
- */
2419
- HOST_LEFT: "server:hostLeft",
2420
- /**
2421
- * Server error
2422
- */
2423
- ERROR: "server:error",
2424
- /**
2425
- * Play sound on client
2426
- */
2427
- PLAY_SOUND: "server:playSound"
2428
- };
2429
- var ClientEvents = {
2430
- /**
2431
- * Load a game UI in the controller iframe
2432
- */
2433
- LOAD_UI: "client:loadUi",
2434
- /**
2435
- * Unload the game UI from the controller iframe
2436
- */
2437
- UNLOAD_UI: "client:unloadUi",
2438
- /**
2439
- * Update game state display
2440
- */
2441
- STATE: "client:state"
2442
- };
2443
- var ChildEvents = {
2444
- /**
2445
- * Server requests child to close
2446
- */
2447
- CLOSE: "child:close"
2448
- };
2449
- var Events = {
2450
- Host: HostEvents,
2451
- Controller: ControllerEvents,
2452
- System: SystemEvents,
2453
- Server: ServerEvents,
2454
- Client: ClientEvents,
2455
- Child: ChildEvents
2456
- };
2457
-
2458
- // src/utils/ids.ts
2459
- var alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
2460
- var generateRoomCode = () => {
2461
- const array = new Uint32Array(4);
2462
- if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
2463
- crypto.getRandomValues(array);
2464
- } else {
2465
- for (let i = 0; i < array.length; i += 1) {
2466
- array[i] = Math.floor(Math.random() * alphabet.length);
2467
- }
2468
- }
2469
- const code = Array.from(
2470
- array,
2471
- (value) => alphabet[value % alphabet.length]
2472
- ).join("");
2473
- return roomCodeSchema.parse(code);
2474
- };
2475
- var generateControllerId = () => {
2476
- const stamp = Math.floor(Date.now() % 1e5).toString().padStart(5, "0");
2477
- const random = alphabet[Math.floor(Math.random() * alphabet.length)];
2478
- return `C${random}${stamp}`;
2479
- };
2480
-
2481
- // src/hooks/use-air-jam-controller.ts
2482
- var getRoomFromLocation = () => {
2483
- if (typeof window === "undefined") {
2484
- return null;
2485
- }
2486
- const params = new URLSearchParams(window.location.search);
2487
- const code = params.get("room");
2488
- return code ? code.toUpperCase() : null;
2489
- };
2490
- var useAirJamController = (options = {}) => {
2491
- const { store, getSocket, disconnectSocket } = useAirJamContext();
2492
- const nicknameRef = useRef(options.nickname ?? "");
2493
- const subControllerParams = useMemo(() => {
2494
- if (typeof window === "undefined") return null;
2495
- const params = new URLSearchParams(window.location.search);
2496
- const room = params.get("aj_room");
2497
- const controllerId2 = params.get("aj_controller_id");
2498
- if (room && controllerId2) {
2499
- return { room, controllerId: controllerId2 };
2500
- }
2501
- return null;
2502
- }, []);
2503
- const parsedRoomId = useMemo(() => {
2504
- const code = subControllerParams?.room ?? options.roomId ?? getRoomFromLocation();
2505
- if (!code) return null;
2506
- try {
2507
- return roomCodeSchema.parse(code.toUpperCase());
2508
- } catch {
2509
- return null;
2510
- }
2511
- }, [options.roomId, subControllerParams]);
2512
- const controllerId = useMemo(() => {
2513
- if (subControllerParams?.controllerId) {
2514
- return subControllerParams.controllerId;
2515
- }
2516
- if (options.controllerId) {
2517
- return options.controllerId;
2518
- }
2519
- if (typeof window !== "undefined") {
2520
- const params = new URLSearchParams(window.location.search);
2521
- const urlControllerId = params.get("controllerId");
2522
- if (urlControllerId) return urlControllerId;
2523
- }
2524
- return generateControllerId();
2525
- }, [options.controllerId, subControllerParams]);
2526
- const onStateRef = useRef(
2527
- options.onState
2528
- );
2529
- useEffect(() => {
2530
- onStateRef.current = options.onState;
2531
- }, [options.onState]);
2532
- const connectionState = useStore(
2533
- store,
2534
- useShallow((state) => ({
2535
- connectionStatus: state.connectionStatus,
2536
- lastError: state.lastError,
2537
- controllerId: state.controllerId,
2538
- players: state.players,
2539
- gameState: state.gameState,
2540
- stateMessage: state.stateMessage
2541
- }))
2542
- );
2543
- const [reconnectKey, setReconnectKey] = useState(0);
2544
- const reconnect = useCallback(() => {
2545
- if (!parsedRoomId) return;
2546
- disconnectSocket("controller");
2547
- setReconnectKey((prev) => prev + 1);
2548
- }, [parsedRoomId, disconnectSocket]);
2549
- const isChildMode = useMemo(() => {
2550
- if (typeof window === "undefined") return false;
2551
- const params = new URLSearchParams(window.location.search);
2552
- return params.get("airjam_mode") === "child";
2553
- }, []);
2554
- const shouldConnect = useMemo(() => {
2555
- if (options.forceConnect) return true;
2556
- if (subControllerParams) return true;
2557
- if (typeof window !== "undefined") {
2558
- const params = new URLSearchParams(window.location.search);
2559
- return params.get("airjam_force_connect") === "true";
2560
- }
2561
- return false;
2562
- }, [options.forceConnect, subControllerParams]);
2563
- const canConnect = useMemo(
2564
- () => !isChildMode || shouldConnect,
2565
- [isChildMode, shouldConnect]
2566
- );
2567
- const socket = useMemo(
2568
- () => canConnect && parsedRoomId ? getSocket("controller") : null,
2569
- [canConnect, parsedRoomId, getSocket]
2570
- );
1920
+ var AirJamOverlay = () => {
1921
+ const host = useAirJamHost();
1922
+ const {
1923
+ roomId,
1924
+ joinUrl,
1925
+ connectionStatus,
1926
+ players,
1927
+ lastError,
1928
+ gameState,
1929
+ toggleGameState,
1930
+ isChildMode
1931
+ } = host;
1932
+ const [qrUrl, setQrUrl] = useState(null);
1933
+ const [qrError, setQrError] = useState(null);
1934
+ const [copied, setCopied] = useState(false);
1935
+ const [copiedPlayerId, setCopiedPlayerId] = useState(null);
2571
1936
  useEffect(() => {
2572
- if (!socket) return;
2573
- const handleSignal = (signal) => {
2574
- if (signal.type !== "HAPTIC") return;
2575
- if (typeof navigator === "undefined" || !navigator.vibrate) return;
2576
- const payload = signal.payload;
2577
- switch (payload.pattern) {
2578
- case "light":
2579
- navigator.vibrate(10);
2580
- break;
2581
- case "medium":
2582
- navigator.vibrate(30);
2583
- break;
2584
- case "heavy":
2585
- navigator.vibrate([50, 20, 50]);
2586
- break;
2587
- case "success":
2588
- navigator.vibrate([10, 30, 10]);
2589
- break;
2590
- case "failure":
2591
- navigator.vibrate([50, 50, 50, 50]);
2592
- break;
2593
- case "custom":
2594
- if (Array.isArray(payload.sequence)) {
2595
- navigator.vibrate(payload.sequence);
2596
- } else if (typeof payload.sequence === "number") {
2597
- navigator.vibrate(payload.sequence);
2598
- }
2599
- break;
1937
+ if (isChildMode) return;
1938
+ let mounted = true;
1939
+ QRCode.toDataURL(joinUrl, {
1940
+ margin: 1,
1941
+ color: {
1942
+ dark: "#0f172a",
1943
+ light: "#ffffff"
1944
+ },
1945
+ width: 320
1946
+ }).then((value) => {
1947
+ if (mounted) {
1948
+ setQrUrl(value);
1949
+ setQrError(null);
2600
1950
  }
2601
- };
2602
- socket.on("server:signal", handleSignal);
1951
+ }).catch((err) => {
1952
+ if (mounted) {
1953
+ setQrError(err.message);
1954
+ }
1955
+ });
2603
1956
  return () => {
2604
- socket.off("server:signal", handleSignal);
1957
+ mounted = false;
2605
1958
  };
2606
- }, [socket]);
2607
- useEffect(() => {
2608
- const storeState = store.getState();
2609
- storeState.setMode(detectRunMode());
2610
- storeState.setRole("controller");
2611
- storeState.setRoomId(parsedRoomId);
2612
- storeState.setStatus(parsedRoomId ? "connecting" : "idle");
2613
- storeState.setError(void 0);
2614
- if (!canConnect) {
2615
- storeState.setStatus("connected");
2616
- const handleMessage = (event) => {
2617
- if (event.source !== window.parent) return;
2618
- const data = event.data;
2619
- if (data?.type === "AIRJAM_STATE") {
2620
- const payload = data.payload;
2621
- if (payload.gameState) storeState.setGameState(payload.gameState);
2622
- if (payload.message !== void 0)
2623
- storeState.setStateMessage(payload.message);
2624
- onStateRef.current?.(payload);
2625
- }
2626
- };
2627
- window.addEventListener("message", handleMessage);
2628
- window.parent.postMessage({ type: "AIRJAM_READY" }, "*");
2629
- return () => {
2630
- window.removeEventListener("message", handleMessage);
2631
- storeState.setStatus("disconnected");
2632
- };
1959
+ }, [joinUrl, isChildMode]);
1960
+ const handleCopyUrl = async () => {
1961
+ if (!joinUrl) return;
1962
+ try {
1963
+ await navigator.clipboard.writeText(joinUrl);
1964
+ setCopied(true);
1965
+ setTimeout(() => setCopied(false), 2e3);
1966
+ } catch {
1967
+ const textArea = document.createElement("textarea");
1968
+ textArea.value = joinUrl;
1969
+ textArea.style.position = "fixed";
1970
+ textArea.style.opacity = "0";
1971
+ document.body.appendChild(textArea);
1972
+ textArea.select();
1973
+ try {
1974
+ document.execCommand("copy");
1975
+ setCopied(true);
1976
+ setTimeout(() => setCopied(false), 2e3);
1977
+ } catch {
1978
+ }
1979
+ document.body.removeChild(textArea);
2633
1980
  }
2634
- if (!parsedRoomId || !socket || !controllerId) {
2635
- storeState.setStatus("idle");
2636
- return;
1981
+ };
1982
+ const handleOpenInNewTab = () => {
1983
+ if (joinUrl) {
1984
+ window.open(joinUrl, "_blank", "noopener,noreferrer");
2637
1985
  }
2638
- storeState.setControllerId(controllerId);
2639
- const handleConnect = () => {
2640
- store.getState().setStatus("connected");
2641
- if (subControllerParams) {
2642
- return;
2643
- }
2644
- const payload = controllerJoinSchema.parse({
2645
- roomId: parsedRoomId,
2646
- controllerId,
2647
- nickname: nicknameRef.current || void 0
2648
- });
2649
- socket.emit("controller:join", payload, (ack) => {
2650
- const storeState2 = store.getState();
2651
- if (!ack.ok) {
2652
- storeState2.setError(ack.message ?? "Unable to join room");
2653
- storeState2.setStatus("disconnected");
2654
- return;
2655
- }
2656
- if (ack.controllerId) {
2657
- storeState2.setControllerId(ack.controllerId);
2658
- }
2659
- storeState2.setStatus("connected");
2660
- });
2661
- };
2662
- const handleDisconnect = () => {
2663
- store.getState().setStatus("disconnected");
2664
- };
2665
- const handleWelcome = (payload) => {
2666
- const storeState2 = store.getState();
2667
- const storeRoomId = storeState2.roomId;
2668
- if (storeRoomId && payload.roomId.toUpperCase() !== storeRoomId.toUpperCase()) {
2669
- return;
2670
- }
2671
- if (!storeRoomId && payload.roomId) {
2672
- storeState2.setRoomId(payload.roomId);
1986
+ };
1987
+ const handleCopyPlayerId = async (playerId) => {
1988
+ try {
1989
+ await navigator.clipboard.writeText(playerId);
1990
+ console.log(`Copied player ID: ${playerId}`);
1991
+ setCopiedPlayerId(playerId);
1992
+ setTimeout(() => setCopiedPlayerId(null), 1e3);
1993
+ } catch {
1994
+ const textArea = document.createElement("textarea");
1995
+ textArea.value = playerId;
1996
+ textArea.style.position = "fixed";
1997
+ textArea.style.opacity = "0";
1998
+ document.body.appendChild(textArea);
1999
+ textArea.select();
2000
+ try {
2001
+ document.execCommand("copy");
2002
+ console.log(`Copied player ID: ${playerId}`);
2003
+ setCopiedPlayerId(playerId);
2004
+ setTimeout(() => setCopiedPlayerId(null), 1e3);
2005
+ } catch {
2673
2006
  }
2674
- if (!payload.player) {
2675
- storeState2.setError(
2676
- "Welcome message received but no player profile included."
2677
- );
2678
- return;
2679
- }
2680
- storeState2.upsertPlayer(payload.player);
2681
- };
2682
- const handleState = (payload) => {
2683
- if (payload.roomId !== parsedRoomId) return;
2684
- const storeState2 = store.getState();
2685
- if (payload.state.gameState) {
2686
- storeState2.setGameState(payload.state.gameState);
2687
- }
2688
- if (payload.state.message !== void 0) {
2689
- storeState2.setStateMessage(payload.state.message);
2007
+ document.body.removeChild(textArea);
2008
+ }
2009
+ };
2010
+ const connectionVariant = useMemo(() => {
2011
+ switch (connectionStatus) {
2012
+ case "connected":
2013
+ return "default";
2014
+ case "connecting":
2015
+ case "reconnecting":
2016
+ return "secondary";
2017
+ default:
2018
+ return "destructive";
2019
+ }
2020
+ }, [connectionStatus]);
2021
+ if (isChildMode) return null;
2022
+ return /* @__PURE__ */ jsxs("div", { className: "dark", children: [
2023
+ !isChildMode && /* @__PURE__ */ jsx("div", { className: "pointer-events-none absolute inset-x-0 top-0 z-99999", children: /* @__PURE__ */ jsx("div", { className: "mx-auto w-full", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-4 py-2", children: [
2024
+ /* @__PURE__ */ jsx("div", { className: "flex items-center gap-3", children: /* @__PURE__ */ jsxs("div", { children: [
2025
+ /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs tracking-[0.18em] uppercase", children: "Room" }),
2026
+ /* @__PURE__ */ jsx("p", { className: "text-foreground text-lg font-semibold", children: roomId })
2027
+ ] }) }),
2028
+ /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2029
+ players.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-center -space-x-2", children: [
2030
+ players.slice(0, 4).map((player) => /* @__PURE__ */ jsx(PlayerAvatar, { player, size: "sm" }, player.id)),
2031
+ players.length > 4 && /* @__PURE__ */ jsxs("div", { className: "border-background bg-muted flex h-8 w-8 items-center justify-center rounded-full border-2 text-xs font-medium", children: [
2032
+ "+",
2033
+ players.length - 4
2034
+ ] })
2035
+ ] }),
2036
+ /* @__PURE__ */ jsx(
2037
+ Button,
2038
+ {
2039
+ type: "button",
2040
+ variant: "ghost",
2041
+ size: "icon",
2042
+ onClick: toggleGameState,
2043
+ "aria-label": gameState === "playing" ? "Pause" : "Play",
2044
+ className: "h-8 w-8",
2045
+ children: gameState === "playing" ? /* @__PURE__ */ jsx(Pause, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Play, { className: "h-4 w-4" })
2046
+ }
2047
+ )
2048
+ ] })
2049
+ ] }) }) }),
2050
+ gameState === "paused" && /* @__PURE__ */ jsx("div", { className: "pointer-events-none fixed inset-0 z-99998 flex items-center justify-center p-4", children: /* @__PURE__ */ jsx("div", { className: "pointer-events-auto w-full max-w-2xl", children: /* @__PURE__ */ jsx(Card, { className: "bg-card/20 flex max-h-[85vh] flex-col overflow-hidden border py-0 shadow-lg backdrop-blur-sm", children: /* @__PURE__ */ jsxs(
2051
+ Tabs,
2052
+ {
2053
+ defaultValue: isChildMode ? "settings" : "room-code",
2054
+ className: "flex h-full w-full flex-col gap-0",
2055
+ children: [
2056
+ /* @__PURE__ */ jsxs(TabsList, { className: "border-border grid w-full shrink-0 grid-cols-2 rounded-none border-b bg-transparent p-0", children: [
2057
+ !isChildMode && /* @__PURE__ */ jsxs(
2058
+ TabsTrigger,
2059
+ {
2060
+ value: "room-code",
2061
+ className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
2062
+ children: [
2063
+ /* @__PURE__ */ jsx(QrCode, { className: "h-4 w-4" }),
2064
+ "Room Code"
2065
+ ]
2066
+ }
2067
+ ),
2068
+ isChildMode && /* @__PURE__ */ jsxs(
2069
+ TabsTrigger,
2070
+ {
2071
+ value: "info",
2072
+ className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
2073
+ children: [
2074
+ /* @__PURE__ */ jsx(MonitorSmartphone, { className: "h-4 w-4" }),
2075
+ "Platform"
2076
+ ]
2077
+ }
2078
+ ),
2079
+ /* @__PURE__ */ jsxs(
2080
+ TabsTrigger,
2081
+ {
2082
+ value: "settings",
2083
+ className: "hover:bg-background/50 data-[state=active]:bg-background/50 flex items-center gap-2 rounded-none border-none bg-transparent",
2084
+ children: [
2085
+ /* @__PURE__ */ jsx(Settings, { className: "h-4 w-4" }),
2086
+ "Settings"
2087
+ ]
2088
+ }
2089
+ )
2090
+ ] }),
2091
+ !isChildMode && /* @__PURE__ */ jsx(
2092
+ TabsContent,
2093
+ {
2094
+ value: "room-code",
2095
+ className: "mt-0 min-h-0 flex-1 overflow-y-auto",
2096
+ children: /* @__PURE__ */ jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-6 md:grid-cols-[auto_1fr]", children: [
2097
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-start gap-4", children: [
2098
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
2099
+ /* @__PURE__ */ jsx(CardTitle, { className: "text-3xl font-bold tracking-wider", children: roomId }),
2100
+ /* @__PURE__ */ jsx(
2101
+ Badge,
2102
+ {
2103
+ variant: connectionVariant,
2104
+ className: "w-fit",
2105
+ children: statusCopy[connectionStatus]
2106
+ }
2107
+ )
2108
+ ] }),
2109
+ /* @__PURE__ */ jsx("div", { className: "border-border bg-card w-48 shrink-0 overflow-hidden rounded-lg border-2 shadow-md", children: qrUrl ? /* @__PURE__ */ jsx(
2110
+ "img",
2111
+ {
2112
+ src: qrUrl,
2113
+ alt: `Join room ${roomId}`,
2114
+ className: "w-full rounded bg-white"
2115
+ }
2116
+ ) : /* @__PURE__ */ jsx("div", { className: "text-muted-foreground flex h-48 items-center justify-center text-sm", children: qrError ? `QR failed: ${qrError}` : "Generating QR code\u2026" }) })
2117
+ ] }),
2118
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-6", children: [
2119
+ /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
2120
+ /* @__PURE__ */ jsx(CardDescription, { className: "text-xs tracking-[0.18em] uppercase", children: "Join URL" }),
2121
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
2122
+ /* @__PURE__ */ jsx(
2123
+ "input",
2124
+ {
2125
+ type: "text",
2126
+ readOnly: true,
2127
+ value: joinUrl,
2128
+ className: "bg-background border-input text-foreground focus:ring-ring flex h-10 w-full rounded-md border px-3 py-2 font-mono text-xs focus:ring-2 focus:ring-offset-2 focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
2129
+ }
2130
+ ),
2131
+ /* @__PURE__ */ jsx(
2132
+ Button,
2133
+ {
2134
+ type: "button",
2135
+ variant: "outline",
2136
+ size: "icon",
2137
+ onClick: handleCopyUrl,
2138
+ className: "h-10 shrink-0",
2139
+ "aria-label": "Copy join URL",
2140
+ children: copied ? /* @__PURE__ */ jsx(Check, { className: "h-4 w-4" }) : /* @__PURE__ */ jsx(Copy, { className: "h-4 w-4" })
2141
+ }
2142
+ ),
2143
+ /* @__PURE__ */ jsx(
2144
+ Button,
2145
+ {
2146
+ type: "button",
2147
+ variant: "outline",
2148
+ size: "icon",
2149
+ onClick: handleOpenInNewTab,
2150
+ className: "h-10 shrink-0",
2151
+ "aria-label": "Open join URL in new tab",
2152
+ children: /* @__PURE__ */ jsx(ExternalLink, { className: "h-4 w-4" })
2153
+ }
2154
+ )
2155
+ ] })
2156
+ ] }),
2157
+ /* @__PURE__ */ jsx("div", { className: "space-y-3", children: players.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-white", children: "Waiting for controllers to join\u2026" }) : /* @__PURE__ */ jsxs(Fragment, { children: [
2158
+ /* @__PURE__ */ jsxs("p", { className: "text-foreground text-sm font-medium", children: [
2159
+ "Connected Players (",
2160
+ players.length,
2161
+ ")"
2162
+ ] }),
2163
+ /* @__PURE__ */ jsx("ul", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3", children: players.map((player) => /* @__PURE__ */ jsx(
2164
+ "li",
2165
+ {
2166
+ className: "flex min-w-0 flex-col items-start gap-2",
2167
+ children: /* @__PURE__ */ jsxs("div", { className: "flex w-full min-w-0 items-center gap-2", children: [
2168
+ /* @__PURE__ */ jsx(
2169
+ PlayerAvatar,
2170
+ {
2171
+ player,
2172
+ size: "md"
2173
+ }
2174
+ ),
2175
+ /* @__PURE__ */ jsxs("div", { className: "flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden", children: [
2176
+ /* @__PURE__ */ jsx("span", { className: "text-card-foreground truncate text-sm font-medium", children: player.label }),
2177
+ /* @__PURE__ */ jsx(
2178
+ "div",
2179
+ {
2180
+ onClick: () => handleCopyPlayerId(player.id),
2181
+ className: "text-muted-foreground m-0 inline min-w-0 cursor-pointer truncate border-0 font-mono text-xs transition-colors hover:text-white",
2182
+ title: "Click to copy player ID",
2183
+ children: copiedPlayerId === player.id ? "Copied!" : player.id.slice(0, 8)
2184
+ }
2185
+ )
2186
+ ] })
2187
+ ] })
2188
+ },
2189
+ player.id
2190
+ )) })
2191
+ ] }) }),
2192
+ lastError && /* @__PURE__ */ jsx(Alert, { variant: "destructive", className: "w-full", children: /* @__PURE__ */ jsx(AlertDescription, { children: lastError }) }),
2193
+ /* @__PURE__ */ jsx("div", { className: "mt-auto flex justify-end", children: /* @__PURE__ */ jsxs(
2194
+ Button,
2195
+ {
2196
+ type: "button",
2197
+ onClick: toggleGameState,
2198
+ size: "lg",
2199
+ children: [
2200
+ /* @__PURE__ */ jsx(Play, { className: "mr-2 h-5 w-5" }),
2201
+ "Play"
2202
+ ]
2203
+ }
2204
+ ) })
2205
+ ] })
2206
+ ] }) })
2207
+ }
2208
+ ),
2209
+ isChildMode && /* @__PURE__ */ jsx(
2210
+ TabsContent,
2211
+ {
2212
+ value: "info",
2213
+ className: "mt-0 min-h-0 flex-1 overflow-y-auto",
2214
+ children: /* @__PURE__ */ jsx("div", { className: "p-6", children: /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
2215
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
2216
+ /* @__PURE__ */ jsx(CardTitle, { className: "text-2xl font-bold tracking-wider", children: "Connected to Platform" }),
2217
+ /* @__PURE__ */ jsx(CardDescription, { children: "This game is running inside the Air Jam Platform." })
2218
+ ] }),
2219
+ /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
2220
+ /* @__PURE__ */ jsxs("p", { className: "text-foreground text-sm font-medium", children: [
2221
+ "Connected Players (",
2222
+ players.length,
2223
+ ")"
2224
+ ] }),
2225
+ /* @__PURE__ */ jsx("ul", { className: "grid grid-cols-2 gap-3 sm:grid-cols-3", children: players.map((player) => /* @__PURE__ */ jsx(
2226
+ "li",
2227
+ {
2228
+ className: "flex min-w-0 flex-col items-start gap-2",
2229
+ children: /* @__PURE__ */ jsxs("div", { className: "flex w-full min-w-0 items-center gap-2", children: [
2230
+ /* @__PURE__ */ jsx(PlayerAvatar, { player, size: "md" }),
2231
+ /* @__PURE__ */ jsx("div", { className: "flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden", children: /* @__PURE__ */ jsx("span", { className: "text-card-foreground truncate text-sm font-medium", children: player.label }) })
2232
+ ] })
2233
+ },
2234
+ player.id
2235
+ )) })
2236
+ ] }),
2237
+ /* @__PURE__ */ jsx("div", { className: "pt-2", children: /* @__PURE__ */ jsxs(
2238
+ Button,
2239
+ {
2240
+ type: "button",
2241
+ onClick: toggleGameState,
2242
+ size: "lg",
2243
+ children: [
2244
+ /* @__PURE__ */ jsx(Play, { className: "mr-2 h-5 w-5" }),
2245
+ "Resume Game"
2246
+ ]
2247
+ }
2248
+ ) })
2249
+ ] }) })
2250
+ }
2251
+ ),
2252
+ /* @__PURE__ */ jsx(
2253
+ TabsContent,
2254
+ {
2255
+ value: "settings",
2256
+ className: "mt-0 min-h-0 flex-1 overflow-y-auto",
2257
+ children: /* @__PURE__ */ jsx(CardContent, { className: "pt-6 pb-6", children: /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
2258
+ /* @__PURE__ */ jsx("div", { className: "space-y-4", children: /* @__PURE__ */ jsx(VolumeControls, {}) }),
2259
+ /* @__PURE__ */ jsxs("div", { className: "space-y-4 border-t pt-4", children: [
2260
+ /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: "Connection" }),
2261
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
2262
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
2263
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: "Status" }),
2264
+ /* @__PURE__ */ jsx(Badge, { variant: connectionVariant, children: statusCopy[connectionStatus] })
2265
+ ] }),
2266
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
2267
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: "Room ID" }),
2268
+ /* @__PURE__ */ jsx("span", { className: "font-mono text-sm", children: roomId })
2269
+ ] }),
2270
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
2271
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: "Players" }),
2272
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-medium", children: players.length })
2273
+ ] })
2274
+ ] })
2275
+ ] }),
2276
+ /* @__PURE__ */ jsxs("div", { className: "space-y-4 border-t pt-4", children: [
2277
+ /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: "Display" }),
2278
+ /* @__PURE__ */ jsx("div", { className: "space-y-2", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
2279
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-sm", children: "Game State" }),
2280
+ /* @__PURE__ */ jsx(Badge, { variant: "outline", className: "capitalize", children: gameState })
2281
+ ] }) })
2282
+ ] })
2283
+ ] }) })
2284
+ }
2285
+ )
2286
+ ]
2690
2287
  }
2691
- onStateRef.current?.(payload.state);
2692
- };
2693
- const handleHostLeft = (payload) => {
2694
- const storeState2 = store.getState();
2695
- storeState2.setError(payload.reason);
2696
- storeState2.setStatus("disconnected");
2697
- storeState2.resetGameState();
2698
- setTimeout(() => {
2699
- disconnectSocket("controller");
2700
- setReconnectKey((prev) => prev + 1);
2701
- }, 1e3);
2702
- };
2703
- const handleError = (payload) => {
2704
- store.getState().setError(payload.message);
2288
+ ) }) }) })
2289
+ ] });
2290
+ };
2291
+ var useFullscreen = () => {
2292
+ const [isFullscreen, setIsFullscreen] = useState(false);
2293
+ useEffect(() => {
2294
+ const handleFullscreenChange = () => {
2295
+ const doc = document;
2296
+ setIsFullscreen(
2297
+ !!(document.fullscreenElement || doc.webkitFullscreenElement || doc.mozFullScreenElement || doc.msFullscreenElement)
2298
+ );
2705
2299
  };
2706
- socket.on("connect", handleConnect);
2707
- socket.on("disconnect", handleDisconnect);
2708
- socket.on("server:welcome", handleWelcome);
2709
- socket.on("server:state", handleState);
2710
- socket.on("server:hostLeft", handleHostLeft);
2711
- socket.on("server:error", handleError);
2712
- socket.connect();
2300
+ document.addEventListener("fullscreenchange", handleFullscreenChange);
2301
+ document.addEventListener("webkitfullscreenchange", handleFullscreenChange);
2302
+ document.addEventListener("mozfullscreenchange", handleFullscreenChange);
2303
+ document.addEventListener("msfullscreenchange", handleFullscreenChange);
2713
2304
  return () => {
2714
- socket.off("connect", handleConnect);
2715
- socket.off("disconnect", handleDisconnect);
2716
- socket.off("server:welcome", handleWelcome);
2717
- socket.off("server:state", handleState);
2718
- socket.off("server:hostLeft", handleHostLeft);
2719
- socket.off("server:error", handleError);
2305
+ document.removeEventListener("fullscreenchange", handleFullscreenChange);
2306
+ document.removeEventListener(
2307
+ "webkitfullscreenchange",
2308
+ handleFullscreenChange
2309
+ );
2310
+ document.removeEventListener(
2311
+ "mozfullscreenchange",
2312
+ handleFullscreenChange
2313
+ );
2314
+ document.removeEventListener(
2315
+ "msfullscreenchange",
2316
+ handleFullscreenChange
2317
+ );
2720
2318
  };
2721
- }, [
2722
- parsedRoomId,
2723
- reconnectKey,
2724
- canConnect,
2725
- socket,
2726
- controllerId,
2727
- subControllerParams,
2728
- store,
2729
- disconnectSocket
2730
- ]);
2731
- const setNickname = useCallback((value) => {
2732
- nicknameRef.current = value;
2733
2319
  }, []);
2734
- const sendInput = useCallback(
2735
- (input) => {
2736
- const storeState = store.getState();
2737
- if (!canConnect) {
2738
- if (typeof window !== "undefined") {
2739
- window.parent.postMessage(
2740
- {
2741
- type: "AIRJAM_INPUT",
2742
- payload: input
2743
- },
2744
- "*"
2745
- );
2320
+ const exitFullscreen = useCallback(async () => {
2321
+ try {
2322
+ const doc = document;
2323
+ if (document.fullscreenElement || doc.webkitFullscreenElement || doc.mozFullScreenElement || doc.msFullscreenElement) {
2324
+ if (document.exitFullscreen) {
2325
+ await document.exitFullscreen();
2326
+ } else if (doc.webkitExitFullscreen) {
2327
+ await doc.webkitExitFullscreen();
2328
+ } else if (doc.mozCancelFullScreen) {
2329
+ await doc.mozCancelFullScreen();
2330
+ } else if (doc.msExitFullscreen) {
2331
+ await doc.msExitFullscreen();
2746
2332
  }
2747
- return true;
2748
- }
2749
- if (!parsedRoomId || !storeState.controllerId || !socket) {
2750
- storeState.setError("Not connected to a room");
2751
- return false;
2752
- }
2753
- if (!socket.connected) {
2754
- return false;
2755
- }
2756
- if (typeof input !== "object" || input === null || Array.isArray(input)) {
2757
- storeState.setError("Input must be an object");
2758
- return false;
2759
2333
  }
2760
- const payload = controllerInputSchema.safeParse({
2761
- roomId: parsedRoomId,
2762
- controllerId: storeState.controllerId,
2763
- input
2764
- });
2765
- if (!payload.success) {
2766
- storeState.setError(payload.error.message);
2767
- return false;
2334
+ } catch (error) {
2335
+ console.error("Error exiting fullscreen:", error);
2336
+ }
2337
+ }, []);
2338
+ const enterFullscreen = useCallback(async (element) => {
2339
+ try {
2340
+ const elem = element || document.documentElement;
2341
+ if (elem.requestFullscreen) {
2342
+ await elem.requestFullscreen();
2343
+ } else if (elem.webkitRequestFullscreen) {
2344
+ await elem.webkitRequestFullscreen();
2345
+ } else if (elem.mozRequestFullScreen) {
2346
+ await elem.mozRequestFullScreen();
2347
+ } else if (elem.msRequestFullscreen) {
2348
+ await elem.msRequestFullscreen();
2768
2349
  }
2769
- socket.emit("controller:input", payload.data);
2770
- return true;
2771
- },
2772
- [parsedRoomId, canConnect, socket, store]
2773
- );
2774
- const sendSystemCommand = useCallback(
2775
- (command) => {
2776
- const storeState = store.getState();
2777
- if (!canConnect) return;
2778
- if (!parsedRoomId || !storeState.controllerId || !socket) return;
2779
- if (!socket.connected) return;
2780
- const payload = controllerSystemSchema.safeParse({
2781
- roomId: parsedRoomId,
2782
- command
2783
- });
2784
- if (payload.success) {
2785
- socket.emit("controller:system", payload.data);
2350
+ } catch (error) {
2351
+ console.error("Error entering fullscreen:", error);
2352
+ }
2353
+ }, []);
2354
+ const toggleFullscreen = useCallback(
2355
+ async (element) => {
2356
+ if (isFullscreen) {
2357
+ await exitFullscreen();
2358
+ } else {
2359
+ await enterFullscreen(element);
2786
2360
  }
2787
2361
  },
2788
- [parsedRoomId, canConnect, socket, store]
2362
+ [isFullscreen, exitFullscreen, enterFullscreen]
2789
2363
  );
2790
2364
  return {
2791
- roomId: parsedRoomId,
2792
- controllerId: connectionState.controllerId,
2793
- connectionStatus: connectionState.connectionStatus,
2794
- lastError: connectionState.lastError,
2795
- gameState: connectionState.gameState,
2796
- stateMessage: connectionState.stateMessage,
2797
- sendInput,
2798
- sendSystemCommand,
2799
- setNickname,
2800
- reconnect,
2801
- players: connectionState.players,
2802
- socket
2365
+ isFullscreen,
2366
+ enterFullscreen,
2367
+ exitFullscreen,
2368
+ toggleFullscreen
2803
2369
  };
2804
2370
  };
2805
- var useAirJamHost = (options = {}) => {
2806
- const { config, store, getSocket, disconnectSocket, inputManager } = useAirJamContext();
2807
- const arcadeParams = useMemo(() => {
2371
+ var extractRoomCode = (text) => {
2372
+ try {
2373
+ const url = new URL(text);
2374
+ const roomParam = url.searchParams.get("room");
2375
+ if (roomParam) {
2376
+ const parsed2 = roomCodeSchema.safeParse(roomParam.toUpperCase());
2377
+ if (parsed2.success) {
2378
+ return parsed2.data;
2379
+ }
2380
+ }
2381
+ } catch {
2382
+ }
2383
+ const parsed = roomCodeSchema.safeParse(text.trim().toUpperCase());
2384
+ if (parsed.success) {
2385
+ return parsed.data;
2386
+ }
2387
+ return null;
2388
+ };
2389
+ var QRScannerDialog = ({
2390
+ isOpen,
2391
+ onClose,
2392
+ onScan,
2393
+ currentRoomId
2394
+ }) => {
2395
+ const [code, setCode] = useState("");
2396
+ const [isCameraAvailable, setIsCameraAvailable] = useState(false);
2397
+ const [joinUrl, setJoinUrl] = useState("");
2398
+ const [copied, setCopied] = useState(false);
2399
+ const scannerRef = useRef(null);
2400
+ const inputRef = useRef(null);
2401
+ const prevIsOpenRef = useRef(false);
2402
+ useEffect(() => {
2403
+ if (isOpen && !prevIsOpenRef.current) {
2404
+ const initialCode = currentRoomId || "";
2405
+ setTimeout(() => {
2406
+ setIsCameraAvailable(false);
2407
+ setCode(initialCode);
2408
+ inputRef.current?.focus();
2409
+ inputRef.current?.select();
2410
+ }, 0);
2411
+ }
2412
+ prevIsOpenRef.current = isOpen;
2413
+ }, [isOpen, currentRoomId]);
2414
+ useEffect(() => {
2415
+ const buildUrl = async () => {
2416
+ const trimmed = code.trim().toUpperCase();
2417
+ const parsed = roomCodeSchema.safeParse(trimmed);
2418
+ if (parsed.success) {
2419
+ try {
2420
+ const url = await urlBuilder.buildControllerUrl(parsed.data);
2421
+ setJoinUrl(url);
2422
+ } catch {
2423
+ setJoinUrl("");
2424
+ }
2425
+ } else {
2426
+ setJoinUrl("");
2427
+ }
2428
+ };
2429
+ buildUrl();
2430
+ }, [code]);
2431
+ useEffect(() => {
2432
+ if (!isOpen) {
2433
+ setTimeout(() => {
2434
+ setIsCameraAvailable(false);
2435
+ }, 0);
2436
+ if (scannerRef.current) {
2437
+ const scanner = scannerRef.current;
2438
+ scanner.stop().catch(() => {
2439
+ }).finally(() => {
2440
+ try {
2441
+ scanner.clear();
2442
+ } catch {
2443
+ }
2444
+ });
2445
+ scannerRef.current = null;
2446
+ }
2447
+ }
2448
+ }, [isOpen]);
2449
+ useEffect(() => {
2450
+ if (!isOpen) {
2451
+ return;
2452
+ }
2453
+ const containerId = "qr-reader";
2454
+ let scanner = null;
2455
+ let scannerRunning = false;
2456
+ let mounted = true;
2457
+ const startScanning = async () => {
2458
+ try {
2459
+ const container = document.getElementById(containerId);
2460
+ if (!container) {
2461
+ return;
2462
+ }
2463
+ const rect = container.getBoundingClientRect();
2464
+ if (rect.width === 0 || rect.height === 0) {
2465
+ return;
2466
+ }
2467
+ scanner = new Html5Qrcode(containerId);
2468
+ scannerRef.current = scanner;
2469
+ let cameraId = null;
2470
+ try {
2471
+ const devices = await Html5Qrcode.getCameras();
2472
+ if (devices && devices.length > 0) {
2473
+ const backCamera = devices.find(
2474
+ (d) => d.label.toLowerCase().includes("back") || d.label.toLowerCase().includes("rear")
2475
+ );
2476
+ const envCamera = devices.find((d) => {
2477
+ const label = d.label.toLowerCase();
2478
+ return label.includes("environment") || label.includes("facing back");
2479
+ });
2480
+ cameraId = (envCamera || backCamera || devices[0])?.id || null;
2481
+ }
2482
+ } catch {
2483
+ }
2484
+ const config = cameraId ? { deviceId: { exact: cameraId } } : { facingMode: "environment" };
2485
+ await scanner.start(
2486
+ config,
2487
+ {
2488
+ fps: 10,
2489
+ qrbox: (viewfinderWidth, viewfinderHeight) => {
2490
+ const minEdge = Math.min(viewfinderWidth, viewfinderHeight);
2491
+ const qrboxSize = Math.min(250, minEdge * 0.8);
2492
+ return {
2493
+ width: qrboxSize,
2494
+ height: qrboxSize
2495
+ };
2496
+ },
2497
+ aspectRatio: 1
2498
+ },
2499
+ (decodedText) => {
2500
+ if (!mounted) return;
2501
+ const roomCode = extractRoomCode(decodedText);
2502
+ if (roomCode) {
2503
+ setCode(roomCode);
2504
+ scannerRunning = false;
2505
+ scanner?.stop().catch(() => {
2506
+ }).finally(() => {
2507
+ if (mounted) {
2508
+ setIsCameraAvailable(false);
2509
+ }
2510
+ });
2511
+ }
2512
+ },
2513
+ () => {
2514
+ }
2515
+ );
2516
+ scannerRunning = true;
2517
+ if (mounted) {
2518
+ setIsCameraAvailable(true);
2519
+ }
2520
+ } catch {
2521
+ if (mounted) {
2522
+ setIsCameraAvailable(false);
2523
+ }
2524
+ if (scanner) {
2525
+ try {
2526
+ scanner.clear();
2527
+ } catch {
2528
+ }
2529
+ }
2530
+ scannerRef.current = null;
2531
+ }
2532
+ };
2533
+ const timeoutId = setTimeout(() => {
2534
+ startScanning();
2535
+ }, 200);
2536
+ return () => {
2537
+ mounted = false;
2538
+ clearTimeout(timeoutId);
2539
+ if (scanner && scannerRunning) {
2540
+ scanner.stop().catch(() => {
2541
+ }).finally(() => {
2542
+ try {
2543
+ scanner?.clear();
2544
+ } catch {
2545
+ }
2546
+ });
2547
+ } else if (scanner) {
2548
+ try {
2549
+ scanner.clear();
2550
+ } catch {
2551
+ }
2552
+ }
2553
+ scannerRef.current = null;
2554
+ };
2555
+ }, [isOpen]);
2556
+ const handleSubmit = () => {
2557
+ const trimmed = code.trim().toUpperCase();
2558
+ const parsed = roomCodeSchema.safeParse(trimmed);
2559
+ if (parsed.success) {
2560
+ onScan(parsed.data);
2561
+ onClose();
2562
+ }
2563
+ };
2564
+ const handleInputFocus = (e) => {
2565
+ e.target.select();
2566
+ };
2567
+ const handleInputChange = (e) => {
2568
+ setCode(e.target.value.toUpperCase());
2569
+ setCopied(false);
2570
+ };
2571
+ const handleCopyUrl = async () => {
2572
+ if (!joinUrl) return;
2573
+ try {
2574
+ await navigator.clipboard.writeText(joinUrl);
2575
+ setCopied(true);
2576
+ setTimeout(() => setCopied(false), 2e3);
2577
+ } catch {
2578
+ const textArea = document.createElement("textarea");
2579
+ textArea.value = joinUrl;
2580
+ textArea.style.position = "fixed";
2581
+ textArea.style.opacity = "0";
2582
+ document.body.appendChild(textArea);
2583
+ textArea.select();
2584
+ try {
2585
+ document.execCommand("copy");
2586
+ setCopied(true);
2587
+ setTimeout(() => setCopied(false), 2e3);
2588
+ } catch {
2589
+ }
2590
+ document.body.removeChild(textArea);
2591
+ }
2592
+ };
2593
+ if (!isOpen) {
2594
+ return null;
2595
+ }
2596
+ const isValid = code.trim().length > 0;
2597
+ return /* @__PURE__ */ jsxs("div", { className: "bg-background fixed inset-0 z-50 flex flex-col items-center justify-center", children: [
2598
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-1 flex-col items-center justify-center", children: [
2599
+ isCameraAvailable && /* @__PURE__ */ jsx("div", { className: "relative flex aspect-square w-full items-center justify-center overflow-hidden p-6", children: /* @__PURE__ */ jsx(
2600
+ "div",
2601
+ {
2602
+ id: "qr-reader",
2603
+ className: "h-full w-full overflow-hidden rounded-lg bg-black"
2604
+ }
2605
+ ) }),
2606
+ /* @__PURE__ */ jsx("div", { className: "w-full max-w-md px-6", children: /* @__PURE__ */ jsx(
2607
+ "input",
2608
+ {
2609
+ ref: inputRef,
2610
+ type: "text",
2611
+ value: code,
2612
+ onChange: handleInputChange,
2613
+ onFocus: handleInputFocus,
2614
+ onKeyDown: (e) => {
2615
+ if (e.key === "Enter" && isValid) {
2616
+ handleSubmit();
2617
+ }
2618
+ },
2619
+ placeholder: "Enter room code",
2620
+ 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",
2621
+ autoComplete: "off",
2622
+ autoCapitalize: "characters"
2623
+ }
2624
+ ) }),
2625
+ joinUrl && /* @__PURE__ */ jsx("div", { className: "mt-4 w-full max-w-md px-6 pb-2", children: /* @__PURE__ */ jsx(
2626
+ "button",
2627
+ {
2628
+ type: "button",
2629
+ onClick: handleCopyUrl,
2630
+ 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",
2631
+ children: copied ? "\u2713 Copied!" : joinUrl
2632
+ }
2633
+ ) })
2634
+ ] }),
2635
+ /* @__PURE__ */ jsxs("div", { className: "flex w-full max-w-md gap-4 px-6 pb-6", children: [
2636
+ /* @__PURE__ */ jsx(
2637
+ Button,
2638
+ {
2639
+ type: "button",
2640
+ variant: "outline",
2641
+ onClick: onClose,
2642
+ className: "flex-1 py-6",
2643
+ children: "Cancel"
2644
+ }
2645
+ ),
2646
+ /* @__PURE__ */ jsx(
2647
+ Button,
2648
+ {
2649
+ type: "button",
2650
+ onClick: handleSubmit,
2651
+ disabled: !isValid,
2652
+ className: "flex-1 py-6",
2653
+ children: "Connect"
2654
+ }
2655
+ )
2656
+ ] })
2657
+ ] });
2658
+ };
2659
+ var describeStatus = (status) => {
2660
+ switch (status) {
2661
+ case "connected":
2662
+ return "Connected to host";
2663
+ case "connecting":
2664
+ return "Connecting\u2026";
2665
+ case "reconnecting":
2666
+ return "Trying to reconnect\u2026";
2667
+ case "disconnected":
2668
+ return "Disconnected";
2669
+ case "idle":
2670
+ default:
2671
+ return "Idle";
2672
+ }
2673
+ };
2674
+ var orientationMatches = (required) => {
2675
+ if (!required) return true;
2676
+ if (typeof window === "undefined" || !window.matchMedia) return true;
2677
+ const matcher = window.matchMedia(`(orientation: ${required})`);
2678
+ return matcher.matches;
2679
+ };
2680
+ var ControllerShell = ({
2681
+ roomId,
2682
+ connectionStatus,
2683
+ forceOrientation,
2684
+ children,
2685
+ gameState = "paused",
2686
+ onTogglePlayPause,
2687
+ onReconnect,
2688
+ onRefresh,
2689
+ customActions
2690
+ }) => {
2691
+ const isChildMode = useMemo(() => detectRunMode() === "platform", []);
2692
+ const [isOrientationOk, setOrientationOk] = useState(
2693
+ () => orientationMatches(forceOrientation)
2694
+ );
2695
+ const [isScannerOpen, setIsScannerOpen] = useState(false);
2696
+ const { isFullscreen, toggleFullscreen } = useFullscreen();
2697
+ const { store } = useAirJamContext();
2698
+ const { controllerId, players } = useStore(
2699
+ store,
2700
+ useShallow(
2701
+ (state) => ({
2702
+ controllerId: state.controllerId,
2703
+ players: state.players
2704
+ })
2705
+ )
2706
+ );
2707
+ const currentPlayer = useMemo(() => {
2708
+ if (!controllerId) return null;
2709
+ const found = players.find((p) => p.id === controllerId);
2710
+ if (!found && connectionStatus === "connected" && players.length > 0) ;
2711
+ return found || null;
2712
+ }, [controllerId, players, connectionStatus]);
2713
+ useEffect(() => {
2714
+ if (!forceOrientation) {
2715
+ setOrientationOk(true);
2716
+ return;
2717
+ }
2718
+ const media = window.matchMedia(`(orientation: ${forceOrientation})`);
2719
+ const handleChange = () => setOrientationOk(media.matches);
2720
+ handleChange();
2721
+ media.addEventListener("change", handleChange);
2722
+ return () => media.removeEventListener("change", handleChange);
2723
+ }, [forceOrientation]);
2724
+ const orientationOk = !forceOrientation ? true : isOrientationOk;
2725
+ const statusDotColor = useMemo(() => {
2726
+ switch (connectionStatus) {
2727
+ case "connected":
2728
+ return "bg-green-500";
2729
+ case "connecting":
2730
+ case "reconnecting":
2731
+ return "bg-yellow-500";
2732
+ case "disconnected":
2733
+ default:
2734
+ return "bg-red-500";
2735
+ }
2736
+ }, [connectionStatus]);
2737
+ if (isChildMode) {
2738
+ return /* @__PURE__ */ jsx("div", { className: "dark", children: /* @__PURE__ */ jsx("div", { className: "text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden bg-transparent select-none", children: /* @__PURE__ */ jsxs("main", { className: "relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4", children: [
2739
+ !orientationOk && /* @__PURE__ */ jsxs("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", children: [
2740
+ /* @__PURE__ */ jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2741
+ /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2742
+ "This game is best experienced in ",
2743
+ forceOrientation,
2744
+ " ",
2745
+ "orientation."
2746
+ ] })
2747
+ ] }),
2748
+ /* @__PURE__ */ jsx(
2749
+ "div",
2750
+ {
2751
+ className: cn(
2752
+ "h-full w-full select-none",
2753
+ !orientationOk && "pointer-events-none opacity-30"
2754
+ ),
2755
+ children
2756
+ }
2757
+ )
2758
+ ] }) }) });
2759
+ }
2760
+ return /* @__PURE__ */ jsx("div", { className: "dark", children: /* @__PURE__ */ jsxs("div", { className: "bg-background text-foreground relative flex h-dvh w-dvw touch-none flex-col overflow-hidden select-none", children: [
2761
+ /* @__PURE__ */ jsxs("header", { className: "pointer-events-none sticky top-0 z-50 flex items-center justify-between border-b px-6 py-2", children: [
2762
+ /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2763
+ typeof window !== "undefined" && (currentPlayer || controllerId) && /* @__PURE__ */ jsxs(
2764
+ "div",
2765
+ {
2766
+ className: "relative",
2767
+ title: describeStatus(connectionStatus),
2768
+ children: [
2769
+ currentPlayer ? /* @__PURE__ */ jsx(PlayerAvatar, { player: currentPlayer, size: "sm" }) : controllerId ? /* @__PURE__ */ jsx(
2770
+ PlayerAvatar,
2771
+ {
2772
+ player: {
2773
+ id: controllerId,
2774
+ label: "Player"
2775
+ },
2776
+ size: "sm"
2777
+ }
2778
+ ) : null,
2779
+ /* @__PURE__ */ jsx(
2780
+ "span",
2781
+ {
2782
+ className: "absolute right-0 bottom-0 h-3 w-3 rounded-full bg-black",
2783
+ "aria-hidden": "true"
2784
+ }
2785
+ ),
2786
+ /* @__PURE__ */ jsx(
2787
+ "span",
2788
+ {
2789
+ className: cn(
2790
+ "absolute right-0.5 bottom-0.5 h-2 w-2 rounded-full",
2791
+ statusDotColor,
2792
+ connectionStatus === "connected" && "animate-pulse"
2793
+ ),
2794
+ "aria-label": describeStatus(connectionStatus)
2795
+ }
2796
+ )
2797
+ ]
2798
+ }
2799
+ ),
2800
+ /* @__PURE__ */ jsxs("div", { children: [
2801
+ /* @__PURE__ */ jsx("p", { className: "text-muted-foreground text-xs tracking-[0.24em] uppercase", children: "Room" }),
2802
+ /* @__PURE__ */ jsx("p", { className: "text-foreground text-lg font-semibold", children: typeof window !== "undefined" ? roomId ?? "N/A" : "N/A" })
2803
+ ] })
2804
+ ] }),
2805
+ /* @__PURE__ */ jsxs("div", { className: "pointer-events-auto flex items-center gap-3", children: [
2806
+ customActions,
2807
+ onRefresh && roomId && /* @__PURE__ */ jsx(
2808
+ Button,
2809
+ {
2810
+ type: "button",
2811
+ variant: "outline",
2812
+ size: "icon",
2813
+ onClick: onRefresh,
2814
+ disabled: connectionStatus === "connecting" || connectionStatus === "reconnecting",
2815
+ "aria-label": "Reconnect",
2816
+ title: "Reconnect to room",
2817
+ children: /* @__PURE__ */ jsx(
2818
+ RefreshCw,
2819
+ {
2820
+ className: cn(
2821
+ "h-5 w-5",
2822
+ (connectionStatus === "connecting" || connectionStatus === "reconnecting") && "animate-spin"
2823
+ )
2824
+ }
2825
+ )
2826
+ }
2827
+ ),
2828
+ onReconnect && /* @__PURE__ */ jsx(
2829
+ Button,
2830
+ {
2831
+ type: "button",
2832
+ variant: "outline",
2833
+ size: "icon",
2834
+ onClick: () => setIsScannerOpen(true),
2835
+ "aria-label": "Scan QR code to reconnect",
2836
+ title: "Scan QR code to reconnect",
2837
+ children: /* @__PURE__ */ jsx(QrCode, { className: "h-5 w-5" })
2838
+ }
2839
+ ),
2840
+ onTogglePlayPause && /* @__PURE__ */ jsx(
2841
+ Button,
2842
+ {
2843
+ type: "button",
2844
+ variant: "outline",
2845
+ size: "icon",
2846
+ onClick: onTogglePlayPause,
2847
+ "aria-label": gameState === "playing" ? "Pause" : "Play",
2848
+ title: gameState === "playing" ? "Pause" : "Play",
2849
+ children: gameState === "playing" ? /* @__PURE__ */ jsx(Pause, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Play, { className: "h-5 w-5" })
2850
+ }
2851
+ ),
2852
+ /* @__PURE__ */ jsx(
2853
+ Button,
2854
+ {
2855
+ type: "button",
2856
+ variant: "outline",
2857
+ size: "icon",
2858
+ onClick: () => toggleFullscreen(),
2859
+ "aria-label": isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2860
+ title: isFullscreen ? "Exit fullscreen" : "Enter fullscreen",
2861
+ children: isFullscreen ? /* @__PURE__ */ jsx(Minimize, { className: "h-5 w-5" }) : /* @__PURE__ */ jsx(Maximize, { className: "h-5 w-5" })
2862
+ }
2863
+ )
2864
+ ] })
2865
+ ] }),
2866
+ /* @__PURE__ */ jsx("main", { className: "relative flex min-h-0 flex-1 items-center justify-center overflow-hidden p-2 select-none sm:p-4", children: /* @__PURE__ */ jsxs("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", children: [
2867
+ !orientationOk && forceOrientation && /* @__PURE__ */ jsxs("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", children: [
2868
+ /* @__PURE__ */ jsx("p", { className: "text-card-foreground text-xl font-semibold", children: "Rotate your device" }),
2869
+ /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground mt-2 text-sm", children: [
2870
+ "This game is best experienced in ",
2871
+ forceOrientation,
2872
+ " ",
2873
+ "orientation."
2874
+ ] })
2875
+ ] }),
2876
+ /* @__PURE__ */ jsx(
2877
+ "div",
2878
+ {
2879
+ className: cn(
2880
+ "h-full w-full select-none",
2881
+ !orientationOk && "pointer-events-none opacity-30"
2882
+ ),
2883
+ children
2884
+ }
2885
+ )
2886
+ ] }) }),
2887
+ onReconnect && /* @__PURE__ */ jsx(
2888
+ QRScannerDialog,
2889
+ {
2890
+ isOpen: isScannerOpen,
2891
+ onClose: () => setIsScannerOpen(false),
2892
+ onScan: (roomCode) => {
2893
+ onReconnect(roomCode);
2894
+ setIsScannerOpen(false);
2895
+ },
2896
+ currentRoomId: roomId
2897
+ }
2898
+ )
2899
+ ] }) });
2900
+ };
2901
+
2902
+ // src/events.ts
2903
+ var HostEvents = {
2904
+ /**
2905
+ * Register as a master host (standalone mode)
2906
+ */
2907
+ REGISTER: "host:register",
2908
+ /**
2909
+ * Register as the system/arcade master host
2910
+ */
2911
+ REGISTER_SYSTEM: "host:registerSystem",
2912
+ /**
2913
+ * Join as a child host (game launched from arcade)
2914
+ */
2915
+ JOIN_AS_CHILD: "host:joinAsChild"
2916
+ };
2917
+ var ControllerEvents = {
2918
+ /**
2919
+ * Controller joins a room
2920
+ */
2921
+ JOIN: "controller:join",
2922
+ /**
2923
+ * Controller sends input
2924
+ */
2925
+ INPUT: "controller:input",
2926
+ /**
2927
+ * Controller leaves a room
2928
+ */
2929
+ LEAVE: "controller:leave",
2930
+ /**
2931
+ * Controller sends game state update
2932
+ */
2933
+ STATE: "controller:state",
2934
+ /**
2935
+ * Controller sends system command
2936
+ */
2937
+ SYSTEM: "controller:system"
2938
+ };
2939
+ var SystemEvents = {
2940
+ /**
2941
+ * Arcade launches a game
2942
+ */
2943
+ LAUNCH_GAME: "system:launchGame",
2944
+ /**
2945
+ * Arcade closes a game
2946
+ */
2947
+ CLOSE_GAME: "system:closeGame"
2948
+ };
2949
+ var ServerEvents = {
2950
+ /**
2951
+ * Welcome message with room/controller info
2952
+ */
2953
+ WELCOME: "server:welcome",
2954
+ /**
2955
+ * Room is ready
2956
+ */
2957
+ ROOM_READY: "server:roomReady",
2958
+ /**
2959
+ * Controller joined notification
2960
+ */
2961
+ CONTROLLER_JOINED: "server:controllerJoined",
2962
+ /**
2963
+ * Controller left notification
2964
+ */
2965
+ CONTROLLER_LEFT: "server:controllerLeft",
2966
+ /**
2967
+ * Host left notification
2968
+ */
2969
+ HOST_LEFT: "server:hostLeft",
2970
+ /**
2971
+ * Server error
2972
+ */
2973
+ ERROR: "server:error",
2974
+ /**
2975
+ * Play sound on client
2976
+ */
2977
+ PLAY_SOUND: "server:playSound"
2978
+ };
2979
+ var ClientEvents = {
2980
+ /**
2981
+ * Load a game UI in the controller iframe
2982
+ */
2983
+ LOAD_UI: "client:loadUi",
2984
+ /**
2985
+ * Unload the game UI from the controller iframe
2986
+ */
2987
+ UNLOAD_UI: "client:unloadUi",
2988
+ /**
2989
+ * Update game state display
2990
+ */
2991
+ STATE: "client:state"
2992
+ };
2993
+ var ChildEvents = {
2994
+ /**
2995
+ * Server requests child to close
2996
+ */
2997
+ CLOSE: "child:close"
2998
+ };
2999
+ var Events = {
3000
+ Host: HostEvents,
3001
+ Controller: ControllerEvents,
3002
+ System: SystemEvents,
3003
+ Server: ServerEvents,
3004
+ Client: ClientEvents,
3005
+ Child: ChildEvents
3006
+ };
3007
+
3008
+ // src/utils/ids.ts
3009
+ var alphabet = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
3010
+ var generateRoomCode = () => {
3011
+ const array = new Uint32Array(4);
3012
+ if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
3013
+ crypto.getRandomValues(array);
3014
+ } else {
3015
+ for (let i = 0; i < array.length; i += 1) {
3016
+ array[i] = Math.floor(Math.random() * alphabet.length);
3017
+ }
3018
+ }
3019
+ const code = Array.from(
3020
+ array,
3021
+ (value) => alphabet[value % alphabet.length]
3022
+ ).join("");
3023
+ return roomCodeSchema.parse(code);
3024
+ };
3025
+ var generateControllerId = () => {
3026
+ const stamp = Math.floor(Date.now() % 1e5).toString().padStart(5, "0");
3027
+ const random = alphabet[Math.floor(Math.random() * alphabet.length)];
3028
+ return `C${random}${stamp}`;
3029
+ };
3030
+
3031
+ // src/hooks/use-air-jam-controller.ts
3032
+ var getRoomFromLocation = () => {
3033
+ if (typeof window === "undefined") {
3034
+ return null;
3035
+ }
3036
+ const params = new URLSearchParams(window.location.search);
3037
+ const code = params.get("room");
3038
+ return code ? code.toUpperCase() : null;
3039
+ };
3040
+ var useAirJamController = (options = {}) => {
3041
+ const { store, getSocket, disconnectSocket } = useAirJamContext();
3042
+ const nicknameRef = useRef(options.nickname ?? "");
3043
+ const subControllerParams = useMemo(() => {
2808
3044
  if (typeof window === "undefined") return null;
2809
3045
  const params = new URLSearchParams(window.location.search);
2810
3046
  const room = params.get("aj_room");
2811
- const token = params.get("aj_token");
2812
- if (room && token) {
2813
- return { room, token };
3047
+ const controllerId2 = params.get("aj_controller_id");
3048
+ if (room && controllerId2) {
3049
+ return { room, controllerId: controllerId2 };
2814
3050
  }
2815
3051
  return null;
2816
3052
  }, []);
2817
- const isChildMode = !!arcadeParams;
2818
- const shouldConnect = true;
2819
- const [fallbackRoomId] = useState(() => generateRoomCode());
2820
3053
  const parsedRoomId = useMemo(() => {
2821
- if (arcadeParams) {
2822
- return roomCodeSchema.parse(arcadeParams.room.toUpperCase());
3054
+ const code = subControllerParams?.room ?? options.roomId ?? getRoomFromLocation();
3055
+ if (!code) return null;
3056
+ try {
3057
+ return roomCodeSchema.parse(code.toUpperCase());
3058
+ } catch {
3059
+ return null;
2823
3060
  }
2824
- if (typeof window !== "undefined") {
2825
- const params = new URLSearchParams(window.location.search);
2826
- const paramRoom = params.get("room");
2827
- if (paramRoom) {
2828
- const result = roomCodeSchema.safeParse(paramRoom.toUpperCase());
2829
- if (result.success) return result.data;
2830
- }
3061
+ }, [options.roomId, subControllerParams]);
3062
+ const controllerId = useMemo(() => {
3063
+ if (subControllerParams?.controllerId) {
3064
+ return subControllerParams.controllerId;
2831
3065
  }
2832
- if (options.roomId) {
2833
- return roomCodeSchema.parse(options.roomId.toUpperCase());
3066
+ if (options.controllerId) {
3067
+ return options.controllerId;
2834
3068
  }
2835
- return fallbackRoomId;
2836
- }, [options.roomId, fallbackRoomId, arcadeParams]);
2837
- useEffect(() => {
2838
- if (inputManager) {
2839
- inputManager.setRoomId(parsedRoomId);
3069
+ if (typeof window !== "undefined") {
3070
+ const params = new URLSearchParams(window.location.search);
3071
+ const urlControllerId = params.get("controllerId");
3072
+ if (urlControllerId) return urlControllerId;
2840
3073
  }
2841
- }, [inputManager, parsedRoomId]);
2842
- const [joinUrl, setJoinUrl] = useState("");
2843
- const onPlayerJoinRef = useRef(options.onPlayerJoin);
2844
- const onPlayerLeaveRef = useRef(options.onPlayerLeave);
2845
- const onChildCloseRef = useRef(options.onChildClose);
3074
+ return generateControllerId();
3075
+ }, [options.controllerId, subControllerParams]);
3076
+ const onStateRef = useRef(
3077
+ options.onState
3078
+ );
2846
3079
  useEffect(() => {
2847
- onPlayerJoinRef.current = options.onPlayerJoin;
2848
- onPlayerLeaveRef.current = options.onPlayerLeave;
2849
- onChildCloseRef.current = options.onChildClose;
2850
- }, [options.onPlayerJoin, options.onPlayerLeave, options.onChildClose]);
3080
+ onStateRef.current = options.onState;
3081
+ }, [options.onState]);
2851
3082
  const connectionState = useStore(
2852
3083
  store,
2853
3084
  useShallow((state) => ({
2854
3085
  connectionStatus: state.connectionStatus,
2855
3086
  lastError: state.lastError,
3087
+ controllerId: state.controllerId,
2856
3088
  players: state.players,
2857
3089
  gameState: state.gameState,
2858
- mode: state.mode
3090
+ stateMessage: state.stateMessage
2859
3091
  }))
2860
3092
  );
2861
- const socket = useMemo(
2862
- () => getSocket("host") ,
2863
- [shouldConnect, getSocket]
2864
- );
2865
- const [lastToggle, setLastToggle] = useState(0);
2866
- const toggleGameState = useCallback(() => {
2867
- const now = Date.now();
2868
- if (now - lastToggle < TOGGLE_DEBOUNCE_MS) {
2869
- return;
2870
- }
2871
- setLastToggle(now);
2872
- if (!socket || !socket.connected) {
2873
- return;
2874
- }
2875
- const payload = controllerSystemSchema.safeParse({
2876
- roomId: parsedRoomId,
2877
- command: "toggle_pause"
2878
- });
2879
- if (payload.success) {
2880
- socket.emit("host:system", payload.data);
3093
+ const [reconnectKey, setReconnectKey] = useState(0);
3094
+ const reconnect = useCallback(() => {
3095
+ if (!parsedRoomId) return;
3096
+ disconnectSocket("controller");
3097
+ setReconnectKey((prev) => prev + 1);
3098
+ }, [parsedRoomId, disconnectSocket]);
3099
+ const isChildMode = useMemo(() => {
3100
+ if (typeof window === "undefined") return false;
3101
+ const params = new URLSearchParams(window.location.search);
3102
+ return params.get("airjam_mode") === "child";
3103
+ }, []);
3104
+ const shouldConnect = useMemo(() => {
3105
+ if (options.forceConnect) return true;
3106
+ if (subControllerParams) return true;
3107
+ if (typeof window !== "undefined") {
3108
+ const params = new URLSearchParams(window.location.search);
3109
+ return params.get("airjam_force_connect") === "true";
2881
3110
  }
2882
- }, [socket, parsedRoomId, lastToggle]);
2883
- const sendState = useCallback(
2884
- (state) => {
2885
- if (!socket || !socket.connected) {
2886
- return false;
2887
- }
2888
- const payload = controllerStateSchema.safeParse({
2889
- roomId: parsedRoomId,
2890
- state
2891
- });
2892
- if (!payload.success) {
2893
- return false;
2894
- }
2895
- socket.emit("host:state", payload.data);
2896
- return true;
2897
- },
2898
- [socket, parsedRoomId]
3111
+ return false;
3112
+ }, [options.forceConnect, subControllerParams]);
3113
+ const canConnect = useMemo(
3114
+ () => !isChildMode || shouldConnect,
3115
+ [isChildMode, shouldConnect]
2899
3116
  );
2900
- const sendSignal = useCallback(
2901
- (type, payload, targetId) => {
2902
- if (!socket || !socket.connected) {
2903
- return;
2904
- }
2905
- const signal = {
2906
- targetId,
2907
- type,
2908
- payload
2909
- };
2910
- socket.emit("host:signal", signal);
2911
- },
2912
- [socket]
3117
+ const socket = useMemo(
3118
+ () => canConnect && parsedRoomId ? getSocket("controller") : null,
3119
+ [canConnect, parsedRoomId, getSocket]
2913
3120
  );
2914
- const reconnect = useCallback(() => {
2915
- disconnectSocket("host");
2916
- if (socket) {
2917
- socket.connect();
2918
- }
2919
- }, [socket, disconnectSocket]);
2920
- useEffect(() => {
2921
- (async () => {
2922
- const url = await urlBuilder.buildControllerUrl(parsedRoomId, {
2923
- path: config.controllerPath,
2924
- host: config.publicHost
2925
- });
2926
- setJoinUrl(url);
2927
- })();
2928
- }, [parsedRoomId, config.controllerPath, config.publicHost]);
2929
- const setRegisteredRoomId = useStore(store, (s) => s.setRegisteredRoomId);
2930
3121
  useEffect(() => {
2931
- const storeState = store.getState();
2932
- storeState.setMode(detectRunMode());
2933
- storeState.setRole("host");
2934
- storeState.setRoomId(parsedRoomId);
2935
- storeState.setStatus("connecting");
2936
- storeState.setError(void 0);
2937
- if (!socket) {
2938
- storeState.setStatus("idle");
2939
- return;
2940
- }
2941
- const registerHost = async () => {
2942
- const storeState2 = store.getState();
2943
- const currentRegisteredRoomId2 = store.getState().registeredRoomId;
2944
- if (currentRegisteredRoomId2 === parsedRoomId && socket.connected) {
2945
- return;
2946
- }
2947
- if (arcadeParams) {
2948
- const childRoomId = roomCodeSchema.parse(
2949
- arcadeParams.room.toUpperCase()
2950
- );
2951
- const payload = {
2952
- roomId: childRoomId,
2953
- joinToken: arcadeParams.token
2954
- };
2955
- socket.emit("host:joinAsChild", payload, (ack) => {
2956
- if (!ack.ok) {
2957
- storeState2.setError(ack.message ?? "Failed to join as child");
2958
- storeState2.setStatus("disconnected");
2959
- setRegisteredRoomId(null);
2960
- return;
2961
- }
2962
- storeState2.setStatus("connected");
2963
- storeState2.setRoomId(childRoomId);
2964
- setRegisteredRoomId(childRoomId);
2965
- });
2966
- } else {
2967
- const payload = hostRegistrationSchema.parse({
2968
- roomId: parsedRoomId,
2969
- maxPlayers: options.maxPlayers ?? config.maxPlayers,
2970
- apiKey: options.apiKey ?? config.apiKey
2971
- });
2972
- socket.emit("host:register", payload, (ack) => {
2973
- if (!ack.ok) {
2974
- storeState2.setError(ack.message ?? "Failed to register host");
2975
- storeState2.setStatus("disconnected");
2976
- setRegisteredRoomId(null);
2977
- return;
2978
- }
2979
- storeState2.setStatus("connected");
2980
- if (ack.roomId) {
2981
- storeState2.setRoomId(ack.roomId);
2982
- setRegisteredRoomId(ack.roomId);
2983
- } else {
2984
- setRegisteredRoomId(parsedRoomId);
3122
+ if (!socket) return;
3123
+ const handleSignal = (signal) => {
3124
+ if (signal.type !== "HAPTIC") return;
3125
+ if (typeof navigator === "undefined" || !navigator.vibrate) return;
3126
+ const payload = signal.payload;
3127
+ switch (payload.pattern) {
3128
+ case "light":
3129
+ navigator.vibrate(10);
3130
+ break;
3131
+ case "medium":
3132
+ navigator.vibrate(30);
3133
+ break;
3134
+ case "heavy":
3135
+ navigator.vibrate([50, 20, 50]);
3136
+ break;
3137
+ case "success":
3138
+ navigator.vibrate([10, 30, 10]);
3139
+ break;
3140
+ case "failure":
3141
+ navigator.vibrate([50, 50, 50, 50]);
3142
+ break;
3143
+ case "custom":
3144
+ if (Array.isArray(payload.sequence)) {
3145
+ navigator.vibrate(payload.sequence);
3146
+ } else if (typeof payload.sequence === "number") {
3147
+ navigator.vibrate(payload.sequence);
2985
3148
  }
2986
- });
3149
+ break;
2987
3150
  }
2988
3151
  };
3152
+ socket.on("server:signal", handleSignal);
3153
+ return () => {
3154
+ socket.off("server:signal", handleSignal);
3155
+ };
3156
+ }, [socket]);
3157
+ useEffect(() => {
3158
+ const storeState = store.getState();
3159
+ storeState.setMode(detectRunMode());
3160
+ storeState.setRole("controller");
3161
+ storeState.setRoomId(parsedRoomId);
3162
+ storeState.setStatus(parsedRoomId ? "connecting" : "idle");
3163
+ storeState.setError(void 0);
3164
+ if (!canConnect) {
3165
+ storeState.setStatus("connected");
3166
+ const handleMessage = (event) => {
3167
+ if (event.source !== window.parent) return;
3168
+ const data = event.data;
3169
+ if (data?.type === "AIRJAM_STATE") {
3170
+ const payload = data.payload;
3171
+ if (payload.gameState) storeState.setGameState(payload.gameState);
3172
+ if (payload.message !== void 0)
3173
+ storeState.setStateMessage(payload.message);
3174
+ onStateRef.current?.(payload);
3175
+ }
3176
+ };
3177
+ window.addEventListener("message", handleMessage);
3178
+ window.parent.postMessage({ type: "AIRJAM_READY" }, "*");
3179
+ return () => {
3180
+ window.removeEventListener("message", handleMessage);
3181
+ storeState.setStatus("disconnected");
3182
+ };
3183
+ }
3184
+ if (!parsedRoomId || !socket || !controllerId) {
3185
+ storeState.setStatus("idle");
3186
+ return;
3187
+ }
3188
+ storeState.setControllerId(controllerId);
2989
3189
  const handleConnect = () => {
2990
3190
  store.getState().setStatus("connected");
2991
- registerHost();
3191
+ if (subControllerParams) {
3192
+ return;
3193
+ }
3194
+ const payload = controllerJoinSchema.parse({
3195
+ roomId: parsedRoomId,
3196
+ controllerId,
3197
+ nickname: nicknameRef.current || void 0
3198
+ });
3199
+ socket.emit("controller:join", payload, (ack) => {
3200
+ const storeState2 = store.getState();
3201
+ if (!ack.ok) {
3202
+ storeState2.setError(ack.message ?? "Unable to join room");
3203
+ storeState2.setStatus("disconnected");
3204
+ return;
3205
+ }
3206
+ if (ack.controllerId) {
3207
+ storeState2.setControllerId(ack.controllerId);
3208
+ }
3209
+ storeState2.setStatus("connected");
3210
+ });
2992
3211
  };
2993
3212
  const handleDisconnect = () => {
2994
3213
  store.getState().setStatus("disconnected");
2995
3214
  };
2996
- const handleJoin = (payload) => {
2997
- if (payload.player) {
2998
- store.getState().upsertPlayer(payload.player);
2999
- setTimeout(() => {
3000
- onPlayerJoinRef.current?.(payload.player);
3001
- }, 0);
3215
+ const handleWelcome = (payload) => {
3216
+ const storeState2 = store.getState();
3217
+ const storeRoomId = storeState2.roomId;
3218
+ if (storeRoomId && payload.roomId.toUpperCase() !== storeRoomId.toUpperCase()) {
3219
+ return;
3002
3220
  }
3003
- };
3004
- const handleLeave = (payload) => {
3005
- store.getState().removePlayer(payload.controllerId);
3006
- onPlayerLeaveRef.current?.(payload.controllerId);
3007
- };
3008
- const handleInput = (payload) => {
3009
- if (inputManager) {
3010
- inputManager.handleInput(payload);
3221
+ if (!storeRoomId && payload.roomId) {
3222
+ storeState2.setRoomId(payload.roomId);
3011
3223
  }
3012
- };
3013
- const handleChildClose = () => {
3014
- onChildCloseRef.current?.();
3224
+ if (!payload.player) {
3225
+ storeState2.setError(
3226
+ "Welcome message received but no player profile included."
3227
+ );
3228
+ return;
3229
+ }
3230
+ storeState2.upsertPlayer(payload.player);
3015
3231
  };
3016
3232
  const handleState = (payload) => {
3017
3233
  if (payload.roomId !== parsedRoomId) return;
@@ -3022,74 +3238,118 @@ var useAirJamHost = (options = {}) => {
3022
3238
  if (payload.state.message !== void 0) {
3023
3239
  storeState2.setStateMessage(payload.state.message);
3024
3240
  }
3241
+ onStateRef.current?.(payload.state);
3242
+ };
3243
+ const handleHostLeft = (payload) => {
3244
+ const storeState2 = store.getState();
3245
+ storeState2.setError(payload.reason);
3246
+ storeState2.setStatus("disconnected");
3247
+ storeState2.resetGameState();
3248
+ setTimeout(() => {
3249
+ disconnectSocket("controller");
3250
+ setReconnectKey((prev) => prev + 1);
3251
+ }, 1e3);
3025
3252
  };
3026
3253
  const handleError = (payload) => {
3027
3254
  store.getState().setError(payload.message);
3028
3255
  };
3029
3256
  socket.on("connect", handleConnect);
3030
3257
  socket.on("disconnect", handleDisconnect);
3031
- socket.on("server:controllerJoined", handleJoin);
3032
- socket.on("server:controllerLeft", handleLeave);
3033
- socket.on("server:input", handleInput);
3034
- socket.on("server:error", handleError);
3035
- socket.on("server:closeChild", handleChildClose);
3258
+ socket.on("server:welcome", handleWelcome);
3036
3259
  socket.on("server:state", handleState);
3260
+ socket.on("server:hostLeft", handleHostLeft);
3261
+ socket.on("server:error", handleError);
3037
3262
  socket.connect();
3038
- const currentRegisteredRoomId = store.getState().registeredRoomId;
3039
- if (socket.connected && currentRegisteredRoomId !== parsedRoomId) {
3040
- registerHost();
3041
- }
3042
- if (currentRegisteredRoomId && currentRegisteredRoomId !== parsedRoomId) {
3043
- setRegisteredRoomId(null);
3044
- }
3045
3263
  return () => {
3046
3264
  socket.off("connect", handleConnect);
3047
3265
  socket.off("disconnect", handleDisconnect);
3048
- socket.off("server:controllerJoined", handleJoin);
3049
- socket.off("server:controllerLeft", handleLeave);
3050
- socket.off("server:input", handleInput);
3051
- socket.off("server:error", handleError);
3052
- socket.off("server:closeChild", handleChildClose);
3266
+ socket.off("server:welcome", handleWelcome);
3053
3267
  socket.off("server:state", handleState);
3268
+ socket.off("server:hostLeft", handleHostLeft);
3269
+ socket.off("server:error", handleError);
3054
3270
  };
3055
3271
  }, [
3056
- config.maxPlayers,
3057
- config.apiKey,
3058
- options.maxPlayers,
3059
- options.apiKey,
3060
3272
  parsedRoomId,
3061
- arcadeParams,
3062
- shouldConnect,
3273
+ reconnectKey,
3274
+ canConnect,
3063
3275
  socket,
3276
+ controllerId,
3277
+ subControllerParams,
3064
3278
  store,
3065
- inputManager,
3066
- setRegisteredRoomId
3279
+ disconnectSocket
3067
3280
  ]);
3068
- const returnSocket = socket ?? getSocket("host");
3069
- const getInput = useCallback(
3070
- (controllerId) => {
3071
- if (!inputManager) {
3072
- return void 0;
3281
+ const setNickname = useCallback((value) => {
3282
+ nicknameRef.current = value;
3283
+ }, []);
3284
+ const sendInput = useCallback(
3285
+ (input) => {
3286
+ const storeState = store.getState();
3287
+ if (!canConnect) {
3288
+ if (typeof window !== "undefined") {
3289
+ window.parent.postMessage(
3290
+ {
3291
+ type: "AIRJAM_INPUT",
3292
+ payload: input
3293
+ },
3294
+ "*"
3295
+ );
3296
+ }
3297
+ return true;
3073
3298
  }
3074
- return inputManager.getInput(controllerId);
3299
+ if (!parsedRoomId || !storeState.controllerId || !socket) {
3300
+ storeState.setError("Not connected to a room");
3301
+ return false;
3302
+ }
3303
+ if (!socket.connected) {
3304
+ return false;
3305
+ }
3306
+ if (typeof input !== "object" || input === null || Array.isArray(input)) {
3307
+ storeState.setError("Input must be an object");
3308
+ return false;
3309
+ }
3310
+ const payload = controllerInputSchema.safeParse({
3311
+ roomId: parsedRoomId,
3312
+ controllerId: storeState.controllerId,
3313
+ input
3314
+ });
3315
+ if (!payload.success) {
3316
+ storeState.setError(payload.error.message);
3317
+ return false;
3318
+ }
3319
+ socket.emit("controller:input", payload.data);
3320
+ return true;
3075
3321
  },
3076
- [inputManager]
3322
+ [parsedRoomId, canConnect, socket, store]
3323
+ );
3324
+ const sendSystemCommand = useCallback(
3325
+ (command) => {
3326
+ const storeState = store.getState();
3327
+ if (!canConnect) return;
3328
+ if (!parsedRoomId || !storeState.controllerId || !socket) return;
3329
+ if (!socket.connected) return;
3330
+ const payload = controllerSystemSchema.safeParse({
3331
+ roomId: parsedRoomId,
3332
+ command
3333
+ });
3334
+ if (payload.success) {
3335
+ socket.emit("controller:system", payload.data);
3336
+ }
3337
+ },
3338
+ [parsedRoomId, canConnect, socket, store]
3077
3339
  );
3078
3340
  return {
3079
3341
  roomId: parsedRoomId,
3080
- joinUrl,
3342
+ controllerId: connectionState.controllerId,
3081
3343
  connectionStatus: connectionState.connectionStatus,
3082
- players: connectionState.players,
3083
3344
  lastError: connectionState.lastError,
3084
- mode: connectionState.mode,
3085
3345
  gameState: connectionState.gameState,
3086
- toggleGameState,
3087
- sendState,
3088
- sendSignal,
3346
+ stateMessage: connectionState.stateMessage,
3347
+ sendInput,
3348
+ sendSystemCommand,
3349
+ setNickname,
3089
3350
  reconnect,
3090
- socket: returnSocket,
3091
- isChildMode,
3092
- getInput
3351
+ players: connectionState.players,
3352
+ socket
3093
3353
  };
3094
3354
  };
3095
3355
  var getRoomFromLocation2 = () => {
@@ -3277,6 +3537,7 @@ var useAirJamShell = (options = {}) => {
3277
3537
  const sendInput = useCallback(
3278
3538
  (input) => {
3279
3539
  const storeState = store.getState();
3540
+ input.action === true || typeof input.vector === "object" && input.vector !== null && (Math.abs(input.vector.x ?? 0) > 0.01 || Math.abs(input.vector.y ?? 0) > 0.01);
3280
3541
  if (!parsedRoomId || !storeState.controllerId || !socket) {
3281
3542
  storeState.setError("Not connected to a room");
3282
3543
  return false;
@@ -3360,7 +3621,146 @@ var useSendSignal = () => {
3360
3621
  );
3361
3622
  return sendSignal;
3362
3623
  };
3624
+ function createAirJamStore2(initializer) {
3625
+ const store = create((set, get, api) => {
3626
+ const baseState = initializer(set, get, api);
3627
+ return {
3628
+ ...baseState,
3629
+ actions: {
3630
+ ...baseState.actions,
3631
+ _syncState: (partial) => {
3632
+ set(partial);
3633
+ }
3634
+ }
3635
+ };
3636
+ });
3637
+ const gameUiUnloadedRef = { current: false };
3638
+ const useSyncedStore = (selector = (s) => s) => {
3639
+ const slice = store(selector);
3640
+ const { getSocket } = useAirJamContext();
3641
+ const role = useAirJamState((state) => state.role);
3642
+ const roomId = useAirJamState((state) => state.roomId);
3643
+ const controllerId = useAirJamState((state) => state.controllerId);
3644
+ const socket = role === "host" ? getSocket("host") : getSocket("controller");
3645
+ const socketRef = useRef(socket);
3646
+ useEffect(() => {
3647
+ socketRef.current = socket;
3648
+ }, [socket]);
3649
+ useEffect(() => {
3650
+ if (!socket || !roomId || !role) {
3651
+ return;
3652
+ }
3653
+ if (role === "host") {
3654
+ const unsubscribe = store.subscribe((newState) => {
3655
+ const { actions, ...stateData } = newState;
3656
+ socket.emit("host:state_sync", { roomId, data: stateData });
3657
+ });
3658
+ const handleAction = (payload) => {
3659
+ const { actionName, args, controllerId: controllerId2 } = payload;
3660
+ const actionFn = store.getState().actions[actionName];
3661
+ if (actionFn) {
3662
+ actionFn(...args, controllerId2);
3663
+ }
3664
+ };
3665
+ socket.on("airjam:action_rpc", handleAction);
3666
+ return () => {
3667
+ unsubscribe();
3668
+ socket.off("airjam:action_rpc", handleAction);
3669
+ };
3670
+ }
3671
+ if (role === "controller") {
3672
+ gameUiUnloadedRef.current = false;
3673
+ const handleSync = (payload) => {
3674
+ const { data } = payload;
3675
+ const currentState = store.getState();
3676
+ const actions = currentState.actions;
3677
+ if (actions._syncState) {
3678
+ actions._syncState(data);
3679
+ } else {
3680
+ store.setState(data);
3681
+ }
3682
+ };
3683
+ socket.on("airjam:state_sync", handleSync);
3684
+ const handleUnloadUi = () => {
3685
+ gameUiUnloadedRef.current = true;
3686
+ socket.off("airjam:state_sync", handleSync);
3687
+ };
3688
+ const handleLoadUi = () => {
3689
+ gameUiUnloadedRef.current = false;
3690
+ };
3691
+ socket.on("client:loadUi", handleLoadUi);
3692
+ const handleDisconnect = () => {
3693
+ gameUiUnloadedRef.current = true;
3694
+ };
3695
+ socket.on("disconnect", handleDisconnect);
3696
+ socket.on("client:unloadUi", handleUnloadUi);
3697
+ return () => {
3698
+ socket.off("airjam:state_sync", handleSync);
3699
+ socket.off("client:loadUi", handleLoadUi);
3700
+ socket.off("client:unloadUi", handleUnloadUi);
3701
+ socket.off("disconnect", handleDisconnect);
3702
+ };
3703
+ }
3704
+ }, [socket, role, roomId, socket?.id]);
3705
+ if (role === "controller" && socket && roomId) {
3706
+ let originalActions = null;
3707
+ if (typeof slice === "object" && slice !== null && "actions" in slice) {
3708
+ originalActions = slice.actions;
3709
+ } else if (typeof slice === "object" && slice !== null) {
3710
+ const fullState = store.getState();
3711
+ if (fullState.actions) {
3712
+ const sliceKeys = Object.keys(slice);
3713
+ const actionKeys = Object.keys(fullState.actions);
3714
+ if (sliceKeys.length > 0 && sliceKeys.every(
3715
+ (key) => typeof slice[key] === "function" && actionKeys.includes(key)
3716
+ )) {
3717
+ originalActions = slice;
3718
+ }
3719
+ }
3720
+ }
3721
+ if (originalActions) {
3722
+ const proxyActions = {};
3723
+ Object.keys(originalActions).forEach((key) => {
3724
+ proxyActions[key] = (...args) => {
3725
+ if (gameUiUnloadedRef.current) {
3726
+ console.warn(
3727
+ `[AirJamStore] Action "${key}" blocked: Game UI unloaded.`
3728
+ );
3729
+ return;
3730
+ }
3731
+ const activeSocket = socketRef.current;
3732
+ if (!activeSocket || !activeSocket.connected) {
3733
+ console.warn(
3734
+ `[AirJamStore] Action "${key}" blocked: Socket disconnected.`
3735
+ );
3736
+ return;
3737
+ }
3738
+ if (!controllerId) {
3739
+ console.warn(
3740
+ "[AirJamStore] Cannot send action RPC: controllerId not set"
3741
+ );
3742
+ return;
3743
+ }
3744
+ activeSocket.emit("controller:action_rpc", {
3745
+ roomId,
3746
+ actionName: key,
3747
+ args,
3748
+ controllerId
3749
+ });
3750
+ };
3751
+ });
3752
+ if (typeof slice === "object" && slice !== null && "actions" in slice) {
3753
+ return { ...slice, actions: proxyActions };
3754
+ } else {
3755
+ return proxyActions;
3756
+ }
3757
+ }
3758
+ }
3759
+ return slice;
3760
+ };
3761
+ return useSyncedStore;
3762
+ }
3363
3763
 
3364
- export { AirJamContext, AirJamOverlay, AirJamProvider, AudioManager, AudioProvider, Button, ChildEvents, ClientEvents, ControllerEvents, ControllerShell, DEFAULT_CONTROLLER_PATH, DEFAULT_MAX_PLAYERS, DEFAULT_SERVER_PORT, Events, HostEvents, INPUT_DEBOUNCE_MS, SOCKET_CONFIG, ServerEvents, Slider, SocketManager, SystemEvents, TOGGLE_DEBOUNCE_MS, UrlBuilder, VolumeControls, buttonVariants, createAudioManager, detectSoundCategory, generateControllerId, generateRoomCode, getLocalNetworkIp, urlBuilder, useAirJamConfig, useAirJamContext, useAirJamController, useAirJamHost, useAirJamShell, useAirJamSocket, useAirJamState, useAudio, useAudioLegacy, useAudioManager, useGetInput, useSendSignal, useVolumeStore };
3764
+ export { AirJamContext, AirJamDebug, AirJamOverlay, AirJamProvider, AudioManager, AudioProvider, Button, CONTROLLER_PATH, ChildEvents, ClientEvents, ControllerEvents, ControllerShell, DEFAULT_MAX_PLAYERS, DEFAULT_SERVER_PORT, DebugStateDialog, Events, HostEvents, INPUT_DEBOUNCE_MS, PlayerAvatar, SOCKET_CONFIG, ServerEvents, Slider, SocketManager, SystemEvents, TOGGLE_DEBOUNCE_MS, UrlBuilder, VolumeControls, buttonVariants, createAirJamStore2 as createAirJamStore, createAudioManager, detectSoundCategory, generateControllerId, generateRoomCode, getLocalNetworkIp, urlBuilder, useAirJamConfig, useAirJamContext, useAirJamController, useAirJamHost, useAirJamShell, useAirJamSocket, useAirJamState, useAudio, useAudioLegacy, useAudioManager, useGetInput, useSendSignal, useVolumeStore };
3365
3765
  //# sourceMappingURL=index.js.map
3366
3766
  //# sourceMappingURL=index.js.map