# Manager UI (part 4): Keyboard and gamepad navigation

> Learn how to extend your UI with gamepad and keyboard navigation support.

> Documentation index: https://coherent-labs.com/llms.txt lists every page of this documentation as Markdown; the full text is in https://coherent-labs.com/llms-full.txt.

Source: https://coherent-labs.com/blog/uitutorials/manager-ui/keyboard-and-gamepad-navigation/

## Manager UI (part 4): Keyboard and gamepad navigation

ui tutorials

4/16/2025

Martin Bozhilov

1. Overview
2. Setting up the Interaction manager
   1. Setting up navigatable areas
3. Setting Up Interaction State
   1. 1\. Define interaction phases
   2. 2\. Hook up global switch events
   3. 3\. Hook up global confirm and back events
   4. 4\. Hook up global remove events
4. Adding keyboard and gamepad interactions to the Grid
   1. 1\. Define key and gamepad-mapping arrays
   2. 2\. Listen for global confirm/back events
   3. 3\. Track the focused grid item
   4. 4\. Handle “Confirm” in the grid
   5. 5\. Handle “Back” in the grid
5. Listening for events in the navigation
6. Adding Controller Button Tips
7. Conclusion

This is the fourth tutorial in the Manager UI series. In the previous tutorial, we added the “Team Roster” screen.

In this tutorial we will extendend our UI by making it fully navigatable using keyboard and gamepad.

If you wish to follow along, begin with the first tutorial of the series where we initialize and setup the project. Additionally, you can find the complete Manager UI sample in the `${Gameface package}/Samples/uiresources/UITutorials/ManagerUI` directory.

## Overview

In this tutorial we’ll add full keyboard and gamepad support by leveraging [Gameface’s Interaction manager ](https://coherentlabs.github.io/GameUIComponents/en/interaction-manager/introduction/). This library makes it easy to define “focusable” zones of your UI—called navigable areas—and to wire up both keyboard and gamepad events to those zones, so users can seamlessly move around your interface using arrow keys, WASD, or a controller.

## Setting up the Interaction manager

Let’s install the library in our project with:

```bash
npm install coherent-gameface-interaction-manager
```

Then, in each component where you need navigation support, import only the modules you’ll use:

### Setting up navigatable areas

To keep the helper interaction functions in one place, let’s create an `interaction` folder in the `src`. In the `index.ts` we can import all interaction manager modules we need and define an `areaMappings` array which we will populate with all navigatable areas.

The [Spatial Navigation ](https://coherentlabs.github.io/GameUIComponents/en/interaction-manager/spatial-navigation/)module expects each area to be an object with:

- `area`: a string key (we’ll enforce this with a TypeScript union type)
- `elements`: an array of CSS selectors identifying the focusable elements in that area

```ts
// @ts-ignore
import { spatialNavigation, keyboard, gamepad, actions } from 'coherent-gameface-interaction-manager';
import { NavigatableAreaName } from '../types/types';

interface NavigatableArea { area: NavigatableAreaName, elements: string[] }
export const areaMappings: NavigatableArea[] = [];
```

By using a `NavigatableAreaName` union, you get autocomplete during development and immediate feedback if you mistype an area name. In the future we can easily extend it by adding more area names to it.

```ts
export type NavigatableAreaName = 'grid' | 'side-nav'
```

Next, in the onMount hook of each component that contains focusable elements—such as your `Grid` and `SideNav` components—push a mapping into `areaMappings`:

```tsx
onMount(() => {
    // Existing code
    areaMappings.push({area: 'grid', elements: [`.${styles.CellItem}`]})
}
```

```tsx
onMount(() => {
    areaMappings.push({area: 'side-nav', elements: [`.${IconStyles['Icon-Image']}`]})
})
```

Once all areas are registered, you can initialize the `Spatial Navigation`:

```tsx
export const initSpatialNavigation = () => {
    spatialNavigation.init(areaMappings)
    // Change keys will add WASD as a valid combination for navigation
    spatialNavigation.changeKeys({ up: 'W', down: 's', left: 'a', right: 'd' });
}

export const deinitSpatialNavigation = () => {
    spatialNavigation.deinit();
}
```

And finally, create a helper to start everything and focus the first element in your sidebar:

```tsx
export const initDefaultNavigationActions = () => {
    initSpatialNavigation()
    spatialNavigation.focusFirst('side-nav')
}
```

Call `initDefaultNavigationActions()` from your `Hud.tsx` entry component (after a short `delayExecution` to ensure the DOM is ready), and you’ll immediately be able to navigate with arrow keys or WASD.

```tsx
import { initDefaultNavigationActions } from '../../Interactions/index';
const Hud = () => {

  setGridState('items', GridData.gridItems)

  delayExecution(() => {
    initDefaultNavigationActions();
  }, 4)
// rest of the component body
```

## Setting Up Interaction State

Before wiring up input handlers, let’s define the “phases” our UI can be in and update our shared state accordingly. We’ll use three primary actions:

- **Confirm** - Triggered by `ENTER` (keyboard) or `X` (PlayStation) / `A` (Xbox) on gamepad. This will select items, begin drags/resizes, or drill into an inner screen.
- **Back** - Triggered by `ESC` (keyboard) or `O` (PlayStation) / `B` (Xbox) on gamepad. This cancels the current action or pops focus back out.
- **Switch** - Triggered by `TAB` (keyboard) or `L1` (PlayStation) / `LB` (Xbox) on gamepad. This toggles focus between different navigable areas (e.g. side-nav ↔ grid).

With that thought through, we can proceed with setting up the listeners for these events, we are going to achieve this with the help of the Interaction manager’s [Keyboard ](https://coherentlabs.github.io/GameUIComponents/en/interaction-manager/keyboard/)and [Gamepad ](https://coherentlabs.github.io/GameUIComponents/en/interaction-manager/gamepad/)classes to bind these actions and emit events via [Gameface UI’s global `eventBus` ](https://gameface-ui.coherent-labs.com/concepts/ui-communication/)class, which allows us to emit and listen for events everywhere in the application.

### 1. Define interaction phases

First, lets declare an TS enum with all UI phases:

```tsx
export enum PHASE {
  SIDE_NAV = "SIDE_NAV",
  GRID_IDLE = "GRID_IDLE",
  GRID_DRAG = "GRID_DRAG",
}

export interface gridInteractionType {
  dragging: boolean,
  resizing: boolean,
  draggedItem: Item | null,
  dropPosition: Position | null,
  isSwapCooldown: boolean,
  shouldDrag: boolean,
  draggedRow: HTMLDivElement | null,
  phase: PHASE
}
```

Then initialize the store in `store/gridInteractionStore.ts`, defaulting to the sidebar being in focus:

```tsx
export const gridInteractionState = createMutable<gridInteractionType>({
    dragging: false,
    resizing: false,
    draggedItem: null,
    dropPosition: null,
    isSwapCooldown: false,
    shouldDrag: true,
    draggedRow: null,
   phase: PHASE.SIDE_NAV,
});
```

### 2. Hook up global switch events

In the src/Interactions/index.ts, register keyboard and gamepad listeners that emit semantic events:

To switch areas we will add press event on keyboard tab or the gamepad right sholder button.

```tsx
export const initDefaultNavigationActions = () => {
    initSpatialNavigation();
    spatialNavigation.focusFirst('side-nav');

    // Switch areas (TAB / L1)
    keyboard.on({
        keys: ['TAB'],
        callback: () => {
            handleTabSwitch();
        },
        type: ['press']
    });

    gamepad.on({
        actions: [4], // playstation.l1 / xbox.lb
        callback: () => {
            handleTabSwitch();
        },
        type: 'press',
    })

}
```

We emit `confirm-pressed` and `back-pressed` events so components can react in a decoupled way. The `handleTabSwitch` function will inspect `gridInteractionState.phase` and call `spatialNavigation.switchArea(...)` to toggle focus on the area.

```ts
const handleTabSwitch = () => {
    let areaToFocus: NavigatableAreaName = 'side-nav';
    switch (gridInteractionState.phase) {
        case PHASE.SIDE_NAV:
            areaToFocus = 'grid';
            gridInteractionState.phase = PHASE.GRID_IDLE;
            break;
        case PHASE.GRID_IDLE:
            areaToFocus = 'side-nav';
            gridInteractionState.phase = PHASE.SIDE_NAV;
            break;
        case PHASE.GRID_DRAG:
            return;
    }

    spatialNavigation.switchArea(areaToFocus);
}
```

### 3. Hook up global confirm and back events

We’ll also add the confirm and back events the same way we did with the switch event:

We’ll bind `ENTER` on the keyboard and `face-button-down` on the gamepad for the confirm action, and `ESC` on the keyboard and `face-button-right` on the gamepad for the back action.

```tsx
export const initDefaultNavigationActions = () => {
    //TAB SWITCH LOGIC HERE

    // Confirm (ENTER / X or A)
    keyboard.on({
        keys: ['ENTER'],
        callback: () => {
            eventBus.emit('confirm-pressed');
        },
        type: ['press']
    })

    gamepad.on({
        actions: [0], // playstation.x / xbox.a
        callback: () => {
            eventBus.emit('confirm-pressed');
        },
        type: 'press',
    })

    // Back (ESC / O or B)
    keyboard.on({
        keys: ['ESC'],
        callback: () => {
            eventBus.emit('back-pressed');
        },
        type: ['press']
    })

    gamepad.on({
        actions: [1], // playstation.circle / xbox.b
        callback: () => {
            eventBus.emit('back-pressed');
        },
        type: 'press',
    })
}
```

### 4. Hook up global remove events

One more thing we have to setup is a ‘remove’ event, which will be responsible for removing a grid item.

We’ll bind `Backspace` on the keyboard and `face-button-up` on the gamepad for the remove action.

```tsx
export const initDefaultNavigationActions = () => {
    // Rest of the events
    keyboard.on({
        keys: ['Backspace'],
        callback: removeItemWithKey,
        type: ['press']
    })

    gamepad.on({
        actions: [3], // playstation.triangle / xbox.y
        callback: removeItemWithKey,
        type: 'press',
    })
}
```

And we can directly implement the `removeItemWithKey` handler function. The logic will be fairly simple:

- If the state is `GRID_IDLE` we want to remove the item we are currently focusing.
- Focus the next available item on the grid.
- If there are no items focus on the side navigatio and change the interaction state to `SIDE_NAV`

```tsx
const removeItemWithKey = () => {
    const item = gridInteractionState.focusedItem;

    if (item && gridInteractionState.phase === PHASE.GRID_IDLE) {
        removeItem(item.id);
        const nextAvailableItem = gridState.items.find((i) => i.active);

        if (nextAvailableItem) {
            gridState.itemRefs.get(nextAvailableItem.id)?.focus();
            return;
        }

        spatialNavigation.switchArea('side-nav');
        gridInteractionState.phase = PHASE.SIDE_NAV;
    }
}
```

## Adding keyboard and gamepad interactions to the Grid

Now that our global confirm/back/tab handlers are in place, it’s time to wire up the `Grid` component so that it responds to those events and lets the user drag, move, and resize items via keyboard or gamepad.

### 1. Define key and gamepad-mapping arrays

At the top of `Grid.tsx`, define two arrays that pair directional inputs with our internal “up/down/left/right” meanings:

```tsx
const keyMovements: {keys: string[], direction: Direction}[] = [
    {keys: ['W', 'ARROW_UP'], direction: 'up'},
    {keys: ['S', 'ARROW_DOWN'], direction: 'down'},
    {keys: ['A', 'ARROW_LEFT'], direction: 'left'},
    {keys: ['D', 'ARROW_RIGHT'], direction: 'right'},
];

const gamepadMappings: {key: string, direction: Direction}[] = [
    {key: 'playstation.d-pad-up', direction: "up"},
    {key: 'playstation.d-pad-down', direction: "down"},
    {key: 'playstation.d-pad-left', direction: "left"},
    {key: 'playstation.d-pad-right', direction: "right"},
];
```

These will be used when we begin dragging/resizing to register actions.

### 2. Listen for global confirm/back events

Inside your `onMount`/`onCleanup` in Grid.tsx, hook into the `eventBus` so we can react when the user presses confirm or back: We must also clean this handlers in the `onCleanup` event **to avoid memory leaks.**

```tsx
onMount(() => {
    delayExecution(() => {
        areaMappings.push({area: 'grid', elements: [`.${styles.CellItem}`]})
       eventBus.on('confirm-pressed', handleConfirm);
       eventBus.on('back-pressed', handleBack);
    })
})

onCleanup(() => {
    window.removeEventListener("mousemove", handleMouseMove);
    window.removeEventListener("mouseup", handleMouseUp);

    eventBus.off('confirm-pressed', handleConfirm);
    eventBus.off('back-pressed', handleBack);
});
```

### 3. Track the focused grid item

Modify your grid‐interaction store (`store/gridInteractionStore.ts`) to include a `focusedItem`: Another thing we have to setup before implementing any logic is to add a `focusedItem` state to our `gridInteractionState` store and add an `onFocus` event to set the focused item state when the item is focused. This way we will be able to extract the properties of the focused item when we need them.

```ts
export interface gridInteractionType {
  // …existing fields…
  focusedItem: Item | null;
  phase: InteractionPhase;
}

export const gridInteractionState = createMutable<gridInteractionType>({
  // …existing initial values…
  focusedItem: null,
  phase: 'SIDE_NAV',
});
```

Now let’s now add the `onFocus` event in the grid component, where we loop through all items and render them. We’ll also disable inactive items so Spatial Navigation skips them:

```tsx
<For each={gridState.items} >
    {(item) => {
        const ScreenComponent = screenRegistry[item.name];
        return (
            <div
                ref={(el) => gridState.itemRefs.set(item.id, el)}
                style={{
                    top: `${item.y}px`,
                    left: `${item.x}px`,
                }}
                class={`${styles[`Item-${item.sizeX}x${item.sizeY}`]} ${styles.CellItem} ${item.active ? styles.Active : styles.Inactive}`}
                bool:disabled={!item.active}
                onFocus={() => gridInteractionState.focusedItem = item}
                onMouseDown={(e) => handleMouseDown(e, item)}>
                <Dynamic component={ScreenComponent} name={item.name} />
                <div class={styles['CellItem-drag']} ></div>
                <div class={styles['CellItem-close']} onClick={() => removeItem(item.id)}>
                    <div class={styles.CloseIcon}>X</div>
                </div>
            </div>
        )
    }}
</For>
```

### 4. Handle “Confirm” in the grid

We can proceed with setting up the `handleConfirm` function.

```tsx
const handleConfirm = () => {
    switch (gridInteractionState.phase) {
        case PHASE.SIDE_NAV:
            eventBus.emit('side-nav-item-selected')
            break;
        case PHASE.GRID_IDLE:
            // Start dragging/move-resize mode
            initGridItemDrag(gridInteractionState.focusedItem!);
            gridInteractionState.phase = PHASE.GRID_DRAG;
            break;
        case PHASE.GRID_DRAG:
            // Switch to inner screen focus
            deinitGridItemDrag();
            selectInnerScreen(gridInteractionState.focusedItem!);
            break;
    }
}
```

First, we need to implement `initGridItemDrag`. In this function we are going to deinit the spatial navigation and register new [Interaction manager actions ](https://coherentlabs.github.io/GameUIComponents/en/interaction-manager/actions/)that we will then register to the relevant keys and buttons from our mapping arrays.

The reason we need to deinit the spatial navigation is that we want to use the same keys that are assigned by the spatial navigation when it is initialized.

The `actions` need to be assigned a name and a callback which will be executed when the action is called:

```tsx
const initGridItemDrag = (item: Item) => {
    gridState.itemRefs.get(item.id)?.classList.add(styles.Moving)

    batch(() => {
        gridInteractionState.dragging = true;
        gridInteractionState.draggedItem = item;
        gridInteractionState.dropPosition = {col: item.col, row: item.row};
    })

    deinitSpatialNavigation();
    keyMovements.forEach(({keys, direction}) => {
        actions.register(`move-item-${direction}`, (e: KeyboardEvent) => handleKeyMove(e, item, direction))
        keys.forEach((key) => {
            keyboard.on({
                keys: [key],
                callback: `move-item-${direction}`,
                type: ['press']
            });
        })
    })

    gamepadMappings.forEach(({key, direction}) => {
        actions.register(`resize-item-${direction}`, () => resizeItem(item, direction));

        gamepad.on({
            actions: [key, 'playstation.r1'],
            callback: `resize-item-${direction}`,
            type: 'hold',
        })
        gamepad.on({
            actions: [key],
            callback: `move-item-${direction}`,
            type: 'press',
        })
    })
}
```

In the `handleKeyMove` function we are going to check if the `ctrl` key has been pressed and if it has been we will trigger item resize. On the gamepad we cannot do this like that because there is no event information. Instead we will just add 2 different key combinations. If one of the `d-pad` keys is pressed in combination with the `r1` button, then we are going to resize, otherwise just move.

First let’s add the `handleKeyMove` implementation:

```tsx
const handleKeyMove = (event: KeyboardEvent | null, item: Item, direction: Direction) => {
    if (event && event.ctrlKey) {
        resizeItem(item, direction);
        return;
    }

    moveItem(item, direction);
    updateDropPosition(item, item.x, item.y);
    setGridState('items', i => i.id === item.id, produce((i) => {
        i.col = gridInteractionState.dropPosition!.col;
        i.row = gridInteractionState.dropPosition!.row;
    }));
}

const moveItem = (item: Item, direction: Direction) => {
    const {cellWidth, cellHeight, gapX, gapY, maxWidth, maxHeight, minWidth, minHeight} = gridState.config;
    let newX = item.x;
    let newY = item.y;

    switch (direction) {
        case 'right':
            newX = clamp(item.x + (cellWidth + gapX), maxWidth, minWidth);
            break;
        case 'left':
            newX = clamp(item.x - (cellWidth + gapX), maxWidth, minWidth);
            break;
        case 'up':
            newY = clamp(item.y - (cellHeight + gapY), maxHeight, minHeight);
            break;
        case 'down':
            newY = clamp(item.y + (cellHeight + gapY), maxHeight, minHeight);
            break;
    }

    setGridState('items', i => i.id === item.id, produce((i) => {
        i.x = newX;
        i.y = newY;
    }));
};

const updateDropPosition = (item: Item, left: number, top: number) => {
    const { col, row } = getGridPosition(left, top, MAXCOLS, MAXROWS)

    const prevPosition = gridInteractionState.dropPosition;
    if (!prevPosition || row !== prevPosition.row || col !== prevPosition.col) {
        gridInteractionState.dropPosition = {col, row}
    }

    if (!memoizedCellValidation()) {
        handleOverlap(row, col, item)
        gridInteractionState.dropPosition = { col: item.col, row: item.row }
    }
}
```

The dragging logic is mostly reused from the mouse move event we set up in the first tutorial of this series, with the exception that instead of checking for the mouse location we are moving one `gridCell` to the direction that has been pressed. To determine if the new position of the item we are dragging is valid we are going to take the exact same piece of logic from the `mousemove` event and put it in a separate `updateDropPosition` function. As a bonus we can now use this new function to simplify the `mouseMoveHandler` function.

```tsx
const handleMouseMove = (e: MouseEvent) => {
    if (!gridInteractionState.draggedItem || !gridRef) return;

    const dx = Math.abs(e.clientX - startMouseX);
    const dy = Math.abs(e.clientY - startMouseY);
    // Only trigger actions if the pointer has moved enough
    if (dx < DRAG_THRESHOLD && dy < DRAG_THRESHOLD) return;

    const mouseX = e.clientX
    const mouseY = e.clientY

    const itemleft = mouseX - offsetX;
    const itemTop = mouseY - offsetY;

    const currentItem = gridInteractionState.draggedItem;

    gridState.itemRefs.get(currentItem!.id)?.classList.add(styles.Dragging)
    // Pass them as fallback to return to prev place
    const currentItemRow = currentItem?.row
    const currentItemCol = currentItem?.col

   if (gridInteractionState.dragging && currentItem) {
        updateDropPosition(currentItem, itemleft, itemTop)
        changeItemPosition(currentItem, mouseX, mouseY);
        const { col, row } = getGridPosition(itemleft, itemTop, MAXCOLS, MAXROWS)

        changeItemPosition(currentItem!, mouseX, mouseY);

        const prevPosition = gridInteractionState.dropPosition;
        if (!prevPosition || row !== prevPosition.row || col !== prevPosition.col) {
            gridInteractionState.dropPosition = {col, row}
        }

        if (!memoizedCellValidation()) {
            handleOverlap(row, col, currentItem)
            gridInteractionState.dropPosition = { col: currentItemCol, row: currentItemRow }
        }
    }

    if (gridInteractionState.resizing && currentItem) {
        const { col, row } = getGridPosition(itemleft, itemTop, MAXCOLS - 1, MAXROWS - 1)
        changeSize(currentItem, mouseX, mouseY, col, row);
        gridInteractionState.dropPosition = { col: currentItemCol, row: currentItemRow }
    }
};
```

Now let’s implement the resize function. The function is fairly simple, we are just taking the current size X or Y of the item and check if the position with this new size is valid (it is not overlapping with other elements) and if it is - we update the state of the item.

```tsx
const resizeItem = (item: Item, direction: Direction) => {
    let newSizeX = item.sizeX;
    let newSizeY = item.sizeY;

    switch (direction) {
        case 'right':
            newSizeX = item.sizeX + 1;
            break;
        case 'left':
            newSizeX = item.sizeX - 1;
            break;
        case 'up':
            newSizeY = item.sizeY - 1;
            break;
        case 'down':
            newSizeY = item.sizeY + 1;
            break;
    }

    const { col, row } = getGridPosition(item.x, item.y, MAXCOLS - 1, MAXROWS - 1)

    if (isCellBlockValid(row, col, item, newSizeX, newSizeY)) {
        setGridState('items', i => i.id === item.id, produce((i) => {
            i.sizeX = clamp(newSizeX, i.maxSizeX, i.minSizeX);
            i.sizeY = clamp(newSizeY, i.maxSizeY, i.minSizeY);
        }));
        gridInteractionState.dropPosition = {col, row}
    }
}
```

We can now use the keyboard and gamepad to drag around and resize the grid items!

Next, we’ll need to handle when the user clicks `confirm` again. We want to end the drag state and focus in on the selected element’s screen. We already set up the function we need to call for this to happen - `deinitGridItemDrag` and `selectInnerScreen`. For now we’ll just setup the former. In the deinit function we will reuse the `handleMouseUp` handler to deinit dragging, unregister the `move-item` actions and keyboard/gamepad events and finally reinit the spatial navigation.

```tsx
const deinitGridItemDrag = () => {
    handleMouseUp();
    gridInteractionState.phase = PHASE.GRID_IDLE;
    //deinit keyboard
    keyMovements.forEach(({keys, direction}) => {
        keys.forEach((key) => keyboard.off([key]));
        actions.remove(`move-item-${direction}`);
    })
    //deinit gamepad
    gamepadMappings.forEach(({key, direction}) => {
        gamepad.off([key, 'playstation.r1']);
        gamepad.off([key]);
        actions.remove(`resize-item-${direction}`);
    })
    initSpatialNavigation();
}
```

We can now proceed with implementing the opposite interactions - pressing back.

### 5. Handle “Back” in the grid

We’ve already referenced the `handleBack` handler, what’s left is to implement it. When the phase is either `SIDE_NAV` or `GRID_IDLE` we’ll just return without doing anything. When the phase is `GRID_DRAG` we are going to again end the dragging state, as well as focus back on the same item, in order to not lose the focus.

```tsx
const handleBack = () => {
    switch (gridInteractionState.phase) {
        case PHASE.SIDE_NAV:
        case PHASE.GRID_IDLE:
            break;
        case PHASE.GRID_DRAG:
            // Switch to inner screen focus
            deinitGridItemDrag();
            gridState.itemRefs.get(gridInteractionState.focusedItem!.id)!.focus();
            gridInteractionState.phase = PHASE.TEAM_ROSTER_TABLE;
            break;
    }
};
```

With all of the above in place, your Grid component will now:

- React to Confirm by entering drag/resize or drilling in
- Let users move items one cell at a time with arrow/WASD or D-pad
- Resize with Ctrl+arrows (keyboard) or D-pad+R1 (gamepad)
- Cancel any drag/resize with Back (Esc/B)
- Restore full spatial navigation once the action completes

## Listening for events in the navigation

When the user confirms while focused on the sidebar (`SIDE_NAV`), we emit a `side-nav-item-selected` event. Next, we’ll make the `SideNav` component react by adding the selected icon to the grid and moving focus forward.

1. **Track the focused icon**\
   In `SideNav.tsx`, add a `selectedItem` signal to remember which `NavIcon` was last focused.

2. **Handle keyboard activation**\
   Create a `handleKeyInteraction` callback that calls your existing `clickHandler` using `selectedItem()`.

3. **Subscribe/unsubscribe to the eventBus**\
   In `onMount`, register `side-nav-item-selected → handleKeyInteraction`; in `onCleanup`, remove that listener.

4. **Wire up `NavIcon`**\
   Pass `setSelectedItem` down to each `<NavIcon>`, then in `NavIcon.tsx` add `focus` and `blur` handlers to update the signal and show/hide the tooltip.

```tsx
import { areaMappings, focusNext } from '../../Interactions/index';
import eventBus from '@components/tools/EventBus';

const SideNav: Component = () => {
    const [toastMessage, setToastMessage] = createSignal("");
    const [showError, setShowError] = createSignal<boolean>(false);
    const [selectedItem, setSelectedItem] = createSignal<Item | null>(null);

    const imageMap = new Map<number, string>([
        [1, teamRosterIcon],
        [2, matchTacticsIcon],
        [3, teamSettingsIcon],
        [4, playerStatsIcon],
        [5, matchCalendarIcon],
        [6, teamMoraleIcon],
        [7, financialsIcon],
        [8, transferMarketIcon],
        [9, matchStatsIcon],
        [10, teamNewsIcon],
        [11, scoutingIcon],
        [12, managerStats],
    ]);

    const clickHandler = (item: Item) => {
        const isAdded = addItem(item.id);
        setShowError(false); // reset first

        if (!isAdded) {
            setToastMessage(`Unable to show ${item.name} window`);
            setTimeout(() => setShowError(true), 0);
        } else {
            setShowError(false);
            focusNext();
        }
    }

    const handleKeyInteraction = () => {
        clickHandler(selectedItem()!);
    }

    onMount(() => {
        areaMappings.push({area: 'side-nav', elements: [`.${IconStyles['Icon-Image']}`]})
        eventBus.on('side-nav-item-selected', handleKeyInteraction)
    })

    onCleanup(() => {
        eventBus.off('side-nav-item-selected', handleKeyInteraction)
    })

    return (
        <Flex direction='column' justify-content='start' align-items='center' class={styles.SideBar}>
            <Block class={styles.Logo}>
                <Image src={GameLogo} class={styles.LogoImage} />
            </Block>
            <Flex direction='column'>
                <For each={gridState.items}>
                   {(item) => <NavIcon item={item} imageMap={imageMap} click={clickHandler} />}
                   {(item) => <NavIcon item={item} imageMap={imageMap} click={clickHandler} setSelectedItem={setSelectedItem} />}
                </For>
            </Flex>
            <Toast show={showError()} onHide={() => setShowError(false)}>
                <Flex align-items='center'>
                    <Image src={cancelIcon} class={styles['Error-Icon']} />
                    <TextBlock>{toastMessage()}</TextBlock>
                </Flex>
            </Toast>
        </Flex>
    )
}

export default SideNav
```

```tsx
type NavIconProps = {
    item: Item,
    imageMap: Map<number, string>,
    click: (item: Item) => void,
    setSelectedItem: Setter<Item | null>
}

const NavIcon: Component<NavIconProps> = ({item, imageMap, click, setSelectedItem}) => {
    const [showTooltip, setShowTooltip] = createSignal(false);

    const handleFocus = () => {
        setShowTooltip(true);
        setSelectedItem(item);
    }

    return (
        <Block class={`${styles.Icon} ${item.active ? styles['Icon-Disabled'] : ''}`} >
            <Tooltip show={showTooltip()}>
                <Flex align-items="center">
                    <Image src={infoIcon} class={styles.InfoIcon} />
                    <TextBlock style={{margin: 0}}>{item.name}</TextBlock>
                </Flex>
            </Tooltip>
            <Image
                class={`${styles['Icon-Image']} ${item.active ? styles['Icon-Image-Disabled'] : ''}`}
                bool:disabled={item.active}
                click={() => click(item)}
                mouseenter={() => setShowTooltip(true)}
                mouseleave={() => setShowTooltip(false)}
                focus={handleFocus}
                blur={() => setShowTooltip(false)}
                src={imageMap.get(item.id)!} />
        </Block>
    )
}

export default NavIcon
```

We’ve also added a `focusNext` utility function which is called if an item has been added successfully to the grid and will just focus the next focusable element in the area.

```ts
export const focusNext = () => {
    actions.execute("move-focus-down")
}
```

With that in place, confirming on a focused icon adds it to the grid and then calls `focusNext()` to advance the highlight.

## Adding Controller Button Tips

To help users remember which buttons do what in each phase, we’ll display context-aware hints in the bottom-right corner.

1. Define your mappings

In` src/Interactions/gamepadMappings.ts`, export a `gamepadMappings` object keyed by each `InteractionPhase`:

```ts
import aButton from "@assets/gamepad-controls/a-filled-green.svg"
import bButton from "@assets/gamepad-controls/b-filled-red.svg"
import rb from "@assets/gamepad-controls/right-bumper.svg"
import lb from "@assets/gamepad-controls/left-bumper.svg"
import rJoystick from "@assets/gamepad-controls/right-joystick.svg"
import { PHASE } from "../types/types"

type GameMappingsType = {
    [K in keyof typeof PHASE]: { icon: string; text: string }[];
};

export const gamepadMappings: GameMappingsType = {
    SIDE_NAV: [
        { icon: aButton, text: 'Add Item' },
        { icon: lb, text: 'Swtich tab' },
    ],
    GRID_IDLE: [
        { icon: aButton, text: 'Select Item' },
        { icon: yButton, text: 'Remove Item' },
        { icon: lb, text: 'Swtich tab' },
    ],
    GRID_DRAG: [
        { icon: aButton, text: 'Enter screen' },
        { icon: bButton, text: 'Back' },
        { icon: rb, text: 'Hold to resize' },
    ],
}
```

2. Expose the current set In src/Interactions/index.ts, add:

```tsx
export const getCurrentGamepadMapping = () => {
    return gamepadMappings[gridInteractionState.phase]
}
```

3. Build the `ButtonTips` component Create `custom-components/Util/ButtonTips.tsx`:

```tsx
import Absolute from "@components/Layout/Absolute/Absolute";
import Flex from "@components/Layout/Flex/Flex";
import { For } from "solid-js";
import { getCurrentGamepadMapping } from "../../Interactions";
import Image from "@components/Media/Image/Image";
import TextBlock from "@components/Basic/TextBlock/TextBlock";

const ButtonTips = () => {
    return (
        <Absolute bottom="0" right="0" style={{color: "white", "font-size": '1vmax', "text-transform": 'uppercase', 'font-weight': 'bold', 'z-index': '9999999'}}>
            <Flex align-items="center">
                <For each={getCurrentGamepadMapping()} >
                    {(item) => (
                        <Flex align-items="center" style={{"margin-right": "1vmax"}}>
                            <Image src={item.icon} style={{"width": "1.5vmax", "height": "1.5vmax", "margin-right": '0.25vmax'}}></Image>
                            <TextBlock>{item.text}</TextBlock>
                        </Flex>
                    )}
                </For>
            </Flex>
        </Absolute>
    )
}

export default ButtonTips;
```

4. Render in your HUD Finally, import and include `<ButtonTips />` in `views/hud/Hud.tsx`:

```tsx
import ButtonTips from '@custom-components/Util/ButtonTips';
const Hud = () => {

  setGridState('items', GridData.gridItems)

  gamepad.enabled = true;
  gamepad.pollingInterval = 100;
  delayExecution(() => {
    initDefaultNavigationActions();
  }, 4)

  return (
    <Layout>
      <Row class={styles.Hud} >
        <Column1>
          <SideNav />
        </Column1>
        <Column11>
          <Grid />
        </Column11>
      </Row>
      <ButtonTips />
    </Layout>
  );
};
```

Now players will always see the relevant gamepad hints—ADD, SELECT, BACK, SWITCH and RESIZE—right when they need them!

## Conclusion

We’ve successfully implemented full keyboard and gamepad navigation in our UI using Gameface’s Interaction Manager. The system is modular, easily extendable, and sets a strong foundation for adding interaction support to additional screens.

In the next part of this tutorial series, we’ll expand this system to include the Team Roster screen and explore how to handle more complex input flows across multiple components.

## On this page
