This is the abridged developer documentation for @gamepadly/sdk # Controller support for web games, in one prompt > @gamepadly/sdk is an open-source JavaScript library that adds Xbox, PlayStation and Switch controller support to web games, with haptics and DualSense adaptive triggers. Give your coding agent one prompt, or add it yourself in about ten lines. `@gamepadly/sdk` is an open-source JavaScript library that adds Xbox, PlayStation and Switch controller support to web games, with haptics and DualSense adaptive triggers. Give your coding agent one prompt, or add it yourself in about ten lines. [Add a controller in 5 minutes](/sdk/start/add-controller)[Use with an AI agent](/sdk/start/ai-agents)[GitHub](https://github.com/gamepadly/gamepadly-sdk) ## Paste this into your coding agent [Section titled “Paste this into your coding agent”](#paste-this-into-your-coding-agent) ```text Read https://gamepadly.com/sdk/llms.txt, then add controller support to this game with @gamepadly/sdk. Keep keyboard and mouse working, add haptics to the main game events, and write a test that runs without a controller. ``` Works with any agent that can read a URL, such as Claude Code, Cursor, Codex or GitHub Copilot. [`llms.txt`](/sdk/llms.txt) is one page written for agents: which API to use in which situation, copy-ready recipes, the mistakes to avoid, and a test template. [More prompts](/sdk/start/ai-agents). ## Or add it yourself [Section titled “Or add it yourself”](#or-add-it-yourself) * Existing keyboard game The bridge presses the keys your game already listens for. The game’s code does not change. ```ts import { createGamepadly } from '@gamepadly/sdk'; import { createKeyMouseBridge } from '@gamepadly/sdk/bridge'; const hub = createGamepadly(); const bridge = createKeyMouseBridge({ player: hub, profile: 'platformer' }); bridge.start(); // D-pad and left stick → arrow keys, A / Cross → Space, ... // Then make the game's own events felt: bridge.triggerHaptic('heavy_impact', { pan: -0.5 }); ``` [Full walkthrough →](/sdk/start/add-controller) * New game Bind each action to controller, keyboard and mouse at once. ```ts import { createGamepadly } from '@gamepadly/sdk'; const hub = createGamepadly(); const p1 = hub.player(0); const actions = p1.createActions({ actions: { jump: ['south', 'Space'], fire: ['r2', 'MouseLeft'] }, axes: { moveX: { stick: 'lx', negativeKeys: ['KeyA'], positiveKeys: ['KeyD'] } }, }); // In your game loop: actions.update(p1.input.getState(), performance.now()); if (actions.justPressed('fire')) p1.haptics.playPreset('recoil'); ``` [Start a new game →](/sdk/start/quick-start) * Single HTML file No build step: load the SDK from a CDN. ```html ``` [Installation options →](/sdk/start/installation) Using a framework? See the recipes for [Three.js](/sdk/recipes/three-js), [Phaser](/sdk/recipes/phaser) and [React](/sdk/recipes/react). ## The right motor on every controller [Section titled “The right motor on every controller”](#the-right-motor-on-every-controller) One call, `p1.haptics.playPreset('recoil')`, plays on whatever the controller has and returns which output it used, so you can log it or assert on it in tests: | Controller | What the player feels | Returns | | -------------------------------------------------------- | ----------------------------------------- | -------------------- | | DualSense with optional 4-channel audio (Windows, USB) | Voice-coil haptics, panned left and right | `'4ch_vcm'` | | Switch Pro Controller, connected with one click (WebHID) | HD Rumble | `'hd_rumble'` | | Xbox Series controller in Chrome or Edge | Trigger motors and rumble | `'impulse_triggers'` | | DualSense and other controllers | Dual-motor rumble | `'dual_rumble'` | | No controller | Nothing; the game keeps running | `'none'` | Want to feel the difference? Plug a controller into the [online controller tester](https://gamepadly.com/), built on this SDK. ## What you get [Section titled “What you get”](#what-you-get) Every controller, one API Xbox, PlayStation, Switch Pro and generic gamepads read the same way. Buttons are named by position: `south` is A on Xbox, Cross on PlayStation and B on Nintendo. Up to four players. Console features in the browser One permission click in desktop Chrome or Edge unlocks DualSense adaptive triggers, gyro, touchpad and lightbar, and Switch Pro HD Rumble. Everything falls back on other controllers. Tests without a controller A mock controller you press in code. Tests run in Vitest or Jest in plain Node, so coding agents and CI can check controller support. Small and safe 17.2 KB gzipped for the core, zero dependencies, MIT. Rumble and triggers reset when the page closes, and the SDK never writes controller firmware. ## Browser and controller support [Section titled “Browser and controller support”](#browser-and-controller-support) Controller input and rumble work in any modern browser that exposes the controller through the Gamepad API, with no prompt. Adaptive triggers, gyro, touchpad and HD Rumble need WebHID, which desktop Chrome and Edge support. Verified on real hardware so far: **Windows with Chrome and Edge**. Other platforms are implemented but not yet verified; the [compatibility matrix](/sdk/compatibility) tracks every combination. ## Examples [Section titled “Examples”](#examples) Each example is one HTML file you can open, read and copy. Every one has a simulation mode, so you can try it without a controller. [![A keyboard arcade shooter running in controller mode](/sdk/_astro/example-bridge-arcade.BT1TOG6O_Z2qfYqo.webp)Keyboard game → controller ↗A keyboard-only shooter gets stick, trigger and haptics through the bridge.](https://gamepadly.github.io/gamepadly-sdk/examples/bridge-arcade.html)[![The haptics playground: preset buttons, pan slider and trigger presets](/sdk/_astro/example-playground.DyyZkQ1J_Z1NhBDq.webp)Haptics playground ↗Every haptic preset, trigger effect and lightbar color, and which output each controller uses.](https://gamepadly.github.io/gamepadly-sdk/examples/playground.html)[![The diagnostics example: stick circularity rings and drift readings](/sdk/_astro/example-diagnostics.CUNWrJTg_Z15fvE1.webp)Custom controller tester ↗A tester built on the diagnostics module: circularity, drift and button bounce.](https://gamepadly.github.io/gamepadly-sdk/examples/diagnostics.html) ## FAQ [Section titled “FAQ”](#faq) ### What is @gamepadly/sdk? An open-source (MIT) JavaScript and TypeScript library that adds controller support to web games: one API for Xbox, PlayStation, Switch Pro and other gamepads, haptics that use the best motor each controller has, DualSense adaptive triggers, and a bridge that makes an existing keyboard game playable on a controller without changing its code. It has no runtime dependencies. ### How do I add controller support to a game made with an AI coding agent? Give the agent this prompt: “Read https\://gamepadly.com/sdk/llms.txt, then add controller support to this game with @gamepadly/sdk.” The [llms.txt](/sdk/llms.txt) file tells the agent which API to use, how to keep keyboard controls working, and how to write a test that runs without a controller. ### Do players need to install anything? No. Controller input and rumble use the browser’s Gamepad API with no prompt. DualSense adaptive triggers, gyro and touchpad and Switch Pro HD Rumble need one permission dialog (WebHID) in desktop Chrome or Edge. Only the optional DualSense speaker and 4-channel haptics on Windows can use a companion app, and games never require it. ### Which controllers and browsers are supported? Xbox controllers (including impulse triggers in Chrome and Edge), DualSense and DualSense Edge, the Switch Pro Controller, and any other controller the browser exposes through the Gamepad API. Verified on real hardware so far: Windows with Chrome and Edge. macOS, Linux, Firefox, Safari and mobile browsers are implemented but not yet verified. See the [compatibility matrix](/sdk/compatibility). ### Does it work with Three.js, Phaser, PixiJS or React? Yes. The SDK does not depend on a framework: you read input once per frame from whatever loop you already have. In React, create the hub in `useEffect` and call `dispose()` in its cleanup. ### How do I test controller support without a controller? `createMockPlayerHandle()` from `@gamepadly/sdk/game` is a fake controller whose buttons and sticks you set in code. Tests run in Vitest or Jest in plain Node. See [the test example](/sdk/start/add-controller#7-test-it-without-a-controller). ### Is it free? Yes. MIT licensed, no account, no API key, no server. It runs entirely in the player’s browser. # Start a new game > Build the input layer of a new web game with @gamepadly/sdk so every action works on controller, keyboard and mouse, with haptics, DualSense adaptive triggers and a test that runs without a controller. When you write the game’s input code yourself, bind actions instead of keys: each action lists every controller button, key and mouse button that triggers it, and the game asks “did the player jump?” once per frame. This page builds that layer with movement, a fire button, haptics, adaptive triggers and a test. Adding a controller to a game that already exists? Start with [Add a controller in 5 minutes](/sdk/start/add-controller). ## 1. Create the hub [Section titled “1. Create the hub”](#1-create-the-hub) ```ts import { createGamepadly } from '@gamepadly/sdk'; const hub = createGamepadly(); const p1 = hub.player(0); // P1; hub.player(1) is P2, up to four players ``` Create one hub per page. It tracks controllers being plugged in and out and resets rumble and triggers when the page closes. No permission prompt appears: every controller the browser exposes through the Gamepad API works. ## 2. Map inputs to actions [Section titled “2. Map inputs to actions”](#2-map-inputs-to-actions) ```ts const actions = p1.createActions({ actions: { fire: ['r2', 'Space', 'MouseLeft'], jump: ['south', 'KeyW', 'ArrowUp'], pause: ['start', 'Escape'], }, axes: { moveX: { stick: 'lx', negativeKeys: ['KeyA', 'ArrowLeft'], positiveKeys: ['KeyD', 'ArrowRight'] }, }, }); ``` A binding is a button name (`south` is A on Xbox, Cross on PlayStation and B on Nintendo; see [Buttons and layouts](/sdk/guides/buttons-and-layouts)), an analog trigger (`l2`, `r2`), a stick direction (`lx+`, `ly-`, …), a `KeyboardEvent.code`, or `MouseLeft` / `MouseRight` / `MouseMiddle`. ## 3. Read actions in your loop [Section titled “3. Read actions in your loop”](#3-read-actions-in-your-loop) ```ts import { createGameLoop } from '@gamepadly/sdk/loop'; const SPEED = 240; const player = { x: 0, jump() {}, fire() {} }; const loop = createGameLoop({ fixedStep: 1 / 60, onUpdate(dt, now) { actions.update(p1.input.getState(), now); // once per update, before reading actions player.x += actions.axis('moveX') * SPEED * dt; // -1..1, stick or keys if (actions.justPressed('jump')) player.jump(); if (actions.justPressed('fire')) { player.fire(); p1.haptics.playPreset('recoil', { pan: 0.3 }); // returns which output played } }, onRender() { // draw }, }); loop.start(); ``` `createGameLoop` is optional: call `actions.update()` from any loop you already have, such as a Three.js `renderer.setAnimationLoop` callback or a Phaser scene’s `update` (see the [Three.js](/sdk/recipes/three-js) and [Phaser](/sdk/recipes/phaser) recipes). `axis()` applies a small deadzone; raw stick values are in `p1.input.getState()`. ## 4. Show what to press [Section titled “4. Show what to press”](#4-show-what-to-press) Browsers hide controllers until the player presses a button. Show a hint until one appears, and label buttons the way they are printed on the controller in the player’s hands: ```ts import { getButtonLabel } from '@gamepadly/sdk'; function renderHint() { const brand = p1.getCapabilities().identity.brand; hint.textContent = p1.input.getState().connected ? `${getButtonLabel('south', brand)} to jump, ${getButtonLabel('r2Btn', brand)} to fire` // "A … RT" or "Cross … R2" : 'Press any button on your controller'; } renderHint(); hub.onCapabilitiesChange(renderHint); ``` ## 5. Offer the console features [Section titled “5. Offer the console features”](#5-offer-the-console-features) DualSense adaptive triggers, gyro and touchpad, and Switch Pro HD Rumble, need one WebHID permission in desktop Chrome or Edge. The browser only opens its device picker from a click: ```ts connectButton.hidden = !('hid' in navigator); connectButton.addEventListener('click', () => void hub.connectWebHID()); void hub.reconnectAuthorized(); // no prompt for controllers approved on an earlier visit const applyTriggers = () => p1.triggers.applyPreset('weapon', 'right'); applyTriggers(); hub.onCapabilitiesChange(applyTriggers); // trigger effects apply once WebHID is connected ``` On controllers without adaptive triggers these calls do nothing, so the same code runs everywhere. ## 6. Test without a controller [Section titled “6. Test without a controller”](#6-test-without-a-controller) ```ts import { expect, it } from 'vitest'; import { createMockPlayerHandle } from '@gamepadly/sdk/game'; it('jumps on the south button and fires with haptics', () => { const pad = createMockPlayerHandle({ brand: 'sony' }); const actions = pad.createActions({ actions: { jump: ['south', 'Space'], fire: ['r2', 'MouseLeft'] }, }); pad.state.buttons.cross = true; // south pad.state.r2 = 1; actions.update(pad.input.getState(), 16); expect(actions.justPressed('jump')).toBe(true); expect(actions.justPressed('fire')).toBe(true); expect(pad.haptics.playPreset('recoil')).toBe('4ch_vcm'); // a DualSense with 4-channel audio }); ``` `createMockPlayerHandle({ brand })` reports realistic capabilities for `'sony'`, `'xbox'`, `'nintendo'` and `'generic'`, and the test runs in plain Node. Games written against the portable game contract can use `createMockGameSDK()` instead: see [Games and testing](/sdk/guides/games-and-testing). ## 7. Clean up [Section titled “7. Clean up”](#7-clean-up) ```ts function destroy() { loop.dispose(); actions.dispose(); hub.dispose(); // stops rumble and resets triggers and lightbar on every controller } ``` In React, create the hub in `useEffect` and call `destroy()` in its cleanup. StrictMode mounts effects twice in development, so anything created outside the effect leaks a second hub. The [React](/sdk/recipes/react) recipe shares one hub through a provider. ## Next steps [Section titled “Next steps”](#next-steps) * [Haptics](/sdk/guides/haptics) and [Adaptive triggers](/sdk/guides/adaptive-triggers) list every preset. * [Multiple players](/sdk/guides/multiplayer) covers P2 to P4 and hot-plugging. * [Examples](/sdk/examples) has complete single-file pages to copy. # Add a controller to your game in 5 minutes > Make an existing keyboard and mouse web game playable with Xbox, PlayStation and Switch controllers in about ten lines, without changing the game's code, then add haptics and a test that runs without a controller. Your game already works with a keyboard. By the end of this page it also works with Xbox, PlayStation and Switch controllers, the controller vibrates when something happens in the game, and a test proves it without a controller plugged in. The game’s own code stays as it is: `@gamepadly/sdk/bridge` reads the controller and presses the keys the game already listens for. ## 1. Install [Section titled “1. Install”](#1-install) ```bash npm install @gamepadly/sdk ``` No bundler? Import from `https://esm.sh/@gamepadly/sdk@0.9.0/browser` in a ` ``` Pin the version in the URL so a future release cannot change your page. Every [example](/sdk/examples) is one HTML file written this way. ## Server-side rendering [Section titled “Server-side rendering”](#server-side-rendering) Importing the SDK and calling `createGamepadly()` is safe on the server (Next.js, Nuxt, Astro, SvelteKit): it reports no controller and does nothing. Controllers only appear in the browser, so create the hub in client code, for example in a React `useEffect`. ## Browser requirements [Section titled “Browser requirements”](#browser-requirements) * **Secure context.** The Gamepad API and WebHID only work over HTTPS or on `localhost`. * **A button press first.** Browsers hide connected controllers until the player presses a button on the page. Show a “Press any button” hint until `p1.input.getState().connected` is true. * **A click for WebHID.** `hub.connectWebHID()` opens the browser’s device picker, so call it from a click handler, never on page load. WebHID is available in desktop Chrome and Edge. See [Compatibility](/sdk/compatibility) for which browsers, systems and controllers have been verified. # Capability tiers > How @gamepadly/sdk progressively enhances from the Gamepad API to WebHID and optional 4-channel audio. The SDK reads every controller through the best channel available and reports what it found. Your game always runs on the lowest tier and picks up extra features when they appear. ## L0: Gamepad API (default) [Section titled “L0: Gamepad API (default)”](#l0-gamepad-api-default) * Works with any controller the browser exposes, with no permission prompt. * Raw stick axes with **no hidden deadzone** (apply your own with `p1.input.applyDeadzone()`). * Dual-motor rumble where the browser supports `vibrationActuator`. * Xbox Series impulse triggers in Chrome and Edge (`trigger-rumble`). ## L1: WebHID (one click, desktop Chrome / Edge) [Section titled “L1: WebHID (one click, desktop Chrome / Edge)”](#l1-webhid-one-click-desktop-chrome--edge) `hub.connectWebHID()` opens the browser’s device picker. After the player chooses a controller: * **DualSense / DualSense Edge** (USB and Bluetooth): 10-zone adaptive triggers, 6-axis gyro and accelerometer, two-finger touchpad, RGB lightbar, battery. * **Switch Pro Controller**: dual-band HD Rumble, 6-axis gyro and accelerometer. The browser remembers the permission. `hub.reconnectAuthorized()` reattaches a remembered controller on the next visit without a prompt, and `hub.disconnectWebHID(slotId, { forget: true })` revokes it. ## L2: 4-channel DualSense audio (optional) [Section titled “L2: 4-channel DualSense audio (optional)”](#l2-4-channel-dualsense-audio-optional) On Windows with a USB DualSense, `@gamepadly/sdk/link` can drive the controller speaker and the left/right voice coils as audio channels. It is entirely optional. See [Optional Link (L2)](/sdk/guides/link). ## Asking what is available [Section titled “Asking what is available”](#asking-what-is-available) ```ts const caps = p1.getCapabilities(); caps.tier; // 'dualsense_full_4ch' | 'dualsense_hid_only' | 'switch_pro_hid' | 'xbox_impulse' | 'standard_gamepad' | 'keyboard_mouse' caps.identity.brand; // 'sony' | 'xbox' | 'nintendo' | 'generic' | 'none' caps.hasAdaptiveTriggers; // also hasHdRumble, hasImpulseTriggers, hasDualRumble, hasGyro, hasTouchpad, ... hub.onCapabilitiesChange(({ active }) => updateHud(active)); ``` `onCapabilitiesChange` fires when a controller connects or disconnects, upgrades to WebHID, becomes the active controller, or gains 4-channel audio. ## Haptic routing [Section titled “Haptic routing”](#haptic-routing) Haptic calls such as `p1.haptics.playPreset('recoil')` pick the richest output the controller has and return which one played: | Return value | Played on | | -------------------- | -------------------------------------------------- | | `'4ch_vcm'` | DualSense voice coils through 4-channel audio (L2) | | `'hd_rumble'` | Switch Pro HD Rumble (L1) | | `'impulse_triggers'` | Xbox trigger motors (L0, Chrome / Edge) | | `'dual_rumble'` | Standard dual-motor rumble (L0) | | `'none'` | Nothing: no controller, or no rumble support | Log it, show it in a debug HUD, or assert on it in tests. # Phaser > Add controller support to a Phaser game with @gamepadly/sdk. Make an existing keyboard game playable on a controller with the bridge, or read an action map in a scene's update, with haptics panned to where things happen and cleanup on scene shutdown. There are two ways to add a controller to a Phaser game. If the game already reads the keyboard through `this.input.keyboard`, the bridge presses those keys from the controller and the scenes do not change. If you are writing the input code, read an action map in the scene’s `update()`. The code runs on Phaser 4 and uses only APIs that Phaser 3 also has. ```bash npm install @gamepadly/sdk phaser ``` ## A game that already uses the keyboard [Section titled “A game that already uses the keyboard”](#a-game-that-already-uses-the-keyboard) This scene only knows about the arrow keys and Space. The three lines at the bottom make it playable on any controller: the D-pad and left stick press the arrows, and the bottom face button presses Space and plays a light click. ```ts import Phaser from 'phaser'; import { createGamepadly } from '@gamepadly/sdk'; import { createKeyMouseBridge } from '@gamepadly/sdk/bridge'; class PlayScene extends Phaser.Scene { private cursors!: Phaser.Types.Input.Keyboard.CursorKeys; private ship!: Phaser.GameObjects.Rectangle; create() { this.cursors = this.input.keyboard!.createCursorKeys(); this.ship = this.add.rectangle(400, 520, 48, 24, 0x0a84ff); } update(_time: number, delta: number) { const dx = (this.cursors.right.isDown ? 1 : 0) - (this.cursors.left.isDown ? 1 : 0); this.ship.x = Phaser.Math.Clamp(this.ship.x + dx * 0.4 * delta, 24, 776); if (Phaser.Input.Keyboard.JustDown(this.cursors.space)) { bridge.triggerHaptic('recoil', { pan: panOf(this, this.ship.x) }); // ... fire } } } // Pan from -1 (left edge of the camera's view) to 1 (right edge). function panOf(scene: Phaser.Scene, worldX: number): number { const view = scene.cameras.main.worldView; return Phaser.Math.Clamp(((worldX - view.x) / view.width) * 2 - 1, -1, 1); } new Phaser.Game({ type: Phaser.AUTO, width: 800, height: 600, scene: PlayScene }); // The controller: the bridge presses the arrow keys and Space for the scene. const hub = createGamepadly(); const bridge = createKeyMouseBridge({ player: hub, profile: 'platformer' }); bridge.start(); ``` Phaser identifies keys by `event.keyCode` and listens on `window`. The bridge fills in `keyCode` for every key it presses and sends the events where `window` receives them, so `createCursorKeys()`, `addKey()` and `JustDown()` all work. If the game sets `input.keyboard.target` to the canvas, pass the same element as the bridge’s `keyTarget`. The `'platformer'` profile maps the D-pad and left stick to the arrows, the bottom face button to Space, and the left face button to Z. For other keys, write a profile: see [Add a controller in 5 minutes](/sdk/start/add-controller). ## New input code: an action map [Section titled “New input code: an action map”](#new-input-code-an-action-map) When you write the scene’s input yourself, bind each action to controller buttons and keys at once, and read it in `update()`: ```ts import Phaser from 'phaser'; import { createGamepadly, type ActionTracker } from '@gamepadly/sdk'; // One hub per page, outside the scenes, so it survives scene restarts. const hub = createGamepadly(); const p1 = hub.player(0); class PlayScene extends Phaser.Scene { private actions!: ActionTracker<'fire' | 'pause', 'moveX'>; private ship!: Phaser.GameObjects.Rectangle; create() { this.ship = this.add.rectangle(400, 520, 48, 24, 0x0a84ff); this.actions = p1.createActions({ actions: { fire: ['south', 'r2', 'Space'], pause: ['start', 'Escape'], }, axes: { moveX: { stick: 'lx', negativeButtons: ['left'], positiveButtons: ['right'], negativeKeys: ['ArrowLeft', 'KeyA'], positiveKeys: ['ArrowRight', 'KeyD'] }, }, }); // A scene's objects go away on shutdown (scene.restart(), scene.start('Other')), and so must its actions. this.events.once(Phaser.Scenes.Events.SHUTDOWN, () => this.actions.dispose()); } update(time: number, delta: number) { this.actions.update(p1.input.getState(), time); // once per update, before reading actions this.ship.x = Phaser.Math.Clamp(this.ship.x + this.actions.axis('moveX') * 0.4 * delta, 24, 776); if (this.actions.justPressed('fire')) { p1.haptics.playPreset('recoil', { pan: (this.ship.x / 800) * 2 - 1 }); // ... fire } if (this.actions.justPressed('pause')) this.scene.pause(); } } const game = new Phaser.Game({ type: Phaser.AUTO, width: 800, height: 600, scene: PlayScene }); game.events.once(Phaser.Core.Events.DESTROY, () => hub.dispose()); ``` A paused scene stops calling `update()`, so it cannot read the button that unpauses it. Read the pause action in a scene that keeps running, such as a UI scene launched in parallel, and call `this.scene.resume('PlayScene')` from there. ## Phaser’s own gamepad plugin [Section titled “Phaser’s own gamepad plugin”](#phasers-own-gamepad-plugin) You do not need it: the SDK reads the controller itself. Phaser leaves its gamepad plugin off unless the game config sets `input: { gamepad: true }`. A game that already uses it can keep it for input and call the SDK only for haptics, adaptive triggers and button labels. Create the hub as above and call `p1.haptics.playPreset()` where things happen. ## Next steps [Section titled “Next steps”](#next-steps) * [Start a new game](/sdk/start/quick-start) adds button prompts that match the player’s controller, a “press any button” hint, DualSense adaptive triggers and a test that runs without a controller. * [Haptics](/sdk/guides/haptics) lists every preset, and [Multiple players](/sdk/guides/multiplayer) covers local co-op with `hub.player(1)` and up. # React > Add controller support to a React game or app with @gamepadly/sdk. Share one hub through a provider that survives StrictMode, run the game loop in an effect without re-rendering every frame, show button prompts for the player's controller, and render on the server safely. In React, the SDK lives in effects: create the hub once for the whole app, run the game loop inside an effect, and re-render only when something the UI shows changes, such as which controller is connected. This page builds those three pieces. The code uses only hooks and `createRoot`, so it needs React 18 or later. ```bash npm install @gamepadly/sdk ``` ## 1. One hub for the app [Section titled “1. One hub for the app”](#1-one-hub-for-the-app) ```tsx 'use client'; // Next.js App Router: the provider uses hooks. Other setups ignore this line. import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'; import { createGamepadly, type GamepadlyHub } from '@gamepadly/sdk'; const GamepadlyContext = createContext(null); export function GamepadlyProvider({ children }: { children: ReactNode }) { const [hub, setHub] = useState(null); useEffect(() => { const created = createGamepadly(); setHub(created); return () => created.dispose(); // stops rumble and resets triggers }, []); return {children}; } /** The app's hub, or null until the provider's effect has run. */ export function useGamepadly(): GamepadlyHub | null { return useContext(GamepadlyContext); } ``` Wrap the app once, near the root: ```tsx import { StrictMode } from 'react'; import { createRoot } from 'react-dom/client'; import { GamepadlyProvider } from './gamepadly'; import { Game } from './Game'; createRoot(document.getElementById('root')!).render( , ); ``` Why an effect and not `useMemo` or a module-level `createGamepadly()`: * **StrictMode** mounts every effect twice in development: effect, cleanup, effect. The cleanup disposes the first hub and the second effect creates a fresh one, so exactly one hub is live. A hub created during render is never disposed. * **Server rendering** (Next.js, Remix, Astro islands) never runs effects, so nothing touches `navigator` on the server. Until the effect runs, `useGamepadly()` returns `null`. * **One hub per page.** Put the provider above everything that uses a controller, not inside a component that mounts and unmounts. ## 2. The game loop in an effect [Section titled “2. The game loop in an effect”](#2-the-game-loop-in-an-effect) Keep game state in the effect, not in React state. Calling `setState` 60 times a second re-renders the tree every frame; drawing to a canvas from the loop does not render at all. ```tsx import { useEffect, useRef } from 'react'; import { useGamepadly } from './gamepadly'; export function Game() { const hub = useGamepadly(); const canvasRef = useRef(null); useEffect(() => { const canvas = canvasRef.current; if (!hub || !canvas) return; const ctx = canvas.getContext('2d')!; const p1 = hub.player(0); const actions = p1.createActions({ actions: { fire: ['south', 'r2', 'Space'] }, axes: { moveX: { stick: 'lx', negativeButtons: ['left'], positiveButtons: ['right'], negativeKeys: ['ArrowLeft'], positiveKeys: ['ArrowRight'] } }, }); const ship = { x: 300 }; let frame = requestAnimationFrame(function tick(now) { actions.update(p1.input.getState(), now); // once per frame, before reading actions ship.x = Math.max(20, Math.min(580, ship.x + actions.axis('moveX') * 6)); if (actions.justPressed('fire')) p1.haptics.playPreset('recoil', { pan: ship.x / 300 - 1 }); ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#0a84ff'; ctx.fillRect(ship.x - 20, 250, 40, 20); frame = requestAnimationFrame(tick); }); return () => { cancelAnimationFrame(frame); actions.dispose(); // removes its keyboard listeners }; }, [hub]); return ; } ``` The effect depends on `hub`, so it starts once the provider has created it and restarts cleanly in StrictMode. ## 3. Prompts for the player’s controller [Section titled “3. Prompts for the player’s controller”](#3-prompts-for-the-players-controller) The UI should say “Press A” to an Xbox player and “Press Cross” to a PlayStation player, and ask for a button press until the browser reports a controller (browsers hide controllers until one is pressed). That information changes rarely, so it is the one thing worth putting in React state: ```tsx import { useEffect, useState } from 'react'; import { getButtonLabel, type ControllerBrand } from '@gamepadly/sdk'; import { useGamepadly } from './gamepadly'; export function useController() { const hub = useGamepadly(); const [controller, setController] = useState<{ connected: boolean; brand: ControllerBrand }>({ connected: false, brand: 'generic' }); useEffect(() => { if (!hub) return; const read = () => { const caps = hub.active.getCapabilities(); setController({ connected: caps.tier !== 'keyboard_mouse', brand: caps.identity.brand }); }; read(); return hub.onCapabilitiesChange(read); // returns the unsubscribe function }, [hub]); return controller; } export function FireHint() { const { connected, brand } = useController(); return

{connected ? `${getButtonLabel('south', brand)} to fire` : 'Press any button on your controller'}

; } ``` DualSense adaptive triggers and Switch Pro HD Rumble need one WebHID permission, which the browser only asks for from a click: ```tsx import { useGamepadly } from './gamepadly'; export function ConnectButton() { const hub = useGamepadly(); if (!hub || !('hid' in navigator)) return null; return ; } ``` ## React Three Fiber [Section titled “React Three Fiber”](#react-three-fiber) The provider works the same. Create the actions in a `useEffect` as above, keep them in a ref, and call `actions.update()` at the top of `useFrame`. The [Three.js](/sdk/recipes/three-js) recipe shows camera-relative movement and panning haptics to a position on screen. ## Next steps [Section titled “Next steps”](#next-steps) * [Start a new game](/sdk/start/quick-start) covers adaptive triggers and a test that runs without a controller. * [Buttons and layouts](/sdk/guides/buttons-and-layouts) lists every button name and label. * [Multiple players](/sdk/guides/multiplayer) covers `hub.player(1)` and up for local co-op. # Three.js > Add controller support to a Three.js game with @gamepadly/sdk. Move with the left stick or WASD, turn the camera with the right stick, read input in renderer.setAnimationLoop, pan haptics to where things happen on screen, and clean up. This page adds a controller to a Three.js scene: the left stick (or WASD) moves the player relative to the camera, the right stick (or the arrow keys) turns the camera, and the bottom face button (or Space) jumps, with haptics when the player lands. Keyboard keeps working, and the SDK has no dependency on Three.js. ```bash npm install @gamepadly/sdk three ``` ## The whole setup [Section titled “The whole setup”](#the-whole-setup) ```ts import * as THREE from 'three'; import { createGamepadly } from '@gamepadly/sdk'; // 1. Input: one hub per page, and the actions the game reads. const hub = createGamepadly(); const p1 = hub.player(0); const actions = p1.createActions({ actions: { jump: ['south', 'Space'], // A on Xbox, Cross on PlayStation, B on Switch }, axes: { moveX: { stick: 'lx', negativeButtons: ['left'], positiveButtons: ['right'], negativeKeys: ['KeyA'], positiveKeys: ['KeyD'] }, moveZ: { stick: 'ly', negativeButtons: ['up'], positiveButtons: ['down'], negativeKeys: ['KeyW'], positiveKeys: ['KeyS'] }, turn: { stick: 'rx', negativeKeys: ['ArrowLeft'], positiveKeys: ['ArrowRight'] }, }, }); // 2. A scene: a floor and a box to move. const renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize(innerWidth, innerHeight); document.body.appendChild(renderer.domElement); const scene = new THREE.Scene(); scene.add(new THREE.HemisphereLight(0xffffff, 0x444444, 3)); scene.add(new THREE.GridHelper(40, 40)); const camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 0.1, 100); const player = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshStandardMaterial({ color: 0x0a84ff })); player.position.y = 0.5; scene.add(player); // 3. The game loop. Three.js passes the frame time in milliseconds. const UP = new THREE.Vector3(0, 1, 0); const CAMERA_OFFSET = new THREE.Vector3(0, 4, 8); const move = new THREE.Vector3(); let yaw = 0; let velocityY = 0; let last = performance.now(); renderer.setAnimationLoop((time) => { const dt = Math.min(0.05, (time - last) / 1000); last = time; actions.update(p1.input.getState(), time); // once per frame, before reading actions yaw -= actions.axis('turn') * 2.5 * dt; // Pushing the stick up gives -1, which is forward (-Z) in Three.js. Rotate it to follow the camera. move.set(actions.axis('moveX'), 0, actions.axis('moveZ')).clampLength(0, 1).applyAxisAngle(UP, yaw); player.position.addScaledVector(move, 6 * dt); const onGround = player.position.y <= 0.5; if (actions.justPressed('jump') && onGround) velocityY = 7; velocityY -= 20 * dt; player.position.y += velocityY * dt; if (player.position.y < 0.5) { // Land: a harder landing plays a stronger haptic. if (velocityY < -3) p1.haptics.playPreset('heavy_impact', { intensity: Math.min(1, -velocityY / 10) }); player.position.y = 0.5; velocityY = 0; } camera.position.copy(CAMERA_OFFSET).applyAxisAngle(UP, yaw).add(player.position); camera.lookAt(player.position); renderer.render(scene, camera); }); addEventListener('resize', () => { camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix(); renderer.setSize(innerWidth, innerHeight); }); ``` ## Read input in the animation loop [Section titled “Read input in the animation loop”](#read-input-in-the-animation-loop) `renderer.setAnimationLoop()` is the right place to read input: it runs once per displayed frame and keeps running in WebXR, where `requestAnimationFrame` stops. Call `actions.update()` once at the top of the callback and pass it the callback’s `time`, which is a `performance.now()` timestamp in milliseconds. `justPressed()` is true for exactly one update after a press, so read it every frame. If the game runs physics at a fixed step, update the actions in the fixed step instead, or a press can land in a frame with zero physics steps. `createGameLoop()` from [`@gamepadly/sdk/loop`](/sdk/start/quick-start#3-read-actions-in-your-loop) does that for you. ## Sticks, the camera and the mouse [Section titled “Sticks, the camera and the mouse”](#sticks-the-camera-and-the-mouse) * Gamepad sticks report up as `-1`. In Three.js forward is `-Z`, so `ly` maps to `moveZ` with no inversion. * `axis()` returns -1 to 1 with the keys merged in and a 0.08 deadzone. Scale it by `dt` so speed does not depend on the frame rate. If a worn stick makes the camera drift, raise that axis’s `deadzone`. * Mouse look is not an action. Keep your existing pointer-lock code and add its movement to the same `yaw`: ```ts let yaw = 0; renderer.domElement.addEventListener('click', () => renderer.domElement.requestPointerLock()); addEventListener('mousemove', (e) => { if (document.pointerLockElement === renderer.domElement) yaw -= e.movementX * 0.003; }); ``` ## Pan haptics to where things happen [Section titled “Pan haptics to where things happen”](#pan-haptics-to-where-things-happen) Every haptic call takes a `pan` from -1 (left) to 1 (right). For an event in the 3D world, project its position to the screen: the projected `x` is already in -1 to 1. ```ts import * as THREE from 'three'; const projected = new THREE.Vector3(); function panOf(object: THREE.Object3D, camera: THREE.Camera): number { projected.setFromMatrixPosition(object.matrixWorld).project(camera); return THREE.MathUtils.clamp(projected.x, -1, 1); } // When something explodes on the left of the screen, the player feels it on the left: p1.haptics.playPreset('heavy_impact', { pan: panOf(explosion, camera) }); ``` On a DualSense with 4-channel audio the pan moves between the two voice coils; on other controllers it shifts the weight between the left and right motors. See [Haptics](/sdk/guides/haptics) for every preset. ## Clean up [Section titled “Clean up”](#clean-up) ```ts function destroy() { renderer.setAnimationLoop(null); actions.dispose(); hub.dispose(); // stops rumble and resets triggers on every controller renderer.dispose(); } ``` Call `destroy()` when the game’s page or view goes away. With Vite, also call it from `import.meta.hot.dispose()`, or every hot reload adds another hub. ## Next steps [Section titled “Next steps”](#next-steps) * [Start a new game](/sdk/start/quick-start) adds button prompts, a “press any button” hint, DualSense adaptive triggers and a test that runs without a controller. All of it works unchanged in a Three.js game. * Using React Three Fiber? Create the hub as in the [React](/sdk/recipes/react) recipe and read the actions in `useFrame`. # Adaptive triggers > Apply DualSense adaptive trigger resistance and Xbox impulse trigger effects with presets or custom zone specs. DualSense triggers can resist, click, or vibrate as the player pulls them. They need the [L1 WebHID connection](/sdk/start/tiers#l1-webhid-one-click-desktop-chrome--edge). On other controllers these calls do nothing, so you can call them unconditionally. ## Presets [Section titled “Presets”](#presets) ```ts p1.triggers.applyPreset('weapon', 'right'); // side: 'left' | 'right' | 'both' (default 'both') p1.triggers.applyPreset('off'); ``` | Preset | Effect | | ------------------ | ---------------------------------------------------- | | `'weapon'` | A resistance wall that gives way, like a gun trigger | | `'heavy_weapon'` | A later, stiffer wall | | `'bow'` | Resistance that builds as you pull | | `'abs'` | Vibration once pulled past a point, like ABS braking | | `'soft_wall'` | Gentle constant resistance from mid-pull | | `'rapid_pulse'` | Fast vibration through most of the pull | | `'precision_damp'` | Light resistance for fine control | | `'off'` | No effect | ## Custom effects [Section titled “Custom effects”](#custom-effects) ```ts p1.triggers.setRight({ type: 'weapon', startZone: 2, endZone: 5, strength: 7 }); p1.triggers.setLeft({ type: 'slope', startZone: 1, endZone: 8, startStrength: 1, endStrength: 7 }); p1.triggers.setBoth({ type: 'feedback', startZone: 4, strength: 4 }, { type: 'off' }); ``` The pull is divided into zones `0` (rest) to `9` (fully pressed). Strengths run from `1` to `8`. | Type | Fields | Behavior | | ------------- | ------------------------------------------------------ | ----------------------------------------------- | | `'feedback'` | `startZone`, `strength` | Constant resistance from `startZone` to the end | | `'slope'` | `startZone`, `endZone`, `startStrength`, `endStrength` | Resistance that ramps between two zones | | `'weapon'` | `startZone`, `endZone`, `strength` | A wall between two zones that snaps when passed | | `'vibration'` | `startZone`, `amplitude`, `frequencyHz` | Vibration from `startZone` onward | | `'off'` | | Releases the trigger | ## Apply effects at the right time [Section titled “Apply effects at the right time”](#apply-effects-at-the-right-time) Trigger effects only reach the controller once WebHID is connected, so set them again when capabilities change: ```ts const syncTriggers = () => p1.triggers.applyPreset('weapon', 'right'); syncTriggers(); hub.onCapabilitiesChange(syncTriggers); ``` Reset with `p1.triggers.reset()` when leaving a mode that used them. `hub.dispose()` and page exit reset every controller automatically. ## Xbox impulse triggers [Section titled “Xbox impulse triggers”](#xbox-impulse-triggers) Xbox Series controllers have small motors in each trigger. Chrome and Edge expose them without WebHID: ```ts p1.triggers.pulseImpulse({ left: 0, right: 0.8, durationMs: 80 }); ``` Haptic presets already use these motors when they are the best output available. # Audio and microphone > Play tones and samples routed to PC speakers or the DualSense, and detect blowing into a microphone. ## Tones and noise [Section titled “Tones and noise”](#tones-and-noise) Synthesized tones play through the hub’s `audio` engine. `createLinkAudio()` from `@gamepadly/sdk/link` provides one, and its PC output works without Gamepadly Link or a DualSense. Without an `audio` engine these calls do nothing. ```ts import { createGamepadly } from '@gamepadly/sdk'; import { createLinkAudio } from '@gamepadly/sdk/link'; const audio = createLinkAudio(); const hub = createGamepadly({ audio }); const p1 = hub.player(0); soundButton.onclick = () => audio.initPcOutput(); // browsers only start audio after a click p1.audio.playPcTone({ freqHz: 880, durationMs: 80, intensity: 0.4 }); p1.audio.playPcNoise({ durationMs: 200, freqHz: 1200, filterType: 'bandpass', pan: -0.3 }); p1.audio.playControllerSpeakerTone({ freqHz: 660, durationMs: 120 }); // DualSense speaker with 4-channel audio ``` ## Samples [Section titled “Samples”](#samples) To play audio files without the Link engine, give the hub a sample bank that wraps a plain `AudioContext` (`createLinkAudio()` already includes one): ```ts import { createGamepadly } from '@gamepadly/sdk'; import { createPcAudioRouting, createSampleBank } from '@gamepadly/sdk/audio'; const ctx = new AudioContext(); const hub = createGamepadly({ samples: createSampleBank(createPcAudioRouting(ctx)) }); const p1 = hub.player(0); await p1.audio.loadSample('door', '/sfx/door.ogg'); const handle = p1.audio.playSample('door', { route: 'pc', pan: 0.5, gain: 0.8 }); // handle.stop() for looping sounds ``` Browsers start an `AudioContext` suspended, so call `ctx.resume()` from a click before the first sound. `route` picks the output: | Route | Output | | ----------- | -------------------------------------------------------------- | | `'pc'` | PC speakers or headphones (default) | | `'speaker'` | The DualSense speaker, falling back to the PC | | `'vcm'` | The DualSense voice coils, falling back to the haptic router | | `'quad'` | All four DualSense channels in sync (speaker plus voice coils) | The controller routes need [4-channel audio (L2)](/sdk/guides/link). Without it they fall back as listed, so one call works for every player. `loadSample` accepts a URL, an encoded `ArrayBuffer`, or raw PCM. To generate voice-coil textures procedurally, see [`createTactileBuffer()`](/sdk/api/sdk#createtactilebuffer) in the API reference. ## Microphone blow detection [Section titled “Microphone blow detection”](#microphone-blow-detection) ```ts import { createMicBlowSensor } from '@gamepadly/sdk/mic'; const mic = createMicBlowSensor(); // prefers the DualSense microphone, falls back to the default mic startButton.onclick = () => mic.start(); // asks for microphone permission, so it needs a click // each frame const { blowing, intensity } = mic.sample(); windmill.speed = intensity; // on exit mic.stop(); ``` The sensor separates breath noise from voice and humming by its spectrum, so talking does not count as blowing. `createMicLevelMeter()` returns a plain input level if you only need volume. # Buttons and layouts > Position-based button names, brand-aware on-screen labels, and handling controllers with non-standard Gamepad API mappings. ## Name buttons by position [Section titled “Name buttons by position”](#name-buttons-by-position) Face buttons carry different labels on every brand. The button Xbox prints **A** is **Cross** on PlayStation and **B** on Nintendo. Bind by position so the same code works everywhere: | Name | Position | Xbox | PlayStation | Nintendo | | -------- | ------------------- | ----- | ----------- | -------- | | `south` | bottom face button | A | Cross | B | | `east` | right face button | B | Circle | A | | `west` | left face button | X | Square | Y | | `north` | top face button | Y | Triangle | X | | `select` | left center button | View | Create | Minus | | `start` | right center button | Menu | Options | Plus | | `home` | logo button | Guide | Home | Home | Shoulders and sticks use `l1`, `r1`, `l2` / `r2` (analog) or `l2Btn` / `r2Btn` (digital), `l3`, `r3`, and the D-pad uses `up`, `down`, `left`, `right`. The aliases resolve to the SDK’s underlying names (`south` → `cross`, `start` → `options`, …), so older code that uses `cross` or `options` keeps working. `resolveButtonName()` performs the same lookup if you need it. ## Show the label the player sees [Section titled “Show the label the player sees”](#show-the-label-the-player-sees) ```ts import { getButtonLabel } from '@gamepadly/sdk'; const brand = p1.getCapabilities().identity.brand; hint.textContent = `Press ${getButtonLabel('south', brand)} to jump`; // "A", "Cross", or "B" ``` Generic and unknown controllers get the A / B / X / Y labels most PC pads print. Labels are plain text. Draw your own icons if you want glyphs. Re-render prompts in `hub.onCapabilitiesChange`, since the player can switch controllers mid-game. ## Non-standard layouts [Section titled “Non-standard layouts”](#non-standard-layouts) Button positions are only reliable when the browser reports the W3C **standard** gamepad layout. Check `p1.input.getState().mapping`: | Value | Meaning | | --------------- | ----------------------------------------------------------------- | | `'standard'` | Standard layout, indices are reliable | | `'nonstandard'` | The browser reported no standard mapping; buttons may be misnamed | | `'custom'` | One of your `gamepadMappings` rules remapped this controller | | `'hid'` | Read directly over WebHID, always correct | | `'none'` | No controller (keyboard / mouse or disconnected) | `'nonstandard'` is more common in Firefox and Safari and with some third-party pads. When you see it, you can: 1. Show the player a hint that buttons may be mixed up. 2. For DualSense or Switch Pro, offer `hub.connectWebHID()`, which reads the controller directly. 3. Pass your own layout: ```ts import { createGamepadly } from '@gamepadly/sdk'; const hub = createGamepadly({ gamepadMappings: [ { match: (pad) => pad.mapping === '' && pad.id.includes('Vendor: 0079'), buttons: { cross: 2, circle: 1, square: 3, triangle: 0 }, axes: { rx: 3, ry: { index: 4, invert: true } }, triggers: { l2: { axis: 2 }, r2: { button: 7 } }, }, ], }); ``` The first rule whose `match` returns true is used. `buttons` maps SDK button names to raw button indices, `axes` maps sticks to raw axis indices, and `triggers` reads each analog trigger from a button value or an axis (signed `-1..1` axes are rescaled to `0..1`). The indices above are illustrative: log `navigator.getGamepads()` for your controller to find the real ones. The [compatibility matrix](/sdk/compatibility) tracks which combinations have been verified. # Controller UX > Make a web game feel right on a controller. Ask for a button press, show the player's own button labels, pause when the controller disconnects, drive menus with a held direction, and let players remap buttons and save their choice. Reading the controller is half the work. This page covers what players notice next: whether the game tells them what to press, survives a dead battery, works in menus, and lets them move a button they do not like. Every snippet uses `hub` and `p1` from [Start a new game](/sdk/start/quick-start). ## Ask for a button press [Section titled “Ask for a button press”](#ask-for-a-button-press) Browsers hide controllers from a page until the player presses a button on one. Until then, say so: ```ts function renderHint() { const connected = p1.input.getState().connected; hint.textContent = connected ? '' : 'Press any button on your controller'; } renderHint(); hub.onCapabilitiesChange(renderHint); ``` Keyboard players can ignore the hint, so keep it small and never block the game on it. ## Show the player’s buttons [Section titled “Show the player’s buttons”](#show-the-players-buttons) The same position is A on Xbox, Cross on PlayStation and B on Nintendo. Name the button the player holds, and update the prompts when they switch controllers: ```ts import { getButtonLabel } from '@gamepadly/sdk'; function renderPrompts() { const brand = p1.getCapabilities().identity.brand; jumpPrompt.textContent = `${getButtonLabel('south', brand)} Jump`; firePrompt.textContent = `${getButtonLabel('r2', brand)} Fire`; // RT, R2 or ZR } renderPrompts(); hub.onCapabilitiesChange(renderPrompts); ``` ## Pause when the controller disconnects [Section titled “Pause when the controller disconnects”](#pause-when-the-controller-disconnects) A controller can drop at any time: a flat battery, a cable pulled, Bluetooth out of range. Pause the game rather than let the character run on: ```ts let hadController = false; hub.onCapabilitiesChange(({ slots }) => { if (slots.length > 0) { hadController = true; } else if (hadController) { pauseGame('Controller disconnected. Reconnect it, or keep playing on the keyboard.'); } }); ``` `hadController` keeps the game from pausing for players who never used a controller. With several players, check each player instead: see [Multiple players](/sdk/guides/multiplayer#when-a-controller-disconnects). ## Menus [Section titled “Menus”](#menus) A menu needs its own action map, with directions that repeat while held. `repeated()` is true on the press, again after 400 ms and then every 100 ms, so holding down scrolls through a list at a steady pace: ```ts const menu = p1.createActions({ actions: { up: ['up', 'ly-', 'ArrowUp'], down: ['down', 'ly+', 'ArrowDown'], confirm: ['south'], // Enter and Space already click a focused button back: ['east', 'Escape'], }, }); const items = Array.from(document.querySelectorAll('#menu button')); function updateMenu() { // Start from the focused button, so Tab and the mouse stay in charge too. let index = Math.max(0, items.indexOf(document.activeElement as HTMLButtonElement)); if (menu.repeated('down')) index = (index + 1) % items.length; if (menu.repeated('up')) index = (index + items.length - 1) % items.length; if (index !== items.indexOf(document.activeElement as HTMLButtonElement)) items[index]?.focus(); if (menu.justPressed('confirm')) items[index]?.click(); if (menu.justPressed('back')) closeMenu(); } ``` Keep the menu as real `