# Manager UI (part 5): Team Roster - 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/team-roster-keyboard-gamepad-interactions/

## Manager UI (part 5): Team Roster - Keyboard and gamepad navigation

ui tutorials

4/17/2025

Martin Bozhilov

1. Overview
2. General setup
   1. Adding the interaction phases
   2. Registering Navigable Areas
   3. Selecting an Inner Screen
   4. Exiting an Inner Screen
   5. Interaction flow
   6. Updating Gamepad Button Hints
3. Implementing the interactions
   1. Handling table sort
   2. Reordering Player Rows
   3. Scrolling with the Right Joystick
4. Conclusion

This is the fifth tutorial in the Manager UI series. In the previous tutorial, we implemented full keyboard and gamepad support using Gameface’s Interaction Manager.

In this tutorial, we’ll build on that by extending the interaction system to support the **Team Roster screen**, enabling users to navigate and interact with it using a controller or keyboard.

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

From this point forward, each screen we add to the Manager UI will include support for keyboard and gamepad interactions. In this post, we’ll enhance the existing **Team Roster** screen by:

- Adding support for spatial navigation between table header and rows
- Enabling sorting via buttons
- Supporting drag-and-drop reordering of rows using a gamepad or keyboard
- Allowing scroll control using the right joystick

## General setup

Just like in the previous tutorial, setting up interaction support for a new screen involves two main steps:

1. Defining the **interaction phases**
2. Registering the screen’s **navigable areas**

We’ll start by extending the interaction phase types to include Team Roster-specific states, and then set up spatial navigation for the new areas.

### Adding the interaction phases

First, extend the `PHASE` enum to include three new states related to the Team Roster screen:

- `TEAM_ROSTER_HEADER` - The player has focused the Team Roster screen. We’ll initially place focus on the table header.
- `TEAM_ROSTER_TABLE` - The player is navigating the rows of the roster table.
- `TEAM_ROSTER_DRAG` - The player has selected a row and entered the drag-and-drop state.

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

### Registering Navigable Areas

Next, we’ll define two new navigable areas: one for the header and one for the table body. These will allow keyboard and gamepad users to move between the table’s UI elements.

In the `onMount` function of the `TeamRoster` component, add the following:

```tsx
onMount(() => {
    areaMappings.push({ area: 'team-roster-header', elements: [`.${styles['Header-Button']}`] })
    areaMappings.push({ area: 'team-roster-table', elements: [`.${styles.PlayerRow}`] })
})
```

Also update the `NavigatableAreaName` type to include these new areas:

```ts
export type NavigatableAreaName = 'grid' | 'side-nav'
export type NavigatableAreaName = 'grid' | 'side-nav' | 'team-roster-header' | 'team-roster-table'
```

Now that we’ve added new interaction phases and areas, we need to update the `handleTabSwitch` function to support switching between them.

```ts
const handleTabSwitch = () => {
    let areaToFocus: NavigatableAreaName = 'side-nav';
    switch (gridInteractionState.phase) {
        case "SIDE_NAV":
            areaToFocus = 'grid';
            gridInteractionState.phase = "GRID_IDLE";
            break;
        case "GRID_IDLE":
            areaToFocus = 'side-nav';
            gridInteractionState.phase = "SIDE_NAV";
            break;
        case "GRID_DRAG":
            return;
        case PHASE.TEAM_ROSTER_HEADER:
            areaToFocus = 'team-roster-table';
            gridInteractionState.phase = PHASE.TEAM_ROSTER_TABLE;
            break;
        case PHASE.TEAM_ROSTER_TABLE:
            areaToFocus = 'team-roster-header';
            gridInteractionState.phase = PHASE.TEAM_ROSTER_HEADER;
            break;
        case PHASE.TEAM_ROSTER_DRAG:
            return;
    }

    spatialNavigation.switchArea(areaToFocus);
}
```

### Selecting an Inner Screen

When the player confirms a grid item selection in the `GRID_DRAG` phase, we call the `selectInnerScreen` function. This function is responsible for transferring focus to the selected screen’s UI and activating any additional behavior.

In the future, this function can handle logic for different screen types. For now, we’ll only implement the behavior for the **Team Roster** screen.

```tsx
const selectInnerScreen = (item: Item) => {
    switch (item.name) {
        case "Team Roster":
            gridInteractionState.phase = PHASE.TEAM_ROSTER_HEADER;
            spatialNavigation.switchArea('team-roster-header');
            eventBus.emit('handle-team-roster-scroll', 'init');
            break;
        default:
            // Until other screens are implemeneted -> return to idle
            handleMouseUp();
            initSpatialNavigation();
            gridState.itemRefs.get(gridInteractionState.focusedItem!.id)!.focus();
            gridInteractionState.phase = PHASE.GRID_IDLE;
            break;
    }

    gridInteractionState.dragging = false;
}
```

In this setup:

- We set the phase to `TEAM_ROSTER_HEADER`
- Focus shifts to the header elements via the `spatialNavigation`
- We emit a `handle-team-roster-scroll` event to enable scrolling with the right joystick

Any unimplemented screens will simply cancel the drag and return to the GRID_IDLE state.

### Exiting an Inner Screen

To complement the `selectInnerScreen` logic, we need a way to exit from an inner screen and return to grid drag mode.

We’ll define an `exitInnerScreen` utility function that:

- Re-initializes the grid drag state
- Sets the current phase to `GRID_DRAG`
- Optionally runs a cleanup callback (useful for deinitializing things like the joystick scrolling)

```tsx
const exitInnerScreen = (fn?: () => void) => {
    initGridItemDrag(gridInteractionState.focusedItem!);
    gridInteractionState.phase = PHASE.GRID_DRAG;

    fn && fn();
}
```

This gives us a consistent way to drill out of an inner screen, and allows each screen to define its own cleanup logic if needed.

### Interaction flow

Now that we’ve defined the phases and set up entry/exit functions, it’s time to expand the interaction handlers. This includes updating both `handleConfirm` and `handleBack` to respond appropriately based on the current phase.

Next we need to determine what the flow of the phases will be and extend the `handleConfirm` and `handleBack` handlers. For the confirm handler the flow will be as follows:

#### Confirm (ENTER / X)

Update `handleConfirm` in `Grid.tsx` to include the following logic:

```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 = "GRID_DRAG";
            break;
        case PHASE.GRID_DRAG:
            // Switch to inner screen focus
            deinitGridItemDrag();
            selectInnerScreen(gridInteractionState.focusedItem!);
            break;
       case PHASE.TEAM_ROSTER_HEADER:
           eventBus.emit('team-roster-table-sort');
           break;
       case PHASE.TEAM_ROSTER_TABLE:
           initPlayerDrag(gridInteractionState.focusedRow.element!, gridInteractionState.focusedRow.index!)
           gridInteractionState.phase = PHASE.TEAM_ROSTER_DRAG;
           break;
       case PHASE.TEAM_ROSTER_DRAG:
           deinitPlayerDrag()
           gridInteractionState.phase = PHASE.TEAM_ROSTER_TABLE;
           break;
        default:
            break;
    }
}
```

#### Back (ESC / O)

Similarly, extend the `handleBack` logic to support backing out of Team Roster phases:

```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();
            break;
        case PHASE.TEAM_ROSTER_HEADER:
            exitInnerScreen(() => eventBus.emit('handle-team-roster-scroll', 'deinit'))
            break;
        case PHASE.TEAM_ROSTER_TABLE:
            exitInnerScreen(() => eventBus.emit('handle-team-roster-scroll', 'deinit'))
            break;
        case PHASE.TEAM_ROSTER_DRAG:
            cancelPlayerDrag()
            gridInteractionState.phase = PHASE.TEAM_ROSTER_TABLE;
            break;
        default:
            break;
    }
};
```

With this setup, each phase now has clear behavior on confirm and back inputs.

### Updating Gamepad Button Hints

To maintain consistent feedback for users, we need to update the `gamepadMappings` object that powers the on-screen button tips.

Add new entries for the Team Roster interaction phases in `gamepadMappings.ts` that we created in the previous tutorial

```ts
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' },
    ],
    TEAM_ROSTER_HEADER: [
        { icon: aButton, text: 'Sort Players' },
        { icon: bButton, text: 'Back' },
        { icon: lb, text: 'Select players' },
        { icon: rJoystick, text: 'Scroll Up/Down' },
    ],
    TEAM_ROSTER_TABLE: [
        { icon: aButton, text: 'Select Player' },
        { icon: bButton, text: 'Back' },
        { icon: lb, text: 'Select header' },
        { icon: rJoystick, text: 'Scroll Up/Down' },
    ],
    TEAM_ROSTER_DRAG: [
        { icon: aButton, text: 'Place player' },
        { icon: bButton, text: 'Cancel' },
        { icon: rJoystick, text: 'Scroll Up/Down' },
    ],
}
```

With the Team Roster phases set up, we can proceed with implementing the logic for these interactions.

## Implementing the interactions

Now that the phases and transitions are wired up, let’s implement the actual behavior for each Team Roster interaction: sorting columns, dragging rows, and enabling scroll with the gamepad.

### Handling table sort

We’ll start by enabling sorting when focused on the table header.

#### Step 1: Track the Focused Column

In `TableHeader.tsx`, add a `currentKey` signal that stores the currently focused column key.

```tsx
const [currentSort, setCurrentSort] = createSignal<sortType>('ability');
const [currentKey, setCurrentKey] = createSignal<sortType>('ability')
```

#### Step 2: Listen for Confirm Events

We’ll respond to the global `team-roster-table-sort` event by calling the sort logic with the current focused key:

```tsx
const handleKeyPress = () => {
  handleSort(currentKey());
};

onMount(() => {
  handleSort(currentSort()); // initial sort
  eventBus.on('team-roster-table-sort', handleKeyPress);
});

onCleanup(() => {
  eventBus.off('team-roster-table-sort', handleKeyPress);
});
```

#### Step 3: Add Focus Handling in HeaderColumn

In `HeaderColumn.tsx`, notify the parent component when the column is focused:

```tsx
import Flex from "@components/Layout/Flex/Flex"
import { Accessor, createEffect, createSignal, ParentComponent, Setter } from "solid-js"
import styles from './TeamRoster.module.css';
import {sortType} from '../../../types/types';

interface Props {
    currentSort: Accessor<sortType>,
    asc: Accessor<boolean>,
    handleSort: (key: sortType) => void,
    setSortKey: Setter<sortType>
    sortBy: sortType
}

const HeaderColumn: ParentComponent<Props> = (props) => {
    const [isActive, setIsActive] = createSignal()

    createEffect(() => {
        const active = props.currentSort() === props.sortBy;
        setIsActive(active);
    });

    const clickHanlder = () => {
        props.handleSort(props.sortBy)
    }

    const focusHandler = () => {
        props.setSortKey(props.sortBy)
    }

    return (
        <Flex align-items="center" justify-content="center" class={styles['Header-Button']} click={clickHanlder} focus={focusHandler}>
            <Flex align-items="center" class={`${isActive() ? styles.ActiveCol : ''} ${props.asc() ? styles.asc: ''}`}>{props.children}</Flex>
        </Flex>
    )
}

export default HeaderColumn
```

Once that’s set up, keyboard/gamepad users can sort the table just by pressing the confirm button on a focused column.

### Reordering Player Rows

To support drag-and-drop row reordering with a controller or keyboard, we’ll reuse our existing mouse logic and expose it via event handlers.

The next state we are going to implement is the player’s row drag and drop. Since these event were set up in one of the previous tutorials with `data-bind-events` and are globaly available, we’d have to take the same approach.

#### Step 1: Track the Focused Row

In your `gridInteractionState`, add a `focusedRow` object:

```ts
export interface gridInteractionType {
    //other properties
    focusedItem: Item | null,
    focusedRow: {element: HTMLDivElement | null, index: number | null},
    phase: PHASE
}
```

```ts
export const gridInteractionState = createMutable<gridInteractionType>({
    //other properties
    focusedItem: null,
    focusedRow: {element: null, index: null},
    phase: PHASE.SIDE_NAV,
});
```

#### Step 2: Emit a Focus Event for Rows

```ts
window.playerFocus = (element: HTMLDivElement, index: number) => {
    gridInteractionState.focusedRow = { element, index };
    window.playerMouseEnter(element, index);
}
```

Now, update each TableRow to use it:

```tsx
const TableRow = (props: {sizeExpression: string}) => {
    return (
        <Row
            data-bind-for={'index, player:{{TeamRosterModel.players}}'}
            class={styles.PlayerRow}
            data-bind-mousedown="playerMouseDown(this, event, {{index}})"
            data-bind-mouseenter="playerMouseEnter(this, {{index}})"
            data-bind-mouseleave="playerMouseLeave(this)"
            data-bind-focus="playerFocus(this, {{index}})"
            data-bind-blur="playerMouseLeave(this)"
            >
            {/* rest of the component */}
```

#### Step 3: Scroll when focusing row out of view

Once we have the focused row’s HTML element, we can easily call the `scrollIntoView` method of the [Scroll ](https://gameface-ui.coherent-labs.com/components/layout/scroll/)component. We’ll add a `createEffect` to listen for state changes of the `focusedRow`-meaning that whenever we move the focus to a different row the code will execute.

```ts
createEffect(() => {
    if (gridInteractionState.focusedRow.element === null) return;

    scrollRef.scrollIntoView(gridInteractionState.focusedRow.element as HTMLDivElement);
})
```

#### Step 4: Create Drag/Drop Utilities

We’ll take some of the swapping logic and put it in separate functions that will take care of initiating and deintiating or canceling out of the dragging state. To not populate the `global.ts` file, we’ll create a separate `team-roster-utils.ts` file and put this logic there.

```ts
import { focusNext } from "../Interactions";
import { updateModel } from ".";
import { gridInteractionState } from "../store/gridInteractionStore";

export const playerDragState = {
    startMouseX: 0,
    startMouseY: 0,
    startLeft: 0,
    startTop: 0,
    startIndex: 0,
    dropIndex: 0,
    draggedRowRef: null as HTMLDivElement | null,
};

export const initPlayerDrag = (element: HTMLDivElement, index: number) => {
    const { width, height, left, top } = element.getBoundingClientRect();
    // clone html element
    gridInteractionState.draggedRow = element.cloneNode(true) as HTMLDivElement;
    const draggedElement = gridInteractionState.draggedRow;

    // set state
    playerDragState.startIndex = index;
    playerDragState.draggedRowRef = element;

    Object.assign(draggedElement.style, {
        width: `${width + 10}px`,
        height: `${height}px`,
        left: `${left}px`,
        top: `${top}px`,
        color: 'white',
    });

    // hide original element
    element.classList.add('hidden');
    focusNext();
    // attach dragging class on the player
    draggedElement.classList.add('player-row-dragging');

    return draggedElement;
}

export const deinitPlayerDrag = () => {
    let { startIndex, dropIndex } = playerDragState;
    // Reset
    cancelPlayerDrag();
    // Swap rows
    const playersArr = TeamRosterModel.players;
    if (startIndex < dropIndex) dropIndex--;
    const [elToSwap] = playersArr.splice(startIndex, 1);
    playersArr.splice(dropIndex, 0, elToSwap)

    updateModel(TeamRosterModel)
}

export const cancelPlayerDrag = () => {
    let { dropIndex, draggedRowRef } = playerDragState;
    // Reset
    gridInteractionState.draggedRow = null;
    draggedRowRef!.classList.remove('hidden');
    (draggedRowRef!.parentElement?.children[dropIndex] as HTMLDivElement).classList.remove('new-row-position');
}
```

**Bonus: Since we are reusing a lot of the logic, we can simplify the mouse logic we set up in the previous Team Roster screen tutorial .**

```ts
import { updatePositionStyles } from "./index";
import { gridInteractionState } from "../store/gridInteractionStore";
import { deinitPlayerDrag, initPlayerDrag, playerDragState } from "./team-roster-utils";

let startMouseX = 0;
let startMouseY = 0;
let startLeft = 0;
let startTop = 0;
let dropIndex = 0;

window.playerMouseDown = (element, event, index) => {
    // disable grid interactions
    gridInteractionState.shouldDrag = false;

    const { clientWidth, clientHeight } = element;

   // clone html element
    gridInteractionState.draggedRow = element.cloneNode(true) as HTMLDivElement;
    const draggedElement = gridInteractionState.draggedRow;

    Object.assign(draggedElement.style, {
        width: `${clientWidth}px`,
        height: `${clientHeight}px`,
        color: 'white',
    });

    // hide original element
    element.classList.add('hidden')

    // get starting mouse coordinates
    startMouseX = event.clientX;
    startMouseY = event.clientY;

    // get initial element position
    startLeft = startMouseX - (element.clientWidth / 2);
    startTop = startMouseY - (element.clientHeight / 2);

    updatePositionStyles(draggedElement, startLeft, startTop);

    // attach dragging class on the player
    draggedElement.classList.add('player-row-dragging');

    const draggedElement = initPlayerDrag(element, index);

    // get starting mouse coordinates
    playerDragState.startMouseX = event.clientX;
    playerDragState.startMouseY = event.clientY;
    // get initial element position
    playerDragState.startLeft = playerDragState.startMouseX - (element.clientWidth / 2);
    playerDragState.startTop = playerDragState.startMouseY - (element.clientHeight / 2);

    const mouseMoveHandler = (e: MouseEvent) => window.playerMouseMove(draggedElement, e);
    const mouseUpHandler = () => {
        window.playerMouseUp(element, index);
        window.removeEventListener("mousemove", mouseMoveHandler);
        window.removeEventListener("mouseup", mouseUpHandler)
    }

    // attach listeners for move and up
    window.addEventListener("mousemove", mouseMoveHandler);
    window.addEventListener("mouseup", mouseUpHandler);
}

window.playerMouseUp = (element, index) => {
window.playerMouseUp = () => {
    gridInteractionState.shouldDrag = true;

    // Reset
    gridInteractionState.draggedRow = null
    element!.classList.remove('hidden');
    (element.parentElement?.children[dropIndex] as HTMLDivElement).classList.remove('new-row-position');

    // Swap rows
    const playersArr = TeamRosterModel.players;
    if (index < dropIndex) dropIndex--;
    const [elToSwap] = playersArr.splice(index, 1);
    playersArr.splice(dropIndex, 0, elToSwap)

    updateModel(TeamRosterModel)
   deinitPlayerDrag();
}
```

Once wired in, confirm places the row, and back cancels it.

### Scrolling with the Right Joystick

The last interaction for the Team Roster screen is to enable the `Scroll` component to be scrolled with the right joystick. We want to initialize this behaviour when the selected inner screen is the `Team Roster` and deinit it when the player drills out of the screen.

We are alreay emitting the `handle-team-roster-scroll` event in our confirm/back handlers, now we need to listen for it in the `TeamRoster` component. When we emit events with the `eventBus` we can pass arguments to the event and use them in the handlers. In this case we are passing a `status` string which will init or deinit the behavior depending on the interaction phase.

```ts
// rest of the component
const handleGamepadScroll = (status: 'init' | 'deinit') => {
    if (status === 'init') useGamepadScroll(
        () => scrollRef.scrollUp(),
        () => scrollRef.scrollDown()
    );
    else deinitGamepadScroll();
}

onMount(() => {
    areaMappings.push({ area: 'team-roster-header', elements: [`.${styles['Header-Button']}`] })
    areaMappings.push({ area: 'team-roster-table', elements: [`.${styles.PlayerRow}`] })

    eventBus.on('handle-team-roster-scroll', handleGamepadScroll)
})

onCleanup(() => {
    eventBus.off('handle-team-roster-scroll', handleGamepadScroll)
})

// rest of the component
```

We also need to add the `useGamepadScroll` and `deinitGamepadScroll` hooks. We can put them in the `Interactions/index.ts` directory.

```ts
export const useGamepadScroll = (scrollUp: () => void, scrollDown: () => void) => {
    gamepad.on({
      actions: ['right.joystick.down'],
      callback: scrollDown,
    });

    gamepad.on({
      actions: ['right.joystick.up'],
      callback: scrollUp,
    })
}

export const deinitGamepadScroll = () => {
    gamepad.off(['right.joystick.down']);
    gamepad.off(['right.joystick.up']);
}
```

## Conclusion

The Team Roster screen is now fully navigable and interactive using keyboard and gamepad input. Players can:

- Sort the table by column
- Toggle focus between the table header and rows
- Drag and reorder player rows
- Scroll the table using the right joystick

In the upcoming tutorials, we’ll continue expanding this system by adding support for additional screens—ensuring a consistent and polished input experience across the entire UI.

## On this page
